unison

package module
v0.76.3 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2024 License: MPL-2.0 Imports: 82 Imported by: 27

README

Unison

Go Reference Go Report Card

A unified graphical user experience toolkit for Go desktop applications. macOS, Windows, and Linux are supported.

Required setup

Unison is built upon glfw. As such, it requires some setup prior to being able to build correctly:

  • On macOS, you need Xcode or Command Line Tools for Xcode (xcode-select --install) for required headers and libraries.
  • On Ubuntu/Debian-like Linux distributions, you need libgl1-mesa-dev and xorg-dev packages.
  • On CentOS/Fedora-like Linux distributions, you need libX11-devel libXcursor-devel libXrandr-devel libXinerama-devel mesa-libGL-devel libXi-devel libXxf86vm-devel packages.
  • On Windows, you need tdm-gcc as well as git-scm for its bash shell.
  • See compilation dependencies for full details.

This version of Unison was built using Go 1.22. It has been compiled under many earlier versions of Go in the past, but only Go 1.22+ will be considered as I make further changes.

Example

An example application can be found in the example directory:

go run example/main.go

Notes

Unison was developed with the needs of my personal projects in mind, so may not be a good fit for your particular needs. I'm open to suggestions on ways to improve the code and will happily consider Pull Requests with bug fixes or feature additions.

Compatibility

Unison is very much a work in progress. As such, it is likely to have breaking changes. To reflect this, a version number of 0.x.x will be in use until such time that I'm comfortable locking things down to ensure compatibility between releases. Please keep this in mind when making the decision to use Unison in your own code.

Look & Feel

Unison defines its own look and feel for widgets and will likely be adjusted over time. This was done to provide as much consistency as possible between all supported platforms. It also side-steps issues where a given platform itself has no or poorly defined standards. Colors, fonts, spacing, how the widgets behave, and more are customizable, so if you are feeling particularly ambitious, you could create your own theming that matches a given platform.

Organization

There are a large number of Go source files in a single, top-level package. Unison didn't start out this way, but user experience code tends to need to have its tentacles in many places, and the logical separations I made kept hindering the ability to do things. Ultimately, I made the decision to collapse nearly everything into a single package to simplify development and greatly reduce the overall complexity of things.

Documentation

Index

Constants

View Source
const (
	ModalResponseDiscard = iota - 1
	ModalResponseOK
	ModalResponseCancel
	ModalResponseUserBase = 100
)

Pre-defined modal response codes. Apps should start their codes at ModalResponseUserBase.

View Source
const (
	LayoutType    = "layout"
	ContainerType = "container"
	DockableType  = "dockable"
)

Possible values for the DockState Type field.

View Source
const (
	// DefaultSystemFamilyName is the default system font family name and will be used as a fallback where needed.
	DefaultSystemFamilyName = "Roboto"
	// DefaultMonospacedFamilyName is the default monospaced font family name.
	DefaultMonospacedFamilyName = "DejaVu Sans Mono"
)
View Source
const (
	UnderlineThicknessIsValidFontMetricsFlag = 1 << iota
	UnderlinePositionIsValidFontMetricsFlag
	StrikeoutThicknessIsValidFontMetricsFlag
	StrikeoutPositionIsValidFontMetricsFlag
	BoundsInvalidFontMetricsFlag
)

FontMetrics flags

View Source
const (
	ButtonLeft   = int(glfw.MouseButtonLeft)
	ButtonRight  = int(glfw.MouseButtonRight)
	ButtonMiddle = int(glfw.MouseButtonMiddle)
)

Constants for mouse buttons.

View Source
const (
	KeyNone           = KeyCode(glfw.KeyUnknown)
	KeySpace          = KeyCode(glfw.KeySpace)
	KeyApostrophe     = KeyCode(glfw.KeyApostrophe)
	KeyComma          = KeyCode(glfw.KeyComma)
	KeyMinus          = KeyCode(glfw.KeyMinus)
	KeyPeriod         = KeyCode(glfw.KeyPeriod)
	KeySlash          = KeyCode(glfw.KeySlash)
	Key0              = KeyCode(glfw.Key0)
	Key1              = KeyCode(glfw.Key1)
	Key2              = KeyCode(glfw.Key2)
	Key3              = KeyCode(glfw.Key3)
	Key4              = KeyCode(glfw.Key4)
	Key5              = KeyCode(glfw.Key5)
	Key6              = KeyCode(glfw.Key6)
	Key7              = KeyCode(glfw.Key7)
	Key8              = KeyCode(glfw.Key8)
	Key9              = KeyCode(glfw.Key9)
	KeySemiColon      = KeyCode(glfw.KeySemicolon)
	KeyEqual          = KeyCode(glfw.KeyEqual)
	KeyA              = KeyCode(glfw.KeyA)
	KeyB              = KeyCode(glfw.KeyB)
	KeyC              = KeyCode(glfw.KeyC)
	KeyD              = KeyCode(glfw.KeyD)
	KeyE              = KeyCode(glfw.KeyE)
	KeyF              = KeyCode(glfw.KeyF)
	KeyG              = KeyCode(glfw.KeyG)
	KeyH              = KeyCode(glfw.KeyH)
	KeyI              = KeyCode(glfw.KeyI)
	KeyJ              = KeyCode(glfw.KeyJ)
	KeyK              = KeyCode(glfw.KeyK)
	KeyL              = KeyCode(glfw.KeyL)
	KeyM              = KeyCode(glfw.KeyM)
	KeyN              = KeyCode(glfw.KeyN)
	KeyO              = KeyCode(glfw.KeyO)
	KeyP              = KeyCode(glfw.KeyP)
	KeyQ              = KeyCode(glfw.KeyQ)
	KeyR              = KeyCode(glfw.KeyR)
	KeyS              = KeyCode(glfw.KeyS)
	KeyT              = KeyCode(glfw.KeyT)
	KeyU              = KeyCode(glfw.KeyU)
	KeyV              = KeyCode(glfw.KeyV)
	KeyW              = KeyCode(glfw.KeyW)
	KeyX              = KeyCode(glfw.KeyX)
	KeyY              = KeyCode(glfw.KeyY)
	KeyZ              = KeyCode(glfw.KeyZ)
	KeyOpenBracket    = KeyCode(glfw.KeyLeftBracket)
	KeyBackslash      = KeyCode(glfw.KeyBackslash)
	KeyCloseBracket   = KeyCode(glfw.KeyRightBracket)
	KeyBackQuote      = KeyCode(glfw.KeyGraveAccent)
	KeyWorld1         = KeyCode(glfw.KeyWorld1)
	KeyWorld2         = KeyCode(glfw.KeyWorld2)
	KeyEscape         = KeyCode(glfw.KeyEscape)
	KeyReturn         = KeyCode(glfw.KeyEnter)
	KeyTab            = KeyCode(glfw.KeyTab)
	KeyBackspace      = KeyCode(glfw.KeyBackspace)
	KeyInsert         = KeyCode(glfw.KeyInsert)
	KeyDelete         = KeyCode(glfw.KeyDelete)
	KeyRight          = KeyCode(glfw.KeyRight)
	KeyLeft           = KeyCode(glfw.KeyLeft)
	KeyDown           = KeyCode(glfw.KeyDown)
	KeyUp             = KeyCode(glfw.KeyUp)
	KeyPageUp         = KeyCode(glfw.KeyPageUp)
	KeyPageDown       = KeyCode(glfw.KeyPageDown)
	KeyHome           = KeyCode(glfw.KeyHome)
	KeyEnd            = KeyCode(glfw.KeyEnd)
	KeyCapsLock       = KeyCode(glfw.KeyCapsLock)
	KeyScrollLock     = KeyCode(glfw.KeyScrollLock)
	KeyNumLock        = KeyCode(glfw.KeyNumLock)
	KeyPrintScreen    = KeyCode(glfw.KeyPrintScreen)
	KeyPause          = KeyCode(glfw.KeyPause)
	KeyF1             = KeyCode(glfw.KeyF1)
	KeyF2             = KeyCode(glfw.KeyF2)
	KeyF3             = KeyCode(glfw.KeyF3)
	KeyF4             = KeyCode(glfw.KeyF4)
	KeyF5             = KeyCode(glfw.KeyF5)
	KeyF6             = KeyCode(glfw.KeyF6)
	KeyF7             = KeyCode(glfw.KeyF7)
	KeyF8             = KeyCode(glfw.KeyF8)
	KeyF9             = KeyCode(glfw.KeyF9)
	KeyF10            = KeyCode(glfw.KeyF10)
	KeyF11            = KeyCode(glfw.KeyF11)
	KeyF12            = KeyCode(glfw.KeyF12)
	KeyF13            = KeyCode(glfw.KeyF13)
	KeyF14            = KeyCode(glfw.KeyF14)
	KeyF15            = KeyCode(glfw.KeyF15)
	KeyF16            = KeyCode(glfw.KeyF16)
	KeyF17            = KeyCode(glfw.KeyF17)
	KeyF18            = KeyCode(glfw.KeyF18)
	KeyF19            = KeyCode(glfw.KeyF19)
	KeyF20            = KeyCode(glfw.KeyF20)
	KeyF21            = KeyCode(glfw.KeyF21)
	KeyF22            = KeyCode(glfw.KeyF22)
	KeyF23            = KeyCode(glfw.KeyF23)
	KeyF24            = KeyCode(glfw.KeyF24)
	KeyF25            = KeyCode(glfw.KeyF25)
	KeyNumPad0        = KeyCode(glfw.KeyKP0)
	KeyNumPad1        = KeyCode(glfw.KeyKP1)
	KeyNumPad2        = KeyCode(glfw.KeyKP2)
	KeyNumPad3        = KeyCode(glfw.KeyKP3)
	KeyNumPad4        = KeyCode(glfw.KeyKP4)
	KeyNumPad5        = KeyCode(glfw.KeyKP5)
	KeyNumPad6        = KeyCode(glfw.KeyKP6)
	KeyNumPad7        = KeyCode(glfw.KeyKP7)
	KeyNumPad8        = KeyCode(glfw.KeyKP8)
	KeyNumPad9        = KeyCode(glfw.KeyKP9)
	KeyNumPadDecimal  = KeyCode(glfw.KeyKPDecimal)
	KeyNumPadDivide   = KeyCode(glfw.KeyKPDivide)
	KeyNumPadMultiply = KeyCode(glfw.KeyKPMultiply)
	KeyNumPadSubtract = KeyCode(glfw.KeyKPSubtract)
	KeyNumPadAdd      = KeyCode(glfw.KeyKPAdd)
	KeyNumPadEnter    = KeyCode(glfw.KeyKPEnter)
	KeyNumPadEqual    = KeyCode(glfw.KeyKPEqual)
	KeyLShift         = KeyCode(glfw.KeyLeftShift)
	KeyLControl       = KeyCode(glfw.KeyLeftControl)
	KeyLOption        = KeyCode(glfw.KeyLeftAlt)
	KeyLCommand       = KeyCode(glfw.KeyLeftSuper)
	KeyRShift         = KeyCode(glfw.KeyRightShift)
	KeyRControl       = KeyCode(glfw.KeyRightControl)
	KeyROption        = KeyCode(glfw.KeyRightAlt)
	KeyRCommand       = KeyCode(glfw.KeyRightSuper)
	KeyMenu           = KeyCode(glfw.KeyMenu)
	KeyLast           = KeyCode(glfw.KeyLast)
)

Virtual key codes.

View Source
const (
	// DefaultMaxSize is the default size that should be used for a maximum dimension if the target has no real
	// preference and can be expanded beyond its preferred size. This is intentionally not something very large to allow
	// basic math operations an opportunity to succeed when laying out panels. It is perfectly acceptable to use a
	// larger value than this, however, if that makes sense for your specific target.
	DefaultMaxSize = 10000
	// StdHSpacing is the typical spacing between columns.
	StdHSpacing = 8
	// StdVSpacing is the typical spacing between rows.
	StdVSpacing = 4
	// StdIconGap is the typical gap between an icon and text.
	StdIconGap = 3
)
View Source
const (
	RootMenuID int = 1 + iota
	AppMenuID
	FileMenuID
	EditMenuID
	WindowMenuID
	HelpMenuID
	ServicesMenuID
	AboutItemID
	PreferencesItemID
	QuitItemID
	CutItemID
	CopyItemID
	PasteItemID
	DeleteItemID
	SelectAllItemID
	MinimizeItemID
	ZoomItemID
	BringAllWindowsToFrontItemID
	CloseItemID
	HideItemID
	HideOthersItemID
	ShowAllItemID
	WindowMenuItemBaseID
	PopupMenuTemporaryBaseID = WindowMenuItemBaseID + maxWindowsListed
	UserBaseID               = 5000
	ContextMenuIDFlag        = 1 << 15 // Should be or'd into IDs for context menus
	MaxUserBaseID            = ContextMenuIDFlag - 1
)

Pre-defined menu IDs. Apps should start their IDs at UserBaseID.

View Source
const DefaultMarkdownWidth = 8 * 100

DefaultMarkdownWidth is the default maximum width to use, roughly equivalent to a page at 100dpi.

View Source
const DialogClientDataKey = "dialog"

DialogClientDataKey is the key used in the ClientData() of the Window the dialog puts up which contains the *Dialog of the owning dialog.

View Source
const NoUndoID = 0

NoUndoID represents an empty undo ID value.

Variables

View Source
var (
	OnLight = RGB(16, 16, 16)
	OnDark  = RGB(240, 240, 240)
)

Colors used for the On() method.

View Source
var (
	AliceBlue            = RGB(240, 248, 255)
	AntiqueWhite         = RGB(250, 235, 215)
	Aqua                 = RGB(0, 255, 255)
	Aquamarine           = RGB(127, 255, 212)
	Azure                = RGB(240, 255, 255)
	Beige                = RGB(245, 245, 220)
	Bisque               = RGB(255, 228, 196)
	Black                = RGB(0, 0, 0)
	BlanchedAlmond       = RGB(255, 235, 205)
	Blue                 = RGB(0, 0, 255)
	BlueViolet           = RGB(138, 43, 226)
	Brown                = RGB(165, 42, 42)
	BurlyWood            = RGB(222, 184, 135)
	CadetBlue            = RGB(95, 158, 160)
	Chartreuse           = RGB(127, 255, 0)
	Chocolate            = RGB(210, 105, 30)
	Coral                = RGB(255, 127, 80)
	CornflowerBlue       = RGB(100, 149, 237)
	Cornsilk             = RGB(255, 248, 220)
	Crimson              = RGB(220, 20, 60)
	Cyan                 = RGB(0, 255, 255)
	DarkBlue             = RGB(0, 0, 139)
	DarkCyan             = RGB(0, 139, 139)
	DarkGoldenRod        = RGB(184, 134, 11)
	DarkGray             = RGB(169, 169, 169)
	DarkGreen            = RGB(0, 100, 0)
	DarkGrey             = RGB(169, 169, 169)
	DarkKhaki            = RGB(189, 183, 107)
	DarkMagenta          = RGB(139, 0, 139)
	DarkOliveGreen       = RGB(85, 107, 47)
	DarkOrange           = RGB(255, 140, 0)
	DarkOrchid           = RGB(153, 50, 204)
	DarkRed              = RGB(139, 0, 0)
	DarkSalmon           = RGB(233, 150, 122)
	DarkSeaGreen         = RGB(143, 188, 143)
	DarkSlateBlue        = RGB(72, 61, 139)
	DarkSlateGray        = RGB(47, 79, 79)
	DarkSlateGrey        = RGB(47, 79, 79)
	DarkTurquoise        = RGB(0, 206, 209)
	DarkViolet           = RGB(148, 0, 211)
	DeepPink             = RGB(255, 20, 147)
	DeepSkyBlue          = RGB(0, 191, 255)
	DimGray              = RGB(105, 105, 105)
	DimGrey              = RGB(105, 105, 105)
	DodgerBlue           = RGB(30, 144, 255)
	FireBrick            = RGB(178, 34, 34)
	FloralWhite          = RGB(255, 250, 240)
	ForestGreen          = RGB(34, 139, 34)
	Fuchsia              = RGB(255, 0, 255)
	Gainsboro            = RGB(220, 220, 220)
	GhostWhite           = RGB(248, 248, 255)
	Gold                 = RGB(255, 215, 0)
	GoldenRod            = RGB(218, 165, 32)
	Gray                 = RGB(128, 128, 128)
	Green                = RGB(0, 128, 0)
	GreenYellow          = RGB(173, 255, 47)
	Grey                 = RGB(128, 128, 128)
	HoneyDew             = RGB(240, 255, 240)
	HotPink              = RGB(255, 105, 180)
	IndianRed            = RGB(205, 92, 92)
	Indigo               = RGB(75, 0, 130)
	Ivory                = RGB(255, 255, 240)
	Khaki                = RGB(240, 230, 140)
	Lavender             = RGB(230, 230, 250)
	LavenderBlush        = RGB(255, 240, 245)
	LawnGreen            = RGB(124, 252, 0)
	LemonChiffon         = RGB(255, 250, 205)
	LightBlue            = RGB(173, 216, 230)
	LightCoral           = RGB(240, 128, 128)
	LightCyan            = RGB(224, 255, 255)
	LightGoldenRodYellow = RGB(250, 250, 210)
	LightGray            = RGB(211, 211, 211)
	LightGreen           = RGB(144, 238, 144)
	LightGrey            = RGB(211, 211, 211)
	LightPink            = RGB(255, 182, 193)
	LightSalmon          = RGB(255, 160, 122)
	LightSeaGreen        = RGB(32, 178, 170)
	LightSkyBlue         = RGB(135, 206, 250)
	LightSlateGray       = RGB(119, 136, 153)
	LightSlateGrey       = RGB(119, 136, 153)
	LightSteelBlue       = RGB(176, 196, 222)
	LightYellow          = RGB(255, 255, 224)
	Lime                 = RGB(0, 255, 0)
	LimeGreen            = RGB(50, 205, 50)
	Linen                = RGB(250, 240, 230)
	Magenta              = RGB(255, 0, 255)
	Maroon               = RGB(128, 0, 0)
	MediumAquaMarine     = RGB(102, 205, 170)
	MediumBlue           = RGB(0, 0, 205)
	MediumOrchid         = RGB(186, 85, 211)
	MediumPurple         = RGB(147, 112, 219)
	MediumSeaGreen       = RGB(60, 179, 113)
	MediumSlateBlue      = RGB(123, 104, 238)
	MediumSpringGreen    = RGB(0, 250, 154)
	MediumTurquoise      = RGB(72, 209, 204)
	MediumVioletRed      = RGB(199, 21, 133)
	MidnightBlue         = RGB(25, 25, 112)
	MintCream            = RGB(245, 255, 250)
	MistyRose            = RGB(255, 228, 225)
	Moccasin             = RGB(255, 228, 181)
	NavajoWhite          = RGB(255, 222, 173)
	Navy                 = RGB(0, 0, 128)
	OldLace              = RGB(253, 245, 230)
	Olive                = RGB(128, 128, 0)
	OliveDrab            = RGB(107, 142, 35)
	Orange               = RGB(255, 165, 0)
	OrangeRed            = RGB(255, 69, 0)
	Orchid               = RGB(218, 112, 214)
	PaleGoldenRod        = RGB(238, 232, 170)
	PaleGreen            = RGB(152, 251, 152)
	PaleTurquoise        = RGB(175, 238, 238)
	PaleVioletRed        = RGB(219, 112, 147)
	PapayaWhip           = RGB(255, 239, 213)
	PeachPuff            = RGB(255, 218, 185)
	Peru                 = RGB(205, 133, 63)
	Pink                 = RGB(255, 192, 203)
	Plum                 = RGB(221, 160, 221)
	PowderBlue           = RGB(176, 224, 230)
	Purple               = RGB(128, 0, 128)
	Red                  = RGB(255, 0, 0)
	RosyBrown            = RGB(188, 143, 143)
	RoyalBlue            = RGB(65, 105, 225)
	SaddleBrown          = RGB(139, 69, 19)
	Salmon               = RGB(250, 128, 114)
	SandyBrown           = RGB(244, 164, 96)
	SeaGreen             = RGB(46, 139, 87)
	SeaShell             = RGB(255, 245, 238)
	Sienna               = RGB(160, 82, 45)
	Silver               = RGB(192, 192, 192)
	SkyBlue              = RGB(135, 206, 235)
	SlateBlue            = RGB(106, 90, 205)
	SlateGray            = RGB(112, 128, 144)
	SlateGrey            = RGB(112, 128, 144)
	Snow                 = RGB(255, 250, 250)
	SpringGreen          = RGB(0, 255, 127)
	SteelBlue            = RGB(70, 130, 180)
	Tan                  = RGB(210, 180, 140)
	Teal                 = RGB(0, 128, 128)
	Thistle              = RGB(216, 191, 216)
	Tomato               = RGB(255, 99, 71)
	Transparent          = Color(0)
	Turquoise            = RGB(64, 224, 208)
	Violet               = RGB(238, 130, 238)
	Wheat                = RGB(245, 222, 179)
	White                = RGB(255, 255, 255)
	WhiteSmoke           = RGB(245, 245, 245)
	Yellow               = RGB(255, 255, 0)
	YellowGreen          = RGB(154, 205, 50)
)

CSS named colors.

View Source
var (
	SystemFont           = &IndirectFont{}
	EmphasizedSystemFont = &IndirectFont{}
	LabelFont            = &IndirectFont{}
	FieldFont            = &IndirectFont{}
	KeyboardFont         = &IndirectFont{}
	MonospacedFont       = &IndirectFont{}
)

Pre-defined fonts

View Source
var (
	BrokenImageSVG = MustSVGFromContentString(brokenImageSVG)

	CircledChevronRightSVG = MustSVGFromContentString(circledChevronRightSVG)

	CircledExclamationSVG = MustSVGFromContentString(circledExclamationSVG)

	CircledQuestionSVG = MustSVGFromContentString(circledQuestionSVG)

	CheckmarkSVG = MustSVGFromContentString(checkmarkSVG)

	ChevronRightSVG = MustSVGFromContentString(chevronRightSVG)

	CircledXSVG = MustSVGFromContentString(circledXSVG)

	DashSVG = MustSVGFromContentString(dashSVG)

	DocumentSVG = MustSVGFromContentString(documentSVG)

	SortAscendingSVG = MustSVGFromContentString(sortAscendingSVG)

	SortDescendingSVG = MustSVGFromContentString(sortDescendingSVG)

	TriangleExclamationSVG = MustSVGFromContentString(triangleExclamationSVG)

	WindowMaximizeSVG = MustSVGFromContentString(windowMaximizeSVG)

	WindowRestoreSVG = MustSVGFromContentString(windowRestoreSVG)
)

Pre-defined SVG images used by Unison.

View Source
var (
	ThemeSurface = DefaultThemeSurface()
	ThemeBanding = DefaultThemeBanding()
	ThemeFocus   = DefaultThemeFocus()
	ThemeTooltip = DefaultThemeTooltip()
	ThemeError   = DefaultThemeError()
	ThemeWarning = DefaultThemeWarning()
)

The theme colors used throughout Unison.

View Source
var (
	ThemeAboveSurface     = ThemeSurface.DeriveLightness(-0.05, 0.05)
	ThemeBelowSurface     = ThemeSurface.DeriveLightness(0.05, -0.05)
	ThemeDeepBelowSurface = ThemeSurface.DeriveLightness(0.1, -0.1)
	ThemeSurfaceEdge      = ThemeSurface.DeriveLightness(-0.1, 0.15)
	ThemeDeepFocus        = ThemeFocus.DeriveLightness(-0.05, -0.05)
	ThemeDeeperFocus      = ThemeFocus.DeriveLightness(-0.1, -0.1)
	ThemeDeepestFocus     = ThemeFocus.DeriveLightness(-0.15, -0.15)
	ThemeTooltipEdge      = ThemeTooltip.DeriveLightness(-0.2, -0.2)

	ThemeOnSurface          = ThemeSurface.DeriveOn()
	ThemeOnAboveSurface     = ThemeAboveSurface.DeriveOn()
	ThemeOnBelowSurface     = ThemeBelowSurface.DeriveOn()
	ThemeOnDeepBelowSurface = ThemeDeepBelowSurface.DeriveOn()
	ThemeOnBanding          = ThemeBanding.DeriveOn()
	ThemeOnFocus            = ThemeFocus.DeriveOn()
	ThemeOnDeepFocus        = ThemeDeepFocus.DeriveOn()
	ThemeOnDeeperFocus      = ThemeDeeperFocus.DeriveOn()
	ThemeOnDeepestFocus     = ThemeDeepestFocus.DeriveOn()
	ThemeOnTooltip          = ThemeTooltip.DeriveOn()
	ThemeOnError            = ThemeError.DeriveOn()
	ThemeOnWarning          = ThemeWarning.DeriveOn()
)

The colors derived from the theme colors.

View Source
var DefaultButtonTheme = ButtonTheme{
	TextDecoration: TextDecoration{
		Font:            SystemFont,
		BackgroundInk:   ThemeAboveSurface,
		OnBackgroundInk: ThemeOnAboveSurface,
	},
	EdgeInk:             ThemeSurfaceEdge,
	SelectionInk:        ThemeFocus,
	OnSelectionInk:      ThemeOnFocus,
	Gap:                 StdIconGap,
	CornerRadius:        4,
	HMargin:             8,
	VMargin:             1,
	DrawableOnlyHMargin: 3,
	DrawableOnlyVMargin: 3,
	ClickAnimationTime:  100 * time.Millisecond,
	HAlign:              align.Middle,
	VAlign:              align.Middle,
	Side:                side.Left,
	HideBase:            false,
}

DefaultButtonTheme holds the default ButtonTheme values for Buttons. Modifying this data will not alter existing Buttons, but will alter any Buttons created in the future.

View Source
var DefaultCheckBoxTheme = CheckBoxTheme{
	TextDecoration: TextDecoration{
		Font:            SystemFont,
		OnBackgroundInk: ThemeOnSurface,
	},
	EdgeInk:            ThemeSurfaceEdge,
	SelectionInk:       ThemeFocus,
	OnSelectionInk:     ThemeOnFocus,
	ControlInk:         ThemeAboveSurface,
	OnControlInk:       ThemeOnAboveSurface,
	Gap:                StdIconGap,
	CornerRadius:       4,
	ClickAnimationTime: 100 * time.Millisecond,
	HAlign:             align.Start,
	VAlign:             align.Middle,
	Side:               side.Left,
}

DefaultCheckBoxTheme holds the default CheckBoxTheme values for CheckBoxes. Modifying this data will not alter existing CheckBoxes, but will alter any CheckBoxes created in the future.

View Source
var DefaultDialogTheme = DialogTheme{
	ErrorIcon: &DrawableSVG{
		SVG:  CircledExclamationSVG,
		Size: Size{Width: 48, Height: 48},
	},
	ErrorIconInk: ThemeError,
	WarningIcon: &DrawableSVG{
		SVG:  TriangleExclamationSVG,
		Size: Size{Width: 48, Height: 48},
	},
	WarningIconInk: ThemeWarning,
	QuestionIcon: &DrawableSVG{
		SVG:  CircledQuestionSVG,
		Size: Size{Width: 48, Height: 48},
	},
	QuestionIconInk: ThemeOnSurface,
}

DefaultDialogTheme holds the default DialogTheme values for Dialogs. Modifying this data will not alter existing Dialogs, but will alter any Dialogs created in the future.

View Source
var DefaultDockHeaderTheme = DockHeaderTheme{
	BackgroundInk: ThemeSurface,
	DropAreaInk:   ThemeWarning,
	HeaderBorder: NewCompoundBorder(
		NewLineBorder(ThemeSurfaceEdge, 0, Insets{Bottom: 1}, false),
		NewEmptyBorder(NewHorizontalInsets(4)),
	),
	MinimumTabWidth: 50,
	TabGap:          4,
	TabInsertSize:   3,
}

DefaultDockHeaderTheme holds the default DockHeaderTheme values for DockHeaders. Modifying this data will not alter existing DockHeaders, but will alter any DockHeaders created in the future.

View Source
var DefaultDockTabTheme = DockTabTheme{
	BackgroundInk:   ThemeAboveSurface,
	OnBackgroundInk: ThemeOnAboveSurface,
	EdgeInk:         ThemeSurfaceEdge,
	TabFocusedInk:   ThemeFocus,
	OnTabFocusedInk: ThemeOnFocus,
	TabCurrentInk:   ThemeDeepestFocus,
	OnTabCurrentInk: ThemeOnDeepestFocus,
	TabBorder:       NewEmptyBorder(Insets{Top: 2, Left: 4, Bottom: 2, Right: 4}),
	Gap:             4,
	LabelTheme:      defaultDockLabelTheme(),
	ButtonTheme:     defaultDockButtonTheme(),
}

DefaultDockTabTheme holds the default DockTabTheme values for DockTabs. Modifying this data will not alter existing DockTabs, but will alter any DockTabs created in the future.

View Source
var DefaultDockTheme = DockTheme{
	BackgroundInk: ThemeSurface,
	GripInk:       ThemeSurfaceEdge,
	DropAreaInk:   ThemeWarning,
	GripCount:     5,
	GripGap:       1,
	GripWidth:     4,
	GripHeight:    2,
	GripMargin:    2,
}

DefaultDockTheme holds the default DockTheme values for Docks. Modifying this data will not alter existing Docks, but will alter any Docks created in the future.

View Source
var DefaultFieldTheme = FieldTheme{
	Font:             FieldFont,
	BackgroundInk:    ThemeSurface,
	OnBackgroundInk:  ThemeOnSurface,
	EditableInk:      ThemeDeepBelowSurface,
	OnEditableInk:    ThemeOnDeepBelowSurface,
	SelectionInk:     ThemeFocus,
	OnSelectionInk:   ThemeOnFocus,
	ErrorInk:         ThemeError,
	OnErrorInk:       ThemeOnError,
	BlinkRate:        560 * time.Millisecond,
	MinimumTextWidth: 10,
	HAlign:           align.Start,
}

DefaultFieldTheme holds the default FieldTheme values for Fields. Modifying this data will not alter existing Fields, but will alter any Fields created in the future.

View Source
var DefaultLabelTheme = LabelTheme{
	TextDecoration: TextDecoration{
		Font:            LabelFont,
		OnBackgroundInk: ThemeOnSurface,
	},
	Gap:    StdIconGap,
	HAlign: align.Start,
	VAlign: align.Middle,
	Side:   side.Left,
}

DefaultLabelTheme holds the default LabelTheme values for Labels. Modifying this data will not alter existing Labels, but will alter any Labels created in the future.

View Source
var DefaultLinkTheme = LinkTheme{
	LabelTheme: LabelTheme{
		TextDecoration: TextDecoration{
			Font:            LabelFont,
			OnBackgroundInk: ThemeFocus,
			Underline:       true,
		},
		Gap:    StdIconGap,
		HAlign: align.Start,
		VAlign: align.Middle,
		Side:   side.Left,
	},
	PressedInk:   ThemeFocus,
	OnPressedInk: ThemeOnFocus,
}

DefaultLinkTheme holds the default Link theme values.

View Source
var DefaultListTheme = ListTheme{
	BackgroundInk:          ThemeBelowSurface,
	OnBackgroundInk:        ThemeOnBelowSurface,
	BandingInk:             ThemeBanding,
	OnBandingInk:           ThemeOnBanding,
	SelectionInk:           ThemeFocus,
	OnSelectionInk:         ThemeOnFocus,
	InactiveSelectionInk:   ThemeDeepFocus,
	OnInactiveSelectionInk: ThemeOnDeepFocus,
	FlashAnimationTime:     100 * time.Millisecond,
}

DefaultListTheme holds the default ListTheme values for Lists. Modifying this data will not alter existing Lists, but will alter any Lists created in the future.

View Source
var DefaultMenuItemTheme = MenuItemTheme{
	TitleFont:         SystemFont,
	KeyFont:           KeyboardFont,
	BackgroundColor:   ThemeSurface,
	OnBackgroundColor: ThemeOnSurface,
	SelectionColor:    ThemeFocus,
	OnSelectionColor:  ThemeOnFocus,
	ItemBorder:        NewEmptyBorder(StdInsets()),
	SeparatorBorder:   NewEmptyBorder(NewVerticalInsets(4)),
	KeyGap:            16,
}

DefaultMenuItemTheme holds the default MenuItemTheme values for menu items. Modifying this data will not alter existing menu items, but will alter any menu items created in the future.

View Source
var DefaultMenuTheme = MenuTheme{
	BarBorder:  NewLineBorder(ThemeSurfaceEdge, 0, Insets{Bottom: 1}, false),
	MenuBorder: NewLineBorder(ThemeSurfaceEdge, 0, NewUniformInsets(1), false),
}

DefaultMenuTheme holds the default MenuTheme values for Menus. Modifying this data will not alter existing Menus, but will alter any Menus created in the future.

View Source
var DefaultPopupMenuTheme = PopupMenuTheme{
	TextDecoration: TextDecoration{
		Font:            SystemFont,
		BackgroundInk:   ThemeAboveSurface,
		OnBackgroundInk: ThemeOnAboveSurface,
	},
	EdgeInk:        ThemeSurfaceEdge,
	SelectionInk:   ThemeFocus,
	OnSelectionInk: ThemeOnFocus,
	CornerRadius:   4,
	HMargin:        8,
	VMargin:        1,
}

DefaultPopupMenuTheme holds the default PopupMenuTheme values for PopupMenus. Modifying this data will not alter existing PopupMenus, but will alter any PopupMenus created in the future.

View Source
var DefaultProgressBarTheme = ProgressBarTheme{
	BackgroundInk:      ThemeSurface,
	FillInk:            ThemeFocus,
	EdgeInk:            ThemeSurfaceEdge,
	TickSpeed:          time.Second / 30,
	FullTraversalSpeed: time.Second,
	PreferredBarHeight: 8,
	CornerRadius:       8,
	IndeterminateWidth: 15,
	EdgeThickness:      1,
}

DefaultProgressBarTheme holds the default ProgressBarTheme values for ProgressBars. Modifying this data will not alter existing ProgressBars, but will alter any ProgressBars created in the future.

View Source
var DefaultRadioButtonTheme = RadioButtonTheme{
	TextDecoration: TextDecoration{
		Font:            SystemFont,
		BackgroundInk:   ThemeAboveSurface,
		OnBackgroundInk: ThemeOnAboveSurface,
	},
	EdgeInk:            ThemeSurfaceEdge,
	SelectionInk:       ThemeFocus,
	OnSelectionInk:     ThemeOnFocus,
	Gap:                StdIconGap,
	CornerRadius:       4,
	ClickAnimationTime: 100 * time.Millisecond,
	HAlign:             align.Middle,
	VAlign:             align.Middle,
	Side:               side.Left,
}

DefaultRadioButtonTheme holds the default RadioButtonTheme values for RadioButtons. Modifying this data will not alter existing RadioButtons, but will alter any RadioButtons created in the future.

View Source
var DefaultScrollBarTheme = ScrollBarTheme{
	EdgeInk:          ThemeSurfaceEdge,
	ThumbInk:         ThemeFocus,
	MinimumThickness: 11,
	MinimumThumb:     16,
	ThumbIndent:      3,
	CornerRadius:     4,
}

DefaultScrollBarTheme holds the default ScrollBarTheme values for ScrollBars. Modifying this data will not alter existing ScrollBars, but will alter any ScrollBars created in the future.

View Source
var DefaultScrollPanelTheme = ScrollPanelTheme{
	BackgroundInk:        ThemeSurface,
	MouseWheelMultiplier: func() float32 { return MouseWheelMultiplier },
}

DefaultScrollPanelTheme holds the default ScrollPanelTheme values for ScrollPanels. Modifying this data will not alter existing ScrollPanels, but will alter any ScrollPanels created in the future.

View Source
var DefaultSeparatorTheme = SeparatorTheme{
	LineInk:  ThemeSurfaceEdge,
	Vertical: false,
}

DefaultSeparatorTheme holds the default SeparatorTheme values for Separators. Modifying this data will not alter existing Separators, but will alter any Separators created in the future.

View Source
var DefaultTableColumnHeaderTheme = LabelTheme{
	TextDecoration: TextDecoration{
		Font:            LabelFont,
		OnBackgroundInk: ThemeOnSurface,
	},
	Gap:    StdIconGap,
	HAlign: align.Middle,
	VAlign: align.Middle,
	Side:   side.Left,
}

DefaultTableColumnHeaderTheme holds the default TableColumnHeaderTheme values for TableColumnHeaders. Modifying this data will not alter existing TableColumnHeaders, but will alter any TableColumnHeaders created in the future.

View Source
var DefaultTableHeaderTheme = TableHeaderTheme{
	BackgroundInk:        ThemeAboveSurface,
	InteriorDividerColor: ThemeAboveSurface,
}

DefaultTableHeaderTheme holds the default TableHeaderTheme values for TableHeaders. Modifying this data will not alter existing TableHeaders, but will alter any TableHeaders created in the future.

View Source
var DefaultTableTheme = TableTheme{
	BackgroundInk:          ThemeBelowSurface,
	OnBackgroundInk:        ThemeOnBelowSurface,
	BandingInk:             ThemeBanding,
	OnBandingInk:           ThemeOnBanding,
	InteriorDividerInk:     ThemeAboveSurface,
	SelectionInk:           ThemeFocus,
	OnSelectionInk:         ThemeOnFocus,
	InactiveSelectionInk:   ThemeDeepFocus,
	OnInactiveSelectionInk: ThemeOnDeepFocus,
	IndirectSelectionInk:   ThemeDeeperFocus,
	OnIndirectSelectionInk: ThemeOnDeeperFocus,
	Padding:                NewUniformInsets(4),
	HierarchyIndent:        16,
	MinimumRowHeight:       16,
	ColumnResizeSlop:       4,
	ShowColumnDivider:      true,
}

DefaultTableTheme holds the default TableTheme values for Tables. Modifying this data will not alter existing Tables, but will alter any Tables created in the future.

View Source
var DefaultTagTheme = TagTheme{
	TextDecoration: TextDecoration{
		Font: &DynamicFont{
			Resolver: func() FontDescriptor {
				desc := LabelFont.Descriptor()
				desc.Size = max(desc.Size-2, 1)
				return desc
			},
		},
		BackgroundInk:   ThemeOnSurface,
		OnBackgroundInk: ThemeSurface,
	},
	Gap:       StdIconGap,
	SideInset: 3,
	RadiusX:   6,
	RadiusY:   6,
	HAlign:    align.Start,
	VAlign:    align.Middle,
	Side:      side.Left,
}

DefaultTagTheme holds the default TagTheme values for Tags. Modifying this data will not alter existing Tags, but will alter any Tags created in the future.

View Source
var (
	// DefaultTitleIcons are the default title icons that will be used for all newly created windows. The image closest to
	// the size desired by the system will be selected and used, scaling if needed. If no images are specified, the system's
	// default icon will be used.
	DefaultTitleIcons []*Image
)
View Source
var DefaultTooltipTheme = TooltipTheme{
	BackgroundInk: ThemeTooltip,
	BaseBorder: NewCompoundBorder(
		NewLineBorder(ThemeTooltipEdge, 0, NewUniformInsets(1), false),
		NewEmptyBorder(StdInsets()),
	),
	Label:     defaultToolTipLabelTheme(),
	Delay:     1500 * time.Millisecond,
	Dismissal: 5 * time.Second,
}

DefaultTooltipTheme holds the default TooltipTheme values for Tooltips. Modifying this data will not alter existing Tooltips, but will alter any Tooltips created in the future.

View Source
var DefaultWellTheme = WellTheme{
	BackgroundInk:      ThemeAboveSurface,
	EdgeInk:            ThemeSurfaceEdge,
	SelectionInk:       ThemeFocus,
	ImageScale:         0.5,
	ContentSize:        20,
	CornerRadius:       4,
	ClickAnimationTime: 100 * time.Millisecond,
	ImageLoadTimeout:   30 * time.Second,
	Mask:               ColorWellMask | GradientWellMask | PatternWellMask,
}

DefaultWellTheme holds the default WellTheme values for Wells. Modifying this data will not alter existing Wells, but will alter any Wells created in the future.

View Source
var (
	// DisableMenus overrides all application menus when set to true, causing them to become disabled. This is primarily
	// provided to allow a way to disable menu key capture temporarily. This will not allow system keys to be captured,
	// but will prevent the menus from capturing keys while it is true.
	DisableMenus bool
)
View Source
var (
	// ErrColorDecode is the sentinel error returned by the ColorDecode function on failure.
	ErrColorDecode = errors.New("invalid color string")
)
View Source
var GlobalClipboard = &Clipboard{}

GlobalClipboard holds the global clipboard.

View Source
var (

	// MouseWheelMultiplier is used by the default theme to multiply incoming mouse wheel event deltas.
	MouseWheelMultiplier = float32(16)
)

Functions

func AllWindowsToFront

func AllWindowsToFront()

AllWindowsToFront brings all of the application's windows to the foreground.

func AlwaysEnabled added in v0.18.0

func AlwaysEnabled(_ any) bool

AlwaysEnabled is a helper function whose signature matches the 'can' function signature required for InstallCmdHandlers() that always returns true.

func Ancestor added in v0.20.0

func Ancestor[T any](paneler Paneler) T

Ancestor returns the first ancestor of the given type. May return nil if no parent matches.

func AncestorIs added in v0.29.0

func AncestorIs(paneler, ancestor Paneler) bool

AncestorIs returns true if the paneler has the given ancestor.

func AncestorIsOrSelf added in v0.29.0

func AncestorIsOrSelf(paneler, ancestor Paneler) bool

AncestorIsOrSelf returns true if the paneler has the given ancestor or is the ancestor.

func AncestorOrSelf added in v0.20.0

func AncestorOrSelf[T any](paneler Paneler) T

AncestorOrSelf returns the provided panel or the first ancestor of the given type. May return nil if nothing matches.

func AttachConsole added in v0.3.0

func AttachConsole()

AttachConsole attempts to fix Windows console output, which is generally broken thanks to their oddball and unnecessary split between graphical and command-line applications. This attempts to fix that by attaching the console so that a graphical application can also be used as a command-line application without having to build two variants. May be called more than once. Subsequent calls do nothing. Does nothing on non-Windows platforms.

func AttemptQuit

func AttemptQuit()

AttemptQuit initiates the termination sequence.

func Beep

func Beep()

Beep plays the system beep sound.

func CannotRedoTitle

func CannotRedoTitle() string

CannotRedoTitle returns the Cannot Redo title.

func CannotUndoTitle

func CannotUndoTitle() string

CannotUndoTitle returns the Cannot Undo title.

func CollectIDsFromRow added in v0.72.0

func CollectIDsFromRow[T TableRowConstraint[T]](node T, ids map[tid.TID]bool)

CollectIDsFromRow returns a map containing the IDs of the provided node and all of its descendants.

func CountTableRows added in v0.20.0

func CountTableRows[T TableRowConstraint[T]](rows []T) int

CountTableRows returns the number of table rows, including all descendants, whether open or not.

func CreateDeriveLightnessFunc added in v0.69.0

func CreateDeriveLightnessFunc(light, dark float32) func(ThemeColor) ThemeColor

CreateDeriveLightnessFunc returns a function that will adjust the lightness of a ThemeColor by the given amount.

func CreatePDF added in v0.29.0

func CreatePDF(s Stream, md *PDFMetaData, pageProvider PageProvider) error

CreatePDF writes a PDF to the given stream. md may be nil.

func CurrentThemeMode added in v0.66.0

func CurrentThemeMode() thememode.Enum

CurrentThemeMode returns the current theme mode state.

func DefaultMarkdownLinkHandler added in v0.44.0

func DefaultMarkdownLinkHandler(_ Paneler, target string)

DefaultMarkdownLinkHandler provides the default link handler, which handles opening a browsers for http and https links.

func DockableHasFocus added in v0.5.0

func DockableHasFocus(dockable Dockable) bool

DockableHasFocus returns true if the given Dockable has the current focus inside it.

func DoubleClickParameters

func DoubleClickParameters() (maxDelay time.Duration, maxMouseDrift float32)

DoubleClickParameters returns the maximum delay between clicks and the maximum pixel drift allowed to register as a double-click.

func DragGestureParameters added in v0.3.0

func DragGestureParameters() (minDelay time.Duration, minMouseDrift float32)

DragGestureParameters returns the minimum delay before mouse movement should be recognized as a drag as well as the minimum pixel drift required to trigger a drag.

func DrawEllipseBase

func DrawEllipseBase(canvas *Canvas, rect Rect, thickness float32, fillInk, strokeInk Ink)

DrawEllipseBase fills and strokes an ellipse.

func DrawLabel

func DrawLabel(canvas *Canvas, rect Rect, hAlign, vAlign align.Enum, font Font, text *Text, onBackgroundInk, backgroundInk Ink, drawable Drawable, drawableSide side.Enum, imgGap float32, applyDisabledFilter bool)

DrawLabel draws a label. Provided as a standalone function so that other types of panels can make use of it.

func DrawRectBase

func DrawRectBase(canvas *Canvas, rect Rect, fillInk, strokeInk Ink)

DrawRectBase fills and strokes a rectangle.

func DrawRoundedRectBase

func DrawRoundedRectBase(canvas *Canvas, rect Rect, cornerRadius, thickness float32, fillInk, strokeInk Ink)

DrawRoundedRectBase fills and strokes a rounded rectangle.

func ErrorDialogWithError

func ErrorDialogWithError(primary string, detail error)

ErrorDialogWithError displays a standard error dialog with the specified primary message and extracts the message from the error for its detail. The full error will be logged via errs.Log(). Embedded line feeds are OK.

func ErrorDialogWithMessage

func ErrorDialogWithMessage(primary, detail string)

ErrorDialogWithMessage displays a standard error dialog with the specified primary and detail messages. Embedded line feeds are OK.

func ErrorDialogWithPanel

func ErrorDialogWithPanel(msgPanel Paneler)

ErrorDialogWithPanel displays a standard error dialog with the specified panel.

func FontFamilies

func FontFamilies() []string

FontFamilies retrieves the names of the installed font families, using a cached version if available.

func FontFamiliesNoCache added in v0.75.1

func FontFamiliesNoCache() []string

FontFamiliesNoCache retrieves the names of the installed font families.

func HasAnyPrefix added in v0.57.0

func HasAnyPrefix(prefixes []string, target string) bool

HasAnyPrefix returns true if the target has a prefix matching one of those found in prefixes.

func HasURLPrefix added in v0.57.0

func HasURLPrefix(target string) bool

HasURLPrefix returns true if the target has a prefix of "http://" or "https://".

func InsertAboutItem

func InsertAboutItem(m Menu, atIndex int, aboutHandler func(MenuItem))

InsertAboutItem creates the standard "About" menu item that will call the provided handler when chosen.

func InsertBringAllToFrontItem

func InsertBringAllToFrontItem(m Menu, atIndex int)

InsertBringAllToFrontItem creates the standard "Bring All to Front" menu item that will call AllWindowsToFront when chosen.

func InsertCloseFocusedWindowItem

func InsertCloseFocusedWindowItem(m Menu, atIndex int)

InsertCloseFocusedWindowItem creates the standard "Close" menu item that will close the currently focused window when chosen.

func InsertMinimizeItem

func InsertMinimizeItem(m Menu, atIndex int)

InsertMinimizeItem creates the standard "Minimize" menu item that will issue the Minimize command to the currently focused window when chosen.

func InsertPreferencesItem

func InsertPreferencesItem(m Menu, atIndex int, prefsHandler func(MenuItem))

InsertPreferencesItem creates the standard "Preferences…" menu item that will call the provided handler when chosen.

func InsertQuitItem

func InsertQuitItem(m Menu, atIndex int)

InsertQuitItem creates the standard "Quit"/"Exit" menu item that will issue the Quit command when chosen.

func InsertStdMenus

func InsertStdMenus(m Menu, aboutHandler, prefsHandler func(MenuItem), updater func(Menu))

InsertStdMenus adds the standard menus to the menu bar.

func InsertZoomItem

func InsertZoomItem(m Menu, atIndex int)

InsertZoomItem creates the standard "Zoom" menu item that will issue the Zoom command to the currently focused window when chosen.

func InstallDefaultFieldBorder added in v0.69.0

func InstallDefaultFieldBorder(focusTarget, borderTarget Paneler)

InstallDefaultFieldBorder installs the default field border on the borderTarget and chains into the focus handling of the focusTarget to adjust the border as focus changes.

func InstallFocusBorders added in v0.69.0

func InstallFocusBorders(focusTarget, borderTarget Paneler, focusedBorder, unfocusedBorder Border)

InstallFocusBorders installs the provided borders on the borderTarget and chains into the focus handling of the focusTarget to adjust the border as focus changes. To prevent the display from shifting around, the borders should have the same insets.

func InvokeTask

func InvokeTask(f func())

InvokeTask calls a function on the UI thread. The function is put into the system event queue and will be run at the next opportunity.

func InvokeTaskAfter

func InvokeTaskAfter(f func(), after time.Duration)

InvokeTaskAfter schedules a function to be run on the UI thread after waiting for the specified duration.

func IsColorModeTrackingPossible added in v0.25.0

func IsColorModeTrackingPossible() bool

IsColorModeTrackingPossible returns true if the underlying platform can provide the current dark mode state. On those platforms that return false from this function, thememode.Auto is the same as thememode.Light.

func IsControlAction

func IsControlAction(keyCode KeyCode, mod Modifiers) bool

IsControlAction returns true if the keyCode should trigger a control, such as a button, that is focused.

func IsDarkModeEnabled

func IsDarkModeEnabled() bool

IsDarkModeEnabled returns true if the OS is currently using a "dark mode".

func MarkDynamicColorsForRebuild

func MarkDynamicColorsForRebuild()

MarkDynamicColorsForRebuild marks the dynamic colors to be updated the next time RebuildDynamicColors() is called.

func NextUndoID added in v0.13.0

func NextUndoID() int64

NextUndoID returns the next available undo ID.

func NormalizeOKLCH added in v0.42.0

func NormalizeOKLCH(lightness, chroma, hue, alpha float32) (l, c, h, a float32)

NormalizeOKLCH returns the normalized lightness (0-1), chroma (0-0.37), and hue (0-360) values using the OKLCH color space.

func QuestionDialog

func QuestionDialog(primary, detail string) int

QuestionDialog displays a standard question dialog with the specified primary and detail messages. Embedded line feeds are OK. This function returns ids.ModalResponseOK if the OK button was pressed and ids.ModalResponseCancel if the Cancel button was pressed.

func QuestionDialogWithPanel

func QuestionDialogWithPanel(msgPanel Paneler) int

QuestionDialogWithPanel displays a standard question dialog with the specified panel. This function returns ids.ModalResponseOK if the OK button was pressed and ids.ModalResponseCancel if the Cancel button was pressed.

func RebuildDynamicColors

func RebuildDynamicColors()

RebuildDynamicColors rebuilds the dynamic colors, but only if a call to MarkDynamicColorsForRebuild() has been made since the last time this function was called.

func ReleaseOnUIThread

func ReleaseOnUIThread(f func())

ReleaseOnUIThread will add f to the release queue and eventually call it on the UI thread.

func ReviseTarget added in v0.57.0

func ReviseTarget(workingDir, target string, altLinkPrefixes []string) (string, error)

ReviseTarget returns a sanitized target with either a link or an absolute path.

func RouteActionToFocusEnabledFunc

func RouteActionToFocusEnabledFunc(action *Action, src any) bool

RouteActionToFocusEnabledFunc is intended to be the EnabledCallback for actions that will route to the currently focused UI widget and call CanPerformCmd() on it.

func RouteActionToFocusExecuteFunc

func RouteActionToFocusExecuteFunc(action *Action, src any)

RouteActionToFocusExecuteFunc is intended to be the ExecuteCallback for actions that will route to the currently focused UI widget and call PerformCmd() on it.

func RowContainsRow added in v0.20.0

func RowContainsRow[T TableRowConstraint[T]](ancestor, descendant T) bool

RowContainsRow returns true if 'descendant' is in fact a descendant of 'ancestor'.

func SanitizeExtensionList

func SanitizeExtensionList(in []string) []string

SanitizeExtensionList ensures the extension list is consistent:

  • removal of leading and trailing white space
  • removal of leading "*." or "."
  • lower-cased
  • removal of duplicates
  • removal of empty extensions

func SetThemeMode added in v0.66.0

func SetThemeMode(mode thememode.Enum)

SetThemeMode sets the current theme mode state.

func Start

func Start(options ...StartupOption)

Start the application. This function does NOT return. While some calls may be safe to make, it should be assumed no calls into unison can be made prior to Start() being called unless explicitly stated otherwise.

func ThemeChanged added in v0.7.0

func ThemeChanged()

ThemeChanged marks dynamic colors for rebuilding, calls any installed theme change callback, and then redraws all windows. This is normally called automatically for you, however, it has been made public to allow you to trigger it on demand.

func UninstallFocusBorders added in v0.69.0

func UninstallFocusBorders(focusTarget, borderTarget Paneler)

UninstallFocusBorders removes the focus handling and border from the borderTarget that was installed by a previous call to InstallFocusBorders.

func ValidateSaveFilePath added in v0.30.0

func ValidateSaveFilePath(filePath, requiredExtension string, forcePrompt bool) (revisedPath string, ok bool)

ValidateSaveFilePath ensures the given path is ok to be used to save a file. If requiredExtension isn't empty, this function will ensure filePath ends with that extension. If the resulting file already exists, the user will be prompted to verify they intend to overwrite the destination. On platforms that prompt for file overwrite in the native dialog, this method will not prompt the user again unless forcePrompt is true, which can be useful if the path in question did not come from a file dialog.

func WarningDialogWithMessage added in v0.5.0

func WarningDialogWithMessage(primary, detail string)

WarningDialogWithMessage displays a standard warning dialog with the specified primary and detail messages. Embedded line feeds are OK.

func WarningDialogWithPanel added in v0.5.0

func WarningDialogWithPanel(msgPanel Paneler)

WarningDialogWithPanel displays a standard error dialog with the specified panel.

func WindowCount

func WindowCount() int

WindowCount returns the number of windows that are open.

func YesNoCancelDialog added in v0.16.0

func YesNoCancelDialog(primary, detail string) int

YesNoCancelDialog displays a standard question dialog with the specified primary and detail messages. Embedded line feeds are OK. This function returns ids.ModalResponseOK if the Yes button was pressed, ids.ModalResponseDiscard if the No button was pressed, and ids.ModalResponseCancel if the Cancel button was pressed.

func YesNoCancelDialogWithPanel added in v0.16.0

func YesNoCancelDialogWithPanel(msgPanel Paneler) int

YesNoCancelDialogWithPanel displays a standard question dialog with the specified panel. Embedded line feeds are OK. This function returns ids.ModalResponseOK if the Yes button was pressed, ids.ModalResponseDiscard if the No button was pressed, and ids.ModalResponseCancel if the Cancel button was pressed.

func YesNoDialog added in v0.56.0

func YesNoDialog(primary, detail string) int

YesNoDialog displays a standard question dialog with the specified primary and detail messages. Embedded line feeds are OK. This function returns ids.ModalResponseOK if the Yes button was pressed and ids.ModalResponseDiscard if the No button was pressed.

func YesNoDialogWithPanel added in v0.56.0

func YesNoDialogWithPanel(msgPanel Paneler) int

YesNoDialogWithPanel displays a standard question dialog with the specified panel. Embedded line feeds are OK. This function returns ids.ModalResponseOK if the Yes button was pressed and ids.ModalResponseDiscard if the No button was pressed.

Types

type Action

type Action struct {
	EnabledCallback func(*Action, any) bool // Should return true if the action can be used. Care should be made to keep this method fast to avoid slowing down the user interface. May be nil, in which case it is assumed to always be enabled.
	ExecuteCallback func(*Action, any)      // Will be called to run the action. May be nil.
	Title           string                  // Typically used in a menu item title or tooltip for a button.
	ID              int                     // Should be unique among all actions and menu items.
	KeyBinding      KeyBinding              // The key binding that will trigger the action.
}

Action describes an action that can be performed.

func CopyAction

func CopyAction() *Action

CopyAction returns the action that copies the selection and places it on the clipboard.

func CutAction

func CutAction() *Action

CutAction returns the action that removes the selection and places it on the clipboard.

func DeleteAction

func DeleteAction() *Action

DeleteAction returns the action that deletes the selection.

func PasteAction

func PasteAction() *Action

PasteAction returns the action that pastes the contents of the clipboard, replacing the selection.

func SelectAllAction

func SelectAllAction() *Action

SelectAllAction returns the action that selects everything in the current focus.

func (*Action) Enabled

func (a *Action) Enabled(src any) bool

Enabled returns true if the action can be used.

func (*Action) Execute

func (a *Action) Execute(src any)

Execute the action. Calls Enabled() to verify execution is permitted.

func (*Action) NewContextMenuItemFromAction

func (a *Action) NewContextMenuItemFromAction(f MenuFactory) MenuItem

NewContextMenuItemFromAction returns a newly created menu item for a context menu using this action. If the menuItem would be disabled, nil is returned instead.

func (*Action) NewMenuItem

func (a *Action) NewMenuItem(f MenuFactory) MenuItem

NewMenuItem returns a newly created menu item using this action.

type Border

type Border interface {
	// Insets returns the insets describing the space the border occupies on each side.
	Insets() Insets
	// Draw the border into rect.
	Draw(canvas *Canvas, rect Rect)
}

Border defines methods required of all border providers.

func NewDefaultFieldBorder added in v0.12.0

func NewDefaultFieldBorder(focused bool) Border

NewDefaultFieldBorder creates the default border for a field.

type Button

type Button struct {
	ClickCallback func()
	Drawable      Drawable
	Text          *Text

	Panel
	ButtonTheme
	Pressed bool
	// contains filtered or unexported fields
}

Button represents a clickable button.

func NewButton

func NewButton() *Button

NewButton creates a new button.

func NewSVGButton added in v0.7.0

func NewSVGButton(svg *SVG) *Button

NewSVGButton creates an SVG icon button with a size equal to the default button theme's font baseline.

func (*Button) Click

func (b *Button) Click()

Click makes the button behave as if a user clicked on it.

func (*Button) DefaultDraw

func (b *Button) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Button) DefaultFocusGained added in v0.16.0

func (b *Button) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*Button) DefaultKeyDown

func (b *Button) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*Button) DefaultMouseDown

func (b *Button) DefaultMouseDown(_ Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*Button) DefaultMouseDrag

func (b *Button) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*Button) DefaultMouseUp

func (b *Button) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*Button) DefaultSizes

func (b *Button) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Button) DefaultUpdateCursor added in v0.44.0

func (b *Button) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor for buttons.

func (*Button) Group added in v0.69.0

func (b *Button) Group() *Group

Group returns the group that this button is a part of.

func (*Button) HorizontalMargin

func (b *Button) HorizontalMargin() float32

HorizontalMargin returns the horizontal margin that will be used.

func (*Button) SetGroup added in v0.69.0

func (b *Button) SetGroup(group *Group)

SetGroup sets the group that this button is a part of. Should only be called by the Group.

func (*Button) SetTitle added in v0.69.0

func (b *Button) SetTitle(text string)

SetTitle sets the text of the button to the specified text. The theme's TextDecoration will be used, so any changes you want to make to it should be done before calling this method. Alternatively, you can directly set the .Text field.

func (*Button) VerticalMargin

func (b *Button) VerticalMargin() float32

VerticalMargin returns the vertical margin that will be used.

type ButtonTheme added in v0.4.0

type ButtonTheme struct {
	EdgeInk        Ink
	SelectionInk   Ink
	OnSelectionInk Ink
	TextDecoration
	Gap                 float32
	CornerRadius        float32
	HMargin             float32
	VMargin             float32
	DrawableOnlyHMargin float32
	DrawableOnlyVMargin float32
	ClickAnimationTime  time.Duration
	HAlign              align.Enum
	VAlign              align.Enum
	Side                side.Enum
	HideBase            bool
	Sticky              bool
}

ButtonTheme holds theming data for a Button.

type Canvas

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

Canvas is a drawing surface.

func (*Canvas) Clear

func (c *Canvas) Clear(color Color)

Clear fills the clip with the color.

func (*Canvas) ClipBounds

func (c *Canvas) ClipBounds() Rect

ClipBounds returns the clip bounds.

func (*Canvas) ClipPath

func (c *Canvas) ClipPath(path *Path, op pathop.Enum, antialias bool)

ClipPath replaces the clip with the intersection of difference of the current clip and path.

func (*Canvas) ClipRect

func (c *Canvas) ClipRect(rect Rect, op pathop.Enum, antialias bool)

ClipRect replaces the clip with the intersection of difference of the current clip and rect.

func (*Canvas) Concat

func (c *Canvas) Concat(matrix Matrix)

Concat the matrix.

func (*Canvas) DrawArc

func (c *Canvas) DrawArc(oval Rect, startAngle, sweepAngle float32, paint *Paint, useCenter bool)

DrawArc draws an arc. startAngle and sweepAngle are in degrees. If useCenter is true, this will draw a wedge that includes lines from the oval center to the arc end points. If useCenter is false, then just and arc between the end points will be drawn.

func (*Canvas) DrawCircle

func (c *Canvas) DrawCircle(cx, cy, radius float32, paint *Paint)

DrawCircle draws the circle with Paint.

func (*Canvas) DrawColor

func (c *Canvas) DrawColor(color Color, mode blendmode.Enum)

DrawColor fills the clip with the color.

func (*Canvas) DrawImage

func (c *Canvas) DrawImage(img *Image, x, y float32, sampling *SamplingOptions, paint *Paint)

DrawImage draws the image at the specified location using its logical size. paint may be nil.

func (*Canvas) DrawImageInRect

func (c *Canvas) DrawImageInRect(img *Image, rect Rect, sampling *SamplingOptions, paint *Paint)

DrawImageInRect draws the image into the area specified by the rect, scaling if necessary. paint may be nil.

func (*Canvas) DrawImageNine

func (c *Canvas) DrawImageNine(img *Image, centerRect, dstRect Rect, filter filtermode.Enum, paint *Paint)

DrawImageNine draws an image stretched proportionally to fit into dstRect. 'center' divides the image into nine sections: four sides, four corners, and the center. Corners are unmodified or scaled down proportionately if their sides are larger than dstRect; center and four sides are scaled to fit remaining space, if any. paint may be nil.

func (*Canvas) DrawImageRectInRect

func (c *Canvas) DrawImageRectInRect(img *Image, srcRect, dstRect Rect, sampling *SamplingOptions, paint *Paint)

DrawImageRectInRect draws a portion of the image into the area specified, scaling if necessary. srcRect should be in raw pixel coordinates, not logical coordinates. dstRect should be in logical coordinates. paint may be nil.

func (*Canvas) DrawLine

func (c *Canvas) DrawLine(sx, sy, ex, ey float32, paint *Paint)

DrawLine draws a line.

func (*Canvas) DrawOval

func (c *Canvas) DrawOval(rect Rect, paint *Paint)

DrawOval draws the oval with Paint.

func (*Canvas) DrawPaint

func (c *Canvas) DrawPaint(paint *Paint)

DrawPaint fills the clip with Paint. Any MaskFilter or PathEffect in the Paint is ignored.

func (*Canvas) DrawPath

func (c *Canvas) DrawPath(path *Path, paint *Paint)

DrawPath draws the path with Paint.

func (*Canvas) DrawPoint

func (c *Canvas) DrawPoint(x, y float32, paint *Paint)

DrawPoint draws a point.

func (*Canvas) DrawPoints

func (c *Canvas) DrawPoints(pts []Point, paint *Paint, mode pointmode.Enum)

DrawPoints draws the points using the given mode.

func (*Canvas) DrawPolygon

func (c *Canvas) DrawPolygon(poly Polygon, mode filltype.Enum, paint *Paint)

DrawPolygon draws a polygon.

func (*Canvas) DrawRect

func (c *Canvas) DrawRect(rect Rect, paint *Paint)

DrawRect draws the rectangle with Paint.

func (*Canvas) DrawRoundedRect

func (c *Canvas) DrawRoundedRect(rect Rect, radiusX, radiusY float32, paint *Paint)

DrawRoundedRect draws a rounded rectangle with Paint.

func (*Canvas) DrawSimpleString added in v0.7.0

func (c *Canvas) DrawSimpleString(str string, x, y float32, font Font, paint *Paint)

DrawSimpleString draws a string. It does not do any processing of embedded line endings nor tabs. It also does not do any font fallback. y is the baseline for the text.

func (*Canvas) DrawTextBlob added in v0.52.0

func (c *Canvas) DrawTextBlob(blob *TextBlob, x, y float32, paint *Paint)

DrawTextBlob draws text from a text blob.

func (*Canvas) Flush

func (c *Canvas) Flush()

Flush any drawing.

func (*Canvas) IsClipEmpty

func (c *Canvas) IsClipEmpty() bool

IsClipEmpty returns true if the clip is empty, i.e. nothing will draw.

func (*Canvas) IsClipRect

func (c *Canvas) IsClipRect() bool

IsClipRect returns true if the clip is a rectangle and not empty.

func (*Canvas) Matrix

func (c *Canvas) Matrix() Matrix

Matrix returns the current transform matrix.

func (*Canvas) QuickRejectPath

func (c *Canvas) QuickRejectPath(path *Path) bool

QuickRejectPath returns true if the path, after transformations by the current matrix, can be quickly determined to be outside of the current clip. May return false even though the path is outside of the clip.

func (*Canvas) QuickRejectRect

func (c *Canvas) QuickRejectRect(rect Rect) bool

QuickRejectRect returns true if the rect, after transformations by the current matrix, can be quickly determined to be outside of the current clip. May return false even though the rect is outside of the clip.

func (*Canvas) ResetMatrix

func (c *Canvas) ResetMatrix()

ResetMatrix sets the current transform matrix to the identity matrix.

func (*Canvas) Restore

func (c *Canvas) Restore()

Restore removes changes to the transformation matrix and clip since the last call to Save() or SaveWithOpacity(). Does nothing if the stack is empty.

func (*Canvas) RestoreToCount

func (c *Canvas) RestoreToCount(count int)

RestoreToCount restores the transformation matrix and clip to the state they where in when the specified count was returned from a call to Save() or SaveWithOpacity(). Does nothing if count is greater than the current state stack count. Restores the state to the initial values if count is <= 1.

func (*Canvas) Rotate

func (c *Canvas) Rotate(degrees float32)

Rotate the coordinate system.

func (*Canvas) Save

func (c *Canvas) Save() int

Save pushes the current transformation matrix and clip onto a stack and returns the current count. Multiple save calls should be balanced by an equal number of calls to Restore().

func (*Canvas) SaveCount

func (c *Canvas) SaveCount() int

SaveCount returns the number of saved states, which equals the number of save calls minus the number of Restore() calls plus 1. The SaveCount() of a new Canvas is 1.

func (*Canvas) SaveLayer

func (c *Canvas) SaveLayer(paint *Paint) int

SaveLayer pushes the current transformation matrix and clip onto a stack and returns the current count. The provided paint will be applied to all subsequent drawing until the corresponding call to Restore(). Multiple save calls should be balanced by an equal number of calls to Restore().

func (*Canvas) SaveWithOpacity

func (c *Canvas) SaveWithOpacity(opacity float32) int

SaveWithOpacity pushes the current transformation matrix and clip onto a stack and returns the current count. The opacity (a value between 0 and 1, where 0 is fully transparent and 1 is fully opaque) will be applied to all subsequent drawing until the corresponding call to Restore(). Multiple save calls should be balanced by an equal number of calls to Restore().

func (*Canvas) Scale

func (c *Canvas) Scale(x, y float32)

Scale the coordinate system.

func (*Canvas) SetMatrix

func (c *Canvas) SetMatrix(matrix Matrix)

SetMatrix replaces the current matrix with the given matrix.

func (*Canvas) Skew

func (c *Canvas) Skew(sx, sy float32)

Skew the coordinate system. A positive value of sx skews the drawing right as y-axis values increase; a positive value of sy skews the drawing down as x-axis values increase.

func (*Canvas) Translate

func (c *Canvas) Translate(dx, dy float32)

Translate the coordinate system.

type CellFactory

type CellFactory interface {
	// CellHeight returns the height to use for the cells. A value less than 1 indicates that each cell's height may be
	// different.
	CellHeight() float32

	// CreateCell creates a new cell.
	CreateCell(owner Paneler, element any, row int, foreground, background Ink, selected, focused bool) Paneler
}

CellFactory defines methods all cell factories must implement.

type CheckBox

type CheckBox struct {
	ClickCallback func()
	Drawable      Drawable
	Text          *Text
	CheckBoxTheme
	Panel
	State   check.Enum
	Pressed bool
}

CheckBox represents a clickable checkbox with an optional label.

func NewCheckBox

func NewCheckBox() *CheckBox

NewCheckBox creates a new checkbox.

func (*CheckBox) Click

func (c *CheckBox) Click()

Click makes the checkbox behave as if a user clicked on it.

func (*CheckBox) DefaultDraw

func (c *CheckBox) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*CheckBox) DefaultFocusGained added in v0.16.0

func (c *CheckBox) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*CheckBox) DefaultKeyDown

func (c *CheckBox) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*CheckBox) DefaultMouseDown

func (c *CheckBox) DefaultMouseDown(_ Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*CheckBox) DefaultMouseDrag

func (c *CheckBox) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*CheckBox) DefaultMouseUp

func (c *CheckBox) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*CheckBox) DefaultSizes

func (c *CheckBox) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*CheckBox) DefaultUpdateCursor added in v0.44.0

func (c *CheckBox) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor for check boxes.

func (*CheckBox) SetTitle added in v0.69.0

func (c *CheckBox) SetTitle(text string)

SetTitle sets the text of the checkbox to the specified text. The theme's TextDecoration will be used, so any changes you want to make to it should be done before calling this method. Alternatively, you can directly set the .Text field.

type CheckBoxTheme added in v0.4.0

type CheckBoxTheme struct {
	EdgeInk        Ink
	SelectionInk   Ink
	OnSelectionInk Ink
	ControlInk     Ink
	OnControlInk   Ink
	TextDecoration
	Gap                float32
	CornerRadius       float32
	ClickAnimationTime time.Duration
	HAlign             align.Enum
	VAlign             align.Enum
	Side               side.Enum
}

CheckBoxTheme holds theming data for a CheckBox.

type Clipboard

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

Clipboard provides access to the system clipboard as well as an internal, application-only, clipboard. Currently, due to limitations in the underlying glfw libraries, only strings may be set onto and retrieved from the system clipboard. The internal clipboard accepts any type of data and is passed around via interface. Due to this, you may want to consider serializing and unserializing your data into bytes to pass it through the clipboard, to avoid accidental mutations.

func (*Clipboard) GetData

func (c *Clipboard) GetData(dataType string) (data any, exists bool)

GetData returns the data associated with the specified type on the application clipboard and does not examine the system clipboard at all.

func (*Clipboard) GetText

func (c *Clipboard) GetText() string

GetText returns text from the current clipboard data. This reads from the system clipboard.

func (*Clipboard) SetData

func (c *Clipboard) SetData(dataType string, data any)

SetData the data for a single type on the application clipboard, clearing out any others that were previously present. If the data can be converted to text by .(string), it will also be set onto the system clipboard, otherwise, the system clipboard will be cleared.

func (*Clipboard) SetMultipleData

func (c *Clipboard) SetMultipleData(pairs []ClipboardData)

SetMultipleData sets the data for multiple types onto the application clipboard, clearing out any others that were previously present. The first one that is convertable to text via .(string) will be used to set the system clipboard value. If none is found, then the system clipboard will be cleared.

func (*Clipboard) SetText

func (c *Clipboard) SetText(str string)

SetText sets text as the current clipboard data. This modifies the system clipboard.

type ClipboardData

type ClipboardData struct {
	Data any
	Type string
}

ClipboardData holds a type and data pair.

type Color

type Color uint32

Color contains the value of a color used for drawing, stored as 0xAARRGGBB.

func ARGB

func ARGB(alpha float32, red, green, blue int) Color

ARGB creates a new Color from RGB (Red, Green Blue) values in the range 0-255 and an alpha value in the range 0-1.

func ARGBfloat

func ARGBfloat(alpha, red, green, blue float32) Color

ARGBfloat creates a new Color from ARGB (Alpha, Red, Green Blue) values in the range 0-1.

func ColorDecode

func ColorDecode(buffer string) (Color, error)

ColorDecode creates a Color from a string. The string may be in any of the standard CSS formats:

- CSS predefined color name, e.g. "Yellow" - CSS rgb(), e.g. "rgb(255, 255, 0)" - CSS rgba(), e.g. "rgba(255, 255, 0, 0.3)" - CSS short hexadecimal colors, e.g. "#FF0" - CSS long hexadecimal colors, e.g. "#FFFF00" - CCS hsl(), e.g. "hsl(120, 100%, 50%)" - CSS hsla(), e.g. "hsla(120, 100%, 50%, 0.3)"

func ColorFromNRGBA added in v0.73.0

func ColorFromNRGBA(c color.NRGBA) Color

ColorFromNRGBA creates a new Color from a color.NRGBA value.

func HSB

func HSB(hue, saturation, brightness float32) Color

HSB creates a new opaque Color from HSB (Hue, Saturation, Brightness) values in the range 0-1.

func HSBA

func HSBA(hue, saturation, brightness, alpha float32) Color

HSBA creates a new Color from HSBA (Hue, Saturation, Brightness, Alpha) values in the range 0-1.

func MustColorDecode added in v0.4.0

func MustColorDecode(buffer string) Color

MustColorDecode is the same as ColorDecode(), but returns Black if an error occurs.

func OKLCH added in v0.42.0

func OKLCH(lightness, chroma, hue, alpha float32) Color

OKLCH creates a Color from lightness (0-1), chroma (0-0.37), hue (0-360), alpha (0-1) values using the OKLCH color space.

func RGB

func RGB(red, green, blue int) Color

RGB creates a new opaque Color from RGB (Red, Green Blue) values in the range 0-255.

func (Color) AdjustBrightness

func (c Color) AdjustBrightness(amount float32) Color

AdjustBrightness creates a new color from this color with its brightness adjusted by the specified amount.

func (Color) AdjustHue

func (c Color) AdjustHue(amount float32) Color

AdjustHue creates a new color from this color with its hue adjusted by the specified amount.

func (Color) AdjustPerceivedLightness added in v0.69.0

func (c Color) AdjustPerceivedLightness(adj float32) Color

AdjustPerceivedLightness returns a new color based on this color with its perceived lightness adjusted by the specified amount.

func (Color) AdjustSaturation

func (c Color) AdjustSaturation(amount float32) Color

AdjustSaturation creates a new color from this color with its saturation adjusted by the specified amount.

func (Color) Alpha

func (c Color) Alpha() int

Alpha returns the alpha channel, in the range of 0-255.

func (Color) AlphaIntensity

func (c Color) AlphaIntensity() float32

AlphaIntensity returns the alpha channel, in the range of 0-1.

func (Color) Blend

func (c Color) Blend(other Color, pct float32) Color

Blend blends this color with another color. pct is the amount of the other color to use.

func (Color) Blue

func (c Color) Blue() int

Blue returns the blue channel, in the range of 0-255.

func (Color) BlueIntensity

func (c Color) BlueIntensity() float32

BlueIntensity returns the blue channel, in the range of 0-1.

func (Color) Brightness

func (c Color) Brightness() float32

Brightness of the color, a value from 0-1.

func (Color) GetColor added in v0.2.0

func (c Color) GetColor() Color

GetColor returns this Color. Here to satisfy the ColorProvider interface.

func (Color) GoString

func (c Color) GoString() string

GoString implements the fmt.GoStringer interface.

func (Color) Green

func (c Color) Green() int

Green returns the green channel, in the range of 0-255.

func (Color) GreenIntensity

func (c Color) GreenIntensity() float32

GreenIntensity returns the green channel, in the range of 0-1.

func (Color) HSB

func (c Color) HSB() (hue, saturation, brightness float32)

HSB returns the hue, saturation and brightness of the color. Values are in the range 0-1.

func (Color) HasAlpha

func (c Color) HasAlpha() bool

HasAlpha returns true if the color is not fully opaque.

func (Color) Hue

func (c Color) Hue() float32

Hue of the color, a value from 0-1.

func (Color) Invisible

func (c Color) Invisible() bool

Invisible returns true if the color is fully transparent.

func (Color) MarshalText

func (c Color) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Color) Monochrome

func (c Color) Monochrome() bool

Monochrome returns true if each color component is the same, making it a shade of gray.

func (Color) OKLCH added in v0.42.0

func (c Color) OKLCH() (rl, rc, rh float32)

OKLCH returns the lightness (0-1), chroma (0-0.37), and hue (0-360) values using the OKLCH color space.

func (Color) On added in v0.69.0

func (c Color) On() Color

On returns OnLight if the input color is light, otherwise OnDark.

func (Color) OnCustom added in v0.69.0

func (c Color) OnCustom(onLightColor, onDarkColor Color) Color

OnCustom returns onLightColor if the input color is light, otherwise onDarkColor.

func (Color) Opaque

func (c Color) Opaque() bool

Opaque returns true if the color is fully opaque.

func (Color) Paint

func (c Color) Paint(_ *Canvas, _ Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this Color. Here to satisfy the Ink interface.

func (Color) PerceivedLightness added in v0.69.0

func (c Color) PerceivedLightness() float32

PerceivedLightness returns a value from 0-1 representing the perceived lightness. Lower values represent darker colors, while higher values represent brighter colors. This is the same as the lightness value returned by calling the .OKLCH() method.

func (Color) Premultiply

func (c Color) Premultiply() Color

Premultiply multiplies the color channels by the alpha channel.

func (Color) RGBA

func (c Color) RGBA() (r, g, b, a uint32)

RGBA implements color.Color. Assumes the color is not premultiplied and must be premultiplied to meet the contract of color.Color.

func (Color) Red

func (c Color) Red() int

Red returns the red channel, in the range of 0-255.

func (Color) RedIntensity

func (c Color) RedIntensity() float32

RedIntensity returns the red channel, in the range of 0-1.

func (Color) Saturation

func (c Color) Saturation() float32

Saturation of the color, a value from 0-1.

func (Color) SetAlpha

func (c Color) SetAlpha(alpha int) Color

SetAlpha returns a new color based on this color, but with the alpha channel replaced.

func (Color) SetAlphaIntensity

func (c Color) SetAlphaIntensity(alpha float32) Color

SetAlphaIntensity returns a new color based on this color, but with the alpha channel replaced.

func (Color) SetBlue

func (c Color) SetBlue(blue int) Color

SetBlue returns a new color based on this color, but with the blue channel replaced.

func (Color) SetBlueIntensity

func (c Color) SetBlueIntensity(blue float32) Color

SetBlueIntensity returns a new color based on this color, but with the blue channel replaced.

func (Color) SetBrightness

func (c Color) SetBrightness(brightness float32) Color

SetBrightness creates a new color from this color with the specified brightness.

func (Color) SetGreen

func (c Color) SetGreen(green int) Color

SetGreen returns a new color based on this color, but with the green channel replaced.

func (Color) SetGreenIntensity

func (c Color) SetGreenIntensity(green float32) Color

SetGreenIntensity returns a new color based on this color, but with the green channel replaced.

func (Color) SetHue

func (c Color) SetHue(hue float32) Color

SetHue creates a new color from this color with the specified hue, a value from 0-1.

func (Color) SetRed

func (c Color) SetRed(red int) Color

SetRed returns a new color based on this color, but with the red channel replaced.

func (Color) SetRedIntensity

func (c Color) SetRedIntensity(red float32) Color

SetRedIntensity returns a new color based on this color, but with the red channel replaced.

func (Color) SetSaturation

func (c Color) SetSaturation(saturation float32) Color

SetSaturation creates a new color from this color with the specified saturation.

func (Color) String

func (c Color) String() string

String implements the fmt.Stringer interface. The output can be used as a color in CSS.

func (*Color) UnmarshalText

func (c *Color) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (Color) Unpremultiply

func (c Color) Unpremultiply() Color

Unpremultiply divides the color channels by the alpha channel, effectively undoing a Premultiply call. Note that you will not necessarily get the original value back after calling Premultiply followed by Unpremultiply.

type ColorFilter

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

ColorFilter is called with source colors and return new colors, which are then passed onto the next stage.

func Alpha30Filter added in v0.20.0

func Alpha30Filter() *ColorFilter

Alpha30Filter returns a ColorFilter that transforms colors by applying a 30% alpha blend.

func Alpha50Filter added in v0.69.0

func Alpha50Filter() *ColorFilter

Alpha50Filter returns a ColorFilter that transforms colors by applying a 50% alpha blend.

func Grayscale30Filter added in v0.20.0

func Grayscale30Filter() *ColorFilter

Grayscale30Filter returns a ColorFilter that transforms colors to grayscale and applies a 30% alpha blend.

func NewAlphaFilter added in v0.4.0

func NewAlphaFilter(alpha float32) *ColorFilter

NewAlphaFilter returns a new ColorFilter that applies an alpha blend.

func NewBlendColorFilter

func NewBlendColorFilter(color Color, blendMode blendmode.Enum) *ColorFilter

NewBlendColorFilter returns a new blend color filter.

func NewComposeColorFilter

func NewComposeColorFilter(outer, inner *ColorFilter) *ColorFilter

NewComposeColorFilter returns a new color filter that combines two other color filters.

func NewHighContrastColorFilter

func NewHighContrastColorFilter(contrast float32, style invertstyle.Enum, grayscale bool) *ColorFilter

NewHighContrastColorFilter returns a new high contrast color filter.

func NewLightingColorFilter

func NewLightingColorFilter(mul, add Color) *ColorFilter

NewLightingColorFilter returns a new lighting color filter.

func NewLumaColorFilter

func NewLumaColorFilter() *ColorFilter

NewLumaColorFilter returns a new luma color filter.

func NewMatrixColorFilter

func NewMatrixColorFilter(array []float32) *ColorFilter

NewMatrixColorFilter returns a new matrix color filter. array should be 20 long. If smaller, it will be filled with zeroes to make it 20.

type ColorFilteredInk added in v0.43.0

type ColorFilteredInk struct {
	OriginalInk Ink
	ColorFilter *ColorFilter
}

ColorFilteredInk holds an ink and a color filter to apply to the ink.

func (*ColorFilteredInk) Paint added in v0.43.0

func (c *ColorFilteredInk) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint implements Ink.

type ColorProvider added in v0.2.0

type ColorProvider interface {
	GetColor() Color
	Ink
}

ColorProvider allows for different types of objects that hold a color to be used interchangeably.

type ColumnInfo added in v0.50.0

type ColumnInfo struct {
	ID          int
	Current     float32
	Minimum     float32
	Maximum     float32
	AutoMinimum float32
	AutoMaximum float32
}

ColumnInfo holds column information.

type CompoundBorder

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

CompoundBorder provides stacking of borders together.

func NewCompoundBorder

func NewCompoundBorder(borders ...Border) *CompoundBorder

NewCompoundBorder creates a border that contains other borders. The first one will be drawn in the outermost position, with each successive one moving further into the interior.

func (*CompoundBorder) Draw

func (b *CompoundBorder) Draw(canvas *Canvas, rect Rect)

Draw the border into rect.

func (*CompoundBorder) Insets

func (b *CompoundBorder) Insets() Insets

Insets returns the insets describing the space the border occupies on each side.

type Contour added in v0.60.0

type Contour = poly.Contour[float32]

Contour is an alias for poly.Contour[float32], for convenience.

type CubicResampler

type CubicResampler struct {
	B float32
	C float32
}

CubicResampler holds the parameters for cubic resampling.

func CatmullRomResampler

func CatmullRomResampler() CubicResampler

CatmullRomResampler is the standard "Catmull-Rom" filter.

func MitchellResampler

func MitchellResampler() CubicResampler

MitchellResampler is the standard "Mitchell" filter.

type Cursor

type Cursor = glfw.Cursor

Cursor provides a graphical cursor for the mouse location.

func ArrowCursor

func ArrowCursor() *Cursor

ArrowCursor returns the standard arrow cursor.

func MoveCursor added in v0.5.0

func MoveCursor() *Cursor

MoveCursor returns the standard move cursor.

func NewCursor

func NewCursor(img *Image, hotSpot Point) *Cursor

NewCursor creates a new custom cursor from an image.

func PointingCursor added in v0.44.0

func PointingCursor() *Cursor

PointingCursor returns the standard pointing cursor.

func ResizeHorizontalCursor added in v0.5.0

func ResizeHorizontalCursor() *Cursor

ResizeHorizontalCursor returns the standard horizontal resize cursor.

func ResizeLeftDiagonalCursor added in v0.5.0

func ResizeLeftDiagonalCursor() *Cursor

ResizeLeftDiagonalCursor returns the standard left diagonal resize cursor.

func ResizeRightDiagonalCursor added in v0.5.0

func ResizeRightDiagonalCursor() *Cursor

ResizeRightDiagonalCursor returns the standard right diagonal resize cursor.

func ResizeVerticalCursor added in v0.5.0

func ResizeVerticalCursor() *Cursor

ResizeVerticalCursor returns the standard vertical resize cursor.

func TextCursor

func TextCursor() *Cursor

TextCursor returns the standard text cursor.

type DefaultCellFactory

type DefaultCellFactory struct {
	Height float32
}

DefaultCellFactory provides a simple implementation of a CellFactory that uses Labels for its cells.

func (*DefaultCellFactory) CellHeight

func (f *DefaultCellFactory) CellHeight() float32

CellHeight implements CellFactory.

func (*DefaultCellFactory) CreateCell

func (f *DefaultCellFactory) CreateCell(_ Paneler, element any, _ int, foreground, _ Ink, _, _ bool) Paneler

CreateCell implements CellFactory.

type DefaultTableColumnHeader added in v0.3.0

type DefaultTableColumnHeader[T TableRowConstraint[T]] struct {
	*Label
	// contains filtered or unexported fields
}

DefaultTableColumnHeader provides a default table column header panel.

func NewTableColumnHeader added in v0.3.0

func NewTableColumnHeader[T TableRowConstraint[T]](title, tooltip string, less func(a, b string) bool) *DefaultTableColumnHeader[T]

NewTableColumnHeader creates a new table column header panel. May pass nil for 'less' to use the table header's Less.

func (*DefaultTableColumnHeader[T]) DefaultDraw added in v0.7.0

func (h *DefaultTableColumnHeader[T]) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*DefaultTableColumnHeader[T]) DefaultMouseUp added in v0.3.0

func (h *DefaultTableColumnHeader[T]) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*DefaultTableColumnHeader[T]) DefaultSizes added in v0.7.0

func (h *DefaultTableColumnHeader[T]) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*DefaultTableColumnHeader[T]) Less added in v0.76.0

func (h *DefaultTableColumnHeader[T]) Less() func(a, b string) bool

Less returns the less function to use for this column, or nil if the table header's Less should be used.

func (*DefaultTableColumnHeader[T]) SetSortState added in v0.3.0

func (h *DefaultTableColumnHeader[T]) SetSortState(state SortState)

SetSortState sets the SortState.

func (*DefaultTableColumnHeader[T]) SortState added in v0.3.0

func (h *DefaultTableColumnHeader[T]) SortState() SortState

SortState returns the current SortState.

type DerivedThemeColor added in v0.69.0

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

DerivedThemeColor holds a ThemeColor that is derived from another ThemeColor.

func (*DerivedThemeColor) Derive added in v0.69.0

func (t *DerivedThemeColor) Derive(deriver func(ThemeColor) ThemeColor) *DerivedThemeColor

Derive returns a new DerivedThemeColor that is derived from this DerivedThemeColor.

func (*DerivedThemeColor) DeriveLightness added in v0.69.0

func (t *DerivedThemeColor) DeriveLightness(light, dark float32) *DerivedThemeColor

DeriveLightness returns a new DerivedThemeColor that has its lightness adjusted by the given amount.

func (*DerivedThemeColor) DeriveOn added in v0.69.0

func (t *DerivedThemeColor) DeriveOn() *DerivedThemeColor

DeriveOn returns a new DerivedThemeColor that is the On color for this DerivedThemeColor.

func (*DerivedThemeColor) GetColor added in v0.69.0

func (t *DerivedThemeColor) GetColor() Color

GetColor returns the current color. Here to satisfy the ColorProvider interface.

func (*DerivedThemeColor) Paint added in v0.69.0

func (t *DerivedThemeColor) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this ThemeColor. Here to satisfy the Ink interface.

type Dialog

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

Dialog holds information about a dialog.

func NewDialog

func NewDialog(icon Drawable, iconInk Ink, msgPanel Paneler, buttonInfo []*DialogButtonInfo, windowOptions ...WindowOption) (*Dialog, error)

NewDialog creates a new standard dialog. To show the dialog you must call .RunModal() on the returned dialog. 'windowOptions' are additional options to be passed to the Window constructor for the dialog. The dialog will be always have te FloatingWindowOption() set.

func (*Dialog) Button

func (d *Dialog) Button(responseCode int) *Button

Button returns the button mapped to the given response code.

func (*Dialog) RunModal

func (d *Dialog) RunModal() int

RunModal displays and brings this dialog to the front, the runs a modal event loop until StopModal is called. Disposes the dialog before it returns.

func (*Dialog) StopModal

func (d *Dialog) StopModal(code int)

StopModal stops the current modal event loop and propagates the provided code as the result to RunModal().

func (*Dialog) Window

func (d *Dialog) Window() *Window

Window returns the underlying window.

type DialogButtonInfo

type DialogButtonInfo struct {
	Title        string
	KeyCodes     []KeyCode
	ResponseCode int
}

DialogButtonInfo holds information for constructing the dialog button panel.

func NewCancelButtonInfo

func NewCancelButtonInfo() *DialogButtonInfo

NewCancelButtonInfo creates a standard cancel button.

func NewNoButtonInfo added in v0.16.0

func NewNoButtonInfo() *DialogButtonInfo

NewNoButtonInfo creates a standard No button.

func NewOKButtonInfo

func NewOKButtonInfo() *DialogButtonInfo

NewOKButtonInfo creates a standard OK button.

func NewOKButtonInfoWithTitle

func NewOKButtonInfoWithTitle(title string) *DialogButtonInfo

NewOKButtonInfoWithTitle creates a standard OK button with a specific title.

func NewYesButtonInfo added in v0.16.0

func NewYesButtonInfo() *DialogButtonInfo

NewYesButtonInfo creates a standard Yes button.

func (*DialogButtonInfo) NewButton

func (bi *DialogButtonInfo) NewButton(d *Dialog) *Button

NewButton creates a new button for the dialog.

type DialogTheme added in v0.5.0

type DialogTheme struct {
	ErrorIcon       Drawable
	ErrorIconInk    Ink
	WarningIcon     Drawable
	WarningIconInk  Ink
	QuestionIcon    Drawable
	QuestionIconInk Ink
}

DialogTheme holds theming data for a Dialog.

type Display

type Display struct {
	Name        string  // The name of the display
	Frame       Rect    // The position of the display in the global screen coordinate system
	Usable      Rect    // The usable area, i.e. the Frame minus the area used by global menu bars or task bars
	ScaleX      float32 // The horizontal scale of content
	ScaleY      float32 // The vertical scale of content
	RefreshRate int     // The refresh rate, in Hz
	WidthMM     int     // The display's physical width, in millimeters
	HeightMM    int     // The display's physical height, in millimeters
}

Display holds information about each available active display.

func AllDisplays

func AllDisplays() []*Display

AllDisplays returns all displays.

func BestDisplayForRect added in v0.35.0

func BestDisplayForRect(r Rect) *Display

BestDisplayForRect returns the display with the greatest overlap with the rectangle, or the primary display if there is no overlap.

func PrimaryDisplay

func PrimaryDisplay() *Display

PrimaryDisplay returns the primary display.

func (*Display) FitRectOnto added in v0.35.0

func (d *Display) FitRectOnto(r Rect) Rect

FitRectOnto returns a rectangle that fits onto this display, trying to preserve its position and size as much as possible.

func (*Display) PPI added in v0.5.0

func (d *Display) PPI() int

PPI returns the pixels-per-inch for the display. Some operating systems do not provide accurate information, either because the monitor's EDID data is incorrect, or because the driver does not report it accurately.

type Dock added in v0.3.0

type Dock struct {
	MaximizedContainer *DockContainer

	DragKey string
	DockTheme
	Panel
	// contains filtered or unexported fields
}

Dock provides an area where Dockable panels can be displayed and rearranged.

func NewDock added in v0.3.0

func NewDock() *Dock

NewDock creates a new, empty, dock.

func (*Dock) DefaultDataDragExit added in v0.3.0

func (d *Dock) DefaultDataDragExit()

DefaultDataDragExit provides the default data drag exit handling.

func (*Dock) DefaultDataDragOver added in v0.3.0

func (d *Dock) DefaultDataDragOver(where Point, data map[string]any) bool

DefaultDataDragOver provides the default data drag over handling.

func (*Dock) DefaultDataDrop added in v0.3.0

func (d *Dock) DefaultDataDrop(where Point, data map[string]any)

DefaultDataDrop provides the default data drop handling.

func (*Dock) DefaultDraw added in v0.3.0

func (d *Dock) DefaultDraw(gc *Canvas, _ Rect)

DefaultDraw fills in the background.

func (*Dock) DefaultDrawOver added in v0.3.0

func (d *Dock) DefaultDrawOver(gc *Canvas, dirty Rect)

DefaultDrawOver draws the dividers and any drag markers.

func (*Dock) DefaultFocusChangeInHierarchy added in v0.3.0

func (d *Dock) DefaultFocusChangeInHierarchy(_, _ *Panel)

DefaultFocusChangeInHierarchy marks the dock for redraw whenever the focus changes within it so that the tabs get the correct highlight state.

func (*Dock) DefaultMouseDown added in v0.3.0

func (d *Dock) DefaultMouseDown(where Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*Dock) DefaultMouseDrag added in v0.3.0

func (d *Dock) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*Dock) DefaultMouseUp added in v0.3.0

func (d *Dock) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*Dock) DefaultUpdateCursor added in v0.3.0

func (d *Dock) DefaultUpdateCursor(where Point) *Cursor

DefaultUpdateCursor adjusts the cursor for any dividers it may be over.

func (*Dock) DockTo added in v0.3.0

func (d *Dock) DockTo(dockable Dockable, target DockLayoutNode, s side.Enum)

DockTo a Dockable within this Dock. If the Dockable already exists in this Dock, it will be moved to the new location. nil may be passed in for the target, in which case the top-most layout is used.

func (*Dock) Maximize added in v0.3.0

func (d *Dock) Maximize(dc *DockContainer)

Maximize the current Dockable.

func (*Dock) NextDockableFor added in v0.5.0

func (d *Dock) NextDockableFor(dockable Dockable) Dockable

NextDockableFor returns the logical next Dockable in the Dock given the one passed in as a starting point. The returned value may be the same as the starting point if there are no other Dockables. Passing in nil will result in the first Dockable found being returned.

func (*Dock) PreviousDockableFor added in v0.5.0

func (d *Dock) PreviousDockableFor(dockable Dockable) Dockable

PreviousDockableFor returns the logical previous Dockable in the Dock given the one passed in as a starting point. The returned value may be the same as the starting point if there are no other Dockables. Passing in nil will result in the last Dockable found being returned.

func (*Dock) Restore added in v0.3.0

func (d *Dock) Restore()

Restore the current Dockable to its non-maximized state.

func (*Dock) RootDockLayout added in v0.4.0

func (d *Dock) RootDockLayout() *DockLayout

RootDockLayout returns the root DockLayout.

type DockContainer added in v0.3.0

type DockContainer struct {
	Dock *Dock

	Panel
	// contains filtered or unexported fields
}

DockContainer holds one or more Dockable panels.

func NewDockContainer added in v0.3.0

func NewDockContainer(dock *Dock, dockable Dockable) *DockContainer

NewDockContainer creates a new DockContainer.

func (*DockContainer) AcquireFocus added in v0.3.0

func (d *DockContainer) AcquireFocus()

AcquireFocus will set the focus within the current Dockable of this DockContainer. If the focus is already within it, nothing is changed.

func (*DockContainer) AttemptClose added in v0.3.0

func (d *DockContainer) AttemptClose(dockable Dockable) bool

AttemptClose attempts to close a Dockable within this DockContainer. This only has an affect if the Dockable is contained by this DockContainer and implements the TabCloser interface. Note that the TabCloser must call this DockContainer's Close(Dockable) method to actually close the tab. Returns true if dockable is closed.

func (*DockContainer) AttemptCloseAll added in v0.69.0

func (d *DockContainer) AttemptCloseAll() bool

AttemptCloseAll attempts to close all Dockables within this DockContainer. Returns true if all Dockables are closed.

func (*DockContainer) AttemptCloseAllExcept added in v0.69.0

func (d *DockContainer) AttemptCloseAllExcept(dockable Dockable) bool

AttemptCloseAllExcept attempts to close all Dockables within this DockContainer except for the specified Dockable. Returns true if all Dockables except for the specified Dockable are closed.

func (*DockContainer) Close added in v0.3.0

func (d *DockContainer) Close(dockable Dockable)

Close the specified Dockable. If the last Dockable within this DockContainer is closed, then this DockContainer is also removed from the Dock.

func (*DockContainer) CurrentDockable added in v0.3.0

func (d *DockContainer) CurrentDockable() Dockable

CurrentDockable returns the frontmost Dockable within this DockContainer. May return nil.

func (*DockContainer) CurrentDockableIndex added in v0.3.0

func (d *DockContainer) CurrentDockableIndex() int

CurrentDockableIndex returns the index of the frontmost Dockable within this DockContainer, or -1 if there are no Dockables.

func (*DockContainer) Dockables added in v0.3.0

func (d *DockContainer) Dockables() []Dockable

Dockables returns the list of Dockables within this DockContainer, in tab order.

func (*DockContainer) LayoutSizes added in v0.3.0

func (d *DockContainer) LayoutSizes(target *Panel, hint Size) (minSize, prefSize, maxSize Size)

LayoutSizes implements Layout.

func (*DockContainer) PerformLayout added in v0.3.0

func (d *DockContainer) PerformLayout(_ *Panel)

PerformLayout implements Layout.

func (*DockContainer) PreferredSize added in v0.3.0

func (d *DockContainer) PreferredSize() Size

PreferredSize implements DockLayoutNode.

func (*DockContainer) SetCurrentDockable added in v0.3.0

func (d *DockContainer) SetCurrentDockable(dockable Dockable)

SetCurrentDockable makes the provided dockable the current one.

func (*DockContainer) Stack added in v0.3.0

func (d *DockContainer) Stack(dockable Dockable, index int)

Stack adds the Dockable to this DockContainer at the specified index. An out-of-bounds index will cause the Dockable to be added at the end.

func (*DockContainer) UpdateTitle added in v0.3.0

func (d *DockContainer) UpdateTitle(dockable Dockable)

UpdateTitle will cause the dock tab for the given Dockable to update itself.

type DockHeaderTheme added in v0.4.0

type DockHeaderTheme struct {
	BackgroundInk   Ink
	DropAreaInk     Ink
	HeaderBorder    Border
	MinimumTabWidth float32
	TabGap          float32
	TabInsertSize   float32
}

DockHeaderTheme holds theming data for a DockHeader.

type DockLayout added in v0.3.0

type DockLayout struct {
	Horizontal bool
	// contains filtered or unexported fields
}

DockLayout provides layout of DockContainers and other DockLayouts within a Dock.

func (*DockLayout) Contains added in v0.3.0

func (d *DockLayout) Contains(node DockLayoutNode) bool

Contains returns true if the node is this DockLayout or one of its descendants.

func (*DockLayout) DividerMaximum added in v0.3.0

func (d *DockLayout) DividerMaximum() float32

DividerMaximum returns the maximum value the divider can be set to. Will always return 0 if Full() returns false.

func (*DockLayout) DividerPosition added in v0.3.0

func (d *DockLayout) DividerPosition() float32

DividerPosition returns the current divider position.

func (*DockLayout) DockTo added in v0.3.0

func (d *DockLayout) DockTo(dc *DockContainer, target DockLayoutNode, s side.Enum)

DockTo docks a DockContainer within this DockLayout. If the DockContainer already exists in this DockLayout, it will be moved to the new location.

func (*DockLayout) Empty added in v0.3.0

func (d *DockLayout) Empty() bool

Empty returns true if this DockLayout has no children.

func (*DockLayout) FindLayout added in v0.3.0

func (d *DockLayout) FindLayout(dc *DockContainer) *DockLayout

FindLayout returns the DockLayout that contains the specified DockContainer, or nil if it is not present. Note that this method will always start at the root and work its way down, even if called on a sub-node.

func (*DockLayout) ForEachDockContainer added in v0.4.0

func (d *DockLayout) ForEachDockContainer(f func(*DockContainer) bool)

ForEachDockContainer iterates through all DockContainers in this DockLayout's hierarchy and calls the given function with them. The function should return true to stop further processing.

func (*DockLayout) FrameRect added in v0.3.0

func (d *DockLayout) FrameRect() Rect

FrameRect implements DockLayoutNode.

func (*DockLayout) Full added in v0.3.0

func (d *DockLayout) Full() bool

Full returns true if both child nodes of this DockLayout are occupied.

func (*DockLayout) LayoutSizes added in v0.3.0

func (d *DockLayout) LayoutSizes(_ *Panel, _ Size) (minSize, prefSize, maxSize Size)

LayoutSizes implements Layout.

func (*DockLayout) PerformLayout added in v0.3.0

func (d *DockLayout) PerformLayout(_ *Panel)

PerformLayout implements Layout.

func (*DockLayout) PreferredSize added in v0.3.0

func (d *DockLayout) PreferredSize() Size

PreferredSize implements DockLayoutNode.

func (*DockLayout) RawDividerPosition added in v0.3.0

func (d *DockLayout) RawDividerPosition() float32

RawDividerPosition returns the divider position, unadjusted for the current content.

func (*DockLayout) Remove added in v0.3.0

func (d *DockLayout) Remove(node DockLayoutNode) bool

Remove a node. Returns true if the node was found and removed.

func (*DockLayout) RootLayout added in v0.3.0

func (d *DockLayout) RootLayout() *DockLayout

RootLayout returns the topmost parent DockLayout.

func (*DockLayout) SetDividerPosition added in v0.3.0

func (d *DockLayout) SetDividerPosition(pos float32)

SetDividerPosition sets the new divider position. Use a value less than 0 to reset the divider to its default mode, which splits the available space evenly between the children.

func (*DockLayout) SetFrameRect added in v0.3.0

func (d *DockLayout) SetFrameRect(r Rect)

SetFrameRect implements DockLayoutNode.

type DockLayoutNode added in v0.3.0

type DockLayoutNode interface {
	PreferredSize() Size
	FrameRect() Rect
	SetFrameRect(r Rect)
}

DockLayoutNode defines the methods for nodes within a DockLayout.

type DockState added in v0.62.0

type DockState struct {
	Type         string       `json:"type"`                    // One of LayoutType, ContainerType or DockableType
	Key          string       `json:"key,omitempty"`           // Only valid when Type == DockableType
	Children     []*DockState `json:"children,omitempty"`      // Only valid when Type != DockableType
	CurrentIndex int          `json:"current_index,omitempty"` // Only valid when Type == ContainerType
	Divider      float32      `json:"divider,omitempty"`       // Only valid when Type == LayoutType
	Horizontal   bool         `json:"horizontal,omitempty"`    // Only valid when Type == LayoutType
}

DockState holds a snapshot of the arrangement of Dockables within a Dock.

func NewDockState added in v0.62.0

func NewDockState(dock *Dock, keyFromDockable func(Dockable) string) *DockState

NewDockState creates a new DockState for the given Dock. keyFromDockable will be passed each Dockable within the Dock and is expected to return a unique string that will be used to locate the Dockable when the Apply() method is called.

func (*DockState) Apply added in v0.62.0

func (d *DockState) Apply(dock *Dock, keyToDockable func(string) Dockable)

Apply the saved DockState to the specified Dock. keyToDockable is called for each Dockable that was in the Dock when the state was captured, passing in the unique key that was used when keyFromDockable in NewDockState() was called.

type DockTabTheme added in v0.4.0

type DockTabTheme struct {
	BackgroundInk   Ink
	OnBackgroundInk Ink
	EdgeInk         Ink
	TabFocusedInk   Ink
	OnTabFocusedInk Ink
	TabCurrentInk   Ink
	OnTabCurrentInk Ink
	TabBorder       Border
	LabelTheme      LabelTheme
	ButtonTheme     ButtonTheme
	Gap             float32
}

DockTabTheme holds theming data for a DockTab.

type DockTheme added in v0.4.0

type DockTheme struct {
	BackgroundInk Ink
	GripInk       Ink
	DropAreaInk   Ink
	GripCount     int
	GripGap       float32
	GripWidth     float32
	GripHeight    float32
	GripMargin    float32
}

DockTheme holds theming data for a Dock.

func (*DockTheme) DockDividerSize added in v0.36.0

func (d *DockTheme) DockDividerSize() float32

DockDividerSize returns the size (running across the divider) of a divider.

func (*DockTheme) DockGripLength added in v0.36.0

func (d *DockTheme) DockGripLength() float32

DockGripLength returns the length (running along the divider) of a divider's grip area.

func (*DockTheme) DrawHorizontalGripper added in v0.36.0

func (d *DockTheme) DrawHorizontalGripper(canvas *Canvas, r Rect)

DrawHorizontalGripper draws the horizontal divider gripper.

func (*DockTheme) DrawVerticalGripper added in v0.36.0

func (d *DockTheme) DrawVerticalGripper(canvas *Canvas, r Rect)

DrawVerticalGripper draws the vertical divider gripper.

type Dockable added in v0.3.0

type Dockable interface {
	Paneler
	// TitleIcon returns an Drawable representing this Dockable.
	TitleIcon(suggestedSize Size) Drawable
	// Title returns the title of this Dockable.
	Title() string
	// Tooltip returns the tooltip of this Dockable.
	Tooltip() string
	// Modified returns true if the dockable has been modified.
	Modified() bool
}

Dockable represents a dockable Panel.

func DockableFromDragData added in v0.3.0

func DockableFromDragData(key string, data map[string]any) Dockable

DockableFromDragData attempts to extract a Dockable from the given key in the data.

type DragData added in v0.3.0

type DragData struct {
	Data            map[string]any
	Drawable        Drawable
	SamplingOptions *SamplingOptions
	Ink             Ink
	Offset          Point
}

DragData holds data drag information.

type Drawable added in v0.3.0

type Drawable interface {
	// LogicalSize returns the logical size of this object.
	LogicalSize() Size

	// DrawInRect draws this object in the given rectangle.
	DrawInRect(canvas *Canvas, rect Rect, sampling *SamplingOptions, paint *Paint)
}

Drawable represents a drawable object.

func NewTableDragDrawable added in v0.20.0

func NewTableDragDrawable[T TableRowConstraint[T]](data *TableDragData[T], svg *SVG, singularName, pluralName string) Drawable

NewTableDragDrawable creates a new drawable for a table row drag.

type DrawableSVG added in v0.3.0

type DrawableSVG struct {
	SVG  *SVG
	Size Size
}

DrawableSVG makes an SVG conform to the Drawable interface.

func (*DrawableSVG) DrawInRect added in v0.3.0

func (s *DrawableSVG) DrawInRect(canvas *Canvas, rect Rect, opts *SamplingOptions, paint *Paint)

DrawInRect implements the Drawable interface.

If paint is not nil, the SVG paths will be drawn with the provided paint, ignoring any fill or stroke attributes within the source SVG. Be sure to set the Paint's style (fill or stroke) as desired.

func (*DrawableSVG) LogicalSize added in v0.3.0

func (s *DrawableSVG) LogicalSize() Size

LogicalSize implements the Drawable interface.

type DynamicColor

type DynamicColor struct {
	Rebuilder func() Color
	Color     Color
}

DynamicColor holds a color that may be changed.

func NewDynamicColor

func NewDynamicColor(rebuilder func() Color) *DynamicColor

NewDynamicColor creates a new DynamicColor and registers it for theme updates. If your color relies on another dynamic color to calculate its value, make sure it is created *after* the colors it relies on, since all dynamic colors are rebuilt in the order they were created.

func (*DynamicColor) GetColor added in v0.2.0

func (c *DynamicColor) GetColor() Color

GetColor returns the current color. Here to satisfy the ColorProvider interface.

func (*DynamicColor) Paint

func (c *DynamicColor) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this DynamicColor. Here to satisfy the Ink interface.

func (*DynamicColor) Unregister

func (c *DynamicColor) Unregister()

Unregister removes this DynamicColor from participating in rebuilds via RebuildDynamicColors.

type DynamicFont

type DynamicFont struct {
	Resolver func() FontDescriptor
	// contains filtered or unexported fields
}

DynamicFont holds a Font that can be dynamically adjusted.

func (*DynamicFont) Baseline added in v0.4.0

func (f *DynamicFont) Baseline() float32

Baseline implements Font.

func (*DynamicFont) Descriptor added in v0.4.0

func (f *DynamicFont) Descriptor() FontDescriptor

Descriptor implements Font.

func (*DynamicFont) Face added in v0.4.0

func (f *DynamicFont) Face() *FontFace

Face implements Font.

func (*DynamicFont) GlyphWidth added in v0.7.0

func (f *DynamicFont) GlyphWidth(glyph uint16) float32

GlyphWidth implements Font.

func (*DynamicFont) GlyphWidths added in v0.7.0

func (f *DynamicFont) GlyphWidths(glyphs []uint16) []float32

GlyphWidths implements Font.

func (*DynamicFont) LineHeight added in v0.4.0

func (f *DynamicFont) LineHeight() float32

LineHeight implements Font.

func (*DynamicFont) Metrics added in v0.4.0

func (f *DynamicFont) Metrics() FontMetrics

Metrics implements Font.

func (*DynamicFont) RuneToGlyph added in v0.7.0

func (f *DynamicFont) RuneToGlyph(r rune) uint16

RuneToGlyph implements Font.

func (*DynamicFont) RunesToGlyphs added in v0.7.0

func (f *DynamicFont) RunesToGlyphs(r []rune) []uint16

RunesToGlyphs implements Font.

func (*DynamicFont) SimpleWidth added in v0.7.0

func (f *DynamicFont) SimpleWidth(str string) float32

SimpleWidth implements Font.

func (*DynamicFont) Size added in v0.4.0

func (f *DynamicFont) Size() float32

Size implements Font.

func (*DynamicFont) TextBlobPosH added in v0.52.0

func (f *DynamicFont) TextBlobPosH(glyphs []uint16, positions []float32, y float32) *TextBlob

TextBlobPosH implements Font.

type EmptyBorder

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

EmptyBorder provides and empty border with the specified insets.

func NewEmptyBorder

func NewEmptyBorder(insets Insets) *EmptyBorder

NewEmptyBorder creates a new empty border with the specified insets.

func (*EmptyBorder) Draw

func (b *EmptyBorder) Draw(_ *Canvas, _ Rect)

Draw the border into rect.

func (*EmptyBorder) Insets

func (b *EmptyBorder) Insets() Insets

Insets returns the insets describing the space the border occupies on each side.

type Field

type Field struct {
	ModifiedCallback func(before, after *FieldState)
	ValidateCallback func() bool

	Watermark string

	FieldTheme
	Panel

	ObscurementRune    rune
	AutoScroll         bool
	NoSelectAllOnFocus bool
	// contains filtered or unexported fields
}

Field provides a text input control.

func NewField

func NewField() *Field

NewField creates a new, empty, field.

func NewMultiLineField added in v0.12.0

func NewMultiLineField() *Field

NewMultiLineField creates a new, empty, multi-line, field.

func (*Field) AllowsMultipleLines added in v0.12.0

func (f *Field) AllowsMultipleLines() bool

AllowsMultipleLines returns true if this field allows embedded line feeds.

func (*Field) ApplyFieldState added in v0.49.0

func (f *Field) ApplyFieldState(state *FieldState)

ApplyFieldState sets the underlying field state to match the input and without triggering calls to the modification callback.

func (*Field) CanCopy

func (f *Field) CanCopy() bool

CanCopy returns true if the field has a selection that can be copied.

func (*Field) CanCut

func (f *Field) CanCut() bool

CanCut returns true if the field has a selection that can be cut.

func (*Field) CanDelete

func (f *Field) CanDelete() bool

CanDelete returns true if the field has a selection that can be deleted.

func (*Field) CanPaste

func (f *Field) CanPaste() bool

CanPaste returns true if the clipboard has content that can be pasted into the field.

func (*Field) CanSelectAll

func (f *Field) CanSelectAll() bool

CanSelectAll returns true if the field's selection can be expanded.

func (*Field) Copy

func (f *Field) Copy()

Copy the selected text to the clipboard.

func (*Field) CurrentUndoID added in v0.49.0

func (f *Field) CurrentUndoID() int64

CurrentUndoID returns the undo ID to use.

func (*Field) Cut

func (f *Field) Cut()

Cut the selected text to the clipboard.

func (*Field) DefaultDraw

func (f *Field) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Field) DefaultFocusGained

func (f *Field) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*Field) DefaultFocusLost

func (f *Field) DefaultFocusLost()

DefaultFocusLost provides the default focus lost handling.

func (*Field) DefaultKeyDown

func (f *Field) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*Field) DefaultMouseDown

func (f *Field) DefaultMouseDown(where Point, button, clickCount int, mod Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*Field) DefaultMouseDrag

func (f *Field) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*Field) DefaultRuneTyped

func (f *Field) DefaultRuneTyped(ch rune) bool

DefaultRuneTyped provides the default rune typed handling.

func (*Field) DefaultSizes

func (f *Field) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Field) DefaultUpdateCursor

func (f *Field) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor update handling.

func (*Field) Delete

func (f *Field) Delete()

Delete removes the currently selected text, if any.

func (*Field) FromSelectionIndex

func (f *Field) FromSelectionIndex(index int) Point

FromSelectionIndex returns a location in local coordinates for the specified rune index.

func (*Field) GetFieldState added in v0.49.0

func (f *Field) GetFieldState() *FieldState

GetFieldState returns the current field state, usually used for undo.

func (*Field) HasSelectionRange

func (f *Field) HasSelectionRange() bool

HasSelectionRange returns true is a selection range is currently present.

func (*Field) Invalid

func (f *Field) Invalid() bool

Invalid returns true if the field is currently marked as invalid.

func (*Field) Paste

func (f *Field) Paste()

Paste any text on the clipboard into the field.

func (*Field) RunesIfPasted added in v0.9.0

func (f *Field) RunesIfPasted(input []rune) []rune

RunesIfPasted returns the resulting runes if the given input was pasted into the field.

func (*Field) ScrollOffset

func (f *Field) ScrollOffset() Point

ScrollOffset returns the current autoscroll offset.

func (*Field) ScrollSelectionIntoView added in v0.47.3

func (f *Field) ScrollSelectionIntoView()

ScrollSelectionIntoView scrolls the selection into view.

func (*Field) SelectAll

func (f *Field) SelectAll()

SelectAll selects all of the text in the field.

func (*Field) SelectedText

func (f *Field) SelectedText() string

SelectedText returns the currently selected text.

func (*Field) Selection

func (f *Field) Selection() (start, end int)

Selection returns the current start and end selection indexes.

func (*Field) SelectionCount

func (f *Field) SelectionCount() int

SelectionCount returns the number of characters currently selected.

func (*Field) SetMinimumTextWidthUsing added in v0.17.0

func (f *Field) SetMinimumTextWidthUsing(candidates ...string)

SetMinimumTextWidthUsing sets the MinimumTextWidth by measuring the provided candidates and using the widest.

func (*Field) SetScrollOffset

func (f *Field) SetScrollOffset(offset Point)

SetScrollOffset sets the autoscroll offset to the specified value.

func (*Field) SetSelection

func (f *Field) SetSelection(start, end int)

SetSelection sets the start and end range of the selection. Values beyond either end will be constrained to the appropriate end. Likewise, an end value less than the start value will be treated as if the start and end values were the same.

func (*Field) SetSelectionTo

func (f *Field) SetSelectionTo(pos int)

SetSelectionTo moves the cursor to the specified index and removes any range that may have been present.

func (*Field) SetSelectionToEnd

func (f *Field) SetSelectionToEnd()

SetSelectionToEnd moves the cursor to the end of the text and removes any range that may have been present.

func (*Field) SetSelectionToStart

func (f *Field) SetSelectionToStart()

SetSelectionToStart moves the cursor to the beginning of the text and removes any range that may have been present.

func (*Field) SetText

func (f *Field) SetText(text string)

SetText sets the content of the field.

func (*Field) SetWrap added in v0.12.0

func (f *Field) SetWrap(wrap bool)

SetWrap sets the wrapping attribute.

func (*Field) Text

func (f *Field) Text() string

Text returns the content of the field.

func (*Field) ToSelectionIndex

func (f *Field) ToSelectionIndex(where Point) int

ToSelectionIndex returns the rune index for the coordinates.

func (*Field) Validate

func (f *Field) Validate()

Validate forces field content validation to be run.

func (*Field) Wrap added in v0.12.0

func (f *Field) Wrap() bool

Wrap returns true if this field wraps lines that don't fit the width of the component.

type FieldState added in v0.49.0

type FieldState struct {
	Text            string
	SelectionStart  int
	SelectionEnd    int
	SelectionAnchor int
}

FieldState holds the text and selection data for the field.

type FieldTheme added in v0.4.0

type FieldTheme struct {
	InitialClickSelectsAll func(*Field) bool
	Font                   Font
	BackgroundInk          Ink
	OnBackgroundInk        Ink
	EditableInk            Ink
	OnEditableInk          Ink
	SelectionInk           Ink
	OnSelectionInk         Ink
	ErrorInk               Ink
	OnErrorInk             Ink
	BlinkRate              time.Duration
	MinimumTextWidth       float32
	HAlign                 align.Enum
}

FieldTheme holds theming data for a Field.

type FileDialog added in v0.59.0

type FileDialog interface {
	// InitialDirectory returns a path pointing to the directory the dialog will open up in.
	InitialDirectory() string
	// SetInitialDirectory sets the directory the dialog will open up in.
	SetInitialDirectory(dir string)
	// AllowedExtensions returns the set of permitted file extensions. nil will be returned if all files are allowed.
	AllowedExtensions() []string
	// SetAllowedExtensions sets the permitted file extensions that may be selected. Just the extension is needed, e.g.
	// "txt", not ".txt" or "*.txt", etc. Pass in nil to allow all files.
	SetAllowedExtensions(extensions ...string)
	// RunModal displays the dialog, allowing the user to make a selection. Returns true if successful or false if
	// canceled.
	RunModal() bool
	// Path returns the path that was chosen.
	Path() string
}

FileDialog represents the common API for open and save dialogs.

type FileStream added in v0.29.0

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

FileStream provides a way to write data to a file. This exists for PDF output, but can be used for other things.

func NewFileStream added in v0.29.0

func NewFileStream(filePath string) (*FileStream, error)

NewFileStream creates a new stream that writes to a file.

func (*FileStream) BytesWritten added in v0.29.0

func (s *FileStream) BytesWritten() int

BytesWritten returns the number of bytes written so far.

func (*FileStream) Close added in v0.29.0

func (s *FileStream) Close()

Close the stream. Further writes should not be done. Note that the underlying skia code does not return any errors from this operation, yet there is the potential for that to occur, since any buffered but not written bytes may not be able to be written. If this is a concern, use a MemoryStream instead and use Go code to write the result.

func (*FileStream) Flush added in v0.29.0

func (s *FileStream) Flush()

Flush the stream to disk. Note that the underlying skia code does not return any errors from this operation, yet there is the potential for that to occur, since any buffered but not written bytes may not be able to be written. If this is a concern, use a MemoryStream instead and use Go code to write the result.

func (*FileStream) Write added in v0.29.0

func (s *FileStream) Write(data []byte) (n int, err error)

type FlexLayout

type FlexLayout struct {
	Columns      int
	HSpacing     float32
	VSpacing     float32
	HAlign       align.Enum
	VAlign       align.Enum
	EqualColumns bool
	// contains filtered or unexported fields
}

FlexLayout lays out the children of its Layoutable based on the FlexLayoutData assigned to each child.

func (*FlexLayout) LayoutSizes

func (f *FlexLayout) LayoutSizes(target *Panel, hint Size) (minSize, prefSize, maxSize Size)

LayoutSizes implements the Layout interface.

func (*FlexLayout) PerformLayout

func (f *FlexLayout) PerformLayout(target *Panel)

PerformLayout implements the Layout interface.

type FlexLayoutData

type FlexLayoutData struct {
	SizeHint Size
	MinSize  Size
	HSpan    int
	VSpan    int
	HAlign   align.Enum
	VAlign   align.Enum
	HGrab    bool
	VGrab    bool
	// contains filtered or unexported fields
}

FlexLayoutData is used to control how an object is laid out by the FlexLayout layout.

type FlowLayout

type FlowLayout struct {
	HSpacing float32
	VSpacing float32
}

FlowLayout is a Layout that lays components out left to right, then top to bottom.

func (*FlowLayout) LayoutSizes

func (f *FlowLayout) LayoutSizes(target *Panel, hint Size) (minSize, prefSize, maxSize Size)

LayoutSizes implements Layout.

func (*FlowLayout) PerformLayout

func (f *FlowLayout) PerformLayout(target *Panel)

PerformLayout implements Layout.

type Font

type Font interface {
	// Face returns the FontFace this Font belongs to.
	Face() *FontFace
	// Size returns the size of the font. This is the value that was passed to FontFace.Font() when creating the font.
	Size() float32
	// Metrics returns a copy of the FontMetrics for this font.
	Metrics() FontMetrics
	// Baseline returns the number of logical pixels to the bottom of characters without descenders.
	Baseline() float32
	// LineHeight returns the recommended line height of the font.
	LineHeight() float32
	// RuneToGlyph converts a rune into a glyph. Missing glyphs will have a value of 0.
	RuneToGlyph(r rune) uint16
	// RunesToGlyphs converts the runes into glyphs. Missing glyphs will have a value of 0.
	RunesToGlyphs(r []rune) []uint16
	// GlyphWidth returns the width for the glyph. This does not do font fallback for missing glyphs.
	GlyphWidth(glyph uint16) float32
	// GlyphWidths returns the widths for each glyph. This does not do font fallback for missing glyphs.
	GlyphWidths(glyphs []uint16) []float32
	// SimpleWidth returns the width of a string. It does not do font fallback, nor does it consider tabs or line
	// endings.
	SimpleWidth(str string) float32
	// TextBlobPosH creates a text blob for glyphs, with specified horizontal positions. The glyphs and positions slices
	// should have the same length.
	TextBlobPosH(glyphs []uint16, positions []float32, y float32) *TextBlob
	// Descriptor returns a FontDescriptor for this Font.
	Descriptor() FontDescriptor
	// contains filtered or unexported methods
}

Font holds a realized FontFace of a specific size that can be used to render text.

type FontDescriptor

type FontDescriptor struct {
	FontFaceDescriptor
	Size float32 `json:"size"`
}

FontDescriptor holds information necessary to construct a Font. The Size field is the value that was passed to FontFace.Font() when creating the font.

func DeriveMarkdownCodeBlockFont added in v0.49.0

func DeriveMarkdownCodeBlockFont(font Font) FontDescriptor

DeriveMarkdownCodeBlockFont derives a FontDescriptor for code from another font. Pass in nil for the font to use MonospacedFont.

func DeriveMarkdownHeadingFont added in v0.44.0

func DeriveMarkdownHeadingFont(font Font, level int) FontDescriptor

DeriveMarkdownHeadingFont derives a FontDescriptor for a heading from another font. Pass in nil for the font to use DefaultMarkdownTheme.Font.

func (FontDescriptor) Font

func (fd FontDescriptor) Font() Font

Font returns the matching Font. If the specified font family cannot be found, the DefaultSystemFamilyName will be substituted.

func (FontDescriptor) MarshalText

func (fd FontDescriptor) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (FontDescriptor) String

func (fd FontDescriptor) String() string

String this returns a string suitable for display. It is not suitable for converting back into a FontDescriptor.

func (*FontDescriptor) UnmarshalText

func (fd *FontDescriptor) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type FontFace

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

FontFace holds the immutable portions of a font description.

func CreateFontFace

func CreateFontFace(data []byte) *FontFace

CreateFontFace creates a new FontFace from font data.

func MatchFontFace

func MatchFontFace(family string, weightValue weight.Enum, spacingValue spacing.Enum, slantValue slant.Enum) *FontFace

MatchFontFace attempts to locate the FontFace with the given family and style. Will return nil if nothing suitable can be found.

func (*FontFace) FallbackForCharacter added in v0.7.0

func (f *FontFace) FallbackForCharacter(ch rune) *FontFace

FallbackForCharacter attempts to locate the FontFace that best matches this FontFace and has the given character. Will return nil if nothing suitable can be found.

func (*FontFace) Family

func (f *FontFace) Family() string

Family returns the name of the FontFamily this FontFace belongs to.

func (*FontFace) Font

func (f *FontFace) Font(capHeightSizeInLogicalPixels float32) Font

Font returns a Font of the given size for this FontFace.

func (*FontFace) Less added in v0.7.0

func (f *FontFace) Less(other *FontFace) bool

Less returns true if this FontFace is logically before the other FontFace.

func (*FontFace) Monospaced

func (f *FontFace) Monospaced() bool

Monospaced returns true if this FontFace has been marked as having a fixed width for every character.

func (*FontFace) Style

func (f *FontFace) Style() (weightValue weight.Enum, spacingValue spacing.Enum, slantValue slant.Enum)

Style returns the style information for this FontFace.

func (*FontFace) UnitsPerEm

func (f *FontFace) UnitsPerEm() int

UnitsPerEm returns the number of coordinate units on the "em square", an abstract square whose height is the intended distance between lines of type in the same type size. This is the size of the design grid on which glyphs are laid out.

type FontFaceDescriptor added in v0.46.0

type FontFaceDescriptor struct {
	Family  string       `json:"family"`
	Weight  weight.Enum  `json:"weight"`
	Spacing spacing.Enum `json:"spacing"`
	Slant   slant.Enum   `json:"slant"`
}

FontFaceDescriptor holds information necessary to construct a FontFace.

func AllFontFaces added in v0.46.0

func AllFontFaces() (all, monospaced []FontFaceDescriptor)

AllFontFaces returns all known font faces as FontFaceDescriptors. This will be computed each time, so it may be worthwhile to cache the result if you don't expect the set of font faces to be changed between calls.

func RegisterFont

func RegisterFont(data []byte) (FontFaceDescriptor, error)

RegisterFont registers a font with the font manager.

func (FontFaceDescriptor) Face added in v0.46.0

func (ffd FontFaceDescriptor) Face() *FontFace

Face returns the matching FontFace, if any.

func (FontFaceDescriptor) MarshalText added in v0.46.0

func (ffd FontFaceDescriptor) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface.

func (FontFaceDescriptor) String added in v0.46.0

func (ffd FontFaceDescriptor) String() string

String this returns a string suitable for display. It is not suitable for converting back into a FontFaceDescriptor.

func (*FontFaceDescriptor) UnmarshalText added in v0.46.0

func (ffd *FontFaceDescriptor) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type FontFamily

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

FontFamily holds information about one font family.

func MatchFontFamily

func MatchFontFamily(family string) *FontFamily

MatchFontFamily returns a FontFamily for the specified family name. If no such family name exists, Count() will be 0.

func (*FontFamily) Count

func (f *FontFamily) Count() int

Count returns the number of Faces within this FontFamily.

func (*FontFamily) Face

func (f *FontFamily) Face(index int) *FontFace

Face returns the FontFace for the given index. Must be >= 0 and < Count().

func (*FontFamily) MatchStyle

func (f *FontFamily) MatchStyle(weightValue weight.Enum, spacingValue spacing.Enum, slantValue slant.Enum) *FontFace

MatchStyle attempts to locate the FontFace within the family with the given style. Will return nil if nothing suitable can be found.

func (*FontFamily) String

func (f *FontFamily) String() string

func (*FontFamily) Style

func (f *FontFamily) Style(index int) (description string, weightValue weight.Enum, spacingValue spacing.Enum, slantValue slant.Enum)

Style returns the style information for the given index. Must be >= 0 and < Count().

type FontMetrics

type FontMetrics = skia.FontMetrics

FontMetrics holds various metrics about a font.

type FontPanel added in v0.75.0

type FontPanel struct {
	FontModifiedCallback func(fd FontDescriptor)

	Panel
	DefaultFontSize float32
	MinFontSize     float32
	MaxFontSize     float32
	// contains filtered or unexported fields
}

FontPanel provides a standard panel for selecting a font.

func NewFontPanel added in v0.75.0

func NewFontPanel() *FontPanel

NewFontPanel creates a new FontPanel.

func (*FontPanel) DefaultFocusLost added in v0.75.0

func (p *FontPanel) DefaultFocusLost()

DefaultFocusLost provides the default focus lost handling for the font size field.

func (*FontPanel) DefaultKeyDown added in v0.75.0

func (p *FontPanel) DefaultKeyDown(keyCode KeyCode, mod Modifiers, repeat bool) bool

DefaultKeyDown provides the default key down handling for the font size field.

func (*FontPanel) DefaultValidate added in v0.75.0

func (p *FontPanel) DefaultValidate() bool

DefaultValidate provides the default validation for the font size field.

func (*FontPanel) FontDescriptor added in v0.75.0

func (p *FontPanel) FontDescriptor() FontDescriptor

FontDescriptor returns the font descriptor.

func (*FontPanel) SetFontDescriptor added in v0.75.0

func (p *FontPanel) SetFontDescriptor(fd FontDescriptor)

SetFontDescriptor sets the font descriptor.

type Gradient

type Gradient struct {
	Stops       []Stop
	Start       Point
	StartRadius float32
	End         Point
	EndRadius   float32
}

Gradient defines a smooth transition between colors across an area. Start and End should hold values from 0 to 1. These will be be used to set a relative starting and ending position for the gradient. If StartRadius and EndRadius are both greater than 0, then the gradient will be a radial one instead of a linear one.

func NewEvenlySpacedGradient

func NewEvenlySpacedGradient(start, end Point, startRadius, endRadius float32, colors ...ColorProvider) *Gradient

NewEvenlySpacedGradient creates a new gradient with the specified colors evenly spread across the whole range. start and end should hold values from 0 to 1, representing the percentage position within the area that will be filled.

func NewHorizontalEvenlySpacedGradient

func NewHorizontalEvenlySpacedGradient(colors ...ColorProvider) *Gradient

NewHorizontalEvenlySpacedGradient creates a new gradient with the specified colors evenly spread across the whole range.

func NewVerticalEvenlySpacedGradient

func NewVerticalEvenlySpacedGradient(colors ...ColorProvider) *Gradient

NewVerticalEvenlySpacedGradient creates a new gradient with the specified colors evenly spread across the whole range.

func (*Gradient) Paint

func (g *Gradient) Paint(_ *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this Gradient.

func (*Gradient) Reversed

func (g *Gradient) Reversed() *Gradient

Reversed creates a copy of the current Gradient and inverts the locations of each color stop in that copy.

type Group

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

Group is used to ensure only one panel in a group is selected at a time.

func NewGroup

func NewGroup(panel ...Grouper) *Group

NewGroup creates a new group for the specified set of panels. Each panel is removed from any other group it may be in and placed in the newly created one.

func (*Group) Add

func (sg *Group) Add(panel Grouper)

Add a panel to the group, removing it from any group it may have previously been associated with.

func (*Group) Remove

func (sg *Group) Remove(panel Grouper)

Remove a panel from the group.

func (*Group) Select

func (sg *Group) Select(panel Grouper)

Select a panel, deselecting all others in the group.

func (*Group) Selected added in v0.69.0

func (sg *Group) Selected(panel Grouper) bool

Selected returns true if the panel is currently selected.

type Grouper added in v0.69.0

type Grouper interface {
	Paneler
	Group() *Group
	SetGroup(group *Group)
}

Grouper is the interface that a panel must implement to be part of a group.

type Image

type Image softref.SoftRef

Image holds a reference to an image.

func MoveCursorImage added in v0.5.0

func MoveCursorImage() *Image

MoveCursorImage returns the standard move cursor image.

func NewImageFromBytes

func NewImageFromBytes(buffer []byte, scale float32) (*Image, error)

NewImageFromBytes creates a new image from raw bytes.

func NewImageFromDrawing added in v0.38.0

func NewImageFromDrawing(width, height, ppi int, draw func(*Canvas)) (*Image, error)

NewImageFromDrawing creates a new image by drawing into it. This is currently fairly inefficient, so take care to use it sparingly.

func NewImageFromFilePathOrURL

func NewImageFromFilePathOrURL(filePathOrURL string, scale float32) (*Image, error)

NewImageFromFilePathOrURL creates a new image from data retrieved from the file path or URL. The http.DefaultClient will be used if the data is remote.

func NewImageFromFilePathOrURLWithContext added in v0.45.0

func NewImageFromFilePathOrURLWithContext(ctx context.Context, filePathOrURL string, scale float32) (*Image, error)

NewImageFromFilePathOrURLWithContext creates a new image from data retrieved from the file path or URL. The http.DefaultClient will be used if the data is remote.

func NewImageFromPixels

func NewImageFromPixels(width, height int, pixels []byte, scale float32) (*Image, error)

NewImageFromPixels creates a new image from pixel data.

func ResizeHorizontalCursorImage added in v0.5.0

func ResizeHorizontalCursorImage() *Image

ResizeHorizontalCursorImage returns the standard horizontal resize cursor image.

func ResizeLeftDiagonalCursorImage added in v0.5.0

func ResizeLeftDiagonalCursorImage() *Image

ResizeLeftDiagonalCursorImage returns the standard left diagonal resize cursor image.

func ResizeRightDiagonalCursorImage added in v0.5.0

func ResizeRightDiagonalCursorImage() *Image

ResizeRightDiagonalCursorImage returns the standard right diagonal resize cursor image.

func ResizeVerticalCursorImage added in v0.5.0

func ResizeVerticalCursorImage() *Image

ResizeVerticalCursorImage returns the standard vertical resize cursor image.

func (*Image) DrawInRect added in v0.3.0

func (img *Image) DrawInRect(canvas *Canvas, rect Rect, sampling *SamplingOptions, paint *Paint)

DrawInRect draws this image in the given rectangle.

func (*Image) LogicalSize

func (img *Image) LogicalSize() Size

LogicalSize returns the logical (device-independent) size.

func (*Image) Scale

func (img *Image) Scale() float32

Scale returns the internal scaling factor for this image.

func (*Image) Size

func (img *Image) Size() Size

Size returns the size, in pixels, of the image. These dimensions will always be whole numbers > 0 for valid images.

func (*Image) ToJPEG

func (img *Image) ToJPEG(quality int) ([]byte, error)

ToJPEG creates JPEG data from the image. quality should be greater than 0 and equal to or less than 100.

func (*Image) ToNRGBA

func (img *Image) ToNRGBA() (*image.NRGBA, error)

ToNRGBA creates an image.NRGBA from the image.

func (*Image) ToPNG

func (img *Image) ToPNG(compressionLevel int) ([]byte, error)

ToPNG creates PNG data from the image. 'compressionLevel' should in the range 0-9 and is equivalent to the zlib compression level. A typical compression level is 6 and is equivalent to the zlib default.

func (*Image) ToWebp

func (img *Image) ToWebp(quality float32, lossy bool) ([]byte, error)

ToWebp creates Webp data from the image. quality should be greater than 0 and equal to or less than 100.

type ImageFilter

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

ImageFilter performs a transformation on the image before drawing it.

func NewArithmeticImageFilter

func NewArithmeticImageFilter(k1, k2, k3, k4 float32, background, foreground *ImageFilter, enforcePMColor bool, cropRect *Rect) *ImageFilter

NewArithmeticImageFilter returns a new arithmetic image filter. Each output pixel is the result of combining the corresponding background and foreground pixels using the 4 coefficients: k1 * foreground * background + k2 * foreground + k3 * background + k4 Both background and foreground may be nil, in which case the source bitmap is used. If enforcePMColor is true, the RGB channels will clamped to the calculated alpha. cropRect may be nil.

func NewBlurImageFilter

func NewBlurImageFilter(sigmaX, sigmaY float32, tileMode tilemode.Enum, input *ImageFilter, cropRect *Rect) *ImageFilter

NewBlurImageFilter returns a new blur image filter. input may be nil, in which case the source bitmap is used. cropRect may be nil.

func NewColorImageFilter

func NewColorImageFilter(colorFilter *ColorFilter, input *ImageFilter, cropRect *Rect) *ImageFilter

NewColorImageFilter returns a new color image filter. input may be nil, in which case the source bitmap is used. cropRect may be nil.

func NewComposeImageFilter

func NewComposeImageFilter(outer, inner *ImageFilter) *ImageFilter

NewComposeImageFilter returns a new combining image filter.

func NewDilateImageFilter

func NewDilateImageFilter(radiusX, radiusY int, input *ImageFilter, cropRect *Rect) *ImageFilter

NewDilateImageFilter returns a new dilate image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewDisplacementImageFilter

func NewDisplacementImageFilter(xChannelSelector, yChannelSelector colorchannel.Enum, scale float32, displacement, color *ImageFilter, cropRect *Rect) *ImageFilter

NewDisplacementImageFilter returns a new displacement image filter. displayment may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewDistantLitDiffuseImageFilter

func NewDistantLitDiffuseImageFilter(x, y, z, scale, reflectivity float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewDistantLitDiffuseImageFilter returns a new distant lit diffuse image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewDistantLitSpecularImageFilter

func NewDistantLitSpecularImageFilter(x, y, z, scale, reflectivity, shine float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewDistantLitSpecularImageFilter returns a new distant lit specular image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewDropShadowImageFilter

func NewDropShadowImageFilter(dx, dy, sigmaX, sigmaY float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewDropShadowImageFilter returns a new drop shadow image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewDropShadowOnlyImageFilter

func NewDropShadowOnlyImageFilter(dx, dy, sigmaX, sigmaY float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewDropShadowOnlyImageFilter returns a new drop shadow only image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewErodeImageFilter

func NewErodeImageFilter(radiusX, radiusY int, input *ImageFilter, cropRect *Rect) *ImageFilter

NewErodeImageFilter returns a new erode image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewImageSourceDefaultImageFilter

func NewImageSourceDefaultImageFilter(canvas *Canvas, img *Image, sampling *SamplingOptions) *ImageFilter

NewImageSourceDefaultImageFilter returns a new image source image filter that uses the default quality and the full image size. If canvas is not nil, a hardware-accellerated image will be used if possible.

func NewImageSourceImageFilter

func NewImageSourceImageFilter(canvas *Canvas, img *Image, srcRect, dstRect Rect, sampling *SamplingOptions) *ImageFilter

NewImageSourceImageFilter returns a new image source image filter. If canvas is not nil, a hardware-accellerated image will be used if possible.

func NewMagnifierImageFilter

func NewMagnifierImageFilter(lensBounds Rect, zoomAmount, inset float32, sampling *SamplingOptions, input *ImageFilter, cropRect *Rect) *ImageFilter

NewMagnifierImageFilter returns a new magnifier image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewMatrixConvolutionImageFilter

func NewMatrixConvolutionImageFilter(width, height int, kernel []float32, gain, bias float32, offsetX, offsetY int, tileMode tilemode.Enum, convolveAlpha bool, input *ImageFilter, cropRect *Rect) *ImageFilter

NewMatrixConvolutionImageFilter returns a new matrix convolution image filter.

width, height: The kernel size in pixels. kernel: The image processing kernel. Must contain width * height elements, in row order. If less than this, zeroes will be added to make up the difference. gain: A scale factor applied to each pixel after convolution. This can be used to normalize the kernel, if it does not already sum to 1. bias: A bias factor added to each pixel after convolution. offsetX, offsetY: An offset applied to each pixel coordinate before convolution. This can be used to center the kernel over the image (e.g., a 3x3 kernel should have an offset of {1, 1}). tileMode: How accesses outside the image are treated. convolveAlpha: If true, all channels are convolved. If false, only the RGB channels are convolved, and alpha is copied from the source image. input: The input image filter, if nil the source bitmap is used instead. cropRect: Rectangle to which the output processing will be limited. May be nil.

func NewMatrixTransformImageFilter

func NewMatrixTransformImageFilter(matrix Matrix, sampling *SamplingOptions, input *ImageFilter) *ImageFilter

NewMatrixTransformImageFilter returns a new matrix transform image filter. input may be nil, in which case the source bitmap will be used.

func NewMergeImageFilter

func NewMergeImageFilter(filters []*ImageFilter, cropRect *Rect) *ImageFilter

NewMergeImageFilter returns a new merge image filter. Each filter will draw their results in order with src-over blending. A nil filter will use the source bitmap instead. cropRect may be nil.

func NewOffsetImageFilter

func NewOffsetImageFilter(dx, dy float32, input *ImageFilter, cropRect *Rect) *ImageFilter

NewOffsetImageFilter returns a new offset image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewPointLitDiffuseImageFilter

func NewPointLitDiffuseImageFilter(x, y, z, scale, reflectivity float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewPointLitDiffuseImageFilter returns a new point lit diffuse image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewPointLitSpecularImageFilter

func NewPointLitSpecularImageFilter(x, y, z, scale, reflectivity, shine float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewPointLitSpecularImageFilter returns a new point lit specular image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewSpotLitDiffuseImageFilter

func NewSpotLitDiffuseImageFilter(x, y, z, targetX, targetY, targetZ, specularExponent, cutoffAngle, scale, reflectivity float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewSpotLitDiffuseImageFilter returns a new spot lit diffuse image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewSpotLitSpecularImageFilter

func NewSpotLitSpecularImageFilter(x, y, z, targetX, targetY, targetZ, specularExponent, cutoffAngle, scale, reflectivity, shine float32, color Color, input *ImageFilter, cropRect *Rect) *ImageFilter

NewSpotLitSpecularImageFilter returns a new spot lit specular image filter. input may be nil, in which case the source bitmap will be used. cropRect may be nil.

func NewTileImageFilter

func NewTileImageFilter(src, dst Rect, input *ImageFilter) *ImageFilter

NewTileImageFilter returns a new tile image filter. input may be nil, in which case the source bitmap will be used.

type IndirectColor added in v0.41.0

type IndirectColor struct {
	Target ColorProvider
}

IndirectColor holds a color that references another color.

func (*IndirectColor) GetColor added in v0.41.0

func (c *IndirectColor) GetColor() Color

GetColor returns the current color. Here to satisfy the ColorProvider interface.

func (*IndirectColor) Paint added in v0.41.0

func (c *IndirectColor) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this IndirectColor. Here to satisfy the Ink interface.

type IndirectFont

type IndirectFont struct {
	Font Font
}

IndirectFont holds a Font that references another font.

func (*IndirectFont) Baseline added in v0.4.0

func (f *IndirectFont) Baseline() float32

Baseline implements Font.

func (*IndirectFont) Descriptor added in v0.4.0

func (f *IndirectFont) Descriptor() FontDescriptor

Descriptor implements Font.

func (*IndirectFont) Face added in v0.4.0

func (f *IndirectFont) Face() *FontFace

Face implements Font.

func (*IndirectFont) GlyphWidth added in v0.7.0

func (f *IndirectFont) GlyphWidth(glyph uint16) float32

GlyphWidth implements Font.

func (*IndirectFont) GlyphWidths added in v0.7.0

func (f *IndirectFont) GlyphWidths(glyphs []uint16) []float32

GlyphWidths implements Font.

func (*IndirectFont) LineHeight added in v0.4.0

func (f *IndirectFont) LineHeight() float32

LineHeight implements Font.

func (*IndirectFont) Metrics added in v0.4.0

func (f *IndirectFont) Metrics() FontMetrics

Metrics implements Font.

func (*IndirectFont) RuneToGlyph added in v0.7.0

func (f *IndirectFont) RuneToGlyph(r rune) uint16

RuneToGlyph implements Font.

func (*IndirectFont) RunesToGlyphs added in v0.7.0

func (f *IndirectFont) RunesToGlyphs(r []rune) []uint16

RunesToGlyphs implements Font.

func (*IndirectFont) SimpleWidth added in v0.7.0

func (f *IndirectFont) SimpleWidth(str string) float32

SimpleWidth implements Font.

func (*IndirectFont) Size added in v0.4.0

func (f *IndirectFont) Size() float32

Size implements Font.

func (*IndirectFont) TextBlobPosH added in v0.52.0

func (f *IndirectFont) TextBlobPosH(glyphs []uint16, positions []float32, y float32) *TextBlob

TextBlobPosH implements Font.

type IndirectInk added in v0.44.0

type IndirectInk struct {
	Target Ink
}

IndirectInk an ink that references another ink.

func (*IndirectInk) Paint added in v0.44.0

func (i *IndirectInk) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint implements Ink.

type Ink

type Ink interface {
	Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint
}

Ink holds a color, pattern, or gradient to draw with.

type InputCallbacks

type InputCallbacks struct {
	// GainedFocusCallback is called when the keyboard focus is gained.
	GainedFocusCallback func()
	// LostFocusCallback is called when the keyboard focus is lost.
	LostFocusCallback func()
	// MouseDownCallback is called when the mouse is pressed. Return true to stop further handling or false to propagate
	// up to parents.
	MouseDownCallback func(where Point, button, clickCount int, mod Modifiers) bool
	// MouseDragCallback is called when the mouse is dragged after being pressed. Return true to stop further handling
	// or false to propagate up to parents.
	MouseDragCallback func(where Point, button int, mod Modifiers) bool
	// MouseUpCallback is called when the mouse is released after being pressed. Return true to stop further handling or
	// false to propagate up to parents.
	MouseUpCallback func(where Point, button int, mod Modifiers) bool
	// MouseEnterCallback is called on mouse entry. Return true to stop further handling or false to propagate up to
	// parents.
	MouseEnterCallback func(where Point, mod Modifiers) bool
	// MouseMoveCallback is called when the mouse moves. Return true to stop further handling or false to propagate up
	// to parents.
	MouseMoveCallback func(where Point, mod Modifiers) bool
	// MouseExitCallback is called on mouse exit. Return true to stop further handling or false to propagate up to
	// parents.
	MouseExitCallback func() bool
	// MouseWheelCallback is called when the mouse wheel is rotated. Return true to stop further handling or false to
	// propagate up to parents.
	MouseWheelCallback func(where, delta Point, mod Modifiers) bool
	// KeyDownCallback is called when a key is pressed. Return true to stop further handling or false to propagate up to
	// parents.
	KeyDownCallback func(keyCode KeyCode, mod Modifiers, repeat bool) bool
	// KeyUpCallback is called when a key is released. Return true to stop further handling or false to propagate up to
	// parents.
	KeyUpCallback func(keyCode KeyCode, mod Modifiers) bool
	// RuneTypedCallback is called when a key is typed. Return true to stop further handling or false to propagate up to
	// parents.
	RuneTypedCallback func(ch rune) bool
	// FileDropCallback is called when files are drag & dropped from the OS.
	FileDropCallback func(files []string)
}

InputCallbacks holds the callbacks that client code can hook into for user input events.

type Insets added in v0.13.0

type Insets = geom.Insets[float32]

Insets is an alias for geom.Insets[float32], for convenience.

func NewHorizontalInsets added in v0.13.0

func NewHorizontalInsets(amount float32) Insets

NewHorizontalInsets creates a new Insets whose left and right edges have the specified value.

func NewSymmetricInsets added in v0.64.0

func NewSymmetricInsets(h, v float32) Insets

NewSymmetricInsets returns an Insets whose edges match their opposite edge.

func NewUniformInsets added in v0.13.0

func NewUniformInsets(amount float32) Insets

NewUniformInsets creates a new Insets whose edges all have the same value.

func NewVerticalInsets added in v0.13.0

func NewVerticalInsets(amount float32) Insets

NewVerticalInsets creates a new Insets whose top and bottom edges have the specified value.

func StdInsets added in v0.15.0

func StdInsets() Insets

StdInsets returns insets preset to the standard spacing.

type KeyBinding added in v0.7.0

type KeyBinding struct {
	KeyCode   KeyCode
	Modifiers Modifiers
}

KeyBinding holds a key code and/or modifier.

func KeyBindingFromKey added in v0.7.0

func KeyBindingFromKey(key string) KeyBinding

KeyBindingFromKey extracts a KeyBinding from a string created via a call to .Key().

func (KeyBinding) Key added in v0.7.0

func (b KeyBinding) Key() string

Key returns a string version of the KeyCode for the purpose of serialization.

func (KeyBinding) MarshalText added in v0.7.0

func (b KeyBinding) MarshalText() (text []byte, err error)

MarshalText implements encoding.TextMarshaler.

func (KeyBinding) ShouldOmit added in v0.7.0

func (b KeyBinding) ShouldOmit() bool

ShouldOmit implements json.Omitter.

func (KeyBinding) String added in v0.7.0

func (b KeyBinding) String() string

func (*KeyBinding) UnmarshalText added in v0.7.0

func (b *KeyBinding) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type KeyCode

type KeyCode int16

KeyCode holds a virtual key code.

func KeyCodeFromKey added in v0.7.0

func KeyCodeFromKey(key string) KeyCode

KeyCodeFromKey extracts KeyCode from a string created via a call to .Key().

func (KeyCode) Key added in v0.7.0

func (k KeyCode) Key() string

Key returns a string version of the KeyCode for the purpose of serialization.

func (KeyCode) MarshalText added in v0.7.0

func (k KeyCode) MarshalText() (text []byte, err error)

MarshalText implements encoding.TextMarshaler.

func (KeyCode) ShouldOmit added in v0.7.0

func (k KeyCode) ShouldOmit() bool

ShouldOmit implements json.Omitter.

func (KeyCode) String added in v0.7.0

func (k KeyCode) String() string

func (*KeyCode) UnmarshalText added in v0.7.0

func (k *KeyCode) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type Label

type Label struct {
	Drawable Drawable
	Text     *Text
	LabelTheme
	Panel
}

Label represents non-interactive text and/or a Drawable.

func NewLabel

func NewLabel() *Label

NewLabel creates a new, empty label.

func NewLink(title, tooltip, target string, theme LinkTheme, clickHandler func(Paneler, string)) *Label

NewLink creates a new RichLabel that can be used as a hyperlink.

func (*Label) DefaultDraw

func (l *Label) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Label) DefaultSizes

func (l *Label) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Label) SetTitle added in v0.69.0

func (l *Label) SetTitle(text string)

SetTitle sets the text of the label to the specified text. The theme's TextDecoration will be used, so any changes you want to make to it should be done before calling this method. Alternatively, you can directly set the .Text field.

func (*Label) String added in v0.69.0

func (l *Label) String() string

type LabelTheme added in v0.4.0

type LabelTheme struct {
	TextDecoration
	Gap    float32
	HAlign align.Enum
	VAlign align.Enum
	Side   side.Enum
}

LabelTheme holds theming data for a Label.

type Layout

type Layout interface {
	LayoutSizes(target *Panel, hint Size) (minSize, prefSize, maxSize Size)
	PerformLayout(target *Panel)
}

Layout defines methods that all layouts must provide.

type LineBorder

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

LineBorder private a lined border.

func NewLineBorder

func NewLineBorder(ink Ink, cornerRadius float32, insets Insets, noInset bool) *LineBorder

NewLineBorder creates a new line border. The cornerRadius specifies the amount of rounding to use on the corners. The insets represent how thick the border will be drawn on that edge. If noInset is true, the Insets() method will return zeroes.

func (*LineBorder) Draw

func (b *LineBorder) Draw(canvas *Canvas, rect Rect)

Draw the border into rect.

func (*LineBorder) Insets

func (b *LineBorder) Insets() Insets

Insets returns the insets describing the space the border occupies on each side.

type LinkTheme added in v0.44.0

type LinkTheme struct {
	PressedInk   Ink
	OnPressedInk Ink
	LabelTheme
}

LinkTheme holds theming data for a link.

type List

type List[T any] struct {
	DoubleClickCallback  func()
	NewSelectionCallback func()
	Factory              CellFactory
	Selection            *xmath.BitSet

	ListTheme
	Panel
	// contains filtered or unexported fields
}

List provides a control that allows the user to select from a list of items, represented by cells.

func NewList

func NewList[T any]() *List[T]

NewList creates a new List control.

func (*List[T]) AllowMultipleSelection

func (l *List[T]) AllowMultipleSelection() bool

AllowMultipleSelection returns whether multiple rows may be selected at once.

func (*List[T]) Anchor

func (l *List[T]) Anchor() int

Anchor returns the index that is the current anchor point. Will be -1 if there is no anchor point.

func (*List[T]) Append

func (l *List[T]) Append(values ...T)

Append values to the list of items.

func (*List[T]) CanSelectAll added in v0.18.0

func (l *List[T]) CanSelectAll() bool

CanSelectAll returns true if the list's selection can be expanded.

func (*List[T]) Clear added in v0.68.0

func (l *List[T]) Clear()

Clear the list of items.

func (*List[T]) Count

func (l *List[T]) Count() int

Count returns the number of rows.

func (*List[T]) DataAtIndex

func (l *List[T]) DataAtIndex(index int) T

DataAtIndex returns the data for the specified row index.

func (*List[T]) DefaultDraw

func (l *List[T]) DefaultDraw(canvas *Canvas, dirty Rect)

DefaultDraw provides the default drawing.

func (*List[T]) DefaultFocusGained added in v0.16.0

func (l *List[T]) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*List[T]) DefaultKeyDown

func (l *List[T]) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*List[T]) DefaultMouseDown

func (l *List[T]) DefaultMouseDown(where Point, _, clickCount int, mod Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*List[T]) DefaultMouseDrag

func (l *List[T]) DefaultMouseDrag(where Point, _ int, mod Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*List[T]) DefaultMouseUp

func (l *List[T]) DefaultMouseUp(_ Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*List[T]) DefaultSizes

func (l *List[T]) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*List[T]) FlashSelection

func (l *List[T]) FlashSelection()

FlashSelection flashes the current selection.

func (*List[T]) Insert

func (l *List[T]) Insert(index int, values ...T)

Insert values at the specified index.

func (*List[T]) Remove

func (l *List[T]) Remove(index int)

Remove the item at the specified index.

func (*List[T]) RemoveRange

func (l *List[T]) RemoveRange(from, to int)

RemoveRange removes the items at the specified index range, inclusive.

func (*List[T]) Replace

func (l *List[T]) Replace(index int, value T)

Replace the value at the specified index.

func (*List[T]) RowRect added in v0.67.0

func (l *List[T]) RowRect(row int) Rect

RowRect returns the rectangle for the specified row.

func (*List[T]) Select

func (l *List[T]) Select(add bool, index ...int)

Select items at the specified indexes. If 'add' is true, then any existing selection is added to rather than replaced.

func (*List[T]) SelectAll added in v0.18.0

func (l *List[T]) SelectAll()

SelectAll selects all of the rows in the list.

func (*List[T]) SelectRange

func (l *List[T]) SelectRange(start, end int, add bool)

SelectRange selects items from 'start' to 'end', inclusive. If 'add' is true, then any existing selection is added to rather than replaced.

func (*List[T]) SetAllowMultipleSelection

func (l *List[T]) SetAllowMultipleSelection(allow bool) *List[T]

SetAllowMultipleSelection sets whether multiple rows may be selected at once.

type ListTheme added in v0.4.0

type ListTheme struct {
	BackgroundInk          Ink
	OnBackgroundInk        Ink
	BandingInk             Ink
	OnBandingInk           Ink
	SelectionInk           Ink
	OnSelectionInk         Ink
	InactiveSelectionInk   Ink
	OnInactiveSelectionInk Ink
	FlashAnimationTime     time.Duration
}

ListTheme holds theming data for a List.

type Markdown added in v0.44.0

type Markdown struct {
	MarkdownTheme
	Panel
	// contains filtered or unexported fields
}

Markdown provides markdown display widget.

func NewMarkdown added in v0.44.0

func NewMarkdown(autoSizingFromParent bool) *Markdown

NewMarkdown creates a new markdown widget. If autoSizingFromParent is true, then the Markdown will attempt to keep its content wrapped to its parent's width. Currently, things like tables don't play nice with width management.

func (*Markdown) ContentBytes added in v0.44.0

func (m *Markdown) ContentBytes() []byte

ContentBytes returns the current markdown content as a byte slice.

func (*Markdown) Rebuild added in v0.70.0

func (m *Markdown) Rebuild()

Rebuild rebuilds the markdown content. This is useful if the theme has been changed.

func (*Markdown) SetContent added in v0.44.0

func (m *Markdown) SetContent(content string, maxWidth float32)

SetContent replaces the current markdown content.

func (*Markdown) SetContentBytes added in v0.44.0

func (m *Markdown) SetContentBytes(content []byte, maxWidth float32)

SetContentBytes replaces the current markdown content. If maxWidth < 1, then the content will be sized based on the parent container or use DefaultMarkdownWidth if no parent is present.

func (*Markdown) SetVSpacing added in v0.44.0

func (m *Markdown) SetVSpacing(spacing float32)

SetVSpacing sets the vertical spacing between blocks. Use this function rather than setting VSpacing directly, since this will also adjust the layout to match.

type MarkdownTheme added in v0.44.0

type MarkdownTheme struct {
	TextDecoration
	HeadingFont         [6]Font
	CodeBlockFont       Font
	CodeBackground      Ink
	OnCodeBackground    Ink
	QuoteBarColor       Ink
	LinkInk             Ink
	LinkOnPressedInk    Ink
	LinkHandler         func(Paneler, string)
	WorkingDirProvider  func(Paneler) string
	AltLinkPrefixes     []string
	VSpacing            float32
	QuoteBarThickness   float32
	CodeAndQuotePadding float32
	Slop                float32
}

MarkdownTheme holds theming data for a Markdown.

var DefaultMarkdownTheme MarkdownTheme

DefaultMarkdownTheme holds the default MarkdownTheme values for Markdown. Modifying this data will not alter existing Markdown, but will alter any Markdown created in the future.

type MaskFilter

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

MaskFilter performs a transformation on the mask before drawing it.

func NewBlurMaskFilter

func NewBlurMaskFilter(style blur.Enum, sigma float32, respectMatrix bool) *MaskFilter

NewBlurMaskFilter returns a new blur mask filter. sigma is the standard deviation of the gaussian blur to apply. Must be greater than 0. If respectMatrix is true, the blur's sigma is modified by the current matrix.

func NewClipMaskFilter

func NewClipMaskFilter(minimum, maximum byte) *MaskFilter

NewClipMaskFilter returns a new clip mask filter.

func NewGammaMaskFilter

func NewGammaMaskFilter(gamma float32) *MaskFilter

NewGammaMaskFilter returns a new gamma mask filter.

func NewShaderMaskFilter

func NewShaderMaskFilter(shader *Shader) *MaskFilter

NewShaderMaskFilter returns a new shader mask filter.

func NewTableMaskFilter

func NewTableMaskFilter(table []byte) *MaskFilter

NewTableMaskFilter returns a new table mask filter. The table should be 256 elements long. If shorter, it will be expanded to 256 elements and the new entries will be filled with 0.

type Matrix added in v0.13.0

type Matrix = geom.Matrix[float32]

Matrix is an alias for geom.Matrix2D[float32], for convenience.

func NewIdentityMatrix added in v0.13.0

func NewIdentityMatrix() Matrix

NewIdentityMatrix creates a new identity transformation 2D matrix.

func NewRotationByDegreesMatrix added in v0.13.0

func NewRotationByDegreesMatrix(degrees float32) Matrix

NewRotationByDegreesMatrix creates a new 2D matrix that rotates by 'degrees'. Positive values are clockwise.

func NewRotationMatrix added in v0.13.0

func NewRotationMatrix(radians float32) Matrix

NewRotationMatrix creates a new 2D matrix that rotates by 'radians'. Positive values are clockwise.

func NewScaleMatrix added in v0.13.0

func NewScaleMatrix(sx, sy float32) Matrix

NewScaleMatrix creates a new 2D matrix that scales by 'sx' and 'sy'.

func NewTranslationMatrix added in v0.13.0

func NewTranslationMatrix(tx, ty float32) Matrix

NewTranslationMatrix creates a new 2D matrix that translates by 'tx' and 'ty'.

type MemoryStream added in v0.29.0

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

MemoryStream provides a way to write data to a buffer. This exists for PDF output, but can be used for other things.

func NewMemoryStream added in v0.29.0

func NewMemoryStream() *MemoryStream

NewMemoryStream creates a new stream that writes to memory.

func (*MemoryStream) Bytes added in v0.29.0

func (s *MemoryStream) Bytes() []byte

Bytes returns the bytes that have been written.

func (*MemoryStream) BytesWritten added in v0.29.0

func (s *MemoryStream) BytesWritten() int

BytesWritten returns the number of bytes written so far.

func (*MemoryStream) Close added in v0.29.0

func (s *MemoryStream) Close()

Close the stream. Further writes should not be done.

func (*MemoryStream) Write added in v0.29.0

func (s *MemoryStream) Write(data []byte) (n int, err error)
type Menu interface {
	// Factory returns the MenuFactory that created this Menu.
	Factory() MenuFactory
	// ID returns the id of this Menu.
	ID() int
	// IsSame returns true if the two menus represent the same object. Do not use == to test for equality.
	IsSame(other Menu) bool
	// ItemAtIndex returns the menu item at the specified index within the menu.
	ItemAtIndex(index int) MenuItem
	// Item returns the menu item with the specified id anywhere in the menu and and its sub-menus.
	Item(id int) MenuItem
	// Menu returns the menu with the specified id anywhere in the menu and and its sub-menus.
	Menu(id int) Menu
	// InsertSeparator inserts a menu separator at the specified menuItem index within this menu. Pass in a negative
	// index to append to the end. If onlyIfNeeded is true, then a separator is only inserted if the menuItem that would
	// precede it at the insertion location is not a separator.
	InsertSeparator(atIndex int, onlyIfNeeded bool)
	// InsertItem inserts a menu item at the specified menuItem index within this menu. Pass in a negative index to
	// append to the end. If the menu item is nil, then nothing happens.
	InsertItem(atIndex int, mi MenuItem)
	// InsertMenu inserts a new sub-menu at the specified menuItem index within this menu. Pass in a negative index to
	// append to the end.
	InsertMenu(atIndex int, subMenu Menu)
	// RemoveItem removes the menu item at the specified index from this menu.
	RemoveItem(index int)
	// RemoveAll removes all menu items from the menu.
	RemoveAll()
	// Title returns the title of this menu.
	Title() string
	// Count of menu items in this menu.
	Count() int
	// Popup the menu at the specified position within the active window.
	Popup(where Rect, itemIndex int)
	// Dispose releases any OS resources associated with this menu.
	Dispose()
}

Menu holds a set of menu items.

func NewAppMenu

func NewAppMenu(f MenuFactory, aboutHandler, prefsHandler func(MenuItem), updater func(Menu)) Menu

NewAppMenu creates a standard 'App' menu. Really only intended for macOS, although other platforms can use it if desired.

func NewEditMenu

func NewEditMenu(f MenuFactory, prefsHandler func(MenuItem), updater func(Menu)) Menu

NewEditMenu creates a standard 'Edit' menu.

func NewFileMenu

func NewFileMenu(f MenuFactory, updater func(Menu)) Menu

NewFileMenu creates a standard 'File' menu.

func NewHelpMenu

func NewHelpMenu(f MenuFactory, aboutHandler func(MenuItem), updater func(Menu)) Menu

NewHelpMenu creates a standard 'Help' menu.

func NewWindowMenu

func NewWindowMenu(f MenuFactory, updater func(Menu)) Menu

NewWindowMenu creates a standard 'Window' menu.

type MenuFactory interface {
	// BarForWindow returns the menu bar for the given window. If this is the first time the menu bar has been returned
	// from this call, initializer will be called so that your code can configure the menus.
	BarForWindow(window *Window, initializer func(Menu)) Menu
	// BarForWindowNoCreate returns the menu bar for the given window. May return nil if no menu bar for the window has
	// been created yet.
	BarForWindowNoCreate(window *Window) Menu
	// BarIsPerWindow returns true if the menu bar returned from this MenuFactory is per-window instead of global.
	BarIsPerWindow() bool
	// NewMenu creates a new Menu. updater is optional and, if present, will be called prior to showing the Menu, giving
	// a chance to modify it.
	NewMenu(id int, title string, updater func(Menu)) Menu
	// NewItem creates a new MenuItem. Both validator and handler may be nil for default behavior.
	NewItem(id int, title string, keyBinding KeyBinding, validator func(MenuItem) bool, handler func(MenuItem)) MenuItem
}

MenuFactory provides methods for creating a menu bar and its menus.

func DefaultMenuFactory

func DefaultMenuFactory() MenuFactory

DefaultMenuFactory returns the default MenuFactory for the platform. Multiple calls always return the same object.

func NewInWindowMenuFactory

func NewInWindowMenuFactory() MenuFactory

NewInWindowMenuFactory creates a new MenuFactory for in-window usage. This is the fallback Go-only version of menus used when a non-platform-native version doesn't exist.

type MenuItem interface {
	// Factory returns the MenuFactory that created this MenuItem.
	Factory() MenuFactory
	// ID returns the id of this menu item.
	ID() int
	// IsSame returns true if the two items represent the same object. Do not use == to test for equality.
	IsSame(other MenuItem) bool
	// Menu returns the owning menu.
	Menu() Menu
	// Index returns the index of the menu item within its menu. Returns -1 if it is not yet attached to a menu.
	Index() int
	// IsSeparator returns true if this menu item is a separator.
	IsSeparator() bool
	// Title returns the menu item's title.
	Title() string
	// SetTitle sets the menu item's title.
	SetTitle(title string)
	// KeyBinding returns the key binding for the menu item.
	KeyBinding() KeyBinding
	// SetKeyBinding sets the key binding for the menu item.
	SetKeyBinding(keyBinding KeyBinding)
	// SubMenu returns the menu item's sub-menu, if any.
	SubMenu() Menu
	// CheckState returns the menu item's current check state.
	CheckState() check.Enum
	// SetCheckState sets the menu item's check state.
	SetCheckState(s check.Enum)
}

MenuItem describes a choice that can be made from a Menu.

type MenuItemTheme struct {
	TitleFont         Font
	KeyFont           Font
	BackgroundColor   Ink
	OnBackgroundColor Ink
	SelectionColor    Ink
	OnSelectionColor  Ink
	ItemBorder        Border
	SeparatorBorder   Border
	KeyGap            float32
}

MenuItemTheme holds theming data for a menu item.

type MenuTheme struct {
	BarBorder  Border
	MenuBorder Border
}

MenuTheme holds theming data for a Menu.

type Modifiers

type Modifiers byte

Modifiers contains flags indicating which modifier keys were down when an event occurred.

const (
	ShiftModifier Modifiers = 1 << iota
	ControlModifier
	OptionModifier
	CommandModifier
	CapsLockModifier
	NumLockModifier
	NonStickyModifiers           = ShiftModifier | ControlModifier | OptionModifier | CommandModifier
	StickyModifiers              = CapsLockModifier | NumLockModifier
	AllModifiers                 = StickyModifiers | NonStickyModifiers
	NoModifiers        Modifiers = 0
)

Possible Modifiers values.

func ModifiersFromKey added in v0.7.0

func ModifiersFromKey(key string) Modifiers

ModifiersFromKey extracts Modifiers from a string created via a call to .Key().

func OSMenuCmdModifier

func OSMenuCmdModifier() Modifiers

OSMenuCmdModifier returns the OS's standard menu command key modifier.

func (Modifiers) CapsLockDown

func (m Modifiers) CapsLockDown() bool

CapsLockDown returns true if the caps lock key is being pressed.

func (Modifiers) CommandDown

func (m Modifiers) CommandDown() bool

CommandDown returns true if the command/meta key is being pressed.

func (Modifiers) ControlDown

func (m Modifiers) ControlDown() bool

ControlDown returns true if the control key is being pressed.

func (Modifiers) DiscontiguousSelectionDown added in v0.39.0

func (m Modifiers) DiscontiguousSelectionDown() bool

DiscontiguousSelectionDown returns true if either the control or command/meta key is being pressed.

func (Modifiers) Key added in v0.7.0

func (m Modifiers) Key() string

Key returns a string version of the Modifiers for the purpose of serialization.

func (Modifiers) MarshalText added in v0.7.0

func (m Modifiers) MarshalText() (text []byte, err error)

MarshalText implements encoding.TextMarshaler.

func (Modifiers) NumLockDown

func (m Modifiers) NumLockDown() bool

NumLockDown returns true if the num lock key is being pressed.

func (Modifiers) OSMenuCmdModifierDown

func (m Modifiers) OSMenuCmdModifierDown() bool

OSMenuCmdModifierDown returns true if the OS's standard menu command key is being pressed.

func (Modifiers) OptionDown

func (m Modifiers) OptionDown() bool

OptionDown returns true if the option/alt key is being pressed.

func (Modifiers) ShiftDown

func (m Modifiers) ShiftDown() bool

ShiftDown returns true if the shift key is being pressed.

func (Modifiers) String

func (m Modifiers) String() string

String returns a text representation of these modifiers.

func (*Modifiers) UnmarshalText added in v0.7.0

func (m *Modifiers) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type NumericField added in v0.30.0

type NumericField[T xmath.Numeric] struct {
	*Field
	Format     func(T) string
	Extract    func(s string) (T, error)
	Prototypes func(minimum, maximum T) []T
	// contains filtered or unexported fields
}

NumericField holds a numeric value that can be edited.

func NewNumericField added in v0.30.0

func NewNumericField[T xmath.Numeric](current, minimum, maximum T, format func(T) string, extract func(s string) (T, error), prototypes func(minimum, maximum T) []T) *NumericField[T]

NewNumericField creates a new field that holds a numeric value and limits its input to a specific range of values. The format and extract functions allow the field to be presented as something other than numbers.

func (*NumericField[T]) DefaultFocusLost added in v0.30.0

func (f *NumericField[T]) DefaultFocusLost()

DefaultFocusLost is the default implementation for the LostFocusCallback.

func (*NumericField[T]) DefaultRuneTyped added in v0.30.0

func (f *NumericField[T]) DefaultRuneTyped(ch rune) bool

DefaultRuneTyped is the default implementation for the RuneTypedCallback.

func (*NumericField[T]) DefaultValidate added in v0.30.0

func (f *NumericField[T]) DefaultValidate() bool

DefaultValidate is the default implementation for the ValidateCallback.

func (*NumericField[T]) Max added in v0.30.0

func (f *NumericField[T]) Max() T

Max returns the maximum value allowed.

func (*NumericField[T]) Min added in v0.30.0

func (f *NumericField[T]) Min() T

Min returns the minimum value allowed.

func (*NumericField[T]) SetMinMax added in v0.30.0

func (f *NumericField[T]) SetMinMax(minimum, maximum T)

SetMinMax sets the minimum and maximum values and then adjusts the minimum text width, if a prototype function has been set.

func (*NumericField[T]) SetValue added in v0.30.0

func (f *NumericField[T]) SetValue(value T)

SetValue sets the current value of the field.

func (*NumericField[T]) Value added in v0.30.0

func (f *NumericField[T]) Value() T

Value returns the current value of the field.

type OpenDialog

type OpenDialog interface {
	FileDialog
	// CanChooseFiles returns true if the open dialog is permitted to select files.
	CanChooseFiles() bool
	// SetCanChooseFiles sets whether the open dialog is permitted to select files.
	SetCanChooseFiles(canChoose bool)
	// CanChooseDirectories returns true if the open dialog is permitted to select directories.
	CanChooseDirectories() bool
	// SetCanChooseDirectories sets whether the open dialog is permitted to select directories.
	SetCanChooseDirectories(canChoose bool)
	// ResolvesAliases returns whether the returned paths have been resolved in the case where the selection was an
	// alias.
	ResolvesAliases() bool
	// SetResolvesAliases sets whether the returned paths will be resolved in the case where the selection was an alias.
	SetResolvesAliases(resolves bool)
	// AllowsMultipleSelection returns true if more than one item can be selected.
	AllowsMultipleSelection() bool
	// SetAllowsMultipleSelection sets whether more than one item can be selected.
	SetAllowsMultipleSelection(allow bool)
	// Paths returns the paths that were chosen.
	Paths() []string
}

OpenDialog represents a dialog that permits a user to select one or more files or directories.

func NewCommonOpenDialog

func NewCommonOpenDialog() OpenDialog

NewCommonOpenDialog creates a new OpenDialog. This is the fallback Go-only version of the OpenDialog used when a non-platform-native version doesn't exist. Where possible, use of NewOpenDialog() should be preferred, since platforms like macOS and Windows usually have restrictions on file access that their native dialogs automatically remove for the user.

func NewOpenDialog

func NewOpenDialog() OpenDialog

NewOpenDialog creates a new open dialog using native support where possible.

type PDFMetaData added in v0.29.0

type PDFMetaData = skia.MetaData

PDFMetaData holds the metadata about a PDF document.

type PageProvider added in v0.29.0

type PageProvider interface {
	HasPage(pageNumber int) bool
	PageSize() Size
	DrawPage(canvas *Canvas, pageNumber int) error
}

PageProvider defines the methods required of a PDF producer.

type Paint

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

Paint controls options applied when drawing.

func NewPaint

func NewPaint() *Paint

NewPaint creates a new Paint.

func (*Paint) Antialias

func (p *Paint) Antialias() bool

Antialias returns true if pixels on the active edges of a path may be drawn with partial transparency.

func (*Paint) BlendMode

func (p *Paint) BlendMode() blendmode.Enum

BlendMode returns the current BlendMode.

func (*Paint) Clone

func (p *Paint) Clone() *Paint

Clone the Paint.

func (*Paint) Color

func (p *Paint) Color() Color

Color returns the current color.

func (*Paint) ColorFilter

func (p *Paint) ColorFilter() *ColorFilter

ColorFilter returns the current ColorFilter.

func (*Paint) Dither

func (p *Paint) Dither() bool

Dither returns true if color error may be distributed to smooth color transition.

func (*Paint) Equivalent added in v0.7.0

func (p *Paint) Equivalent(other *Paint) bool

Equivalent returns true if these Paint objects are equivalent.

func (*Paint) FillPath

func (p *Paint) FillPath(path *Path, resScale float32) (result *Path, hairline bool)

FillPath returns a path representing the path if it was stroked. resScale determines the precision used. Values >1 increase precision, while those <1 reduce precision to favor speed and size. If hairline returns true, the path represents a hairline, otherwise it represents a fill.

func (*Paint) FillPathWithCull

func (p *Paint) FillPathWithCull(path *Path, cullRect *Rect, resScale float32) (result *Path, hairline bool)

FillPathWithCull returns a path representing the path if it was stroked. cullRect, if not nil, will prune any parts outside of the rect. resScale determines the precision used. Values >1 increase precision, while those <1 reduce precision to favor speed and size. If hairline returns true, the path represents a hairline, otherwise it represents a fill.

func (*Paint) ImageFilter

func (p *Paint) ImageFilter() *ImageFilter

ImageFilter returns the current ImageFilter.

func (*Paint) MaskFilter

func (p *Paint) MaskFilter() *MaskFilter

MaskFilter returns the current MaskFilter.

func (*Paint) PathEffect

func (p *Paint) PathEffect() *PathEffect

PathEffect returns the current PathEffect.

func (*Paint) Reset

func (p *Paint) Reset()

Reset the Paint back to its default state.

func (*Paint) SetAntialias

func (p *Paint) SetAntialias(enabled bool)

SetAntialias sets whether pixels on the active edges of a path may be drawn with partial transparency.

func (*Paint) SetBlendMode

func (p *Paint) SetBlendMode(blendMode blendmode.Enum)

SetBlendMode sets the BlendMode.

func (*Paint) SetColor

func (p *Paint) SetColor(color Color)

SetColor sets the color.

func (*Paint) SetColorFilter

func (p *Paint) SetColorFilter(filter *ColorFilter)

SetColorFilter sets the ColorFilter.

func (*Paint) SetDither

func (p *Paint) SetDither(enabled bool)

SetDither sets whether color error may be distributed to smooth color transition.

func (*Paint) SetImageFilter

func (p *Paint) SetImageFilter(filter *ImageFilter)

SetImageFilter sets the ImageFilter.

func (*Paint) SetMaskFilter

func (p *Paint) SetMaskFilter(filter *MaskFilter)

SetMaskFilter sets the MaskFilter.

func (*Paint) SetPathEffect

func (p *Paint) SetPathEffect(effect *PathEffect)

SetPathEffect sets the PathEffect.

func (*Paint) SetShader

func (p *Paint) SetShader(shader *Shader)

SetShader sets the Shader.

func (*Paint) SetStrokeCap

func (p *Paint) SetStrokeCap(strokeCap strokecap.Enum)

SetStrokeCap sets the StrokeCap.

func (*Paint) SetStrokeJoin

func (p *Paint) SetStrokeJoin(strokeJoin strokejoin.Enum)

SetStrokeJoin sets the StrokeJoin.

func (*Paint) SetStrokeMiter

func (p *Paint) SetStrokeMiter(miter float32)

SetStrokeMiter sets the miter limit for sharp corners.

func (*Paint) SetStrokeWidth

func (p *Paint) SetStrokeWidth(width float32)

SetStrokeWidth sets the stroke width.

func (*Paint) SetStyle

func (p *Paint) SetStyle(style paintstyle.Enum)

SetStyle sets the PaintStyle.

func (*Paint) Shader

func (p *Paint) Shader() *Shader

Shader returns the current Shader.

func (*Paint) StrokeCap

func (p *Paint) StrokeCap() strokecap.Enum

StrokeCap returns the current StrokeCap.

func (*Paint) StrokeJoin

func (p *Paint) StrokeJoin() strokejoin.Enum

StrokeJoin returns the current StrokeJoin.

func (*Paint) StrokeMiter

func (p *Paint) StrokeMiter() float32

StrokeMiter returns the current stroke miter limit for sharp corners.

func (*Paint) StrokeWidth

func (p *Paint) StrokeWidth() float32

StrokeWidth returns the current stroke width.

func (*Paint) Style

func (p *Paint) Style() paintstyle.Enum

Style returns the current PaintStyle.

type Panel

type Panel struct {
	InputCallbacks
	Self any

	DrawCallback                        func(gc *Canvas, rect Rect)
	DrawOverCallback                    func(gc *Canvas, rect Rect)
	UpdateCursorCallback                func(where Point) *Cursor
	UpdateTooltipCallback               func(where Point, suggestedAvoidInRoot Rect) Rect
	FrameChangeCallback                 func()
	FrameChangeInChildHierarchyCallback func(panel *Panel)
	ScrollRectIntoViewCallback          func(rect Rect) bool
	ParentChangedCallback               func()
	FocusChangeInHierarchyCallback      func(from, to *Panel)
	// DataDragOverCallback is called when a data drag is over a potential drop target. Return true to stop further
	// handling or false to propagate up to parents.
	DataDragOverCallback func(where Point, data map[string]any) bool
	// DataDragExitCallback is called when a previous call to DataDragOverCallback returned true and the data drag
	// leaves the component.
	DataDragExitCallback func()
	// DataDragDropCallback is called when a data drag is dropped and a previous call to DataDragOverCallback returned
	// true.
	DataDragDropCallback func(where Point, data map[string]any)
	Tooltip              *Panel

	RefKey string

	NeedsLayout bool

	Hidden           bool
	TooltipImmediate bool
	// contains filtered or unexported fields
}

Panel is the basic user interface element that interacts with the user. During construction, new objects must always set the Self field to the final object. Failure to do so may result in incorrect behavior.

func NewMessagePanel

func NewMessagePanel(primary, detail string) *Panel

NewMessagePanel creates a new panel containing the given primary and detail messages. Embedded line feeds are OK.

func NewPanel

func NewPanel() *Panel

NewPanel creates a new panel.

func NewTooltipBase

func NewTooltipBase() *Panel

NewTooltipBase returns the base for a tooltip.

func NewTooltipWithSecondaryText

func NewTooltipWithSecondaryText(primary, secondary string) *Panel

NewTooltipWithSecondaryText creates a text tooltip panel containing a primary piece of text along with a secondary piece of text in a slightly smaller font.

func NewTooltipWithText

func NewTooltipWithText(text string) *Panel

NewTooltipWithText creates a standard text tooltip panel.

func (*Panel) AddChild

func (p *Panel) AddChild(child Paneler)

AddChild adds child to this panel, removing it from any previous parent it may have had.

func (*Panel) AddChildAtIndex

func (p *Panel) AddChildAtIndex(child Paneler, index int)

AddChildAtIndex adds child to this panel at the index, removing it from any previous parent it may have had. Passing in a negative value for the index will add it to the end.

func (*Panel) AsPanel

func (p *Panel) AsPanel() *Panel

AsPanel returns this object as a panel.

func (*Panel) Border

func (p *Panel) Border() Border

Border returns the border for this panel, if any.

func (*Panel) CanPerformCmd added in v0.17.0

func (p *Panel) CanPerformCmd(src any, id int) bool

CanPerformCmd checks if this panel or its ancestors can perform the command. May be called on a nil Panel object.

func (*Panel) Children

func (p *Panel) Children() []*Panel

Children returns the direct descendents of this panel.

func (*Panel) ClientData

func (p *Panel) ClientData() map[string]any

ClientData returns a map of client data for this Panel.

func (*Panel) ContentRect

func (p *Panel) ContentRect(includeBorder bool) Rect

ContentRect returns the location and size of the panel in local coordinates.

func (*Panel) Draw

func (p *Panel) Draw(gc *Canvas, rect Rect)

Draw is called by its owning window when a panel needs to be drawn. The canvas has already had its clip set to rect.

func (*Panel) Enabled

func (p *Panel) Enabled() bool

Enabled returns true if this panel is currently enabled and can receive events.

func (*Panel) FindRefKey added in v0.24.0

func (p *Panel) FindRefKey(refKey string) *Panel

FindRefKey looks for refKey starting with this panel and then descending into its children recursively, returning the first match or nil if none is found.

func (*Panel) FirstFocusableChild added in v0.13.0

func (p *Panel) FirstFocusableChild() *Panel

FirstFocusableChild returns the first focusable child or nil.

func (*Panel) FlushDrawing

func (p *Panel) FlushDrawing()

FlushDrawing is a convenience for calling the parent window's (if any) FlushDrawing() method.

func (*Panel) Focusable

func (p *Panel) Focusable() bool

Focusable returns true if this panel can have the keyboard focus.

func (*Panel) Focused

func (p *Panel) Focused() bool

Focused returns true if this panel has the keyboard focus.

func (*Panel) FrameRect

func (p *Panel) FrameRect() Rect

FrameRect returns the location and size of the panel in its parent's coordinate system.

func (*Panel) HasInSelfOrDescendants added in v0.44.0

func (p *Panel) HasInSelfOrDescendants(checker func(*Panel) bool) bool

HasInSelfOrDescendants calls checker for this panel and each of its descendants (depth-first), returning true for the first one that checker() returns true for.

func (*Panel) IndexOfChild

func (p *Panel) IndexOfChild(child Paneler) int

IndexOfChild returns the index of the specified child, or -1 if the passed in panel is not a child of this panel.

func (*Panel) InstallCmdHandlers added in v0.18.0

func (p *Panel) InstallCmdHandlers(id int, can func(any) bool, do func(any)) (formerCan func(any) bool, formerDo func(any))

InstallCmdHandlers installs handlers for the command with the given ID, returning any previously installed handlers.

func (*Panel) Is

func (p *Panel) Is(other Paneler) bool

Is returns true if this panel is the other panel.

func (*Panel) IsDragGesture added in v0.3.0

func (p *Panel) IsDragGesture(where Point) bool

IsDragGesture returns true if a gesture to start a drag operation was made.

func (*Panel) LastFocusableChild added in v0.13.0

func (p *Panel) LastFocusableChild() *Panel

LastFocusableChild returns the last focusable child or nil.

func (*Panel) Layout

func (p *Panel) Layout() Layout

Layout returns the Layout for this panel, if any.

func (*Panel) LayoutData

func (p *Panel) LayoutData() any

LayoutData returns the layout data, if any, associated with this panel.

func (*Panel) MarkForLayoutAndRedraw

func (p *Panel) MarkForLayoutAndRedraw()

MarkForLayoutAndRedraw marks this panel as needing to be laid out as well as redrawn at the next update.

func (*Panel) MarkForLayoutRecursively added in v0.11.0

func (p *Panel) MarkForLayoutRecursively()

MarkForLayoutRecursively marks this panel and all of its descendents as needing to be laid out.

func (*Panel) MarkForLayoutRecursivelyUpward added in v0.20.0

func (p *Panel) MarkForLayoutRecursivelyUpward()

MarkForLayoutRecursivelyUpward marks this panel and all of its parents as needing to be laid out.

func (*Panel) MarkForRedraw

func (p *Panel) MarkForRedraw()

MarkForRedraw finds the parent window and marks it for drawing at the next update. Note that currently I have found no way to get glfw to both only redraw a subset of the window AND retain the previous contents of that window, such that incremental updates can be done. So... we just redraw everything in the window every time.

func (*Panel) Pack added in v0.11.5

func (p *Panel) Pack()

Pack resizes the panel to its preferred size.

func (*Panel) PanelAt

func (p *Panel) PanelAt(pt Point) *Panel

PanelAt returns the leaf-most child panel containing the point, or this panel if no child is found.

func (*Panel) Parent

func (p *Panel) Parent() *Panel

Parent returns the parent panel, if any.

func (*Panel) PerformCmd added in v0.17.0

func (p *Panel) PerformCmd(src any, id int)

PerformCmd returns true if the command was handled, either by this panel or its ancestors. May be called on a nil Panel object. First calls CanPerformCmd() to ensure the command is permitted to be performed.

func (*Panel) PointFromRoot

func (p *Panel) PointFromRoot(pt Point) Point

PointFromRoot converts root coordinates (i.e. window-local, when rooted within a window) into panel-local coordinates.

func (*Panel) PointTo added in v0.44.0

func (p *Panel) PointTo(pt Point, target *Panel) Point

PointTo converts panel-local coordinates into another panel's coordinates.

func (*Panel) PointToRoot

func (p *Panel) PointToRoot(pt Point) Point

PointToRoot converts panel-local coordinates into root coordinates, which when rooted within a window, will be window-local coordinates.

func (*Panel) RectFromRoot

func (p *Panel) RectFromRoot(rect Rect) Rect

RectFromRoot converts root coordinates (i.e. window-local, when rooted within a window) into panel-local coordinates.

func (*Panel) RectTo added in v0.44.0

func (p *Panel) RectTo(rect Rect, target *Panel) Rect

RectTo converts panel-local coordinates into another panel's coordinates.

func (*Panel) RectToRoot

func (p *Panel) RectToRoot(rect Rect) Rect

RectToRoot converts panel-local coordinates into root coordinates, which when rooted within a window, will be window-local coordinates.

func (*Panel) RemoveAllChildren

func (p *Panel) RemoveAllChildren()

RemoveAllChildren removes all child panels from this panel.

func (*Panel) RemoveChild

func (p *Panel) RemoveChild(child Paneler)

RemoveChild removes 'child' from this panel. If 'child' is not a direct descendent of this panel, nothing happens.

func (*Panel) RemoveChildAtIndex

func (p *Panel) RemoveChildAtIndex(index int)

RemoveChildAtIndex removes the child panel at 'index' from this panel. If 'index' is out of range, nothing happens.

func (*Panel) RemoveCmdHandler added in v0.18.0

func (p *Panel) RemoveCmdHandler(id int)

RemoveCmdHandler removes the handlers for the command with the given ID.

func (*Panel) RemoveFromParent

func (p *Panel) RemoveFromParent()

RemoveFromParent removes this panel from its parent, if any.

func (*Panel) RequestFocus

func (p *Panel) RequestFocus()

RequestFocus attempts to make this panel the keyboard focus.

func (*Panel) Scale added in v0.8.0

func (p *Panel) Scale() float32

Scale returns the scale that has been applied to this panel. This will be automatically applied, transforming the graphics and mouse events.

func (*Panel) ScrollIntoView

func (p *Panel) ScrollIntoView()

ScrollIntoView attempts to scroll this panel into the current view if it is not already there, using ScrollAreas in this Panel's hierarchy.

func (*Panel) ScrollRectIntoView

func (p *Panel) ScrollRectIntoView(rect Rect)

ScrollRectIntoView attempts to scroll the rect (in coordinates local to this Panel) into the current view if it is not already there, using scroll areas in this Panel's hierarchy.

func (*Panel) ScrollRoot added in v0.19.0

func (p *Panel) ScrollRoot() *ScrollPanel

ScrollRoot returns the containing ScrollPanel, if any.

func (*Panel) SetBorder

func (p *Panel) SetBorder(b Border)

SetBorder sets the border for this panel. May be nil.

func (*Panel) SetEnabled

func (p *Panel) SetEnabled(enabled bool)

SetEnabled sets this panel's enabled state.

func (*Panel) SetFocusable

func (p *Panel) SetFocusable(focusable bool)

SetFocusable sets whether this panel can have the keyboard focus.

func (*Panel) SetFrameRect

func (p *Panel) SetFrameRect(rect Rect)

SetFrameRect sets the location and size of the panel in its parent's coordinate system.

func (*Panel) SetLayout

func (p *Panel) SetLayout(lay Layout)

SetLayout sets the Layout for this panel. May be nil.

func (*Panel) SetLayoutData

func (p *Panel) SetLayoutData(data any)

SetLayoutData sets layout data on this panel. May be nil.

func (*Panel) SetScale added in v0.8.0

func (p *Panel) SetScale(scale float32)

SetScale sets the scale for this panel and the panels in the hierarchy below it.

func (*Panel) SetSizer

func (p *Panel) SetSizer(sizer Sizer)

SetSizer sets the sizer for this panel. May be nil.

func (*Panel) Sizer

func (p *Panel) Sizer() Sizer

Sizer returns the sizer for this panel, if any.

func (*Panel) Sizes

func (p *Panel) Sizes(hint Size) (minSize, prefSize, maxSize Size)

Sizes returns the minimum, preferred, and maximum sizes the panel wishes to be. It does this by first asking the panel's layout. If no layout is present, then the panel's sizer is asked. If no sizer is present, then it finally uses a default set of sizes that are used for all panels.

func (*Panel) StartDataDrag added in v0.3.0

func (p *Panel) StartDataDrag(data *DragData)

StartDataDrag starts a data drag operation.

func (*Panel) String

func (p *Panel) String() string

func (*Panel) UpdateCursorNow

func (p *Panel) UpdateCursorNow()

UpdateCursorNow causes the cursor to be updated as if the mouse had moved.

func (*Panel) ValidateLayout

func (p *Panel) ValidateLayout()

ValidateLayout performs any layout that needs to be run by this panel or its children.

func (*Panel) ValidateScrollRoot added in v0.19.0

func (p *Panel) ValidateScrollRoot()

ValidateScrollRoot calls ValidateLayout() on the containing ScrollPanel, if any.

func (*Panel) Window

func (p *Panel) Window() *Window

Window returns the containing window, if any.

type Paneler

type Paneler interface {
	AsPanel() *Panel
}

Paneler is used to convert widgets into the base Panel type.

type Path

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

Path holds geometry.

func CombinePaths

func CombinePaths(ops []PathOpPair) (*Path, error)

CombinePaths combines two or more paths into a new path. There is an implied empty path as the starting point.

func NewPath

func NewPath() *Path

NewPath creates a new, empty path.

func NewPathFromSVGString

func NewPathFromSVGString(svg string) (*Path, error)

NewPathFromSVGString attempts to create a path from the given SVG string.

func (*Path) ArcTo

func (p *Path) ArcTo(x, y, rx, ry, rotation float32, arcSize arcsize.Enum, dir direction.Enum)

ArcTo appends an arc. rotation is in degrees.

func (*Path) ArcToFromTangent

func (p *Path) ArcToFromTangent(x1, y1, x2, y2, radius float32)

ArcToFromTangent appends an arc. The arc is contained by the tangent from the current point to (x1, y1) and the tangent from (x1, y1) to (x2, y2). The arc is part of the circle sized to radius, positioned so it touches both tangent lines.

func (*Path) ArcToOval

func (p *Path) ArcToOval(bounds Rect, startAngle, sweepAngle float32, forceMoveTo bool)

ArcToOval appends an arc bounded by an oval. Both startAngle and sweepAngle are in degrees. A positive sweepAngle extends clockwise while a negative value extends counter-clockwise. If forceMoveTo is true, a new contour is started.

func (*Path) ArcToRelative

func (p *Path) ArcToRelative(dx, dy, rx, ry, rotation float32, arcSize arcsize.Enum, dir direction.Enum)

ArcToRelative appends an arc. The destination point is relative to the current point. rotation is in degrees.

func (*Path) Bounds

func (p *Path) Bounds() Rect

Bounds returns the bounding rectangle of the path. This is an approximation and may be different than the actual area covered when drawn.

func (*Path) Circle

func (p *Path) Circle(x, y, radius float32)

Circle adds a circle to the path with a clockwise direction. The circle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) CircleWithDirection

func (p *Path) CircleWithDirection(x, y, radius float32, dir direction.Enum)

CircleWithDirection adds a circle to the path. The circle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) Clone

func (p *Path) Clone() *Path

Clone this path.

func (*Path) Close

func (p *Path) Close()

Close the current contour.

func (*Path) ComputeTightBounds

func (p *Path) ComputeTightBounds() Rect

ComputeTightBounds returns the bounding rectangle of the path. This is an approximation and may be different than the actual area covered when drawn. When a path contains only lines, this method is functionally equivalent a call to Bounds(), though slower. When a path contains curves, the computed bounds includes the maximum extent of the quad, conic, or cubic.

func (*Path) ConicTo

func (p *Path) ConicTo(cpx, cpy, x, y, weight float32)

ConicTo appends a conic curve.

func (*Path) ConicToRelative

func (p *Path) ConicToRelative(cpdx, cpdy, dx, dy, weight float32)

ConicToRelative appends a conic curve. The control point and end point are relative to the current point.

func (*Path) Contains

func (p *Path) Contains(x, y float32) bool

Contains returns true if the point is within the path, taking into account the FillType.

func (*Path) CubicTo

func (p *Path) CubicTo(cp1x, cp1y, cp2x, cp2y, x, y float32)

CubicTo appends a cubic curve.

func (*Path) CubicToRelative

func (p *Path) CubicToRelative(cp1dx, cp1dy, cp2dx, cp2dy, dx, dy float32)

CubicToRelative appends a cubic curve. The control point and end point are relative to the current point.

func (*Path) CurrentPt

func (p *Path) CurrentPt() Point

CurrentPt returns the current point.

func (*Path) FillType

func (p *Path) FillType() filltype.Enum

FillType returns the FillType for this path.

func (*Path) Intersect added in v0.60.0

func (p *Path) Intersect(other *Path) bool

Intersect this path with the other path. Returns true if successful. Path is left unmodified if not successful.

func (*Path) LineTo

func (p *Path) LineTo(x, y float32)

LineTo appends a straight line segment.

func (*Path) LineToRelative

func (p *Path) LineToRelative(x, y float32)

LineToRelative appends a straight line segment. The end point is relative to the current point.

func (*Path) MoveTo

func (p *Path) MoveTo(x, y float32)

MoveTo begins a new contour at the specified point.

func (*Path) MoveToRelative

func (p *Path) MoveToRelative(x, y float32)

MoveToRelative begins a new contour at the specified point, which is relative to the current point.

func (*Path) NewRotated

func (p *Path) NewRotated(degrees float32) *Path

NewRotated creates a copy of this path and then rotates it.

func (*Path) NewScaled

func (p *Path) NewScaled(sx, sy float32) *Path

NewScaled creates a copy of this path and then scales it.

func (*Path) NewTransformed

func (p *Path) NewTransformed(matrix Matrix) *Path

NewTransformed creates a copy of this path and then transforms it by the provided matrix.

func (*Path) NewTranslated

func (p *Path) NewTranslated(x, y float32) *Path

NewTranslated creates a copy of this path and then translates it.

func (*Path) Oval

func (p *Path) Oval(bounds Rect)

Oval adds an oval to the path with a clockwise direction. The oval is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) OvalWithDirection

func (p *Path) OvalWithDirection(bounds Rect, dir direction.Enum)

OvalWithDirection adds an oval to the path. The oval is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) Path

func (p *Path) Path(path *Path, extend bool)

Path appends a path. If extend is true, a line from the current point to the start of the added path is created.

func (*Path) PathReverse

func (p *Path) PathReverse(path *Path)

PathReverse appends a path in reverse order.

func (*Path) PathRotated

func (p *Path) PathRotated(path *Path, degrees float32, extend bool)

PathRotated appends a path after rotating it. If extend is true, a line from the current point to the start of the added path is created.

func (*Path) PathScaled

func (p *Path) PathScaled(path *Path, sx, sy float32, extend bool)

PathScaled appends a path after scaling it. If extend is true, a line from the current point to the start of the added path is created.

func (*Path) PathTransformed

func (p *Path) PathTransformed(path *Path, matrix Matrix, extend bool)

PathTransformed appends a path after transforming it. If extend is true, a line from the current point to the start of the added path is created.

func (*Path) PathTranslated

func (p *Path) PathTranslated(path *Path, offsetX, offsetY float32, extend bool)

PathTranslated appends a path after translating it with the given offset. If extend is true, a line from the current point to the start of the added path is created.

func (*Path) Poly

func (p *Path) Poly(pts []Point, closePath bool)

Poly appends the line segments represented by pts to the path.

func (*Path) Polygon

func (p *Path) Polygon(poly Polygon)

Polygon appends the polygon to the path.

func (*Path) QuadTo

func (p *Path) QuadTo(cpx, cpy, x, y float32)

QuadTo appends a quadratic curve.

func (*Path) Rect

func (p *Path) Rect(bounds Rect)

Rect adds a rectangle to the path with a clockwise direction. The rectangle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) RectWithDirection

func (p *Path) RectWithDirection(bounds Rect, dir direction.Enum)

RectWithDirection adds a rectangle to the path. The rectangle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) Reset

func (p *Path) Reset()

Reset the path, as if it was newly created.

func (*Path) Rewind

func (p *Path) Rewind()

Rewind resets the path, as if it was newly created, but retains any allocated memory for future use, improving performance at the cost of memory.

func (*Path) Rotate

func (p *Path) Rotate(degrees float32)

Rotate the path.

func (*Path) RoundedRect

func (p *Path) RoundedRect(bounds Rect, radiusX, radiusY float32)

RoundedRect adds a rectangle with curved corners to the path with a clockwise direction. The rectangle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) RoundedRectWithDirection

func (p *Path) RoundedRectWithDirection(bounds Rect, radiusX, radiusY float32, dir direction.Enum)

RoundedRectWithDirection adds a rectangle with curved corners to the path. The rectangle is a complete contour, i.e. it starts with a MoveTo and ends with a Close operation.

func (*Path) Scale

func (p *Path) Scale(sx, sy float32)

Scale the path.

func (*Path) SetFillType

func (p *Path) SetFillType(fillType filltype.Enum)

SetFillType sets the FillType for this path.

func (*Path) Simplify added in v0.60.0

func (p *Path) Simplify() bool

Simplify this path. Returns true if successful. Path is left unmodified if not successful.

func (*Path) Subtract added in v0.60.0

func (p *Path) Subtract(other *Path) bool

Subtract the other path from this path. Returns true if successful. Path is left unmodified if not successful.

func (*Path) ToSVGString

func (p *Path) ToSVGString(useAbsoluteValues bool) string

ToSVGString returns an SVG string that represents this path.

func (*Path) Transform

func (p *Path) Transform(matrix Matrix)

Transform the path by the provided matrix.

func (*Path) Translate

func (p *Path) Translate(x, y float32)

Translate the path.

func (*Path) Union added in v0.60.0

func (p *Path) Union(other *Path) bool

Union this path with the other path. Returns true if successful. Path is left unmodified if not successful.

func (*Path) Xor added in v0.60.0

func (p *Path) Xor(other *Path) bool

Xor this path with the other path. Returns true if successful. Path is left unmodified if not successful.

type PathEffect

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

PathEffect affects the geometry of a drawing primitive before it is transformed by the canvas' matrix and drawn.

func DashEffect added in v0.20.0

func DashEffect() *PathEffect

DashEffect returns a 4-4 dash effect.

func New1dPathPathEffect

func New1dPathPathEffect(path *Path, advance, phase float32, style patheffect.Enum) *PathEffect

New1dPathPathEffect creates a new 1D path PathEffect.

func New2dLinePathEffect

func New2dLinePathEffect(width float32, matrix Matrix) *PathEffect

New2dLinePathEffect creates a new 2D line PathEffect.

func New2dPathEffect

func New2dPathEffect(matrix Matrix, path *Path) *PathEffect

New2dPathEffect creates a new 2D PathEffect.

func NewComposePathEffect

func NewComposePathEffect(outer, inner *PathEffect) *PathEffect

NewComposePathEffect creates a new PathEffect that combines two PathEffects.

func NewCornerPathEffect

func NewCornerPathEffect(radius float32) *PathEffect

NewCornerPathEffect creates a new corner PathEffect.

func NewDashPathEffect

func NewDashPathEffect(intervals []float32, phase float32) *PathEffect

NewDashPathEffect creates a new dash PathEffect.

func NewDiscretePathEffect

func NewDiscretePathEffect(segLength, deviation float32, seedAssist uint32) *PathEffect

NewDiscretePathEffect creates a new discrete PathEffect.

func NewSumPathEffect

func NewSumPathEffect(first, second *PathEffect) *PathEffect

NewSumPathEffect creates a new sum PathEffect.

func NewTrimPathEffect

func NewTrimPathEffect(start, stop float32, mode trimmode.Enum) *PathEffect

NewTrimPathEffect creates a new trim PathEffect.

type PathOpPair

type PathOpPair struct {
	Path *Path
	Op   pathop.Enum
}

PathOpPair holds the combination of a Path and a PathOp.

type Pattern

type Pattern struct {
	Image           *Image
	Offset          Point
	Scale           Point
	TileModeX       tilemode.Enum
	TileModeY       tilemode.Enum
	SamplingOptions SamplingOptions
}

Pattern holds the information necessary to draw an image in a pattern.

func (*Pattern) Paint

func (p *Pattern) Paint(canvas *Canvas, _ Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this Pattern.

type Point added in v0.13.0

type Point = geom.Point[float32]

Point is an alias for geom.Point[float32], for convenience.

func NewPoint added in v0.13.0

func NewPoint(x, y float32) Point

NewPoint creates a new Point.

type Polygon added in v0.60.0

type Polygon = poly.Polygon[float32]

Polygon is an alias for poly.Polygon[float32], for convenience.

type PopupMenu

type PopupMenu[T comparable] struct {
	MenuFactory              MenuFactory
	WillShowMenuCallback     func(popup *PopupMenu[T])
	ChoiceMadeCallback       func(popup *PopupMenu[T], index int, item T)
	SelectionChangedCallback func(popup *PopupMenu[T])

	PopupMenuTheme
	Panel
	// contains filtered or unexported fields
}

PopupMenu represents a clickable button that displays a menu of choices.

func NewPopupMenu

func NewPopupMenu[T comparable]() *PopupMenu[T]

NewPopupMenu creates a new PopupMenu.

func (*PopupMenu[T]) AddDisabledItem added in v0.7.0

func (p *PopupMenu[T]) AddDisabledItem(item T)

AddDisabledItem appends a disabled menu item to the end of the PopupMenu.

func (*PopupMenu[T]) AddItem

func (p *PopupMenu[T]) AddItem(item ...T)

AddItem appends one or more menu items to the end of the PopupMenu.

func (*PopupMenu[T]) AddSeparator

func (p *PopupMenu[T]) AddSeparator()

AddSeparator adds a separator to the end of the PopupMenu.

func (*PopupMenu[T]) Click

func (p *PopupMenu[T]) Click()

Click performs any animation associated with a click and triggers the popup menu to appear.

func (*PopupMenu[T]) DefaultDraw

func (p *PopupMenu[T]) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*PopupMenu[T]) DefaultFocusGained added in v0.16.0

func (p *PopupMenu[T]) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*PopupMenu[T]) DefaultKeyDown

func (p *PopupMenu[T]) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*PopupMenu[T]) DefaultMouseDown

func (p *PopupMenu[T]) DefaultMouseDown(_ Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*PopupMenu[T]) DefaultMouseDrag added in v0.39.0

func (p *PopupMenu[T]) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag is the default implementation of the MouseDragCallback.

func (*PopupMenu[T]) DefaultMouseUp added in v0.39.0

func (p *PopupMenu[T]) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp is the default implementation of the MouseUpCallback.

func (*PopupMenu[T]) DefaultSizes

func (p *PopupMenu[T]) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*PopupMenu[T]) DefaultUpdateCursor added in v0.44.0

func (p *PopupMenu[T]) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor for popup menus.

func (*PopupMenu[T]) IndexOfItem

func (p *PopupMenu[T]) IndexOfItem(item T) int

IndexOfItem returns the index of the specified menu item. -1 will be returned if the menu item isn't present.

func (*PopupMenu[T]) ItemAt

func (p *PopupMenu[T]) ItemAt(index int) (item T, ok bool)

ItemAt returns the item at the specified index. 'ok' will be false if the index is out of range or the specified index contains a separator.

func (*PopupMenu[T]) ItemCount

func (p *PopupMenu[T]) ItemCount() int

ItemCount returns the number of items in this PopupMenu.

func (*PopupMenu[T]) ItemEnabledAt added in v0.75.0

func (p *PopupMenu[T]) ItemEnabledAt(index int) bool

ItemEnabledAt returns whether the item at the specified index is enabled or not.

func (*PopupMenu[T]) RemoveAllItems

func (p *PopupMenu[T]) RemoveAllItems()

RemoveAllItems removes all items from the PopupMenu.

func (*PopupMenu[T]) RemoveItem

func (p *PopupMenu[T]) RemoveItem(item T)

RemoveItem from the PopupMenu.

func (*PopupMenu[T]) RemoveItemAt

func (p *PopupMenu[T]) RemoveItemAt(index int)

RemoveItemAt the specified index from the PopupMenu.

func (*PopupMenu[T]) Select

func (p *PopupMenu[T]) Select(item ...T)

Select one or more items, replacing any existing selection.

func (*PopupMenu[T]) SelectIndex

func (p *PopupMenu[T]) SelectIndex(index ...int)

SelectIndex selects one or more items by their indexes, replacing any existing selection.

func (*PopupMenu[T]) Selected

func (p *PopupMenu[T]) Selected() (item T, ok bool)

Selected returns the currently selected item. 'ok' will be false if there is no selection. The first selected item will be returned if there are multiple.

func (*PopupMenu[T]) SelectedIndex

func (p *PopupMenu[T]) SelectedIndex() int

SelectedIndex returns the currently selected item index. -1 will be returned if no selection is present. The first selected item will be returned if there are multiple.

func (*PopupMenu[T]) SelectedIndexes added in v0.51.0

func (p *PopupMenu[T]) SelectedIndexes() []int

SelectedIndexes returns the currently selected item indexes.

func (*PopupMenu[T]) SetItemAt

func (p *PopupMenu[T]) SetItemAt(index int, item T, enabled bool)

SetItemAt sets the item at the specified index.

func (*PopupMenu[T]) SetItemEnabledAt added in v0.75.0

func (p *PopupMenu[T]) SetItemEnabledAt(index int, enabled bool)

SetItemEnabledAt sets the enabled state of the item at the specified index.

func (*PopupMenu[T]) Text

func (p *PopupMenu[T]) Text() string

Text the currently shown text.

type PopupMenuTheme added in v0.4.0

type PopupMenuTheme struct {
	EdgeInk        Ink
	SelectionInk   Ink
	OnSelectionInk Ink
	TextDecoration
	CornerRadius float32
	HMargin      float32
	VMargin      float32
}

PopupMenuTheme holds theming data for a PopupMenu.

type ProgressBar

type ProgressBar struct {
	ProgressBarTheme
	Panel
	// contains filtered or unexported fields
}

ProgressBar provides a meter showing progress.

func NewProgressBar

func NewProgressBar(maximum float32) *ProgressBar

NewProgressBar creates a new progress bar. A max of zero will create an indeterminate progress bar, i.e. one whose meter animates back and forth.

func (*ProgressBar) Current

func (p *ProgressBar) Current() float32

Current returns the current value of the progress bar towards its maximum.

func (*ProgressBar) DefaultDraw

func (p *ProgressBar) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*ProgressBar) DefaultSizes

func (p *ProgressBar) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*ProgressBar) Maximum

func (p *ProgressBar) Maximum() float32

Maximum returns the maximum value of the progress bar.

func (*ProgressBar) SetCurrent

func (p *ProgressBar) SetCurrent(value float32)

SetCurrent sets the current value.

func (*ProgressBar) SetMaximum

func (p *ProgressBar) SetMaximum(value float32)

SetMaximum sets the maximum value.

type ProgressBarTheme added in v0.4.0

type ProgressBarTheme struct {
	BackgroundInk      Ink
	FillInk            Ink
	EdgeInk            Ink
	TickSpeed          time.Duration
	FullTraversalSpeed time.Duration
	PreferredBarHeight float32
	CornerRadius       float32
	IndeterminateWidth float32
	EdgeThickness      float32
}

ProgressBarTheme holds theming data for a ProgressBar.

type RadioButton

type RadioButton struct {
	ClickCallback func()
	Drawable      Drawable
	Text          *Text

	RadioButtonTheme
	Panel
	Pressed bool
	// contains filtered or unexported fields
}

RadioButton represents a clickable radio button with an optional label.

func NewRadioButton

func NewRadioButton() *RadioButton

NewRadioButton creates a new radio button.

func (*RadioButton) Click

func (r *RadioButton) Click()

Click makes the radio button behave as if a user clicked on it.

func (*RadioButton) DefaultDraw

func (r *RadioButton) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*RadioButton) DefaultFocusGained added in v0.16.0

func (r *RadioButton) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*RadioButton) DefaultKeyDown

func (r *RadioButton) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*RadioButton) DefaultMouseDown

func (r *RadioButton) DefaultMouseDown(_ Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*RadioButton) DefaultMouseDrag

func (r *RadioButton) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*RadioButton) DefaultMouseUp

func (r *RadioButton) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*RadioButton) DefaultSizes

func (r *RadioButton) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*RadioButton) DefaultUpdateCursor added in v0.44.0

func (r *RadioButton) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor for radio buttons.

func (*RadioButton) Group added in v0.69.0

func (r *RadioButton) Group() *Group

Group returns the group that this button is a part of.

func (*RadioButton) SetGroup added in v0.69.0

func (r *RadioButton) SetGroup(group *Group)

SetGroup sets the group that this button is a part of. Should only be called by the Group.

func (*RadioButton) SetTitle added in v0.69.0

func (r *RadioButton) SetTitle(text string)

SetTitle sets the text of the radio button to the specified text. The theme's TextDecoration will be used, so any changes you want to make to it should be done before calling this method. Alternatively, you can directly set the .Text field.

type RadioButtonTheme added in v0.4.0

type RadioButtonTheme struct {
	EdgeInk        Ink
	SelectionInk   Ink
	OnSelectionInk Ink
	TextDecoration
	Gap                float32
	CornerRadius       float32
	ClickAnimationTime time.Duration
	HAlign             align.Enum
	VAlign             align.Enum
	Side               side.Enum
}

RadioButtonTheme holds theming data for a RadioButton.

type Rect added in v0.13.0

type Rect = geom.Rect[float32]

Rect is an alias for geom.Rect[float32], for convenience.

func NewRect added in v0.13.0

func NewRect(x, y, width, height float32) Rect

NewRect creates a new Rect.

type SVG added in v0.3.0

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

SVG holds an SVG.

func MustSVG added in v0.44.0

func MustSVG(size Size, svgPathStr string) *SVG

MustSVG creates a new SVG the given svg path string (the contents of a single "d" attribute from an SVG "path" element) and panics if an error would be generated. The 'size' should be gotten from the original SVG's 'viewBox' parameter.

Note: It is probably better to use one of the other Must... methods that take the full SVG content.

func MustSVGFromContentString added in v0.61.0

func MustSVGFromContentString(content string, options ...SVGOption) *SVG

MustSVGFromContentString creates a new SVG and panics if an error would be generated. The content should contain valid SVG file data. Note that this only reads a very small subset of an SVG currently. Specifically, the "viewBox" attribute and any "d" attributes from enclosed SVG "path" elements.

func MustSVGFromReader added in v0.61.0

func MustSVGFromReader(r io.Reader, options ...SVGOption) *SVG

MustSVGFromReader creates a new SVG and panics if an error would be generated. The reader should contain valid SVG file data. Note that this only reads a very small subset of an SVG currently. Specifically, the "viewBox" attribute and any "d" attributes from enclosed SVG "path" elements.

func NewSVG added in v0.3.0

func NewSVG(size Size, svgPathStr string) (*SVG, error)

NewSVG creates a new SVG the given svg path string (the contents of a single "d" attribute from an SVG "path" element). The 'size' should be gotten from the original SVG's 'viewBox' parameter.

Note: It is probably better to use one of the other New... methods that take the full SVG content.

func NewSVGFromContentString added in v0.61.0

func NewSVGFromContentString(content string, options ...SVGOption) (*SVG, error)

NewSVGFromContentString creates a new SVG. The content should contain valid SVG file data. Note that this only reads a very small subset of an SVG currently. Specifically, the "viewBox" attribute and any "d" attributes from enclosed SVG "path" elements.

func NewSVGFromReader added in v0.61.0

func NewSVGFromReader(r io.Reader, options ...SVGOption) (*SVG, error)

NewSVGFromReader creates a new SVG. The reader should contain valid SVG file data. Note that this only reads a very small subset of an SVG currently. Specifically, the "viewBox" attribute and any "d" attributes from enclosed SVG "path" elements.

func (*SVG) AspectRatio added in v0.73.0

func (s *SVG) AspectRatio() float32

AspectRatio returns the SVG's width to height ratio.

func (*SVG) DrawInRect added in v0.73.0

func (s *SVG) DrawInRect(canvas *Canvas, rect Rect, _ *SamplingOptions, paint *Paint)

DrawInRect draws this SVG resized to fit in the given rectangle. If paint is not nil, the SVG paths will be drawn with the provided paint, ignoring any fill or stroke attributes within the source SVG. Be sure to set the Paint's style (fill or stroke) as desired.

func (*SVG) DrawInRectPreservingAspectRatio added in v0.73.0

func (s *SVG) DrawInRectPreservingAspectRatio(canvas *Canvas, rect Rect, opts *SamplingOptions, paint *Paint)

DrawInRectPreservingAspectRatio draws this SVG resized to fit in the given rectangle, preserving the aspect ratio. If paint is not nil, the SVG paths will be drawn with the provided paint, ignoring any fill or stroke attributes within the source SVG. Be sure to set the Paint's style (fill or stroke) as desired.

func (*SVG) OffsetToCenterWithinScaledSize added in v0.3.0

func (s *SVG) OffsetToCenterWithinScaledSize(size Size) Point

OffsetToCenterWithinScaledSize returns the scaled offset values to use to keep the image centered within the given size.

func (*SVG) Size added in v0.3.0

func (s *SVG) Size() Size

Size returns the original size.

type SVGOption added in v0.73.0

type SVGOption func(s *svgOptions) error

SVGOption is an option that may be passed to SVG construction functions.

func SVGOptionIgnoreParseErrors added in v0.73.0

func SVGOptionIgnoreParseErrors() SVGOption

SVGOptionIgnoreParseErrors is an option that will ignore some errors when parsing an SVG. If the XML is not well formed an error will still be generated.

func SVGOptionIgnoreUnsupported added in v0.73.0

func SVGOptionIgnoreUnsupported() SVGOption

SVGOptionIgnoreUnsupported is an option that will ignore unsupported SVG features that might be encountered in an SVG.

If this option is not present, then unsupported features will result in an error when constructing the SVG.

func SVGOptionWarnParseErrors added in v0.73.0

func SVGOptionWarnParseErrors() SVGOption

SVGOptionWarnParseErrors is an option that will issue warnings to the log for some errors when parsing an SVG. If the XML is not well formed an error will still be generated.

type SamplingOptions

type SamplingOptions struct {
	MaxAniso int32
	UseCubic bool

	CubicResampler CubicResampler
	FilterMode     filtermode.Enum
	MipMapMode     mipmapmode.Enum
	// contains filtered or unexported fields
}

SamplingOptions controls how images are sampled.

type SaveDialog

type SaveDialog interface {
	FileDialog
	// InitialFileName returns the initial file name that will be used.
	InitialFileName() string
	// SetInitialFileName sets the file name that should be used when the dialog is first presented.
	SetInitialFileName(name string)
}

SaveDialog represents a dialog that permits a user to select where to save a file.

func NewCommonSaveDialog

func NewCommonSaveDialog() SaveDialog

NewCommonSaveDialog creates a new SaveDialog. This is the fallback Go-only version of the SaveDialog used when a non-platform-native version doesn't exist. Where possible, use of NewSaveDialog() should be preferred, since platforms like macOS and Windows usually have restrictions on file access that their native dialogs automatically remove for the user.

func NewSaveDialog

func NewSaveDialog() SaveDialog

NewSaveDialog creates a new save dialog using native support where possible.

type ScrollBar

type ScrollBar struct {
	ChangedCallback func()
	ScrollBarTheme
	Panel
	// contains filtered or unexported fields
}

ScrollBar holds the data necessary for tracking a scroll bar's state.

func NewScrollBar

func NewScrollBar(horizontal bool) *ScrollBar

NewScrollBar creates a new scroll bar.

func (*ScrollBar) DefaultDraw

func (s *ScrollBar) DefaultDraw(gc *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*ScrollBar) DefaultMouseDown

func (s *ScrollBar) DefaultMouseDown(where Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*ScrollBar) DefaultMouseDrag

func (s *ScrollBar) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*ScrollBar) DefaultMouseEnter

func (s *ScrollBar) DefaultMouseEnter(where Point, _ Modifiers) bool

DefaultMouseEnter provides the default mouse enter handling.

func (*ScrollBar) DefaultMouseExit

func (s *ScrollBar) DefaultMouseExit() bool

DefaultMouseExit provides the default mouse enter handling.

func (*ScrollBar) DefaultMouseMove

func (s *ScrollBar) DefaultMouseMove(where Point, _ Modifiers) bool

DefaultMouseMove provides the default mouse move handling.

func (*ScrollBar) DefaultMouseUp

func (s *ScrollBar) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*ScrollBar) DefaultSizes

func (s *ScrollBar) DefaultSizes(_ Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*ScrollBar) Extent

func (s *ScrollBar) Extent() float32

Extent returns the amount of space representing the visible content area.

func (*ScrollBar) Horizontal

func (s *ScrollBar) Horizontal() bool

Horizontal returns true if this is a horizontal scroll bar.

func (*ScrollBar) Max

func (s *ScrollBar) Max() float32

Max returns the amount of space representing the whole content area.

func (*ScrollBar) MaxValue

func (s *ScrollBar) MaxValue() float32

MaxValue returns the maximum value that can be set without adjusting the extent or max.

func (*ScrollBar) SetRange

func (s *ScrollBar) SetRange(value, extent, maximum float32)

SetRange sets the value, extent and max values.

func (*ScrollBar) Thumb

func (s *ScrollBar) Thumb() Rect

Thumb returns the location of the thumb.

func (*ScrollBar) Value

func (s *ScrollBar) Value() float32

Value returns the current value.

func (*ScrollBar) Vertical

func (s *ScrollBar) Vertical() bool

Vertical returns true if this is a vertical scroll bar.

type ScrollBarTheme added in v0.4.0

type ScrollBarTheme struct {
	EdgeInk          Ink
	ThumbInk         Ink
	MinimumThickness float32
	MinimumThumb     float32
	ThumbIndent      float32
	CornerRadius     float32
}

ScrollBarTheme holds theming data for a ScrollBar.

type ScrollPanel

type ScrollPanel struct {
	ScrollPanelTheme
	Panel
	// contains filtered or unexported fields
}

ScrollPanel provides a scrollable area.

func NewScrollPanel

func NewScrollPanel() *ScrollPanel

NewScrollPanel creates a new scrollable area.

func (*ScrollPanel) Bar

func (s *ScrollPanel) Bar(horizontal bool) *ScrollBar

Bar returns the specified scroll bar.

func (*ScrollPanel) ColumnHeader

func (s *ScrollPanel) ColumnHeader() Paneler

ColumnHeader returns the current column header, if any.

func (*ScrollPanel) ColumnHeaderView added in v0.7.0

func (s *ScrollPanel) ColumnHeaderView() *Panel

ColumnHeaderView returns the column header view port. May be nil, if there is no column header.

func (*ScrollPanel) Content

func (s *ScrollPanel) Content() Paneler

Content returns the content panel.

func (*ScrollPanel) ContentView added in v0.7.0

func (s *ScrollPanel) ContentView() *Panel

ContentView returns the content view port.

func (*ScrollPanel) DefaultDraw

func (s *ScrollPanel) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*ScrollPanel) DefaultFrameChangeInChildHierarchy

func (s *ScrollPanel) DefaultFrameChangeInChildHierarchy(_ *Panel)

DefaultFrameChangeInChildHierarchy provides the default frame change in child hierarchy handling.

func (*ScrollPanel) DefaultKeyDown added in v0.63.0

func (s *ScrollPanel) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*ScrollPanel) DefaultMouseWheel

func (s *ScrollPanel) DefaultMouseWheel(_, delta Point, _ Modifiers) bool

DefaultMouseWheel provides the default mouse wheel handling.

func (*ScrollPanel) DefaultScrollRectIntoView

func (s *ScrollPanel) DefaultScrollRectIntoView(rect Rect) bool

DefaultScrollRectIntoView provides the default scroll rect into contentView handling.

func (*ScrollPanel) LayoutSizes

func (s *ScrollPanel) LayoutSizes(_ *Panel, hint Size) (minSize, prefSize, maxSize Size)

LayoutSizes implements the Layout interface.

func (*ScrollPanel) PerformLayout

func (s *ScrollPanel) PerformLayout(_ *Panel)

PerformLayout implements the Layout interface.

func (*ScrollPanel) Position

func (s *ScrollPanel) Position() (h, v float32)

Position returns the current scroll position.

func (*ScrollPanel) RowHeader

func (s *ScrollPanel) RowHeader() Paneler

RowHeader returns the current row header, if any.

func (*ScrollPanel) RowHeaderView added in v0.7.0

func (s *ScrollPanel) RowHeaderView() *Panel

RowHeaderView returns the row header view port. May be nil, if there is no row header.

func (*ScrollPanel) SetColumnHeader

func (s *ScrollPanel) SetColumnHeader(p Paneler)

SetColumnHeader sets the current column header. May be nil.

func (*ScrollPanel) SetContent

func (s *ScrollPanel) SetContent(p Paneler, widthBehavior, heightBehavior behavior.Enum)

SetContent sets the content panel.

func (*ScrollPanel) SetPosition

func (s *ScrollPanel) SetPosition(h, v float32)

SetPosition sets the current scroll position.

func (*ScrollPanel) SetRowHeader

func (s *ScrollPanel) SetRowHeader(p Paneler)

SetRowHeader sets the current row header. May be nil.

func (*ScrollPanel) Sync added in v0.8.0

func (s *ScrollPanel) Sync()

Sync the headers and content with the current scroll state.

type ScrollPanelTheme added in v0.4.0

type ScrollPanelTheme struct {
	BackgroundInk        Ink
	MouseWheelMultiplier func() float32
}

ScrollPanelTheme holds theming data for a ScrollPanel.

type Separator

type Separator struct {
	SeparatorTheme
	Panel
}

Separator provides a simple vertical or horizontal separator line.

func NewSeparator

func NewSeparator() *Separator

NewSeparator creates a new separator line.

func (*Separator) DefaultDraw

func (s *Separator) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Separator) DefaultSizes

func (s *Separator) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

type SeparatorTheme added in v0.4.0

type SeparatorTheme struct {
	LineInk  Ink
	Vertical bool
}

SeparatorTheme holds theming data for a Separator.

type Shader

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

Shader specifies the source color(s) for what is being drawn. If a paint has no shader, then the paint's color is used. If the paint has a shader, then the shader's color(s) are use instead, but they are modulated by the paint's alpha. This makes it easy to create a shader once (e.g. bitmap tiling or gradient) and then change its transparency without having to modify the original shader... only the paint's alpha needs to be modified.

func New2PtConicalGradientShader

func New2PtConicalGradientShader(startPt, endPt Point, startRadius, endRadius float32, colors []Color, colorPos []float32, tileMode tilemode.Enum, matrix Matrix) *Shader

New2PtConicalGradientShader creates a new 2-point conical gradient Shader. matrix may be nil.

func NewBlendShader

func NewBlendShader(blendMode blendmode.Enum, dst, src *Shader) *Shader

NewBlendShader creates a new blend Shader.

func NewColorShader

func NewColorShader(color Color) *Shader

NewColorShader creates a new color Shader.

func NewFractalPerlinNoiseShader

func NewFractalPerlinNoiseShader(baseFreqX, baseFreqY, seed float32, numOctaves, tileWidth, tileHeight int) *Shader

NewFractalPerlinNoiseShader creates a new fractal perlin noise Shader.

func NewImageShader

func NewImageShader(canvas *Canvas, img *Image, tileModeX, tileModeY tilemode.Enum, sampling *SamplingOptions, matrix Matrix) *Shader

NewImageShader creates a new image Shader. If canvas is not nil, a hardware-accellerated image will be used if possible.

func NewLinearGradientShader

func NewLinearGradientShader(start, end Point, colors []Color, colorPos []float32, tileMode tilemode.Enum, matrix Matrix) *Shader

NewLinearGradientShader creates a new linear gradient Shader. matrix may be nil.

func NewRadialGradientShader

func NewRadialGradientShader(center Point, radius float32, colors []Color, colorPos []float32, tileMode tilemode.Enum, matrix Matrix) *Shader

NewRadialGradientShader creates a new radial gradient Shader. matrix may be nil.

func NewSweepGradientShader

func NewSweepGradientShader(center Point, startAngle, endAngle float32, colors []Color, colorPos []float32, tileMode tilemode.Enum, matrix Matrix) *Shader

NewSweepGradientShader creates a new sweep gradient Shader. matrix may be nil.

func NewTurbulencePerlinNoiseShader

func NewTurbulencePerlinNoiseShader(baseFreqX, baseFreqY, seed float32, numOctaves, tileWidth, tileHeight int) *Shader

NewTurbulencePerlinNoiseShader creates a new turbulence perlin noise Shader.

func (*Shader) NewWithColorFilter

func (s *Shader) NewWithColorFilter(filter *ColorFilter) *Shader

NewWithColorFilter creates a new copy of this shader with a color filter applied.

func (*Shader) NewWithLocalMatrix

func (s *Shader) NewWithLocalMatrix(matrix Matrix) *Shader

NewWithLocalMatrix creates a new copy of this shader with a local matrix applied.

type SimpleTableModel added in v0.20.0

type SimpleTableModel[T TableRowConstraint[T]] struct {
	// contains filtered or unexported fields
}

SimpleTableModel is a simple implementation of TableModel.

func (*SimpleTableModel[T]) RootRowCount added in v0.20.0

func (m *SimpleTableModel[T]) RootRowCount() int

RootRowCount implements TableModel.

func (*SimpleTableModel[T]) RootRows added in v0.20.0

func (m *SimpleTableModel[T]) RootRows() []T

RootRows implements TableModel.

func (*SimpleTableModel[T]) SetRootRows added in v0.20.0

func (m *SimpleTableModel[T]) SetRootRows(rows []T)

SetRootRows implements TableModel.

type Size added in v0.13.0

type Size = geom.Size[float32]

Size is an alias for geom.Size[float32], for convenience.

func LabelContentSizes added in v0.69.0

func LabelContentSizes(text *Text, drawable Drawable, font Font, drawableSide side.Enum, gap float32) (size, txtSize Size)

LabelContentSizes returns the preferred size of a label, as well as the preferred size of the text within the label. When no drawable is present, the two values will be the same. Provided as a standalone function so that other types of panels can make use of it.

func MaxSize

func MaxSize(size Size) Size

MaxSize returns the size that is at least as large as DefaultMaxSize in both dimensions, but larger if the size that is passed in is larger.

func NewSize added in v0.13.0

func NewSize(width, height float32) Size

NewSize creates a new Size.

type SizedDrawable added in v0.57.0

type SizedDrawable struct {
	Drawable Drawable
	Size     Size
}

SizedDrawable allows the Drawable's logical size to be overridden.

func (*SizedDrawable) DrawInRect added in v0.57.0

func (d *SizedDrawable) DrawInRect(canvas *Canvas, rect Rect, sampling *SamplingOptions, paint *Paint)

DrawInRect implements Drawable.

func (*SizedDrawable) LogicalSize added in v0.57.0

func (d *SizedDrawable) LogicalSize() Size

LogicalSize implements Drawable.

type Sizer

type Sizer func(hint Size) (minSize, prefSize, maxSize Size)

Sizer returns minimum, preferred, and maximum sizes. The hint will contain values other than zero for a dimension that has already been determined.

type SortState added in v0.3.0

type SortState struct {
	Order     int // A negative value indicates it isn't participating at the moment.
	Ascending bool
	Sortable  bool // A false value indicates it is not sortable at all
}

SortState holds data regarding a sort state.

type StartupOption

type StartupOption func(startupOption) error

StartupOption holds an option for application startup.

func AllowQuitCallback

func AllowQuitCallback(f func() bool) StartupOption

AllowQuitCallback will cause f to be called when app termination has been requested. Return true to permit the request. By default, app termination requests are permitted.

func NoGlobalMenuBar

func NoGlobalMenuBar() StartupOption

NoGlobalMenuBar will disable the global menu bar on platforms that normally use it, instead using the in-window menu bar.

func OpenFilesCallback added in v0.5.0

func OpenFilesCallback(f func(urls []string)) StartupOption

OpenFilesCallback will cause f to be called when the application is asked to open one or more files by the OS or an external application. By default, nothing is done with the request.

func QuitAfterLastWindowClosedCallback

func QuitAfterLastWindowClosedCallback(f func() bool) StartupOption

QuitAfterLastWindowClosedCallback will cause f to be called when the last window is closed to determine if the application should quit as a result. By default, the app will terminate when the last window is closed.

func QuittingCallback

func QuittingCallback(f func()) StartupOption

QuittingCallback will cause f to be called just before the app terminates.

func RecoveryCallback

func RecoveryCallback(f errs.RecoveryHandler) StartupOption

RecoveryCallback will cause f to be called should a task invoked via task.InvokeTask() or task.InvokeTaskAfter() panic. If no recovery callback is set, the panic will be logged via errs.Log(err).

func StartupFinishedCallback

func StartupFinishedCallback(f func()) StartupOption

StartupFinishedCallback will cause f to be called once application startup has completed and it is about to start servicing the event loop. You should create your app's windows at this point.

func ThemeChangedCallback

func ThemeChangedCallback(f func()) StartupOption

ThemeChangedCallback will cause f to be called when the theme is changed. This occurs after the colors have been updated, but before any windows have been redraw.

type Stop

type Stop struct {
	Color    ColorProvider
	Location float32
}

Stop provides information about the color and position of one 'color stop' in a gradient.

func (Stop) String

func (s Stop) String() string

type Stream added in v0.29.0

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

Stream provides a way to use different streams for the same purpose. These streams currently only exist for Skia's PDF support, which requires a stream to write to.

type TabCloser added in v0.3.0

type TabCloser interface {
	// MayAttemptClose returns true if a call to AttemptClose() is permitted.
	MayAttemptClose() bool
	// AttemptClose attempts to close the tab. On success, returns true.
	AttemptClose() bool
}

TabCloser defines the methods that must be implemented to cause the tabs to show a close button.

type Table added in v0.3.0

type Table[T TableRowConstraint[T]] struct {
	SelectionChangedCallback func()
	DoubleClickCallback      func()
	DragRemovedRowsCallback  func() // Called whenever a drag removes one or more rows from a model, but only if the source and destination tables were different.
	DropOccurredCallback     func() // Called whenever a drop occurs that modifies the model.
	Columns                  []ColumnInfo
	Model                    TableModel[T]

	TableTheme
	Panel

	PreventUserColumnResize bool
	// contains filtered or unexported fields
}

Table provides a control that can display data in columns and rows.

func NewTable added in v0.3.0

func NewTable[T TableRowConstraint[T]](model TableModel[T]) *Table[T]

NewTable creates a new Table control.

func (*Table[T]) ApplyFilter added in v0.37.0

func (t *Table[T]) ApplyFilter(filter func(row T) bool)

ApplyFilter applies a filter to the data. When a non-nil filter is applied, all rows (recursively) are passed through the filter. Only those that the filter returns false for will be visible in the table. When a filter is applied, no hierarchy is display and no modifications to the row data should be performed.

func (*Table[T]) CellFrame added in v0.3.0

func (t *Table[T]) CellFrame(row, col int) Rect

CellFrame returns the frame of the given cell.

func (*Table[T]) CellWidth added in v0.6.0

func (t *Table[T]) CellWidth(row, col int) float32

CellWidth returns the current width of a given cell.

func (*Table[T]) ClearDrawRowRange added in v0.29.0

func (t *Table[T]) ClearDrawRowRange()

ClearDrawRowRange clears any restricted range for sizing and drawing the table.

func (*Table[T]) ClearSelection added in v0.7.0

func (t *Table[T]) ClearSelection()

ClearSelection clears the selection.

func (*Table[T]) ColumnEdges added in v0.20.0

func (t *Table[T]) ColumnEdges(col int) (left, right float32)

ColumnEdges returns the x-coordinates of the left and right sides of the column.

func (*Table[T]) ColumnIndexForID added in v0.50.0

func (t *Table[T]) ColumnIndexForID(id int) int

ColumnIndexForID returns the column index with the given ID, or -1 if not found.

func (*Table[T]) CopySelectionMap added in v0.21.0

func (t *Table[T]) CopySelectionMap() map[tid.TID]bool

CopySelectionMap returns a copy of the current selection map.

func (*Table[T]) CurrentDrawRowRange added in v0.29.0

func (t *Table[T]) CurrentDrawRowRange() (start, endBefore int)

CurrentDrawRowRange returns the range of rows that are considered for sizing and drawing.

func (*Table[T]) DefaultDraw added in v0.3.0

func (t *Table[T]) DefaultDraw(canvas *Canvas, dirty Rect)

DefaultDraw provides the default drawing.

func (*Table[T]) DefaultFocusGained added in v0.16.0

func (t *Table[T]) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*Table[T]) DefaultKeyDown added in v0.21.0

func (t *Table[T]) DefaultKeyDown(keyCode KeyCode, mod Modifiers, repeat bool) bool

DefaultKeyDown provides the default key down handling.

func (*Table[T]) DefaultMouseDown added in v0.3.0

func (t *Table[T]) DefaultMouseDown(where Point, button, clickCount int, mod Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*Table[T]) DefaultMouseDrag added in v0.3.0

func (t *Table[T]) DefaultMouseDrag(where Point, button int, mod Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*Table[T]) DefaultMouseEnter added in v0.7.0

func (t *Table[T]) DefaultMouseEnter(where Point, mod Modifiers) bool

DefaultMouseEnter provides the default mouse enter handling.

func (*Table[T]) DefaultMouseExit added in v0.7.0

func (t *Table[T]) DefaultMouseExit() bool

DefaultMouseExit provides the default mouse exit handling.

func (*Table[T]) DefaultMouseMove added in v0.3.0

func (t *Table[T]) DefaultMouseMove(where Point, mod Modifiers) bool

DefaultMouseMove provides the default mouse move handling.

func (*Table[T]) DefaultMouseUp added in v0.3.0

func (t *Table[T]) DefaultMouseUp(where Point, button int, mod Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*Table[T]) DefaultSizes added in v0.3.0

func (t *Table[T]) DefaultSizes(_ Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Table[T]) DefaultUpdateCursorCallback added in v0.3.0

func (t *Table[T]) DefaultUpdateCursorCallback(where Point) *Cursor

DefaultUpdateCursorCallback provides the default cursor update handling.

func (*Table[T]) DefaultUpdateTooltipCallback added in v0.3.0

func (t *Table[T]) DefaultUpdateTooltipCallback(where Point, avoid Rect) Rect

DefaultUpdateTooltipCallback provides the default tooltip update handling.

func (*Table[T]) DeselectByIndex added in v0.7.0

func (t *Table[T]) DeselectByIndex(indexes ...int)

DeselectByIndex deselects the given indexes.

func (*Table[T]) DeselectRange added in v0.21.0

func (t *Table[T]) DeselectRange(start, end int)

DeselectRange deselects the given range.

func (*Table[T]) DiscloseRow added in v0.7.0

func (t *Table[T]) DiscloseRow(row T, delaySync bool) bool

DiscloseRow ensures the given row can be viewed by opening all parents that lead to it. Returns true if any modification was made.

func (*Table[T]) EventuallySizeColumnsToFit added in v0.3.0

func (t *Table[T]) EventuallySizeColumnsToFit(adjust bool)

EventuallySizeColumnsToFit sizes each column to its preferred size after a short delay, allowing multiple back-to-back calls to this function to only do work once. If 'adjust' is true, the Table's FrameRect will be set to its preferred size as well.

func (*Table[T]) EventuallySyncToModel added in v0.6.0

func (t *Table[T]) EventuallySyncToModel()

EventuallySyncToModel syncs the table to its underlying model after a short delay, allowing multiple back-to-back calls to this function to only do work once.

func (*Table[T]) FirstSelectedRowIndex added in v0.17.0

func (t *Table[T]) FirstSelectedRowIndex() int

FirstSelectedRowIndex returns the first selected row index, or -1 if there is no selection.

func (*Table[T]) HasSelection added in v0.17.0

func (t *Table[T]) HasSelection() bool

HasSelection returns true if there is a selection.

func (*Table[T]) InstallDragSupport added in v0.20.0

func (t *Table[T]) InstallDragSupport(svg *SVG, dragKey, singularName, pluralName string)

InstallDragSupport installs default drag support into a table. This will chain a function to any existing MouseDragCallback.

func (*Table[T]) IsFiltered added in v0.37.0

func (t *Table[T]) IsFiltered() bool

IsFiltered returns true if a filter is currently applied. When a filter is applied, no hierarchy is display and no modifications to the row data should be performed.

func (*Table[T]) IsRowOrAnyParentSelected added in v0.3.0

func (t *Table[T]) IsRowOrAnyParentSelected(index int) bool

IsRowOrAnyParentSelected returns true if the specified row index or any of its parents are selected.

func (*Table[T]) IsRowSelected added in v0.7.0

func (t *Table[T]) IsRowSelected(index int) bool

IsRowSelected returns true if the specified row index is selected.

func (*Table[T]) LastRowIndex added in v0.20.0

func (t *Table[T]) LastRowIndex() int

LastRowIndex returns the index of the last row. Will be -1 if there are no rows.

func (*Table[T]) LastSelectedRowIndex added in v0.17.0

func (t *Table[T]) LastSelectedRowIndex() int

LastSelectedRowIndex returns the last selected row index, or -1 if there is no selection.

func (*Table[T]) OverColumn added in v0.3.0

func (t *Table[T]) OverColumn(x float32) int

OverColumn returns the column index that the x coordinate is over, or -1 if it isn't over any column.

func (*Table[T]) OverColumnDivider added in v0.3.0

func (t *Table[T]) OverColumnDivider(x float32) int

OverColumnDivider returns the column index of the column divider that the x coordinate is over, or -1 if it isn't over any column divider.

func (*Table[T]) OverRow added in v0.3.0

func (t *Table[T]) OverRow(y float32) int

OverRow returns the row index that the y coordinate is over, or -1 if it isn't over any row.

func (*Table[T]) PruneSelectionOfUndisclosedNodes added in v0.27.0

func (t *Table[T]) PruneSelectionOfUndisclosedNodes()

PruneSelectionOfUndisclosedNodes removes any nodes in the selection map that are no longer disclosed from the selection map.

func (*Table[T]) RootRowCount added in v0.20.0

func (t *Table[T]) RootRowCount() int

RootRowCount returns the number of top-level rows.

func (*Table[T]) RootRows added in v0.20.0

func (t *Table[T]) RootRows() []T

RootRows returns the top-level rows. Do not alter the returned list.

func (*Table[T]) RowFrame added in v0.7.0

func (t *Table[T]) RowFrame(row int) Rect

RowFrame returns the frame of the row.

func (*Table[T]) RowFromIndex added in v0.17.0

func (t *Table[T]) RowFromIndex(index int) T

RowFromIndex returns the row data for the given index.

func (*Table[T]) RowHeights added in v0.29.0

func (t *Table[T]) RowHeights() []float32

RowHeights returns the heights of each row.

func (*Table[T]) RowToIndex added in v0.7.0

func (t *Table[T]) RowToIndex(rowData T) int

RowToIndex returns the row's index within the displayed data, or -1 if it isn't currently in the disclosed rows.

func (*Table[T]) ScrollRowCellIntoView added in v0.17.0

func (t *Table[T]) ScrollRowCellIntoView(row, col int)

ScrollRowCellIntoView scrolls the cell from the row and column at the given indexes into view.

func (*Table[T]) ScrollRowIntoView added in v0.7.0

func (t *Table[T]) ScrollRowIntoView(row int)

ScrollRowIntoView scrolls the row at the given index into view.

func (*Table[T]) SelectAll added in v0.20.0

func (t *Table[T]) SelectAll()

SelectAll selects all rows.

func (*Table[T]) SelectByIndex added in v0.7.0

func (t *Table[T]) SelectByIndex(indexes ...int)

SelectByIndex selects the given indexes. The first one will be considered the anchor selection if no existing anchor selection exists.

func (*Table[T]) SelectRange added in v0.21.0

func (t *Table[T]) SelectRange(start, end int)

SelectRange selects the given range. The start will be considered the anchor selection if no existing anchor selection exists.

func (*Table[T]) SelectedRows added in v0.4.0

func (t *Table[T]) SelectedRows(minimal bool) []T

SelectedRows returns the currently selected rows. If 'minimal' is true, then children of selected rows that may also be selected are not returned, just the topmost row that is selected in any given hierarchy.

func (*Table[T]) SelectionCount added in v0.26.0

func (t *Table[T]) SelectionCount() int

SelectionCount returns the number of rows explicitly selected.

func (*Table[T]) SetDrawRowRange added in v0.29.0

func (t *Table[T]) SetDrawRowRange(start, endBefore int)

SetDrawRowRange sets a restricted range for sizing and drawing the table. This is intended primarily to be able to draw different sections of the table on separate pages of a display and should not be used for anything requiring interactivity.

func (*Table[T]) SetRootRows added in v0.20.0

func (t *Table[T]) SetRootRows(rows []T)

SetRootRows sets the top-level rows this table will display. This will call SyncToModel() automatically.

func (*Table[T]) SetSelectionMap added in v0.21.0

func (t *Table[T]) SetSelectionMap(selMap map[tid.TID]bool)

SetSelectionMap sets the current selection map.

func (*Table[T]) SizeColumnToFit added in v0.3.0

func (t *Table[T]) SizeColumnToFit(col int, adjust bool)

SizeColumnToFit sizes the specified column to its preferred size. If 'adjust' is true, the Table's FrameRect will be set to its preferred size as well.

func (*Table[T]) SizeColumnsToFit added in v0.3.0

func (t *Table[T]) SizeColumnsToFit(adjust bool)

SizeColumnsToFit sizes each column to its preferred size. If 'adjust' is true, the Table's FrameRect will be set to its preferred size as well.

func (*Table[T]) SizeColumnsToFitWithExcessIn added in v0.10.0

func (t *Table[T]) SizeColumnsToFitWithExcessIn(columnID int)

SizeColumnsToFitWithExcessIn sizes each column to its preferred size, with the exception of the column with the given ID, which gets set to any remaining width left over. If the provided column ID doesn't exist, the first column will be used instead.

func (*Table[T]) SyncToModel added in v0.3.0

func (t *Table[T]) SyncToModel()

SyncToModel causes the table to update its internal caches to reflect the current model.

type TableColumnHeader added in v0.3.0

type TableColumnHeader[T TableRowConstraint[T]] interface {
	Paneler
	SortState() SortState
	SetSortState(state SortState)
	Less() func(a, b string) bool // May return nil -- if so, the Less() from the table header will be used
}

TableColumnHeader defines the methods a table column header must implement.

type TableDragData added in v0.20.0

type TableDragData[T TableRowConstraint[T]] struct {
	Table *Table[T]
	Rows  []T
}

TableDragData holds the data from a table row drag.

type TableDrop added in v0.20.0

type TableDrop[T TableRowConstraint[T], U any] struct {
	Table         *Table[T]
	TableDragData *TableDragData[T]
	AllDragData   map[string]any

	TargetParent T
	DragKey      string
	TargetIndex  int
	// contains filtered or unexported fields
}

TableDrop provides default support for dropping data into a table. This should only be instantiated by a call to Table.InstallDropSupport().

func InstallDropSupport added in v0.20.0

func InstallDropSupport[T TableRowConstraint[T], U any](t *Table[T], dragKey string, shouldMoveDataCallback func(from, to *Table[T]) bool, willDropCallback func(from, to *Table[T], move bool) *UndoEdit[U], didDropCallback func(undo *UndoEdit[U], from, to *Table[T], move bool)) *TableDrop[T, U]

InstallDropSupport installs default drop support into a table. This will replace any existing DataDragOverCallback, DataDragExitCallback, and DataDragDropCallback functions. It will also chain a function to any existing DrawOverCallback. The shouldMoveDataCallback is called when a drop is about to occur to determine if the data should be moved (i.e. removed from the source) or copied to the destination. The willDropCallback is called before the actual data changes are made, giving an opportunity to start an undo event, which should be returned. The didDropCallback is called after data changes are made and is passed the undo event (if any) returned by the willDropCallback, so that the undo event can be completed and posted.

func (*TableDrop[T, U]) DataDragDropCallback added in v0.20.0

func (d *TableDrop[T, U]) DataDragDropCallback(_ Point, data map[string]any)

DataDragDropCallback handles processing a drop.

func (*TableDrop[T, U]) DataDragExitCallback added in v0.20.0

func (d *TableDrop[T, U]) DataDragExitCallback()

DataDragExitCallback handles resetting the state when a drag is no longer of interest.

func (*TableDrop[T, U]) DataDragOverCallback added in v0.20.0

func (d *TableDrop[T, U]) DataDragOverCallback(where Point, data map[string]any) bool

DataDragOverCallback handles determining if a given drag is one that we are interested in.

func (*TableDrop[T, U]) DrawOverCallback added in v0.20.0

func (d *TableDrop[T, U]) DrawOverCallback(gc *Canvas, rect Rect)

DrawOverCallback handles drawing the drop zone feedback.

type TableHeader added in v0.3.0

type TableHeader[T TableRowConstraint[T]] struct {
	ColumnHeaders []TableColumnHeader[T]
	Less          func(s1, s2 string) bool
	TableHeaderTheme
	Panel
	// contains filtered or unexported fields
}

TableHeader provides a header for a Table.

func NewTableHeader added in v0.3.0

func NewTableHeader[T TableRowConstraint[T]](table *Table[T], columnHeaders ...TableColumnHeader[T]) *TableHeader[T]

NewTableHeader creates a new TableHeader.

func (*TableHeader[T]) ApplySort added in v0.3.0

func (h *TableHeader[T]) ApplySort()

ApplySort sorts the table according to the current sort criteria.

func (*TableHeader[T]) ColumnFrame added in v0.3.0

func (h *TableHeader[T]) ColumnFrame(col int) Rect

ColumnFrame returns the frame of the given column.

func (*TableHeader[T]) DefaultDraw added in v0.3.0

func (h *TableHeader[T]) DefaultDraw(canvas *Canvas, dirty Rect)

DefaultDraw provides the default drawing.

func (*TableHeader[T]) DefaultMouseDown added in v0.3.0

func (h *TableHeader[T]) DefaultMouseDown(where Point, button, clickCount int, mod Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*TableHeader[T]) DefaultMouseDrag added in v0.3.0

func (h *TableHeader[T]) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*TableHeader[T]) DefaultMouseMove added in v0.3.0

func (h *TableHeader[T]) DefaultMouseMove(where Point, mod Modifiers) bool

DefaultMouseMove provides the default mouse move handling.

func (*TableHeader[T]) DefaultMouseUp added in v0.3.0

func (h *TableHeader[T]) DefaultMouseUp(where Point, button int, mod Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*TableHeader[T]) DefaultSizes added in v0.3.0

func (h *TableHeader[T]) DefaultSizes(_ Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*TableHeader[T]) DefaultUpdateCursorCallback added in v0.3.0

func (h *TableHeader[T]) DefaultUpdateCursorCallback(where Point) *Cursor

DefaultUpdateCursorCallback provides the default cursor update handling.

func (*TableHeader[T]) DefaultUpdateTooltipCallback added in v0.3.0

func (h *TableHeader[T]) DefaultUpdateTooltipCallback(where Point, _ Rect) Rect

DefaultUpdateTooltipCallback provides the default tooltip update handling.

func (*TableHeader[T]) HasSort added in v0.37.0

func (h *TableHeader[T]) HasSort() bool

HasSort returns true if at least one column is marked for sorting.

func (*TableHeader[T]) SortOn added in v0.3.0

func (h *TableHeader[T]) SortOn(header TableColumnHeader[T])

SortOn adjusts the sort such that the specified header is the primary sort column. If the header was already the primary sort column, then its ascending/descending flag will be flipped instead.

type TableHeaderTheme added in v0.4.0

type TableHeaderTheme struct {
	BackgroundInk        Ink
	InteriorDividerColor Ink
	HeaderBorder         Border
}

TableHeaderTheme holds theming data for a TableHeader.

type TableModel added in v0.20.0

type TableModel[T TableRowConstraint[T]] interface {
	// RootRowCount returns the number of top-level rows.
	RootRowCount() int
	// RootRows returns the top-level rows. Do not alter the returned list.
	RootRows() []T
	// SetRootRows sets the top-level rows this table will display. After calling this method, any tables using this
	// model should have their SyncToModel() method called.
	SetRootRows(rows []T)
}

TableModel provides access to the root nodes of the table's data underlying model.

type TableRowConstraint added in v0.20.0

type TableRowConstraint[T any] interface {
	comparable
	TableRowData[T]
}

TableRowConstraint defines the constraints required of the data type used for data rows in tables.

type TableRowData added in v0.3.0

type TableRowData[T any] interface {
	// CloneForTarget creates a duplicate of this row with its parent set to 'newParent'. 'target' is the table that the
	// row will be placed within. Limitations in the way generics work in Go prevent this from being declared as a
	// *Table.
	CloneForTarget(target Paneler, newParent T) T
	// ID returns the ID of this data.
	ID() tid.TID
	// Parent returns the parent of this row, or nil if it is a root node.
	Parent() T
	// SetParent sets the parent of this row. parent will be nil if this is a top-level row.
	SetParent(parent T)
	// CanHaveChildren returns true if this row can have children, even if it currently does not have any.
	CanHaveChildren() bool
	// Children returns the child rows.
	Children() []T
	// SetChildren sets the children of this row.
	SetChildren(children []T)
	// CellDataForSort returns the string that represents the data in the specified cell.
	CellDataForSort(col int) string
	// ColumnCell returns the panel that should be placed at the position of the cell for the given column index. If you
	// need for the cell to retain widget state, make sure to return the same widget each time rather than creating a
	// new one.
	ColumnCell(row, col int, foreground, background Ink, selected, indirectlySelected, focused bool) Paneler
	// IsOpen returns true if the row can have children and is currently showing its children.
	IsOpen() bool
	// SetOpen sets the row's open state.
	SetOpen(open bool)
}

TableRowData provides information about a single row of data.

type TableTheme added in v0.4.0

type TableTheme struct {
	BackgroundInk          Ink
	OnBackgroundInk        Ink
	BandingInk             Ink
	OnBandingInk           Ink
	InteriorDividerInk     Ink
	SelectionInk           Ink
	OnSelectionInk         Ink
	InactiveSelectionInk   Ink
	OnInactiveSelectionInk Ink
	IndirectSelectionInk   Ink
	OnIndirectSelectionInk Ink
	Padding                Insets
	HierarchyColumnID      int
	HierarchyIndent        float32
	MinimumRowHeight       float32
	ColumnResizeSlop       float32
	ShowRowDivider         bool
	ShowColumnDivider      bool
}

TableTheme holds theming data for a Table.

type Tag added in v0.58.0

type Tag struct {
	Drawable Drawable
	Text     *Text
	TagTheme
	Panel
}

Tag represents non-interactive text and/or a Drawable with a bubble around it.

func NewTag added in v0.58.0

func NewTag() *Tag

NewTag creates a new, empty Tag.

func (*Tag) DefaultDraw added in v0.58.0

func (t *Tag) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Tag) DefaultSizes added in v0.58.0

func (t *Tag) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Tag) SetTitle added in v0.69.0

func (t *Tag) SetTitle(text string)

SetTitle sets the text of the tag to the specified text. The theme's TextDecoration will be used, so any changes you want to make to it should be done before calling this method. Alternatively, you can directly set the .Text field.

type TagTheme added in v0.58.0

type TagTheme struct {
	TextDecoration
	Gap       float32
	SideInset float32
	RadiusX   float32
	RadiusY   float32
	HAlign    align.Enum
	VAlign    align.Enum
	Side      side.Enum
}

TagTheme holds theming data for a Tag.

type Text

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

Text holds data necessary to draw a string using font fallbacks where necessary.

func NewSmallCapsText added in v0.69.0

func NewSmallCapsText(text string, decoration *TextDecoration) *Text

NewSmallCapsText creates a new Text object with the given text, but with lowercase letters replaced by small caps.

func NewText

func NewText(str string, decoration *TextDecoration) *Text

NewText creates a new Text. Note that tabs and line endings are not considered.

func NewTextFromRunes added in v0.7.0

func NewTextFromRunes(runes []rune, decoration *TextDecoration) *Text

NewTextFromRunes creates a new Text. Note that tabs and line endings are not considered. This is more efficient than NewText(), since the string doesn't have to be converted to runes first.

func NewTextLines added in v0.7.0

func NewTextLines(text string, decoration *TextDecoration) []*Text

NewTextLines creates a new list of Text, one for each logical line. Tabs are not considered, but the text is split on any line feeds found.

func NewTextWrappedLines added in v0.7.0

func NewTextWrappedLines(text string, decoration *TextDecoration, width float32) []*Text

NewTextWrappedLines creates a new list of Text, potentially multiple for each logical line. Tabs are not considered, but the text is split on any line feeds found and then wrapped to the given width. See Text.BreakToWidth().

func (*Text) AddRunes added in v0.7.0

func (t *Text) AddRunes(runes []rune, decoration *TextDecoration)

AddRunes adds runes with the given decoration to this Text. This is more efficient than AddString(), since the string doesn't have to be converted to runes first.

func (*Text) AddString added in v0.7.0

func (t *Text) AddString(str string, decoration *TextDecoration)

AddString adds a string with the given decoration to this Text.

func (*Text) AdjustDecorations added in v0.43.0

func (t *Text) AdjustDecorations(adjuster func(decoration *TextDecoration)) map[*TextDecoration]TextDecoration

AdjustDecorations calls adjuster for each decoration in no particular order. The returned map can be passed to RestoreDecorations() to restore the decorations to their original state.

func (*Text) Baseline added in v0.7.0

func (t *Text) Baseline() float32

Baseline returns the baseline that will be used, which is based on the original font passed in at creation time.

func (*Text) BreakToWidth added in v0.7.0

func (t *Text) BreakToWidth(width float32) []*Text

BreakToWidth breaks the given text into multiple lines that are <= width. Trailing whitespace is not considered for purposes of fitting within the given width. A minimum of one word will be placed on a line, even if that word is wider than the given width.

func (*Text) Draw added in v0.7.0

func (t *Text) Draw(canvas *Canvas, x, y float32)

Draw the Text at the given location. y is where the baseline of the text will be placed.

func (*Text) Empty added in v0.59.1

func (t *Text) Empty() bool

Empty returns true if this doesn't hold any characters. May be called on a nil *Text.

func (*Text) Extents added in v0.7.0

func (t *Text) Extents() Size

Extents returns the width and height.

func (*Text) Height added in v0.7.0

func (t *Text) Height() float32

Height returns the height.

func (*Text) PositionForRuneIndex added in v0.7.0

func (t *Text) PositionForRuneIndex(index int) float32

PositionForRuneIndex returns the x-coordinate where the specified rune index starts. The returned coordinate assumes 0 is the start of the string. Note that this does not account for any embedded line endings nor tabs.

func (*Text) RestoreDecorations added in v0.69.0

func (t *Text) RestoreDecorations(m map[*TextDecoration]TextDecoration)

RestoreDecorations restores the decorations to the state they were in when AdjustDecorations() was called.

func (*Text) RuneIndexForPosition added in v0.7.0

func (t *Text) RuneIndexForPosition(x float32) int

RuneIndexForPosition returns the rune index within the string for the specified x-coordinate, where 0 is the start of the string.

func (*Text) Runes added in v0.7.0

func (t *Text) Runes() []rune

Runes returns the runes comprising this Text. Do not modify this slice.

func (*Text) Slice added in v0.7.0

func (t *Text) Slice(i, j int) *Text

Slice creates a new Text that is a slice of this Text. The indexes refer to rune positions.

func (*Text) String added in v0.7.0

func (t *Text) String() string

String returns the string representation of this Text.

func (*Text) Width added in v0.7.0

func (t *Text) Width() float32

Width returns the width.

type TextBlob added in v0.52.0

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

TextBlob represents runs of text for a font, that may be drawn on a Canvas.

type TextDecoration added in v0.7.0

type TextDecoration struct {
	Font            Font
	BackgroundInk   Ink
	OnBackgroundInk Ink
	BaselineOffset  float32
	Underline       bool
	StrikeThrough   bool
}

TextDecoration holds the decorations that can be applied to text when drawn.

func (*TextDecoration) Clone added in v0.43.0

func (d *TextDecoration) Clone() *TextDecoration

Clone the TextDecoration.

func (*TextDecoration) DrawText added in v0.14.0

func (d *TextDecoration) DrawText(canvas *Canvas, text string, x, y, width float32)

DrawText draws the given text using this TextDecoration.

func (*TextDecoration) Equivalent added in v0.7.0

func (d *TextDecoration) Equivalent(other *TextDecoration) bool

Equivalent returns true if this TextDecoration is equivalent to the other.

type ThemeColor

type ThemeColor struct {
	Light Color `json:"light"`
	Dark  Color `json:"dark"`
}

ThemeColor holds a pair of colors, one for light mode and one for dark mode.

func DefaultThemeBanding added in v0.73.0

func DefaultThemeBanding() *ThemeColor

DefaultThemeBanding returns the default banding color.

func DefaultThemeError added in v0.69.0

func DefaultThemeError() *ThemeColor

DefaultThemeError returns the default error color.

func DefaultThemeFocus added in v0.69.0

func DefaultThemeFocus() *ThemeColor

DefaultThemeFocus returns the default focus color.

func DefaultThemeSurface added in v0.69.0

func DefaultThemeSurface() *ThemeColor

DefaultThemeSurface returns the default surface color.

func DefaultThemeTooltip added in v0.69.0

func DefaultThemeTooltip() *ThemeColor

DefaultThemeTooltip returns the default tooltip color.

func DefaultThemeWarning added in v0.69.0

func DefaultThemeWarning() *ThemeColor

DefaultThemeWarning returns the default warning color.

func DeriveOn added in v0.69.0

func DeriveOn(basedOn ThemeColor) ThemeColor

DeriveOn returns a new ThemeColor that is the On color for the passed in ThemeColor.

func (*ThemeColor) Derive added in v0.69.0

func (t *ThemeColor) Derive(deriver func(ThemeColor) ThemeColor) *DerivedThemeColor

Derive returns a new DerivedThemeColor that is derived from this ThemeColor.

func (*ThemeColor) DeriveLightness added in v0.69.0

func (t *ThemeColor) DeriveLightness(light, dark float32) *DerivedThemeColor

DeriveLightness returns a new DerivedThemeColor that has its lightness adjusted by the given amount.

func (*ThemeColor) DeriveOn added in v0.69.0

func (t *ThemeColor) DeriveOn() *DerivedThemeColor

DeriveOn returns a new DerivedThemeColor that is the On color for this ThemeColor.

func (*ThemeColor) GetColor added in v0.2.0

func (t *ThemeColor) GetColor() Color

GetColor returns the current color. Here to satisfy the ColorProvider interface.

func (*ThemeColor) Paint

func (t *ThemeColor) Paint(canvas *Canvas, rect Rect, style paintstyle.Enum) *Paint

Paint returns a Paint for this ThemeColor. Here to satisfy the Ink interface.

type TooltipTheme added in v0.4.0

type TooltipTheme struct {
	SecondaryTextFont Font
	BackgroundInk     Ink
	BaseBorder        Border
	Label             LabelTheme
	Delay             time.Duration
	Dismissal         time.Duration
}

TooltipTheme holds theming data for a Tooltip.

type UndoEdit

type UndoEdit[T any] struct {
	UndoFunc    func(*UndoEdit[T])
	RedoFunc    func(*UndoEdit[T])
	AbsorbFunc  func(*UndoEdit[T], Undoable) bool
	ReleaseFunc func(*UndoEdit[T])
	BeforeData  T
	AfterData   T
	EditName    string
	ID          int64
	EditCost    int
}

UndoEdit provides a standard Undoable.

func (*UndoEdit[T]) Absorb

func (e *UndoEdit[T]) Absorb(other Undoable) bool

Absorb implements Undoable

func (*UndoEdit[T]) Cost

func (e *UndoEdit[T]) Cost() int

Cost implements Undoable

func (*UndoEdit[T]) Name

func (e *UndoEdit[T]) Name() string

Name implements Undoable

func (*UndoEdit[T]) Redo

func (e *UndoEdit[T]) Redo()

Redo implements Undoable

func (*UndoEdit[T]) Release

func (e *UndoEdit[T]) Release()

Release implements Undoable

func (*UndoEdit[T]) Undo

func (e *UndoEdit[T]) Undo()

Undo implements Undoable

type UndoManager

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

UndoManager provides management of an undo/redo stack.

func NewUndoManager

func NewUndoManager(costLimit int, recoveryHandler errs.RecoveryHandler) *UndoManager

NewUndoManager creates a new undo/redo manager.

func UndoManagerFor added in v0.11.0

func UndoManagerFor(paneler Paneler) *UndoManager

UndoManagerFor returns the UndoManager for a given Paneler. May return nil.

func (*UndoManager) Add

func (m *UndoManager) Add(edit Undoable)

Add an edit. If one or more undos have been performed, this will cause any redo capability beyond this point to be lost.

func (*UndoManager) CanRedo

func (m *UndoManager) CanRedo() bool

CanRedo returns true if Redo() can be called successfully.

func (*UndoManager) CanUndo

func (m *UndoManager) CanUndo() bool

CanUndo returns true if Undo() can be called successfully.

func (*UndoManager) Clear

func (m *UndoManager) Clear()

Clear removes all edits from this UndoManager.

func (*UndoManager) CostLimit

func (m *UndoManager) CostLimit() int

CostLimit returns the current cost limit permitted by this undo manager.

func (*UndoManager) Redo

func (m *UndoManager) Redo()

Redo re-applies the current state by one edit.

func (*UndoManager) RedoTitle

func (m *UndoManager) RedoTitle() string

RedoTitle returns the title for the current redo state.

func (*UndoManager) SetCostLimit

func (m *UndoManager) SetCostLimit(limit int)

SetCostLimit sets a new cost limit, potentially trimming existing edits to fit within the new limit. Note that if the most recent edit has a cost larger than the new limit, that last edit (and only that last edit) will still be retained.

func (*UndoManager) Undo

func (m *UndoManager) Undo()

Undo rewinds the current state by one edit.

func (*UndoManager) UndoTitle

func (m *UndoManager) UndoTitle() string

UndoTitle returns the title for the current undo state.

type UndoManagerProvider added in v0.11.0

type UndoManagerProvider interface {
	UndoManager() *UndoManager
}

UndoManagerProvider defines the method a provider of UndoManager should define.

type Undoable added in v0.11.0

type Undoable interface {
	// Name returns the localized name of the edit, suitable for displaying in a user interface menu. Note that no
	// leading "Undo " or "Redo " should be part of this name, as the UndoManager will add this.
	Name() string
	// Cost returns a cost factor for this edit. When the cost values of the edits within a given UndoManager exceed the
	// UndoManager's defined cost limit, the oldest edits will be discarded until the cost values are less than or equal
	// to the UndoManager's defined limit. Note that if this method returns a value less than 1, it will be set to 1 for
	// purposes of this calculation.
	Cost() int
	// Undo the state.
	Undo()
	// Redo the state.
	Redo()
	// Absorb gives this edit a chance to absorb a new edit that is about to be added to the manager. If this method
	// returns true, it is assumed this edit has incorporated any necessary state into itself to perform an undo/redo
	// and the other edit will be discarded.
	Absorb(other Undoable) bool
	// Release is called when this edit is no longer needed by the UndoManager.
	Release()
}

Undoable defines the required methods an undoable edit must implement.

type Well

type Well struct {
	ImageFromSpecCallback func(ctx context.Context, filePathOrURL string, scale float32) (*Image, error)
	InkChangedCallback    func()
	ClickCallback         func()
	ValidateImageCallback func(*Image) *Image

	WellTheme
	Panel
	Pressed bool
	// contains filtered or unexported fields
}

Well represents a control that holds and lets a user choose an ink.

func NewWell

func NewWell() *Well

NewWell creates a new Well.

func (*Well) Click

func (w *Well) Click()

Click makes the ink well behave as if a user clicked on it.

func (*Well) DefaultClick

func (w *Well) DefaultClick()

DefaultClick provides the default click handling, which shows a dialog for selecting an ink.

func (*Well) DefaultDraw

func (w *Well) DefaultDraw(canvas *Canvas, _ Rect)

DefaultDraw provides the default drawing.

func (*Well) DefaultFileDrop

func (w *Well) DefaultFileDrop(files []string)

DefaultFileDrop provides the default file drop behavior.

func (*Well) DefaultFocusGained added in v0.16.0

func (w *Well) DefaultFocusGained()

DefaultFocusGained provides the default focus gained handling.

func (*Well) DefaultKeyDown

func (w *Well) DefaultKeyDown(keyCode KeyCode, mod Modifiers, _ bool) bool

DefaultKeyDown provides the default key down handling.

func (*Well) DefaultMouseDown

func (w *Well) DefaultMouseDown(_ Point, _, _ int, _ Modifiers) bool

DefaultMouseDown provides the default mouse down handling.

func (*Well) DefaultMouseDrag

func (w *Well) DefaultMouseDrag(where Point, _ int, _ Modifiers) bool

DefaultMouseDrag provides the default mouse drag handling.

func (*Well) DefaultMouseUp

func (w *Well) DefaultMouseUp(where Point, _ int, _ Modifiers) bool

DefaultMouseUp provides the default mouse up handling.

func (*Well) DefaultSizes

func (w *Well) DefaultSizes(hint Size) (minSize, prefSize, maxSize Size)

DefaultSizes provides the default sizing.

func (*Well) DefaultUpdateCursor added in v0.44.0

func (w *Well) DefaultUpdateCursor(_ Point) *Cursor

DefaultUpdateCursor provides the default cursor for wells.

func (*Well) Ink

func (w *Well) Ink() Ink

Ink returns the well's ink.

func (*Well) SetInk

func (w *Well) SetInk(ink Ink)

SetInk sets the ink well's ink.

type WellMask

type WellMask uint8

WellMask is used to limit the types of ink permitted in the ink well.

const (
	ColorWellMask WellMask = 1 << iota
	GradientWellMask
	PatternWellMask
)

Possible ink well masks.

type WellTheme added in v0.4.0

type WellTheme struct {
	BackgroundInk      Ink
	EdgeInk            Ink
	SelectionInk       Ink
	ClickAnimationTime time.Duration
	ImageLoadTimeout   time.Duration
	ImageScale         float32
	ContentSize        float32
	CornerRadius       float32
	Mask               WellMask
}

WellTheme holds theming data for a Well.

type Window

type Window struct {
	InputCallbacks
	// MinMaxContentSizeCallback returns the minimum and maximum size for the window content.
	MinMaxContentSizeCallback func() (minimum, maximum Size)
	// MovedCallback is called when the window is moved.
	MovedCallback func()
	// ResizedCallback is called when the window is resized.
	ResizedCallback func()
	// AllowCloseCallback is called when the user has requested that the window be closed. Return true to permit it,
	// false to cancel the operation. Defaults to always returning true.
	AllowCloseCallback func() bool
	// WillCloseCallback is called just prior to the window closing.
	WillCloseCallback func()
	// DragIntoWindowWillStart is called just prior to a drag into the window starting.
	DragIntoWindowWillStart func()
	// DragIntoWindowFinished is called just after a drag into the window completes, whether a drop occurs or not.
	DragIntoWindowFinished func()
	// contains filtered or unexported fields
}

Window holds window information.

func ActiveWindow

func ActiveWindow() *Window

ActiveWindow returns the window that currently has the keyboard focus, or nil if none of your application windows has the keyboard focus.

func NewWindow

func NewWindow(title string, options ...WindowOption) (*Window, error)

NewWindow creates a new, initially hidden, window. Call Show() or ToFront() to make it visible.

func Windows

func Windows() []*Window

Windows returns a slice containing the current set of open windows.

func (*Window) AttemptClose

func (w *Window) AttemptClose() bool

AttemptClose closes the window if permitted. Returns true on success.

func (*Window) BackingScale

func (w *Window) BackingScale() (x, y float32)

BackingScale returns the scale of the backing store for this window.

func (*Window) ClearTooltip

func (w *Window) ClearTooltip()

ClearTooltip clears any existing tooltip and resets the timer.

func (*Window) ClientData

func (w *Window) ClientData() map[string]any

ClientData returns a map of client data for this window.

func (*Window) Content

func (w *Window) Content() *Panel

Content returns the content panel for the window.

func (*Window) ContentRect

func (w *Window) ContentRect() Rect

ContentRect returns the boundaries in display coordinates of the window's content area.

func (*Window) ContentRectForFrameRect

func (w *Window) ContentRectForFrameRect(frame Rect) Rect

ContentRectForFrameRect returns the content rect for the given frame rect.

func (*Window) CurrentKeyModifiers added in v0.53.0

func (w *Window) CurrentKeyModifiers() Modifiers

CurrentKeyModifiers returns the current key modifiers, which is usually the same as calling .LastKeyModifiers(), however, on platforms that are using native menus, this will also capture modifier changes that occurred while the menu is being displayed.

func (*Window) Dispose

func (w *Window) Dispose()

Dispose of the window.

func (*Window) Draw

func (w *Window) Draw(c *Canvas)

Draw the window contents.

func (*Window) FlushDrawing

func (w *Window) FlushDrawing()

FlushDrawing causes any areas marked for drawing to be drawn now.

func (*Window) Focus

func (w *Window) Focus() *Panel

Focus returns the panel with the keyboard focus in this window.

func (*Window) FocusNext

func (w *Window) FocusNext()

FocusNext moves the keyboard focus to the next focusable panel.

func (*Window) FocusPrevious

func (w *Window) FocusPrevious()

FocusPrevious moves the keyboard focus to the previous focusable panel.

func (*Window) Focused

func (w *Window) Focused() bool

Focused returns true if the window has the current keyboard focus.

func (*Window) FrameRect

func (w *Window) FrameRect() Rect

FrameRect returns the boundaries in display coordinates of the frame of this window (i.e. the area that includes both the content and its border and window controls).

func (*Window) FrameRectForContentRect

func (w *Window) FrameRectForContentRect(cr Rect) Rect

FrameRectForContentRect returns the frame rect for the given content rect.

func (*Window) Hide

func (w *Window) Hide()

Hide hides the window, if it was previously visible. If the window is already hidden or is in full screen mode, this function does nothing.

func (*Window) HideCursor

func (w *Window) HideCursor()

HideCursor hides the cursor.

func (*Window) HideCursorUntilMouseMoves

func (w *Window) HideCursorUntilMouseMoves()

HideCursorUntilMouseMoves hides the cursor until the mouse is moved.

func (*Window) InDrag added in v0.29.0

func (w *Window) InDrag() bool

InDrag returns true if a drag is currently in progress in this window.

func (*Window) IsDragGesture added in v0.3.0

func (w *Window) IsDragGesture(where Point) bool

IsDragGesture returns true if a gesture to start a drag operation was made.

func (*Window) IsValid

func (w *Window) IsValid() bool

IsValid returns true if the window is still valid (i.e. hasn't been disposed).

func (*Window) IsVisible

func (w *Window) IsVisible() bool

IsVisible returns true if the window is currently being shown.

func (*Window) LastDrawDuration added in v0.52.0

func (w *Window) LastDrawDuration() time.Duration

LastDrawDuration returns the duration of the window's most recent draw.

func (*Window) LastKeyModifiers added in v0.52.0

func (w *Window) LastKeyModifiers() Modifiers

LastKeyModifiers returns the last set of key modifiers that this window has received.

func (*Window) LocalContentRect

func (w *Window) LocalContentRect() Rect

LocalContentRect returns the boundaries in local coordinates of the window's content area.

func (*Window) MarkForRedraw

func (w *Window) MarkForRedraw()

MarkForRedraw marks this window for drawing at the next update.

func (*Window) Minimize

func (w *Window) Minimize()

Minimize performs the minimize function on the window.

func (*Window) MouseLocation

func (w *Window) MouseLocation() Point

MouseLocation returns the current mouse location relative to this window.

func (*Window) Pack

func (w *Window) Pack()

Pack sets the window's content size to match the preferred size of the root panel.

func (*Window) Resizable

func (w *Window) Resizable() bool

Resizable returns true if the window can be resized by the user.

func (*Window) RunModal

func (w *Window) RunModal() int

RunModal displays and brings this window to the front, the runs a modal event loop until StopModal is called. Disposes the window before it returns.

func (*Window) SetContent

func (w *Window) SetContent(panel Paneler)

SetContent sets the content panel for the window.

func (*Window) SetContentRect

func (w *Window) SetContentRect(rect Rect)

SetContentRect sets the boundaries of the frame of this window by converting the content rect into a suitable frame rect and then applying it to the window.

func (*Window) SetFocus

func (w *Window) SetFocus(target Paneler)

SetFocus sets the keyboard focus to the specified target.

func (*Window) SetFrameRect

func (w *Window) SetFrameRect(rect Rect)

SetFrameRect sets the boundaries of the frame of this window.

func (*Window) SetTitle

func (w *Window) SetTitle(title string)

SetTitle sets the title of this window.

func (*Window) SetTitleIcons added in v0.32.0

func (w *Window) SetTitleIcons(images []*Image)

SetTitleIcons sets the title icon of the window. The image closest to the size desired by the system will be selected and used, scaling if needed. If no images are specified, the window reverts to its default icon.

func (*Window) Show

func (w *Window) Show()

Show makes the window visible, if it was previously hidden. If the window is already visible or is in full screen mode, this function does nothing.

func (*Window) ShowCursor

func (w *Window) ShowCursor()

ShowCursor shows the cursor.

func (*Window) StartDataDrag added in v0.3.0

func (w *Window) StartDataDrag(data *DragData)

StartDataDrag starts a data drag operation.

func (*Window) StopModal

func (w *Window) StopModal(code int)

StopModal stops the current modal event loop and propagates the provided code as the result to RunModal().

func (*Window) String

func (w *Window) String() string

func (*Window) Title

func (w *Window) Title() string

Title returns the title of this window.

func (*Window) TitleIcons added in v0.32.0

func (w *Window) TitleIcons() []*Image

TitleIcons the title icons that were previously set, if any.

func (*Window) ToFront

func (w *Window) ToFront()

ToFront attempts to bring the window to the foreground and give it the keyboard focus. If it is hidden, it will be made visible first.

func (*Window) UndoManager added in v0.11.0

func (w *Window) UndoManager() *UndoManager

UndoManager returns the UndoManager for the currently focused panel in the Window. May return nil.

func (*Window) UpdateCursorNow

func (w *Window) UpdateCursorNow()

UpdateCursorNow causes the cursor to be updated as if the mouse had moved.

func (*Window) ValidateLayout

func (w *Window) ValidateLayout()

ValidateLayout performs any layout that needs to be run by this window or its children.

func (*Window) Zoom

func (w *Window) Zoom()

Zoom performs the zoom function on the window.

type WindowOption

type WindowOption func(*Window) error

WindowOption holds an option for window creation.

func FloatingWindowOption

func FloatingWindowOption() WindowOption

FloatingWindowOption causes the window to float in front of all other non-floating windows.

func NotResizableWindowOption added in v0.2.0

func NotResizableWindowOption() WindowOption

NotResizableWindowOption prevents the window from being resized by the user.

func TitleIconsWindowOption added in v0.32.0

func TitleIconsWindowOption(images []*Image) WindowOption

TitleIconsWindowOption sets the title icon of the window. The image closest to the size desired by the system will be selected and used, scaling if needed. If no images are specified, the system's default window icon will be used.

func TransientWindowOption

func TransientWindowOption() WindowOption

TransientWindowOption causes the window to be marked as transient, which means it will never be considered the active window.

func UndecoratedWindowOption

func UndecoratedWindowOption() WindowOption

UndecoratedWindowOption prevents the standard window decorations (title as well as things like close buttons) from being shown.

Source Files

Jump to

Keyboard shortcuts

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