platform

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package platform defines the contract between the public mygo API and the native backends (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows).

Threading rules: unless a method says otherwise it must be called on the main (UI) thread, and every handler callback is invoked on the main thread. The public package is responsible for hopping onto the main thread.

Index

Constants

View Source
const (
	TextChangeMove   = 2 // AXTextStateChangeTypeSelectionMove
	TextChangeExtend = 3 // AXTextStateChangeTypeSelectionExtend

	TextDirectionUnknown       = 0
	TextDirectionBeginning     = 1
	TextDirectionEnd           = 2
	TextDirectionPrevious      = 3
	TextDirectionNext          = 4
	TextDirectionDiscontiguous = 5

	TextGranularityUnknown   = 0
	TextGranularityCharacter = 1
	TextGranularityWord      = 2
	TextGranularityLine      = 3
	TextGranularityDocument  = 7
)

The values of WebKit's AXTextStateChangeType, AXTextSelectionDirection and AXTextSelectionGranularity.

View Source
const DragSessionFormat transfer.Format = "application/x-mygo-drag-session"

DragSessionFormat carries an unguessable, process-local registry key. It never contains a pointer. Only the core resolves it while a drag lives.

View Source
const MenuIconSize = 16

MenuIconSize is the box, in points (DIPs), that a menu item's icon is drawn to fit, keeping its aspect: the size of the icons of the system's own menus on macOS, Windows and Linux.

View Source
const PictureInPictureActive = "return String(!!document.pictureInPictureElement)"

PictureInPictureActive is the body of an async function that tells whether a video of the page's document is in picture in picture: "true" or "false".

View Source
const TogglePictureInPicture = `` /* 464-byte string literal not displayed */

TogglePictureInPicture is the script that moves the page's video into picture in picture, or the one out back, for backends whose web view has no call for it: the video playing, else the largest that loaded, of the page's document. It runs as a user's gesture, which requestPictureInPicture() needs.

Variables

View Source
var DefaultDoubleClick = DoubleClick{Time: 500 * time.Millisecond, DX: 5, DY: 5}

DefaultDoubleClick is the double click where the system tells none.

View Source
var DefaultTexts = Texts{OK: "OK", Cancel: "Cancel", Open: "Open", Save: "Save", SelectFolder: "Select Folder", About: "About \x00"}

DefaultTexts are the texts in English, before package mygo sets others.

View Source
var EditCommands = map[string]bool{
	"undo": true, "redo": true, "cut": true, "copy": true, "paste": true, "pasteAndMatchStyle": true,
	"delete": true, "selectAll": true,
}

EditCommands are the menu roles of edit commands, which native UI takes as a SurfaceCommand and answers SurfaceCommandEnabled for.

View Source
var ErrClipboardChanged = errors.New("mygo: clipboard contents changed while reading")

ErrClipboardChanged prevents a read from mixing representations from different native clipboard owners while a toolkit pumps its event loop.

View Source
var ErrClipboardPersistence = errors.New("mygo: desktop cannot persist clipboard contents")

ErrClipboardPersistence means the desktop has no storage for clipboard data after the owner exits (for example, X11 without a clipboard manager).

View Source
var ErrFileWatchOverflow = errors.New("file watch queue overflow")

ErrFileWatchOverflow is the Err of a notice when the system dropped changes, for example because its queue overflowed.

View Source
var ErrNotificationsDenied = errors.New("mygo: the user does not allow notifications")

ErrNotificationsDenied is what ShowNotification fails with when the user does not allow the app to show notifications.

View Source
var ErrSecretNotFound = errors.New("mygo: secret not found")

ErrSecretNotFound is what Secrets.Secret fails with when the store has no secret for the service and account.

View Source
var ErrUnsupported error = unsupportedError{}

ErrUnsupported is returned by features the current backend cannot provide. It is errors.ErrUnsupported too (errors.Is), which apps check.

Functions

func CertificateIssuer added in v0.9.0

func CertificateIssuer(der []byte) (issuer string, from, to int64, ok bool)

CertificateIssuer reads the issuer's name and the validity of a DER-encoded certificate, for a backend whose platform does not name them: the issuer's common name (its organization when it has none), and the unix seconds it is valid from and to. ok is false when der is not a certificate.

It walks the few fields it needs instead of using crypto/x509, which would grow every app, whether it handles client certificates or not.

func ContentRulesIdentifier added in v0.6.3

func ContentRulesIdentifier(id, rules string) string

ContentRulesIdentifier names the list compiled from rules for id: the id and a hash of the rules, so that a later launch with the same rules loads what it compiled before, and changed rules compile again.

func CookieMatchesURL added in v0.5.0

func CookieMatchesURL(c Cookie, u *url.URL) bool

CookieMatchesURL reports whether a request to u sends c, by the rules of RFC 6265 section 5.4: its domain, path and Secure attribute.

func FitIcon added in v0.7.0

func FitIcon(w, h, box int) (int, int)

FitIcon returns the size of an image of w by h pixels drawn to fit a box of box by box pixels, keeping its aspect, at least a pixel each way.

func InRegion added in v0.9.0

func InRegion(region []Rect, x, y float64) bool

InRegion reports whether x, y is in one of the rectangles of region, their far edges excluded: the input region of a window (Window.SetInputRegion), in DIPs from the top-left corner of its content.

func InsideCorners added in v0.8.0

func InsideCorners(w, h float64, radii [4]float64, x, y float64) bool

InsideCorners reports whether x, y is inside the corners of radii (from the top-left clockwise) of a box w by h at the origin.

func KeyByPosition added in v0.4.3

func KeyByPosition(key, physical Key, mods Modifiers) bool

KeyByPosition reports whether a key press whose layout key is key may stand for its physical key: only when the layout types no US key, and a shortcut modifier is held, so that typing stays on the layout.

func LetsMouseThrough added in v0.9.0

func LetsMouseThrough(region []Rect, x, y float64, held, through bool) bool

LetsMouseThrough tells whether a window with an input region lets the mouse through to what is behind it, the pointer at x, y in DIPs from the top-left corner of its content, for a backend whose system shapes no window's input and lets the mouse through all of a window or none of it (macOS, Windows), switching as the pointer moves: through outside the rectangles, and as it was, through, while a button is held, held. A press that started on the window, as one dragging it by its character, keeps the window until it ends, as one that started behind it keeps what is behind; the release settles it.

func LineOfUnit added in v0.9.1

func LineOfUnit(value string, u int) int

LineOfUnit returns the line of value that UTF-16 unit u is on, from 0: how many line feeds come before it. A unit past the end is on the last line.

func LineUnits added in v0.9.1

func LineUnits(value string, line int) (start, n int, ok bool)

LineUnits returns the UTF-16 units of line of value, from start, n of them, its line feed included, and false for a line value does not have: one below 0 or past the last.

func ParseAuthChallenge added in v0.7.2

func ParseAuthChallenge(challenge string) (scheme, realm string)

ParseAuthChallenge returns the scheme, lowercase, and the realm of an HTTP authentication challenge, as a WWW-Authenticate header gives it: `Basic realm="intranet", charset="UTF-8"` is "basic" and "intranet".

func SetTexts added in v0.5.0

func SetTexts(t Texts)

SetTexts sets the texts backends say.

func StaleContentRules added in v0.6.3

func StaleContentRules(id, current, identifier string) bool

StaleContentRules reports whether identifier names a list compiled for id from other rules than current, which is ContentRulesIdentifier's.

func UTF16ByteOffset added in v0.2.17

func UTF16ByteOffset(s string, offset int) int

UTF16ByteOffset rounds an offset inside a surrogate pair down to its rune.

func UTF16Len added in v0.2.17

func UTF16Len(s string) (n int)

UTF16Len counts native text offsets without allocating an encoded string.

Types

type AboutPanelOptions

type AboutPanelOptions struct {
	ApplicationName    string
	ApplicationVersion string
	Version            string
	Copyright          string
	Credits            string
}

AboutPanelOptions configures the standard about panel.

type AccessActionKind added in v0.2.0

type AccessActionKind uint8

AccessActionKind is the action of an AccessAction event.

const (
	AccessPress AccessActionKind = iota
	AccessFocus
	AccessIncrement
	AccessDecrement
	AccessSetValue
	AccessScrollIntoView
	AccessExpand
	AccessCollapse
	// AccessSelectText selects runes From to To of a text field's Value.
	AccessSelectText
	// AccessInsertText replaces the selection of a text field with Text,
	// as typing it does: at the caret when nothing is selected.
	AccessInsertText
)

type AccessActions added in v0.2.0

type AccessActions uint8

AccessActions are the actions an element of an AccessTree takes.

const (
	ActionPress AccessActions = 1 << iota
	ActionFocus
	ActionIncrement
	ActionDecrement
	ActionSetValue
	// ActionScrollIntoView scrolls the containers around the element to
	// show it, as assistive technology moving to it out of view asks.
	ActionScrollIntoView
	// ActionExpand opens and closes an item of a tree with children
	// (AccessExpand, AccessCollapse), which pressing chooses.
	ActionExpand
)

type AccessAutoComplete added in v0.8.0

type AccessAutoComplete uint8

AccessAutoComplete is what the suggestions of a text field complete as the user types, as ARIA's aria-autocomplete says.

const (
	// AutoCompleteNone suggests nothing as the user types.
	AutoCompleteNone AccessAutoComplete = iota
	// AutoCompleteInline completes the text in place, the rest of the
	// value inserted after the caret and selected.
	AutoCompleteInline
	// AutoCompleteList shows a popup of the values that complete it.
	AutoCompleteList
	// AutoCompleteBoth shows the popup and completes the text in place
	// with the option the arrows are on.
	AutoCompleteBoth
)

func (AccessAutoComplete) String added in v0.8.0

func (a AccessAutoComplete) String() string

String returns the value of aria-autocomplete that a is, "" for AutoCompleteNone.

type AccessCurrent added in v0.8.0

type AccessCurrent uint8

AccessCurrent is the item an element is the current one of among those around it, as ARIA's aria-current says.

const (
	// CurrentNone is not current.
	CurrentNone AccessCurrent = iota
	// CurrentItem is the current item of a set, aria-current="true".
	CurrentItem
	// CurrentPage is the page the user is on, as the last crumb of a
	// breadcrumb trail or the link of a navigation bar to it.
	CurrentPage
	// CurrentStep is the step of a process the user is at.
	CurrentStep
	// CurrentLocation is the place shown, as in a flow chart.
	CurrentLocation
	// CurrentDate is today in a calendar, and CurrentTime now in a
	// timetable.
	CurrentDate
	CurrentTime
)

func (AccessCurrent) String added in v0.8.0

func (c AccessCurrent) String() string

String returns the value of aria-current that c is, "" for CurrentNone.

type AccessLineBox added in v0.9.1

type AccessLineBox struct {
	// Line is the line's index in Value, from 0: how many line feeds come
	// before it.
	Line int
	// Count is how many lines from Line the box holds, 0 for one: a run
	// of lines collapsed under one row, as the unchanged lines a diff's
	// separator stands for, or those of a fold.
	Count int
	// Bounds is its box, all of its rows when it wraps, in DIPs relative
	// to the surface, as the node's Bounds.
	Bounds RectF
}

AccessLineBox is where a line of the Value of a text field shows (AccessNode.LineBoxes).

type AccessNode added in v0.2.0

type AccessNode struct {
	// ID identifies the element from frame to frame.
	ID uint64
	// Parent is the index of the parent node in AccessTree.Nodes, -1 for
	// the elements at the top.
	Parent int
	Role   AccessRole
	// Label names the element; Value is its value, as the text of a text
	// field, for elements that have one.
	Label, Value string
	// Bounds is the element's visible box, in DIPs relative to the
	// surface.
	Bounds RectF
	States AccessStates
	// Min, Max and Now are the range and the value of a slider or a
	// progress bar; Now is below Min for progress of unknown length. Step
	// is how far an increment moves the value, 0 for none.
	Min, Max, Now, Step float64
	// SelStart and SelEnd are the selection of a text field, in runes,
	// and Placeholder what it shows while empty.
	SelStart, SelEnd int
	Placeholder      string
	// Description tells more about the element than its name, as help
	// text read after it: a field's description and its error, or a
	// tooltip.
	Description string
	// KeyShortcuts are the keys that press or focus the element, as
	// ARIA's aria-keyshortcuts, written as the platform's menus write
	// them ("⌘K" on macOS, "Ctrl+K" elsewhere), separated by spaces.
	KeyShortcuts string
	// Level is how deep an item of a tree is, or the rank of a heading,
	// from 1; 0 for other nodes.
	Level int
	// Current says which item the element is the current one of, as the
	// page the user is on.
	Current AccessCurrent
	// AutoComplete says what the suggestions of a text field or a combo
	// box complete as the user types, as ARIA's aria-autocomplete.
	AutoComplete AccessAutoComplete
	// PosInSet is the place of an item in its set, from 1, and SetSize
	// the size of the set, 0 when not given: a list's rows say which of
	// all they are, whether or not the others are built, and the list how
	// many rows it has.
	PosInSet, SetSize int
	// RowCount and ColCount are how many rows and columns a table, a grid
	// or a tree grid has, built or not, as ARIA's aria-rowcount and
	// aria-colcount; RowIndex and ColIndex are the place of a row or a
	// cell among them, from 1, header rows counted (aria-rowindex,
	// aria-colindex). 0 when the app gives none: a row's PosInSet and its
	// table's SetSize then tell its place, and the rows and cells built
	// the rest.
	RowCount, ColCount, RowIndex, ColIndex int
	// RowSpan and ColSpan are how many rows and columns of its table a
	// cell covers, as ARIA's aria-rowspan and aria-colspan: 0 for one.
	// The cell after one spanning columns in its row is in the column
	// after those it covers.
	RowSpan, ColSpan int
	// Actions are the actions the element takes in AccessAction events.
	Actions AccessActions
	// RoleDescription is what screen readers read for the element's role
	// in place of its own, as "carousel" for a group or "slide" for a tab
	// panel: ARIA's aria-roledescription. "" reads the role.
	RoleDescription string
	// Controls are the IDs of the nodes whose content or presence the
	// element controls, as the region a disclosure button opens: ARIA's
	// aria-controls.
	Controls []uint64
	// DescribedBy are the IDs of the nodes whose text describes the
	// element, as a hint below a field, which Description holds: ARIA's
	// aria-describedby. ErrorMessage are those of the nodes holding the
	// message of an element that is AccessInvalid, whose text Description
	// starts with: ARIA's aria-errormessage, given only while invalid.
	DescribedBy, ErrorMessage []uint64
	// HasPopup is the kind of popup the element opens, as ARIA's
	// aria-haspopup.
	HasPopup AccessPopup
	// WebView is the web view whose page the node stands for, if any
	// (Surface.NewWebView): assistive technology finds the page's elements
	// inside it, and it has no children of its own.
	WebView WebView
	// TextRuns are the formats of the runes of a text field's Value, as a
	// rich text editor's: runs in order, from rune Start to End, that
	// screen readers read as bold, italic, links and headings. Runes no
	// run holds take the text's default font. Empty for plain text.
	TextRuns []AccessTextRun
	// LineBoxes are where the lines of a text field's Value in view
	// show, as a code editor lays them out, in the order of the lines:
	// assistive technology finds where a range of the text is by them
	// (RangeBounds). Empty for a field that gives none, whose
	// Bounds then stand for any range.
	LineBoxes []AccessLineBox
}

AccessNode is an element of an AccessTree.

type AccessPopup added in v0.8.0

type AccessPopup uint8

AccessPopup is the kind of popup an element opens, as ARIA's aria-haspopup says.

const (
	// PopupNone opens no popup.
	PopupNone AccessPopup = iota
	// PopupMenu opens a menu, aria-haspopup="menu" (or "true").
	PopupMenu
	// PopupListBox opens a list of options, PopupTree a tree, PopupGrid
	// a grid, as a calendar's, and PopupDialog a dialog.
	PopupListBox
	PopupTree
	PopupGrid
	PopupDialog
)

func (AccessPopup) String added in v0.8.0

func (p AccessPopup) String() string

String returns the value of aria-haspopup that p is, "" for PopupNone.

type AccessRole added in v0.2.0

type AccessRole uint8

AccessRole is the kind of an element of an AccessTree.

const (
	RoleGroup AccessRole = iota
	RoleText
	RoleButton
	RoleLink
	RoleCheckBox
	RoleRadio
	RoleSwitch
	RoleSlider
	RoleProgress
	RoleTextField
	RoleImage
	RoleList
	RoleScroll
	RoleDialog
	RolePopup
	RoleTooltip
	RolePopUpButton
	RoleTabList
	RoleTab
	RoleSplitter
	RoleStatus
	RoleTable
	RoleRow
	RoleCell
	RoleColumnHeader
	RoleTree
	RoleTreeItem
	RoleListItem
	RoleMenuButton
	RoleToolbar
	RoleRadioGroup
	// RoleToggleButton is pressed while AccessChecked.
	RoleToggleButton
	// RoleComboBox is a text field with a popup of options, which is
	// AccessExpanded while it shows.
	RoleComboBox
	// RoleDisclosure is a button showing or hiding content below it, which
	// is AccessExpanded while it shows: the trigger of a collapsible, or
	// the header of an accordion's section.
	RoleDisclosure
	// RoleMeter shows a value in a range, as a level indicator, and
	// RoleStepper steps one, as a spin button: both have Min, Max and Now.
	RoleMeter
	RoleStepper
	// RoleColorWell is a button showing a color, its Value, which opens a
	// picker of it, as AppKit's color well.
	RoleColorWell
	// RoleAlertDialog is a dialog asking about something important, its
	// Description the message.
	RoleAlertDialog
	// RoleMenu holds the items of a menu, RoleMenuBar the menus' titles
	// along a window, and RoleMenuItem is an item of either, which
	// RoleMenuItemCheckBox and RoleMenuItemRadio are when they show a
	// choice, AccessChecked (AccessMixed) while chosen.
	RoleMenu
	RoleMenuBar
	RoleMenuItem
	RoleMenuItemCheckBox
	RoleMenuItemRadio
	// RoleHeading is the title of a section, Level its rank: 1 for the
	// highest.
	RoleHeading
	// RoleRegion is a landmark with a name, as a panel screen readers list
	// among the window's landmarks: ARIA's region.
	RoleRegion
	// RoleLog, RoleTimer and RoleAlert are ARIA's live regions of those
	// roles: content added to a log is read out as it is added
	// (AccessTree.Announcements), a timer's changes only when the user
	// goes to it, and an alert's content at once, as it appears or
	// changes (AccessTree.Alerts).
	RoleLog
	RoleTimer
	RoleAlert
	// RoleSeparator divides groups of content or controls, as a rule
	// between a toolbar's groups of buttons, AccessVertical when it runs
	// up and down.
	RoleSeparator
	// RoleRowHeader is the cell of a table's row naming the row, as
	// RoleColumnHeader names a column.
	RoleRowHeader
	// RoleSearch is a landmark holding what searches the app or a
	// document, as a search field and its button: ARIA's search.
	RoleSearch
	// RoleArticle is a self-contained piece of content, as a post of a
	// feed or a comment of a thread: ARIA's article, no landmark.
	RoleArticle
	// RoleNavigation is a landmark holding links that move around the app
	// or a document, as a breadcrumb trail or a navigation bar: ARIA's
	// navigation.
	RoleNavigation
	// RoleGrid is a table whose cells take the focus and the arrow keys,
	// as a spreadsheet's, and RoleTreeGrid one whose rows open and close
	// as a tree's items do: ARIA's grid and treegrid. Their rows and
	// cells are RoleRow, RoleCell and RoleColumnHeader, as a table's.
	RoleGrid
	RoleTreeGrid
	// RoleDeletion and RoleInsertion hold content removed from or added
	// to a document, as the lines of a diff or a price struck out:
	// ARIA's deletion and insertion, HTML's del and ins.
	RoleDeletion
	RoleInsertion
	// RoleTabPanel holds the content of a tab, which labels it and
	// points to it (Controls): ARIA's tabpanel.
	RoleTabPanel
	// RoleMain, RoleBanner, RoleContentInfo and RoleComplementary are
	// landmarks: ARIA's main, banner, contentinfo and complementary,
	// HTML's main, a page's header, a page's footer and aside.
	RoleMain
	RoleBanner
	RoleContentInfo
	RoleComplementary
)

func (AccessRole) Live added in v0.8.0

func (r AccessRole) Live() (live string, atomic bool)

Live returns how content changing in a live region of a role is read, as ARIA's aria-live, "polite" or "assertive", and whether the region is read whole (aria-atomic): "" for roles that are no live region. Statuses and logs are read after what is being read, an alert at once; a timer is read only when the user goes to it.

func (AccessRole) Ranged added in v0.2.5

func (r AccessRole) Ranged() bool

Ranged reports whether nodes of a role have a value in a range (Min, Max and Now).

func (AccessRole) Tabular added in v0.8.0

func (r AccessRole) Tabular() bool

Tabular reports whether nodes of a role hold rows of cells: tables, grids and tree grids.

type AccessStates added in v0.2.0

type AccessStates uint32

AccessStates are the states of an element of an AccessTree. AccessChecked is the choice among a tab list's tabs, a tree's items, and the rows of a list or a table that are AccessSelectable.

const (
	AccessFocusable AccessStates = 1 << iota
	AccessDisabled
	AccessChecked
	AccessMixed
	AccessSelected
	AccessExpanded
	AccessMultiline
	AccessPassword
	AccessReadOnly
	AccessSelectable
	// AccessOffscreen is set on elements built but out of view, as the
	// rows a list builds beyond its edges.
	AccessOffscreen
	// AccessMultiselectable is set on a list, a table, a grid or a tree
	// whose user chooses several rows (aria-multiselectable).
	AccessMultiselectable
	// AccessSegment is set on the segments of a segmented control or a
	// group of toggles, as AppKit's subrole AXSegment says.
	AccessSegment
	// AccessSearch is set on a text field for searching.
	AccessSearch
	// AccessInvalid is set on a control whose value is not valid, as a
	// field with an error.
	AccessInvalid
	// AccessSortAscending and AccessSortDescending are set on the header
	// of the column a table's rows are sorted by.
	AccessSortAscending
	AccessSortDescending
	// AccessExpandable is set on an item of a tree with children, which
	// AccessExpanded shows.
	AccessExpandable
	// AccessVertical is set on a slider going up, a separator running up
	// and down, and an element the app says runs up and down, as ARIA's
	// aria-orientation="vertical".
	AccessVertical
	// AccessBusy is set on an element whose content is about to change,
	// as a region loading, which assistive technology waits for before
	// reading it: ARIA's aria-busy.
	AccessBusy
	// AccessSortOther is set on the header of the column a table's rows
	// are sorted by in an order neither ascending nor descending.
	AccessSortOther
	// AccessHorizontal is set on an element the app says runs across, as
	// ARIA's aria-orientation="horizontal". A slider or a separator that
	// is neither AccessVertical nor AccessHorizontal runs across; other
	// elements then have no orientation.
	AccessHorizontal
)

type AccessTextRun added in v0.5.0

type AccessTextRun struct {
	// Start and End are the run's runes of Value.
	Start, End int
	// Family is its font's family, "" for the system's; Size its size in
	// DIPs, 0 for the text's; Weight from 100 to 900, 0 for 400.
	Family                           string
	Size                             float32
	Weight                           int
	Italic, Underline, Strikethrough bool
	// Color and Background are RGBA, transparent where unset.
	Color, Background [4]uint8
	// Link is the URL the run links to.
	Link string
	// Heading is the level of the heading the run is in, from 1, 0 in a
	// body paragraph.
	Heading int
}

AccessTextRun is a run of the Value of a text field with formats of its own (AccessNode.TextRuns).

type AccessTree added in v0.2.0

type AccessTree struct {
	// Nodes are the elements in tree order: a parent before its children.
	Nodes []AccessNode
	// Focus is the ID of the element with the keyboard focus, 0 for none.
	Focus uint64
	// Announcements are texts for assistive technology to read out once,
	// after what it is reading, as the title of a page shown or a toast:
	// news the focus does not bring.
	Announcements []string
	// Alerts are texts to read out at once, interrupting what is being
	// read: what an alert (RoleAlert) shows as it appears or changes, as
	// ARIA's assertive live regions.
	Alerts []string
	// Selected is the word for a chosen cell of a grid in the window's
	// language ("selected"), given while a cell says whether it is
	// chosen, for a bridge whose screen reader reads no chosen state of
	// cells to say with its name.
	Selected string
}

AccessTree is the content of a surface for assistive technology, such as screen readers: the elements a user can perceive and act on.

type Align added in v0.4.1

type Align uint8

Align lines a flyout up with its anchor along the side it goes to: its left or top edges (start), centers, or right or bottom edges (end).

const (
	AlignStart Align = iota
	AlignCenter
	AlignEnd
)

Alignments.

type AppController

type AppController interface {
	SetActivationPolicy(policy string)
	Activate()
	// AllowForeground lets the next process to ask bring its windows to
	// the front, which Windows only lets the process in front do.
	AllowForeground()
	// WithActivationToken runs fn with the startup notification or XDG
	// activation token of the launch that caused it, which the window fn
	// shows or focuses first may need to take the focus (Wayland).
	WithActivationToken(token string, fn func())
	Hide()
	Unhide()
	IsHidden() bool
	// IsActive reports whether the app is the active one: in front on
	// macOS, with a window that has the keyboard elsewhere.
	IsActive() bool
	SetBadge(label string)
	Badge() string
	// Bounce requests user attention and returns an id for CancelBounce.
	Bounce(critical bool) int
	CancelBounce(id int)
	SetDockIcon(png []byte) error
	// SetDockMenu sets the menu of the Dock icon (macOS); nil removes it.
	SetDockMenu(m *Menu)
	// NewDataStore makes a website data store other than the default one
	// (mygo.Session), which WindowOptions.DataStore and the calls below
	// take. The core makes one store per session and closes it with
	// DataStore.Close.
	NewDataStore(opts DataStoreOptions) (DataStore, error)
	// ClearBrowsingData deletes the data of types pages stored in store,
	// nil for the default one; done runs on the main thread.
	ClearBrowsingData(store DataStore, types SiteData, done func(error))
	// Cookie operations address store, nil for the default page store.
	// Calls and exactly-once completions run on main; ListCookies returns
	// independent Go values: every cookie, or with an http or https url
	// the cookies a request to it sends (CookieMatchesURL where the engine
	// cannot tell).
	ListCookies(store DataStore, url string, done func([]Cookie, error))
	SetCookie(store DataStore, cookie Cookie, done func(error))
	DeleteCookie(store DataStore, key CookieKey, done func(error))
	ClearCookies(store DataStore, done func(error))
	// CompileContentRules makes a content rule list of rules, in WebKit's
	// content blocker JSON format: it loads the list kept as identifier
	// (ContentRulesIdentifier) where the engine keeps compiled lists,
	// else compiles rules, keeps the list as identifier and removes the
	// lists kept for id under other identifiers (StaleContentRules).
	// done runs on the main thread exactly once, with a handle
	// Page.SetContentRules takes.
	CompileContentRules(id, identifier, rules string, done func(list any, err error))
	ShowAboutPanel(opts AboutPanelOptions)
	// PreferredLanguages returns the languages the user reads, most
	// preferred first, as the system's settings list them, in the forms
	// the system writes them (the core normalizes them): never what the
	// app chose for itself (SaveLocale). Safe before Init.
	PreferredLanguages() []string
	// Region returns the user's regional formats. Safe before Init.
	Region() Region
	// SavedLocale returns the language the app chose for itself, as the
	// system keeps it, and whether the system keeps one at all (macOS:
	// AppleLanguages in the app's own defaults, which System Settings
	// shows as the app's language; browsers: localStorage). Where it
	// keeps none, the core keeps it in a file. Safe before Init.
	SavedLocale() (tag string, kept bool)
	// SaveLocale keeps tag where SavedLocale reads it, "" to forget it,
	// and reports whether the system keeps one at all.
	SaveLocale(tag string) bool
	// SetLanguages tells the backend the languages the app shows, its
	// own language first, and whether it is laid out right to left, for
	// what shows text the core does not draw: the web views it creates
	// later and, where it can change, those it created, and the system's
	// own texts and widgets.
	SetLanguages(tags []string, rtl bool)
	// RegisterURLScheme makes the app, identified by id (its identifier)
	// and named name, the handler of the URLs of scheme for the user.
	RegisterURLScheme(scheme, id, name string) error
	UnregisterURLScheme(scheme, id, name string) error
	IsURLSchemeRegistered(scheme, id, name string) bool
	// SetOpenAtLogin makes the app start at login, passing arg where the
	// start command takes arguments; OpenedAtLogin reports whether the
	// system started it so without one (macOS login items).
	SetOpenAtLogin(open bool, id, name, arg string) error
	OpenAtLogin(id, name, arg string) bool
	OpenedAtLogin() bool
	// Package describes the application bundle the process runs from; ok
	// is false for a plain executable (e.g. `go run`). Safe to call from
	// any goroutine, before Init too.
	Package() (info PackageInfo, ok bool)
	// AddRecentDocument records the absolute path of a document the user
	// opened in the system's recent documents; ClearRecentDocuments
	// removes the ones the app recorded.
	AddRecentDocument(path string) error
	ClearRecentDocuments() error
	// SetJumpList commits the app's whole jump list (Windows); elsewhere
	// it does nothing.
	SetJumpList(list JumpList) error
}

AppController exposes application level native features.

type AppHandler

type AppHandler interface {
	Ready()
	// Dispatch drains the queue of functions scheduled for the main thread.
	Dispatch()
	// QuitRequested is called when the user or the OS asks the application
	// to quit (Cmd+Q, Dock > Quit, logout). Returning true lets the quit
	// proceed.
	QuitRequested() bool
	// Terminating is called right before the process is terminated by the
	// OS (logout/shutdown); Run will not return. The core runs the quit
	// listeners then, unless a quit ran them, and finishes the app.
	Terminating()
	// Activated is called when the application is re-activated, e.g. by
	// clicking its Dock icon.
	Activated(hasVisibleWindows bool)
	DidBecomeActive()
	DidResignActive()
	OpenURLs(urls []string)
	OpenFiles(paths []string)
	MenuItemClicked(id int)
	ThemeChanged()
	DisplaysChanged()
	// LocaleChanged is called when the languages the user prefers, or the
	// regional formats, may have changed, on the systems that report it.
	LocaleChanged()
	// PowerEvent is "suspend", "resume", "lock-screen" or "unlock-screen".
	PowerEvent(event string)
	// NetworkChanged reports the network's status, once Network.Watch was
	// called, when it may have changed.
	NetworkChanged(status NetworkStatus)
	HotkeyPressed(id int)
	// HotkeyBound reports the keys a desktop that binds global shortcuts
	// for apps has for one, as it writes them, "" when it bound none.
	HotkeyBound(id int, keys string)
	NotificationClicked(id string)
	// MediaCommand reports a media key or a remote command for what
	// NowPlaying shows; position is where MediaSeek asks to go.
	MediaCommand(cmd MediaCommand, position time.Duration)
}

AppHandler receives application level events from the backend.

type AppOptions

type AppOptions struct {
	Name string
	// ActivationPolicy is "regular" (default), "accessory" or "prohibited".
	// Only meaningful on macOS.
	ActivationPolicy string
	// DMABUFRenderer is "off" (or ""), "on" or "auto": whether WebKitGTK
	// may draw with its DMA-BUF renderer. Only meaningful on Linux.
	DMABUFRenderer string
	// Background starts the app without bringing it to the front, as
	// `mygo dev -background` asks. Only meaningful on macOS, where an
	// executable that is no bundle is brought there as it starts; the
	// core shows the windows without the focus everywhere.
	Background bool
}

AppOptions configures Backend.Init.

type Application added in v0.5.0

type Application struct {
	Name, ID, Path string
}

Application is an installed application (Backend.Applications): Path is where FileIcon finds its icon and OpenApplication starts it.

type AuthRequest added in v0.7.2

type AuthRequest struct {
	// Host and Port of the server asking, or of the proxy.
	Host string
	Port int
	// Realm is the protection space the server named, "" for none.
	Realm string
	// Scheme is the authentication scheme, lowercase: "basic", "digest",
	// "ntlm" or "negotiate".
	Scheme  string
	IsProxy bool
}

AuthRequest is an HTTP authentication challenge of a page, or of what it loads (WindowHandler.AuthRequested).

type AuthResponse added in v0.7.2

type AuthResponse struct {
	Default            bool
	Username, Password string
}

AuthResponse answers an AuthRequest. Default leaves the challenge to the web view, as if nobody had been asked; otherwise the request goes on with Username and Password, or, when both are empty, without credentials: the page gets the server's refusal (401 or 407).

type Backend

type Backend interface {
	// Name identifies the backend, for example "darwin/wkwebview".
	Name() string

	// Init prepares the native application. It is called once, on the main
	// thread, before Run.
	Init(h AppHandler, opts AppOptions) error
	// Run runs the native event loop until Quit is called. h.Ready is
	// invoked once the application has finished launching.
	Run() error
	// Quit makes Run return.
	Quit()

	// IsMainThread reports whether the caller runs on the UI thread. Safe
	// to call from any goroutine.
	IsMainThread() bool
	// Signal asks the backend to invoke AppHandler.Dispatch on the main
	// thread as soon as possible. Safe to call from any goroutine.
	Signal()
	// Step blocks until at least one native event has been processed or
	// Wake has been called. Main thread only; used for nested waits.
	Step()
	// Wake unblocks a pending Step. Safe to call from any goroutine.
	Wake()

	NewWindow(opts *WindowOptions, h WindowHandler) (Window, error)

	SetApplicationMenu(m *Menu)
	// PopupMenu shows a context menu. pos is relative to the window's
	// content area; nil means the current mouse location. It blocks until
	// the menu is dismissed.
	PopupMenu(m *Menu, w Window, pos *Point)
	// UpdateMenuItem refreshes label/state of every native item created
	// for item.ID.
	UpdateMenuItem(item *MenuItem)

	App() AppController
	Dialogs() Dialogs
	Clipboard() Clipboard
	Shell() Shell
	Screen() Screen
	Theme() Theme
	Power() Power
	Network() Network
	NowPlaying() NowPlaying
	// Secrets may be called before Init, from any goroutine.
	Secrets() Secrets
	// Applications lists the applications installed on the computer.
	// Unlike other methods it may be called from any goroutine once Init
	// returned: it reads the disk, which the core does off the main thread.
	Applications() ([]Application, error)

	// NewFileWatch starts watching files, with no target yet. notify is
	// called on a goroutine of the backend, one notice at a time.
	// NewFileWatch may be called before Init, from any goroutine.
	NewFileWatch(notify func(FileWatchNotice)) (FileWatch, error)
	// ReplaceFile replaces the file at target with the file at
	// replacement, in the same directory, keeping what the system keeps of
	// the target's metadata (permissions, owner, extended attributes,
	// creation date); replacement is gone afterwards. It may be called
	// before Init, from any goroutine.
	ReplaceFile(target, replacement string) error

	// NewTray makes a tray icon. id is TrayOptions.ID, which Linux needs
	// as the icon is made; the other backends take it through Tray.SetID.
	NewTray(id string, h TrayHandler) (Tray, error)
	// RegisterHotkey makes accelerator a global shortcut. description says
	// what it does, for desktops that show the app's shortcuts to the
	// user; such desktops tell the keys they bound with HotkeyBound.
	RegisterHotkey(id int, accelerator, description string) error
	UnregisterHotkey(id int)

	NotificationsSupported() bool
	// ShowNotification shows n; done runs on the main thread once the
	// system has it, or with why it could not.
	ShowNotification(n *Notification, done func(error))
	RemoveNotification(id string)
	// RemoveAllNotifications removes the app's notifications, on macOS
	// those of earlier runs too.
	RemoveAllNotifications()

	// WebViewAvailable reports whether the system webview is there, and so
	// whether windows showing web pages can work: WKWebView on macOS,
	// WebKitGTK on Linux, the WebView2 Runtime on Windows. A window showing
	// native UI needs none, so an app whose windows all do runs without one.
	// It may be called before Init, from any goroutine.
	WebViewAvailable() bool
}

Backend is implemented by every native backend.

type BackgroundSurface added in v0.7.2

type BackgroundSurface interface {
	// SetBackground sets the color, opaque, or transparent for none.
	SetBackground(c Color)
}

BackgroundSurface is a Surface told the color the content's frames fill the window with, which its window shows where no frame of its size shows yet: on Windows, DWM can show a window at its new size, as the user drags its border, before the frame of that size, and would show black where the window grew.

type BadgeAlignment added in v0.9.1

type BadgeAlignment string

BadgeAlignment is where an item's badge sits in the column the badges of its menu share.

const (
	BadgeAlignLeft   BadgeAlignment = "left"
	BadgeAlignCenter BadgeAlignment = "center"
	BadgeAlignRight  BadgeAlignment = "right"
)

type BadgeShape added in v0.9.2

type BadgeShape string

BadgeShape is the background behind a badge.

const (
	BadgeShapeSquare  BadgeShape = "square"
	BadgeShapeRounded BadgeShape = "rounded"
	BadgeShapePill    BadgeShape = "pill"
)

type CaptureKind added in v0.7.2

type CaptureKind int

CaptureKind is a kind of device a page captures (Page.CaptureState).

const (
	CaptureCamera CaptureKind = iota
	CaptureMicrophone
	// CaptureDisplay is the capture of a screen or a window,
	// getDisplayMedia().
	CaptureDisplay
)

type CaptureState added in v0.7.2

type CaptureState int

CaptureState is whether a page captures a kind of device. The values are WebKit's WKMediaCaptureState and WebKitMediaCaptureState.

const (
	CaptureNone CaptureState = iota
	CaptureActive
	CaptureMuted
)

type CertificateError added in v0.7.2

type CertificateError struct {
	// URL is what was loading; Host the server's host in it.
	URL, Host string
	// Error tells what is wrong, in the platform's words.
	Error string
	// Certificate is the server's certificate, DER-encoded.
	Certificate []byte
}

CertificateError is a server certificate that does not verify (WindowHandler.CertificateError).

type ClickCounter added in v0.5.2

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

ClickCounter counts quick successive presses for a backend whose system reports no count with a press, by the system's double-click time and distance where it has them.

func (*ClickCounter) Press added in v0.5.2

func (c *ClickCounter) Press(button int, x, y float64, ms uint32, d DoubleClick) int

Press counts a press of button at x, y at ms, the event's time in milliseconds, which may wrap around as the system's does: one more than the last press's count when that press was of the same button and within d of it; else 1. The event's time rather than now's keeps presses waiting for a busy main thread as far apart as they were made.

type ClientCertificate added in v0.9.0

type ClientCertificate struct {
	// DER is the certificate, DER-encoded; x509.ParseCertificate reads
	// it. It is nil where the platform names its certificates without
	// their bytes.
	DER []byte
	// Subject and Issuer name it as the platform does, and ValidFrom and
	// ValidTo are the unix seconds it is valid from and to.
	Subject, Issuer    string
	ValidFrom, ValidTo int64
	// Native is the platform's own certificate, which a backend fills in
	// and an answer carries back: an ICoreWebView2ClientCertificate on
	// Windows, a SecIdentityRef on macOS. Zero where the platform offers
	// none.
	Native uintptr
}

ClientCertificate is one of the certificates a platform can offer a server that asks for one (ClientCertificateRequest.Certificates).

type ClientCertificateRequest added in v0.9.0

type ClientCertificateRequest struct {
	// Host and Port of the server asking, or of the proxy.
	Host    string
	Port    int
	IsProxy bool
	// Certificates are those the platform can offer, which an answer may
	// return. Linux lists none: WebKitGTK has no way to, and an answer
	// can only take the default or cancel there.
	Certificates []ClientCertificate
}

ClientCertificateRequest is a server, or a proxy, asking for the certificate of a TLS connection of the page, or of what it loads (WindowHandler.ClientCertificateRequested).

type ClientCertificateResponse added in v0.9.0

type ClientCertificateResponse struct {
	Default     bool
	Cancel      bool
	Certificate *ClientCertificate
}

ClientCertificateResponse answers a ClientCertificateRequest. Default leaves the challenge to the platform, the choice of the web view. An answer with no certificate and not Default refuses the challenge where the platform can: the load fails, as a user dismissing a browser's prompt does.

type Clipboard

type Clipboard interface {
	// WatchChanges observes clipboard changes without reading data. It does
	// not report the initial contents. changed and the returned stop function
	// run on the main thread; stop prevents later callbacks. Only one watch
	// is active at a time. Unsupported backends return ErrUnsupported.
	WatchChanges(changed func()) (stop func(), err error)
	// Data reads copy accepted representations, so returned data outlives
	// native ownership. Nil formats reads all; a missing explicit match is
	// transfer.ErrFormat. WriteData takes an application-owned snapshot;
	// concealed marks it as confidential for the clipboard managers that
	// read the platform's mark; released runs once when native providers
	// are no longer needed, never after a failed write. Neither operation
	// depends on a source window.
	ReadData(formats []transfer.Format) (transfer.Data, error)
	WriteData(data transfer.Data, concealed bool, released func()) error
	Formats() []transfer.Format
	// Flush materializes owned providers and asks the system to persist the
	// data. Close drops any remaining owned providers at app shutdown.
	Flush() error
	Close()
	ReadText() string
	WriteText(text string)
	ReadHTML() string
	WriteHTML(markup string)
	ReadImage() []byte
	WriteImage(png []byte) error
	Clear()
	AvailableFormats() []string
}

Clipboard accesses the system clipboard.

type Color

type Color struct{ R, G, B, A uint8 }

Color is an 8-bit RGBA color.

type ContextMenu added in v0.7.2

type ContextMenu struct {
	// Pointer is set for a menu the pointer opened, at X, Y in DIPs from
	// the top-left corner of the web view; a menu the keyboard opened has
	// none.
	Pointer bool
	X, Y    float64
	// Target is what the backend tells of what was clicked. The core takes
	// what it leaves empty from the page's own contextmenu event, which
	// the bridge records just before, unless Complete says it told all:
	// the event of another frame than the page's own never reaches it.
	Target   ContextMenuTarget
	Complete bool
	// Items are the web view's items, each with its Native number.
	Items []*MenuItem
}

ContextMenu is a page's context menu about to open (WindowHandler.ContextMenu): what was clicked, as far as the backend tells, and the web view's own items.

type ContextMenuResponse added in v0.7.2

type ContextMenuResponse struct {
	Default bool
	Menu    *Menu
}

ContextMenuResponse answers a ContextMenu. Default shows the web view's menu as it is, as if nobody had been asked; otherwise Menu is the menu to show, of the web view's items (by Native, each once) and the app's, or nil to show none.

type ContextMenuTarget added in v0.7.2

type ContextMenuTarget struct {
	// LinkURL and LinkText are those of the link clicked; ImageURL of
	// the image, MediaURL of the video or audio.
	LinkURL, LinkText string
	ImageURL          string
	MediaURL          string
	// SelectionText is the text selected where the menu opened.
	SelectionText string
	// Editable is set over a text field or editable content.
	Editable bool
	// FrameURL is the URL of the frame clicked, when it is not the
	// page's own document but a frame in it.
	FrameURL string
}

ContextMenuTarget is what a context menu was opened on.

type Cookie struct {
	Name, Value, Domain, Path string
	Expires                   time.Time
	Secure, HTTPOnly          bool
	SameSite                  string
}

Cookie is a normalized snapshot of a cookie in a page store. SameSite is lax, strict, none, or empty (unknown on output only). A zero Expires denotes a session cookie.

type CookieKey added in v0.5.0

type CookieKey struct{ Name, Domain, Path string }

CookieKey identifies a cookie without request URL matching.

type Cursor added in v0.2.0

type Cursor uint8

Cursor is a pointer shape.

const (
	CursorDefault Cursor = iota
	CursorPointer
	CursorText
	CursorMove
	CursorResizeEW
	CursorResizeNS
	CursorResizeNWSE
	CursorResizeNESW
	CursorNotAllowed
	CursorCrosshair
	CursorGrab
	CursorGrabbing
	CursorResizeN
	CursorResizeE
	CursorResizeS
	CursorResizeW
	CursorResizeColumn
	CursorResizeRow
	CursorVerticalText
	CursorCopy
	CursorAlias
	CursorContextMenu
	CursorNone
	CursorProgress
	CursorWait
	CursorHelp
	CursorCell
	CursorZoomIn
	CursorZoomOut
	CursorAllScroll
	CursorNoDrop
)

type DamageSurface added in v0.2.9

type DamageSurface interface {
	// PresentDamage is PresentPixels for a frame that differs from the
	// last one presented only within damage, in device pixels.
	PresentDamage(pix []byte, stride, width, height int, damage []image.Rectangle)
}

DamageSurface is a Surface that shows a frame drawn in memory by what changed since the last one: Linux's, whose toolkit then repaints, and the compositor takes, only that.

type DataDragEvent added in v0.2.17

type DataDragEvent struct {
	Offer     transfer.Offer
	Session   string
	Local     any
	Data      transfer.Data
	Operation transfer.Operation
	Formats   []transfer.Format
	HasFiles  bool
	Resolved  bool // the core substituted its process-local data
}

DataDragEvent is a synchronous destination query. The core resolves Session to Local and the original Data only for a live local source. Content sets Operation and Formats to accept. Backends read those formats on drop, never while hovering, and copy the bytes into Data.

type DataStore added in v0.7.2

type DataStore interface {
	// Close lets the store go once the backend no longer needs it: the
	// core calls it when no page uses an ephemeral store, whose data then
	// goes, and makes another store for the session's next page. Calls
	// under way finish.
	Close()
}

DataStore is a website data store a backend made: cookies, local and session storage, IndexedDB, caches and service workers that the pages using it share, apart from those of other stores.

type DataStoreOptions added in v0.7.2

type DataStoreOptions struct {
	// ID identifies a persistent store from one run to the next: a UUID
	// in lowercase hex with dashes, which the core derives from the
	// session's name. It is empty for an ephemeral store.
	ID string
	// Ephemeral keeps the store's data in memory, where it goes with the
	// store.
	Ephemeral bool
	// DataDir and CacheDir are where a persistent store keeps its data and
	// its caches, for the backends that choose (Linux).
	DataDir, CacheDir string
}

DataStoreOptions describe a website data store (AppController.NewDataStore).

type Dialogs

type Dialogs interface {
	ShowOpenDialog(parent Window, opts *OpenDialogOptions, cb func(paths []string, err error))
	ShowSaveDialog(parent Window, opts *SaveDialogOptions, cb func(path string, err error))
	ShowMessageBox(parent Window, opts *MessageBoxOptions, cb func(res MessageBoxResult, err error))
}

Dialogs shows native dialogs. Callbacks run on the main thread exactly once. parent may be nil for application modal dialogs.

type Display

type Display struct {
	ID          int64
	Label       string
	Bounds      Rect
	WorkArea    Rect
	ScaleFactor float64
	Rotation    int
	Internal    bool
	Primary     bool
}

Display describes a monitor.

type DoubleClick added in v0.5.2

type DoubleClick struct {
	Time   time.Duration
	DX, DY float64
}

DoubleClick is how far apart in time and on each axis two presses make a double click.

type DragRequest added in v0.2.17

type DragRequest struct {
	Data                      transfer.Data
	Operations                transfer.Operation
	Session                   string
	X, Y                      float64
	Preview                   []byte // premultiplied BGRA, one pixel per DIP
	Width, Height, HotX, HotY int
	Done                      func(transfer.Result)
}

DragRequest starts a native drag on the main thread during a pointer gesture. Done must be called exactly once on the main thread. Windows may run a native nested event loop; other backends return immediately.

type ExitBackend added in v0.9.2

type ExitBackend interface {
	Exiting()
}

ExitBackend releases what the native application must not take into the process's exit (Windows: its windows, whose window procedure is Go's and cannot run once the process exits). The app calls Exiting once, on the main thread, when it has finished and is about to exit; nothing native is used after it.

type FileFilter

type FileFilter struct {
	Name       string
	Extensions []string
	MIMETypes  []string
}

FileFilter restricts the files shown in file dialogs: those of its Extensions, and of its MIMETypes, which may be "kind/*".

type FileWatch added in v0.5.0

type FileWatch interface {
	Add(target FileWatchTarget) error
	Remove(id uint64)
	Close()
}

FileWatch watches the targets the core adds. Its methods may be called from any goroutine, one at a time. Close stops the watch and waits until every handle is released and notify will not be called again; it must not be called from notify.

type FileWatchKind added in v0.5.0

type FileWatchKind uint8

FileWatchKind says what changed. Backends report what the system tells them; the core rescans what a notice names, so a kind is only a hint.

const (
	// FileWatchDirty means something about the target or its child changed.
	FileWatchDirty FileWatchKind = iota
	FileWatchWrite
	FileWatchCreate
	FileWatchRemove
	FileWatchMoveFrom
	FileWatchMoveTo
	// FileWatchLost means the system stopped watching the target, for
	// example because it was deleted; the core enrolls it again if it
	// still exists.
	FileWatchLost
)

type FileWatchNotice added in v0.5.0

type FileWatchNotice struct {
	Target uint64
	Kind   FileWatchKind
	Name   string
	Err    error
}

FileWatchNotice reports a change to a target (Name empty) or to one of the immediate children of a directory target (Name its name; a path for a Subtree target). A notice with Err set ends the watch, except ErrFileWatchOverflow, after which the core rescans everything.

type FileWatchTarget added in v0.5.0

type FileWatchTarget struct {
	ID   uint64
	Path string
	// Directory says the target is a directory. A backend that watches a
	// file only through its directory, which the core enrolls before it
	// lists it, returns ErrUnsupported for a target that isn't one, and
	// the core enrolls no more files.
	Directory bool
	// Info is what the core's scan saw at Path. Backends open the target
	// and check it is still the same file, so that a replacement racing
	// the enrollment is not watched in its place.
	Info fs.FileInfo
	// Subtree asks to watch everything beneath the directory with this one
	// target, and to name what changes deeper down by its slash-separated
	// path relative to it. A backend that can't returns ErrUnsupported,
	// and the core enrolls every directory instead.
	Subtree bool
}

FileWatchTarget is a file or directory the core enrolls in a FileWatch. IDs are never reused within a FileWatch.

type FirstFrameSurface added in v0.7.4

type FirstFrameSurface interface {
	// FirstFrame tells that the content presented its first frame. It is
	// called once, within the frame, before the window is told it is
	// ready to show.
	FirstFrame()
}

FirstFrameSurface is a Surface told when the content's first frame reached it: a window made hidden draws that frame while hidden, which no paint or refresh of the display asks for, and which makes it ready to show. Windows' window also stays out of sight until then, rather than show what it holds before, white.

type Flyout added in v0.4.1

type Flyout struct {
	// Anchor is the rectangle the flyout is placed against, in DIPs
	// relative to the parent's content area.
	Anchor Rect
	// Tray anchors the flyout to a tray icon, where it shows without a
	// parent, above the windows of other apps: the icon's Bounds are the
	// anchor, on the screen. Where they are empty, it goes in the middle
	// of the primary display's work area.
	Tray Tray
	// Side is where the flyout goes from Anchor, and Align how it lines
	// up with it along that side.
	Side  Side
	Align Align
	// Gap is the distance between Anchor and the flyout, in DIPs.
	Gap int
	// Focusable makes the flyout take the keyboard as it shows, and close
	// (WindowHandler.ShouldClose) when the user presses outside it or
	// another window takes the keyboard. Others never take the keyboard
	// and stay until closed.
	Focusable bool
	// Popover shows the flyout in a popover of the system, which draws its
	// background and an arrow pointing at the middle of Anchor, and places
	// it (macOS); Align and Gap do not apply. Elsewhere it is ignored.
	Popover bool
	// Radius rounds the flyout's corners, in DIPs, its content, material
	// and shadow with them (macOS).
	Radius int
}

Flyout makes a window a flyout (WindowOptions.Flyout): a borderless window owned by its parent and placed next to a rectangle of it, which may extend beyond the parent but stays in the work area of a display.

func (*Flyout) Gravities added in v0.4.1

func (f *Flyout) Gravities() (anchor, window Gravity, dx, dy int)

Gravities returns the point of the anchor the flyout is placed at, the point of the flyout that goes there, and the offset between them.

func (*Flyout) Place added in v0.4.1

func (f *Flyout) Place(anchor Rect, size Size, work Rect) (r Rect, flippedX, flippedY bool)

Place returns where a flyout of the given size goes, its anchor being at anchor on the screen, in the work area of the display that work returns for anchor. It resolves the placement as GTK places popups on X11 (gdk_window_move_to_rect, with GDK_ANCHOR_FLIP, GDK_ANCHOR_SLIDE and GDK_ANCHOR_RESIZE) and Wayland compositors do (xdg_positioner): on each axis the flyout flips to the other side of the anchor, or to the other end of it, where it would not fit and the flipped one would; then it slides along the edge it would cross, back into the work area; then it shrinks to it. flippedX and flippedY tell whether it flipped.

type FontRendering added in v0.2.4

type FontRendering struct {
	// Antialias is "none", "gray" or "subpixel".
	Antialias string
	// Hinting is "none", "slight", "medium" or "full".
	Hinting string
	// Subpixels is the order of the screen's subpixels: "rgb", "bgr",
	// "vrgb" or "vbgr".
	Subpixels string
}

FontRendering is how the desktop's settings say to rasterize text, as GTK's gtk-xft settings: each field is "" for the default, or unknown.

type FrameRateSurface added in v0.7.0

type FrameRateSurface interface {
	// SetFrameRate tells how many frames a second come from now on while
	// they follow each other, a whole fraction of RefreshRate, or 0 for
	// one each refresh.
	SetFrameRate(fps float64)
}

FrameRateSurface is a Surface that can have its display refresh less often than it can while frames come at a lower rate, as macOS's display links do on ProMotion displays.

type GlassPlacement added in v0.8.0

type GlassPlacement struct {
	// ID identifies the element showing the glass from one frame to the
	// next.
	ID uint64
	// Frame is the glass's box; Clip the part of it that shows.
	Frame, Clip RectF
	// Radii are the corners of the hole the content leaves, clockwise
	// from the top left, and CornerRadius the one the glass view takes,
	// where it takes one.
	Radii        [4]float64
	CornerRadius float64
	// Style is NSGlassEffectView's style: 0 regular, 1 clear.
	Style int
	// Tint colors the glass, nil for none.
	Tint *Color
}

GlassPlacement is where a surface shows the system's glass (Surface.PlaceGlass), under its content, in DIPs from its top left.

type GlassSurface added in v0.8.0

type GlassSurface interface {
	// NativeGlassSupported reports whether the system's glass is available.
	NativeGlassSupported() bool
	// PlaceGlass shows the glass where the content's last frame shows it,
	// and hides the rest.
	PlaceGlass(places []GlassPlacement)
}

GlassSurface is a Surface that draws the system's glass under its content, as macOS 26's NSGlassEffectView does, where the content leaves a hole.

type Gravity added in v0.4.1

type Gravity struct{ X, Y int }

Gravity is one of the nine points of a rectangle: its corners, the middles of its edges and its center, as GdkGravity and Wayland's xdg_positioner anchors and gravities name them. X and Y are -1 for the left or top, 0 for the middle, 1 for the right or bottom.

type HeldKeys added in v0.8.0

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

HeldKeys keeps the keys whose presses a backend sent the content and whose releases it has not, for a backend whose system keeps some releases from the window: those an input method takes, those a menu's loop takes, and, in a Mac's browsers, those let go of while Command is held. The backend lets go of them itself (Lift, LiftAll), so that the content never holds a key the user let go of (KeyReleased).

func (*HeldKeys) Lift added in v0.8.0

func (h *HeldKeys) Lift(key, physical Key, mods Modifiers, send func(SurfaceEvent) bool)

Lift sends the release of the key held at physical (or key, where its position is unknown), whose own release the system keeps from the window, as an input method takes it, through send, which tracks it. It does nothing when no such key is held.

func (*HeldKeys) LiftAll added in v0.8.0

func (h *HeldKeys) LiftAll(mods Modifiers, send func(SurfaceEvent) bool)

LiftAll sends the releases of every key held through send, as a menu's loop takes the keyboard.

func (*HeldKeys) Track added in v0.8.0

func (h *HeldKeys) Track(ev SurfaceEvent) bool

Track notes ev, an event the backend is about to send the content, and reports whether to send it: false for the release of a key Lift or LiftAll let go of already.

type IdleSurface added in v0.2.9

type IdleSurface interface {
	// Idle tells that no frame came for a while: the surface may give
	// back memory that drawing frames took and freed.
	Idle()
}

IdleSurface is a Surface that can give back memory once frames stop.

type ImmediateFrameSurface added in v0.7.0

type ImmediateFrameSurface interface {
	// FramesAtOnce marks the surface.
	FramesAtOnce()
}

ImmediateFrameSurface is a Surface whose RequestFrame sends a SurfaceFrame at once, as Windows' does, rather than at the display's next refresh: a frame due at a later refresh waits on a timer instead.

type InputComposition added in v0.2.17

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

InputComposition preserves the native end-preedit/commit ordering without owning text. Some input methods unmark before delivering their result.

func (*InputComposition) Cancel added in v0.8.0

func (c *InputComposition) Cancel(client TextInputClient)

Cancel discards the marked text, for an input method that gives its composition up without emptying it first. The rest of the document, the selection included, stays as it is.

func (*InputComposition) End added in v0.2.17

func (c *InputComposition) End(client TextInputClient)

func (*InputComposition) Replace added in v0.2.17

func (c *InputComposition) Replace(client TextInputClient, r *TextRange, text string)

func (*InputComposition) Reset added in v0.2.17

func (c *InputComposition) Reset()

type InputRegionWindow added in v0.9.0

type InputRegionWindow interface {
	SetInputRegion(region []Rect)
}

InputRegionWindow is a window that takes the mouse only where its input region is (macOS, Linux, Windows): SetInputRegion limits it to region, in DIPs from the top-left corner of the content, and lets the mouse through elsewhere; nil gives it all of the window, an empty region none. SetIgnoreMouseEvents(true) wins over it. Apart from Window, so that only apps setting a region link it.

type JumpList added in v0.5.0

type JumpList struct {
	Tasks []JumpListTask
}

JumpList is the whole jump list of the app: Windows replaces all of it at each commit.

type JumpListTask added in v0.5.0

type JumpListTask struct {
	Title       string
	Description string
	Path        string
	Args        []string
	WorkingDir  string
	IconPath    string
	IconIndex   int
}

JumpListTask is a task of a jump list: a program to run with its arguments, unquoted, its label, tooltip and icon.

type Key added in v0.2.0

type Key uint16

Key identifies a key. Letter and digit keys follow the keyboard layout: KeyA is the key that types an a.

const (
	KeyUnknown Key = iota
	KeyEnter
	KeyEscape
	KeyBackspace
	KeyTab
	KeySpace
	KeyDelete
	KeyInsert
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyLeft
	KeyRight
	KeyUp
	KeyDown
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyMinus
	KeyEqual
	KeyComma
	KeyPeriod
	KeySlash
	KeySemicolon
	KeyQuote
	KeyBracketLeft
	KeyBracketRight
	KeyBackslash
	KeyBackquote
	KeyContextMenu
	Key0
	Key1
	Key2
	Key3
	Key4
	Key5
	Key6
	Key7
	Key8
	Key9
	KeyA
	KeyB
	KeyC
	KeyD
	KeyE
	KeyF
	KeyG
	KeyH
	KeyI
	KeyJ
	KeyK
	KeyL
	KeyM
	KeyN
	KeyO
	KeyP
	KeyQ
	KeyR
	KeyS
	KeyT
	KeyU
	KeyV
	KeyW
	KeyX
	KeyY
	KeyZ
	// KeyBack and KeyForward go back and forward in a history: the side
	// buttons of a mouse, the keys of keyboards that have them, and on
	// macOS swipes between pages.
	KeyBack
	KeyForward
)

func KeyForRune added in v0.2.0

func KeyForRune(r rune) Key

KeyForRune returns the key typing r unshifted, KeyUnknown for others.

func KeyForScancode added in v0.4.3

func KeyForScancode(code uint16) Key

KeyForScancode returns the key at a scancode's position on an ANSI US keyboard, whatever the layout types (SurfaceEvent.PhysicalKey), or KeyUnknown for a key it does not map. A scancode is Linux's evdev code (the X keycode less 8) or Windows's XT set 1 code without the extended flag.

type KeyCode added in v0.8.0

type KeyCode uint16

KeyCode is a key by its position on the keyboard, whatever the layout types and whichever system reports it: a USB HID usage ID of the keyboard page (0x07), named after the code of UI Events' KeyboardEvent. Unlike Key it tells the sides of the modifiers and every key of a full keyboard.

const (
	CodeUnknown KeyCode = 0

	CodeKeyA KeyCode = iota + 3
	CodeKeyB
	CodeKeyC
	CodeKeyD
	CodeKeyE
	CodeKeyF
	CodeKeyG
	CodeKeyH
	CodeKeyI
	CodeKeyJ
	CodeKeyK
	CodeKeyL
	CodeKeyM
	CodeKeyN
	CodeKeyO
	CodeKeyP
	CodeKeyQ
	CodeKeyR
	CodeKeyS
	CodeKeyT
	CodeKeyU
	CodeKeyV
	CodeKeyW
	CodeKeyX
	CodeKeyY
	CodeKeyZ
	CodeDigit1
	CodeDigit2
	CodeDigit3
	CodeDigit4
	CodeDigit5
	CodeDigit6
	CodeDigit7
	CodeDigit8
	CodeDigit9
	CodeDigit0
	CodeEnter
	CodeEscape
	CodeBackspace
	CodeTab
	CodeSpace
	CodeMinus
	CodeEqual
	CodeBracketLeft
	CodeBracketRight
	CodeBackslash
)

The keys by position.

const (
	CodeSemicolon KeyCode = iota + 0x33
	CodeQuote
	CodeBackquote
	CodeComma
	CodePeriod
	CodeSlash
	CodeCapsLock
	CodeF1
	CodeF2
	CodeF3
	CodeF4
	CodeF5
	CodeF6
	CodeF7
	CodeF8
	CodeF9
	CodeF10
	CodeF11
	CodeF12
	CodePrintScreen
	CodeScrollLock
	CodePause
	CodeInsert
	CodeHome
	CodePageUp
	CodeDelete
	CodeEnd
	CodePageDown
	CodeArrowRight
	CodeArrowLeft
	CodeArrowDown
	CodeArrowUp
	CodeNumLock
	CodeNumpadDivide
	CodeNumpadMultiply
	CodeNumpadSubtract
	CodeNumpadAdd
	CodeNumpadEnter
	CodeNumpad1
	CodeNumpad2
	CodeNumpad3
	CodeNumpad4
	CodeNumpad5
	CodeNumpad6
	CodeNumpad7
	CodeNumpad8
	CodeNumpad9
	CodeNumpad0
	CodeNumpadDecimal
	CodeIntlBackslash
	CodeContextMenu
	CodePower
	CodeNumpadEqual
	CodeF13
	CodeF14
	CodeF15
	CodeF16
	CodeF17
	CodeF18
	CodeF19
	CodeF20
	CodeF21
	CodeF22
	CodeF23
	CodeF24
)
const (
	CodeAudioVolumeMute KeyCode = iota + 0x7F
	CodeAudioVolumeUp
	CodeAudioVolumeDown
)
const (
	CodeNumpadComma KeyCode = 0x85
	CodeIntlRo      KeyCode = 0x87
	CodeKanaMode    KeyCode = 0x88
	CodeIntlYen     KeyCode = 0x89
	CodeConvert     KeyCode = 0x8A
	CodeNonConvert  KeyCode = 0x8B
	CodeLang1       KeyCode = 0x90
	CodeLang2       KeyCode = 0x91
	CodeLang3       KeyCode = 0x92
	CodeLang4       KeyCode = 0x93
)
const (
	CodeControlLeft KeyCode = iota + 0xE0
	CodeShiftLeft
	CodeAltLeft
	CodeSuperLeft
	CodeControlRight
	CodeShiftRight
	CodeAltRight
	CodeSuperRight
)

func KeyCodeForDOM added in v0.8.0

func KeyCodeForDOM(code string) KeyCode

KeyCodeForDOM returns the key of a KeyboardEvent's code, CodeUnknown for one it does not map.

func KeyCodeForEvdev added in v0.8.0

func KeyCodeForEvdev(code uint16) KeyCode

KeyCodeForEvdev returns the key of a Linux evdev code (KEY_*; an X or GDK hardware keycode less 8), CodeUnknown for one it does not map.

func KeyCodeForMac added in v0.8.0

func KeyCodeForMac(code uint16) KeyCode

KeyCodeForMac returns the key of a macOS virtual key code, CodeUnknown for one it does not map, as Fn.

func KeyCodeForXT added in v0.8.0

func KeyCodeForXT(scan uint8, extended bool) KeyCode

KeyCodeForXT returns the key of an XT set 1 scancode as Windows reports it in a key message's lParam, extended being its bit 24, CodeUnknown for one it does not map. Windows's own quirks are in it: NumLock is the extended 0x45 and Pause the plain one, Alt+Print Screen and Ctrl+Pause have codes of their own, and CJK input methods set the extended bit of the right Shift.

func MacFlagsChanged added in v0.8.0

func MacFlagsChanged(keyCode uint16, flags uint) (code KeyCode, down bool)

MacFlagsChanged returns the key of a flagsChanged: event, of virtual key code keyCode and NSEvent modifierFlags flags, and whether it pressed that key rather than let go of it; CodeUnknown for one of no modifier (AppKit sends some with other codes) and for Fn, which has no code. The flags' device-dependent bits tell the sides; where the left and right bits are both clear while the side-independent bit is set, as in events another program made, it counts as pressed. Caps Lock counts as pressed: macOS tells of it once for each change of the lock, the backend gives it a release at once.

type LaterClipboard added in v0.8.0

type LaterClipboard interface {
	WriteTextThen(text string, done func(error))
}

LaterClipboard is a clipboard whose writes finish later, as a browser's, whose clipboard answers with a promise: WriteTextThen puts text there as WriteText does, and gives done what came of it, on the main thread. Desktops' clipboards answer at once (WriteData).

type MaterialSurface added in v0.3.4

type MaterialSurface interface {
	// ShowsMaterial reports whether the window shows a material behind the
	// content now: what its frames leave transparent shows it, rather than
	// nothing.
	ShowsMaterial() bool
}

MaterialSurface is a Surface whose window can show a material (vibrancy) behind the content, wherever its frames are transparent.

type MaximizeButtonSurface added in v0.6.0

type MaximizeButtonSurface interface {
	// SetMaximizeButton tells where the content shows the window's
	// maximize button, in DIPs from the top-left corner of the content.
	// The zero RectF is nowhere.
	SetMaximizeButton(r RectF)
}

MaximizeButtonSurface is a Surface whose window makes the maximize button its content draws (in a window without its own, as WindowOptions.HideWindowButtons) the system's for the pointer: Windows shows the snap layouts over it. Package ui reaches it only once a view marks such a button (ui.Element.MaximizeButton), for apps that mark none not to link it.

type MediaCommand added in v0.7.0

type MediaCommand uint32

MediaCommand is a command of the system's media controls, or a set of them (NowPlayingInfo.Commands).

const (
	MediaPlay MediaCommand = 1 << iota
	MediaPause
	MediaTogglePlayPause
	MediaStop
	MediaNext
	MediaPrevious
	MediaSeek
	// MediaRaise asks for the app's window in front, as MPRIS's Raise
	// does. The core answers it whatever the info's Commands, which never
	// hold it.
	MediaRaise
)
type Menu struct {
	Items []*MenuItem
	// RightToLeft lays a context menu out right to left, as that of an
	// interface laid out so: its items from the right, opening to the
	// left of where it shows, which is its top right corner.
	RightToLeft bool
}

Menu is a snapshot of a menu tree.

func (m *Menu) Apply(it *MenuItem)

Apply gives the items of the menu that it is a snapshot of, by ID, its state: a backend that keeps a snapshot to build menus from later (a tray's, the application menu for new windows) keeps it current with the updates it is given.

func (m *Menu) TidySeparators()

TidySeparators drops the separators of a menu shown that would start or end it, or follow another, as the items removed between them leave: Remove(ContextMenuBack, ContextMenuForward, ContextMenuReload) leaves the one after them first.

type MenuIcon struct {
	// PNG is the image, its bytes never changed once made.
	PNG []byte
	// Template is a black and transparent image, which takes the color of
	// the menu's text where the backend can tint it.
	Template bool
	// contains filtered or unexported fields
}

MenuIcon is the image a menu item shows beside its label. Package mygo shares one between the snapshots of the items showing the same image, and makes a new one when an item's image changes, so a backend tells a change by the pointer and decodes each image once (Native).

func (ic *MenuIcon) Native(make func() any) any

Native returns what make made of the icon the first time it was asked: a backend's decoding of it, kept for as long as the icon is, which make may free with runtime.AddCleanup. A nil result is kept too, as an image that cannot be decoded. Backends call it on the main thread.

type MenuItem struct {
	ID             int
	Type           MenuItemType
	Label          string
	Subtitle       string
	Badge          string
	BadgeAlign     BadgeAlignment
	BadgeShape     BadgeShape
	BadgeColor     *Color
	BadgeTextColor *Color
	KeepOpen       bool
	Role           string
	Accelerator    string
	Enabled        bool
	Visible        bool
	Checked        bool
	ToolTip        string
	// Icon is the image beside the label, nil for none.
	Icon *MenuIcon
	// IconColor, when set, is the color of a template Icon in the menus
	// package ui draws, in place of the text's; backends ignore it.
	IconColor *Color
	Submenu   *Menu
	// Native is set on the web view's own items of a page's context menu
	// (WindowHandler.ContextMenu): the backend's number for the item,
	// from 1, which it shows where the core puts it, doing what the web
	// view does; ID is then not the backend's business. Name is such an
	// item's name (ContextMenuReload and the other names of package mygo,
	// else the platform's own), and Accelerator the platform's own text of
	// its shortcut, shown as it is, where the backend draws the menu.
	Native int
	Name   string
}

MenuItem is a snapshot of a menu item. ID identifies the public item the native item was built from.

func (it *MenuItem) LabelWithBadge() string

LabelWithBadge is the label of a backend that shows the subtitle on a line of its own, followed by the badge.

func (it *MenuItem) LabelWithSubtitle() string

LabelWithSubtitle is the label of a backend that can't show the subtitle on a line of its own.

func (it *MenuItem) LabelWithSubtitleAndBadge() string

LabelWithSubtitleAndBadge is the label of a backend that can show neither the subtitle nor the badge on its own: both follow the label.

type MenuItemType int

MenuItemType is the kind of a menu item.

const (
	MenuItemNormal MenuItemType = iota
	MenuItemSeparator
	MenuItemSubmenu
	MenuItemCheckbox
	MenuItemRadio
)

Menu item kinds.

type MessageBoxOptions

type MessageBoxOptions struct {
	// Type is "none", "info", "error", "question" or "warning".
	Type            string
	Title           string
	Message         string
	Detail          string
	Buttons         []string
	DefaultID       int
	CancelID        int
	DestructiveIDs  []int
	CheckboxLabel   string
	CheckboxChecked bool
}

MessageBoxOptions configures a message box.

type MessageBoxResult

type MessageBoxResult struct {
	Response        int
	CheckboxChecked bool
}

MessageBoxResult is the outcome of a message box.

type Modifiers added in v0.2.0

type Modifiers uint8

Modifiers are the modifier keys held during an event.

const (
	ModShift Modifiers = 1 << iota
	ModCtrl
	ModAlt
	// ModSuper is Command on macOS and the Windows key elsewhere.
	ModSuper
)
type Navigation struct {
	URL           string
	IsMainFrame   bool
	UserInitiated bool
	// Unasked is true for the navigations the app is not asked about
	// (OnWillNavigate): reloads, history navigations and the loads the app
	// starts.
	Unasked bool
	// Reload is true for a reload of the main frame's document, whoever
	// started it: Reload, the page's location.reload(), the web view's own
	// menus.
	Reload bool
}

Navigation describes a pending navigation.

type Network added in v0.5.0

type Network interface {
	// Watch starts reporting AppHandler.NetworkChanged, which may also be
	// called when the status stayed the same.
	Watch()
	// Status returns the current state.
	Status() NetworkStatus
}

Network reports the state of the computer's network connection.

type NetworkStatus added in v0.5.0

type NetworkStatus struct {
	Online  bool
	Metered bool // expensive, metered or in a low data mode
}

NetworkStatus is the state of the computer's network connection.

type NewWindowRequest

type NewWindowRequest struct {
	URL         string
	FrameName   string
	Disposition string
	// Width/Height/X/Y come from window.open() features; zero when absent.
	X, Y, Width, Height int
	// UserInitiated is true when a user's gesture, as a click or a key
	// press, opened the window: a click on the link, or its handler
	// calling window.open().
	UserInitiated bool
	// Native must be copied into WindowOptions.Native of the window that is
	// returned.
	Native uintptr
}

NewWindowRequest describes a window.open() or target=_blank request.

type Notification

type Notification struct {
	ID       string
	Title    string
	Subtitle string
	Body     string
	Silent   bool
	// Group gathers the notifications that share it (threadIdentifier on
	// macOS).
	Group string
	// Image is shown with the notification: PNG or JPEG, or nil. The core
	// links the backend's code of images (LinkNotificationImages) before
	// it gives one.
	Image  []byte
	Sender *NotificationSender
}

Notification is a desktop notification.

type NotificationSender added in v0.6.0

type NotificationSender struct {
	ID, Name string
	Avatar   []byte
}

NotificationSender describes an incoming direct message's sender.

type NowPlaying added in v0.7.0

type NowPlaying interface {
	// Set shows info; nil removes it and stops reporting commands.
	Set(info *NowPlayingInfo)
}

NowPlaying shows what the app plays where the system shows media, and reports AppHandler.MediaCommand for the commands the info enables.

type NowPlayingInfo added in v0.7.0

type NowPlayingInfo struct {
	Title, Artist, Album string
	// Artists are the track's artists, one each, for the systems that
	// take a list (MPRIS); Artist is them joined with ", ".
	Artists  []string
	Artwork  []byte // PNG or JPEG, or nil
	Duration time.Duration
	// Position is where playback was when the core set the info; the
	// system advances it at Rate while State is "playing".
	Position time.Duration
	Rate     float64 // the speed while playing, 1 by default
	State    string  // "playing", "paused" or "stopped"
	Commands MediaCommand
}

NowPlayingInfo is what the app plays, fully defaulted by the core.

type OccludableSurface added in v0.2.9

type OccludableSurface interface {
	// Occluded reports whether nothing of the surface shows on screen. The
	// surface sends SurfaceHidden as none of it shows any more, and
	// SurfaceShown once some of it shows again.
	Occluded() bool
}

OccludableSurface is a Surface that tells when nothing of it shows, as when other windows cover its window, while the system may still give it frames: the content then draws nothing that moves until it shows again.

type OpenDialogOptions

type OpenDialogOptions struct {
	Title                      string
	DefaultPath                string
	ButtonLabel                string
	Message                    string
	Filters                    []FileFilter
	OpenFiles                  bool
	OpenDirectories            bool
	Multiple                   bool
	ShowHiddenFiles            bool
	CreateDirectories          bool
	TreatPackagesAsDirectories bool
}

OpenDialogOptions configures an open panel.

type PDFOptions

type PDFOptions struct {
	Landscape                                        bool
	PageWidth, PageHeight                            float64
	MarginTop, MarginRight, MarginBottom, MarginLeft float64
	Background                                       bool
}

PDFOptions configures Window.PrintToPDF; lengths are in inches.

type PacedSurface added in v0.6.0

type PacedSurface interface {
	// FrameNow sends a SurfaceFrame at once, as a refresh would, for a
	// frame a Paced one left to draw.
	FrameNow()
}

PacedSurface is a Surface whose frames following each other come at the display's refreshes, marked Paced: a renderer that waits for the display lets such a frame draw once the display can take it, with FrameNow.

type PackageInfo

type PackageInfo struct {
	Name       string
	Version    string
	Identifier string
}

PackageInfo is metadata of a packaged application.

type Page added in v0.4.0

type Page interface {
	// WebViewHandle returns the native webview object.
	WebViewHandle() uintptr

	LoadURL(url string)
	LoadHTML(html, baseURL string)
	LoadFile(path, readAccessDir string)
	Reload(ignoreCache bool)
	StopLoading()
	GoBack()
	GoForward()
	CanGoBack() bool
	CanGoForward() bool
	URL() string
	IsLoading() bool
	// Eval runs JavaScript in the main frame and ignores the result.
	Eval(js string)
	// SetUserScripts replaces the scripts of WindowOptions.UserScripts:
	// the documents the page loads from then on run the new ones, while
	// the current document keeps what it ran. Scripts a backend injects
	// itself, as the title bar's, stay.
	SetUserScripts(scripts []UserScript)
	// SetContentRules replaces the content rule lists the page's loads
	// go through from then on with lists, handles of
	// AppController.CompileContentRules; none removes them.
	SetContentRules(lists []any)
	// CallAsyncFunction runs body as the body of an async function in the
	// main frame, awaits it and reports the returned value, which the
	// caller arranges to be a string. err is non-nil when the body fails to
	// compile or the evaluation fails natively. Page CSP does not apply.
	CallAsyncFunction(body string, cb func(result string, err error))
	SetZoom(factor float64)
	Zoom() float64
	SetUserAgent(ua string)
	UserAgent() string
	// ProcessID returns the ID of the operating system's process that
	// the backend reports for the page (see Page.ProcessID in package
	// mygo for which one), 0 when it reports none.
	ProcessID() int
	// GPUProcessID returns the ID of the operating system's process that
	// does the page's graphics and media (see Page.GPUProcessID in
	// package mygo), 0 when the backend reports none.
	GPUProcessID() int
	// IsAudible reports whether the page plays sound, from any of its
	// frames, as WindowHandler.AudibleChanged reports its changes; false
	// where the backend cannot tell.
	IsAudible() bool
	// SetAudioMuted mutes the page's sound, or lets it play again. A
	// backend whose web view does not exist yet mutes it once it does;
	// one that cannot mute does nothing.
	SetAudioMuted(muted bool)
	// IsAudioMuted reports what SetAudioMuted set, false where the
	// backend cannot mute.
	IsAudioMuted() bool
	// CaptureState reports whether the page captures kind, and whether
	// it is muted, as WindowHandler.CaptureStateChanged reports its
	// changes; CaptureNone where the backend cannot tell.
	CaptureState(kind CaptureKind) CaptureState
	// SetCaptureState mutes the page's capture of kind (CaptureMuted),
	// lets it go on (CaptureActive) or stops it (CaptureNone). It does
	// nothing while the page captures no such device, and where the
	// backend cannot.
	SetCaptureState(kind CaptureKind, state CaptureState)
	// TogglePictureInPicture moves a video of the page into picture in
	// picture, or the one out back into the page (see
	// Page.TogglePictureInPicture in package mygo for which video); a
	// backend that cannot does nothing.
	TogglePictureInPicture()
	// PictureInPictureActive tells cb whether a video of the page is in
	// picture in picture, false where the backend cannot tell. cb runs on
	// the main thread exactly once, maybe before PictureInPictureActive
	// returns.
	PictureInPictureActive(cb func(active bool))
	// SessionState returns the engine's own state of the page's
	// back/forward list, with the scroll positions and form state it
	// saved of its entries, nil where the backend keeps none.
	SessionState() []byte
	// RestoreSessionState puts back a back/forward list that
	// SessionState returned and loads its current entry, as LoadURL
	// loads a page, and reports whether it did: false where the backend
	// keeps no state or can't read this one, for the core to load the
	// page's URL instead.
	RestoreSessionState(state []byte) bool
	OpenDevTools()
	CloseDevTools()
	IsDevToolsOpened() bool
	// CapturePage takes a PNG snapshot of the visible page.
	CapturePage(cb func(png []byte, err error))
	// PrintToPDF renders the page as a PDF document.
	PrintToPDF(opts PDFOptions, cb func(pdf []byte, err error))
	// DroppedFiles returns the paths of the files of the latest drop on
	// the page and forgets them. The page reports the drop itself (a
	// "drop" message); backends record the paths before the page sees it.
	DroppedFiles() []string
	Print()
}

Page is the web page of a Window, or of a WebView.

type Point

type Point struct{ X, Y int }

Point is a position in screen coordinates (DIPs, origin top-left of the primary display).

type PointerAccuracy added in v0.8.0

type PointerAccuracy uint8

PointerAccuracy is how accurately a pointing device points.

const (
	// PointerFine is a mouse's, a touchpad's or a pen's.
	PointerFine PointerAccuracy = iota
	// PointerCoarse is a finger's on a touch screen.
	PointerCoarse
	// PointerNone is that of no pointing device at all.
	PointerNone
)

type PointerKind added in v0.8.0

type PointerKind uint8

PointerKind is the kind of device of a pointer event.

const (
	// PointerMouse is a mouse, or a touchpad, which moves the pointer as
	// one does.
	PointerMouse PointerKind = iota
	// PointerPen is a pen on a tablet or a screen, its eraser too.
	PointerPen
	// PointerTouch is a finger on a touchscreen.
	PointerTouch
)

type Power

type Power interface {
	// Watch starts reporting AppHandler.PowerEvent.
	Watch()
	// KeepAwake keeps the system, and with display the display, from
	// sleeping while idle until release is called.
	KeepAwake(display bool, reason string) (release func())
	// KeepRunning keeps the system from slowing the app down while none
	// of its windows shows, as macOS's App Nap does, until release is
	// called; it leaves the system free to sleep when idle.
	KeepRunning(reason string) (release func())
	OnBattery() bool
	IdleTime() time.Duration
}

Power reports power and session events and keeps the computer awake.

type Preferences added in v0.2.5

type Preferences struct {
	// Accent is the accent color the user chose; A is 0 where the desktop
	// has none.
	Accent Color
	// ReduceMotion asks for less motion: macOS's Reduce Motion, Windows's
	// animation effects and GNOME's animations turned off.
	ReduceMotion bool
	// ReduceTransparency asks for opaque surfaces in place of translucent
	// ones: macOS's Reduce Transparency, Windows's transparency effects
	// turned off, prefers-reduced-transparency in browsers. Linux desktops
	// have no such setting.
	ReduceTransparency bool
	// HighContrast asks for more contrast: macOS's Increase Contrast,
	// Windows's contrast themes, the desktop portal's higher contrast.
	HighContrast bool
	// TextScale is how many times larger than usual text should be, as
	// Windows's and GNOME's text size settings say; 0 or 1 for usual.
	TextScale float64
	// Pointer is how accurate the primary pointing device is, and
	// AnyPointer the most accurate of all, as Media Queries 4's pointer
	// and any-pointer: PointerFine, a mouse's, where it is not known.
	Pointer, AnyPointer PointerAccuracy
	// NoHover tells that the primary pointing device cannot hover, as a
	// touch screen, and NoAnyHover that none can (hover and any-hover:
	// none).
	NoHover, NoAnyHover bool
}

Preferences are settings of the desktop that the system's own controls follow, and native UI with them.

type Rect

type Rect struct{ X, Y, Width, Height int }

Rect is a rectangle in screen coordinates (DIPs).

func Centered added in v0.4.1

func Centered(size Size, work Rect) Rect

Centered returns where a flyout of the given size goes without an anchor: in the middle of the work area, as large as it fits.

func PrimaryWorkArea added in v0.4.1

func PrimaryWorkArea(displays []Display) Rect

PrimaryWorkArea returns the work area of the primary display.

func WorkAreaFor added in v0.4.1

func WorkAreaFor(r Rect, displays []Display) Rect

WorkAreaFor returns the work area of the display a flyout anchored at r goes to, as GDK picks it: the one whose work area overlaps r the most, else the one nearest to r's center.

type RectF added in v0.2.0

type RectF struct{ X, Y, W, H float64 }

RectF is a rectangle in DIPs with fractional coordinates.

func RangeBounds added in v0.9.1

func RangeBounds(n *AccessNode, u, count int) RectF

RangeBounds returns where UTF-16 units from u, count of them, of n's Value show: the union of the boxes of the lines they are on (LineBoxes), a run of lines collapsed sharing one, or the node's Bounds where it gives none of them, as for lines out of view.

func (RectF) Contains added in v0.4.0

func (r RectF) Contains(x, y float64) bool

Contains reports whether the point is inside r.

type RefreshSurface added in v0.7.0

type RefreshSurface interface {
	// AwaitRefresh returns once the display shows its next refresh, or
	// at once when nothing is to show. It blocks, and is called from a
	// goroutine of its own, never the main thread.
	AwaitRefresh()
}

RefreshSurface is a PacedSurface whose frames drawn in memory (PresentPixels) show at once, and whose frames asked for (RequestFrame) come at once, not at the display's refreshes, as Windows' do: after each frame drawn in memory, the content waits for the next refresh off the main thread, and Paced frames that come meanwhile wait for it.

type Region added in v0.5.0

type Region struct {
	// Locale is the locale of the formats, in the form the system writes
	// it, "" when unknown.
	Locale string
	// FirstWeekday is the first day of the week, 0 for Sunday to 6 for
	// Saturday, or -1 when the system does not say.
	FirstWeekday int
	// HourCycle is 12 or 24, or 0 when the system does not say.
	HourCycle int
}

Region is the user's regional formats, as the system's settings have them with the user's changes.

type SaveDialogOptions

type SaveDialogOptions struct {
	Title                      string
	DefaultPath                string
	ButtonLabel                string
	Message                    string
	NameFieldLabel             string
	Filters                    []FileFilter
	ShowHiddenFiles            bool
	CreateDirectories          bool
	TreatPackagesAsDirectories bool
}

SaveDialogOptions configures a save panel.

type SchemeBodyWriter added in v0.1.3

type SchemeBodyWriter interface {
	// WriteBody writes p once Respond has run. It is called off the main
	// thread, never at the same time as the other methods, and fails
	// once the webview no longer reads the response.
	WriteBody(p []byte) error
}

SchemeBodyWriter is implemented by SchemeResponders that take the body from the goroutine serving the request instead of through Write, blocking while the webview has not read enough of it: a large response then takes little memory however slowly the webview reads it.

type SchemeRequest

type SchemeRequest struct {
	// Context is cancelled when the webview no longer needs the response.
	Context context.Context
	Method  string
	URL     string
	// Header is an http.Header, of an unnamed type so that platform does
	// not import net/http, which builds for browsers leave out: values of
	// either type assign to the other.
	Header map[string][]string
	// Body is nil for requests without a body.
	Body io.ReadCloser
	// Responder methods must be called on the main thread, Respond first.
	Responder SchemeResponder
}

SchemeRequest is a request for a custom protocol.

type SchemeResponder

type SchemeResponder interface {
	Respond(status int, header map[string][]string) // an http.Header
	Write(p []byte)
	Finish()
	Fail(err error)
}

SchemeResponder delivers a custom protocol response to the webview.

type Screen

type Screen interface {
	Displays() []Display
	CursorPoint() Point
}

Screen queries monitors.

type Secrets added in v0.5.0

type Secrets interface {
	SetSecret(service, account string, secret []byte) error
	// Secret fails with ErrSecretNotFound when there is none.
	Secret(service, account string) ([]byte, error)
	// DeleteSecret succeeds when there is no secret to delete.
	DeleteSecret(service, account string) error
}

Secrets keeps small secrets in the system's credential store: the Keychain on macOS, the Secret Service on Linux (through libsecret) and the Credential Manager on Windows. A secret is identified by a service, the app, and an account, its key, as Electron's keytar stores them.

Unlike other platform methods these may be called from any goroutine, and they may block while the system asks the user, e.g. to unlock the keyring: the core never calls them on the main thread of a running app.

type Shell

type Shell interface {
	OpenExternal(url string) error
	OpenPath(path string) error
	ShowItemInFolder(path string)
	TrashItem(path string) error
	// TrashItemResult moves the item at path to the trash and returns the
	// path where it landed inside the trash directory. It is supported on
	// macOS only; all other platforms return ("", ErrUnsupported).
	TrashItemResult(path string) (string, error)
	// PreviewItem shows the item at path in the Quick Look panel, the
	// preview Finder opens with the space bar. It is supported on macOS
	// only; all other platforms return ErrUnsupported.
	PreviewItem(path string) error
	Beep()
	// FileIcon returns the icon the file manager shows for a file, a
	// folder or an application, as a PNG image of size by size pixels.
	FileIcon(path string, size int) ([]byte, error)
	// TypeIcon returns the icon the file manager shows for files with the
	// extension ext (without its dot), as FileIcon does, though no such
	// file exists.
	TypeIcon(ext string, size int) ([]byte, error)
	// OpenApplication starts the application at Application.Path, or
	// brings it to the front.
	OpenApplication(path string) error
	// DefaultApp returns the application the system would use to open
	// url. url may be a web URL such as https://example.com, a file://
	// URL, or any URL whose scheme is registered with the system. It
	// is supported on macOS, Linux and Windows; other platforms return
	// (Application{}, ErrUnsupported).
	DefaultApp(url string) (Application, error)
}

Shell integrates with the desktop environment.

type Side added in v0.4.1

type Side uint8

Side is the side of the anchor a flyout goes to.

const (
	SideBottom Side = iota
	SideTop
	SideRight
	SideLeft
)

Sides.

type SiteData added in v0.7.2

type SiteData uint

SiteData are kinds of data pages store, for ClearBrowsingData.

const (
	SiteDataCookies SiteData = 1 << iota
	// SiteDataLocalStorage is localStorage and sessionStorage.
	SiteDataLocalStorage
	// SiteDataIndexedDB is IndexedDB, and WebSQL where the engine has it.
	SiteDataIndexedDB
	// SiteDataCaches is the HTTP caches, and Cache Storage.
	SiteDataCaches
	SiteDataServiceWorkers
	// SiteDataAll is all the data the engine keeps for sites, the kinds
	// above and the others (HSTS, media keys, …).
	SiteDataAll SiteData = 1<<iota - 1 | 1<<31
)

func (SiteData) All added in v0.7.2

func (t SiteData) All() bool

All reports whether t asks for all the data, SiteDataAll.

type Size

type Size struct{ Width, Height int }

Size is a width and height in DIPs.

type StyleBackend added in v0.8.0

type StyleBackend interface {
	SetStyleSheet(css string) error
}

StyleBackend styles the widgets the toolkit draws for the app with the app's own style sheet (Linux: GTK's CSS, Theme.SetGTKCSS). SetStyleSheet replaces the sheet set before, or removes it for "", and keeps that one when css does not parse, returning why.

type Surface added in v0.2.0

type Surface interface {
	// Native returns the native objects a GPU renderer draws into, which it
	// calls before making one: a surface that shows frames drawn in memory
	// through those objects (Windows' Composed) lets go of them then.
	Native() SurfaceNative
	// Size returns the size of the drawing area in DIPs and how many
	// device pixels a DIP is.
	Size() (width, height, scale float64)
	// RequestFrame asks for a SurfaceFrame event at the next opportunity
	// to draw: the next display refresh, WM_PAINT or GTK draw. Requests
	// made before it comes coalesce.
	RequestFrame()
	// RefreshRate returns how many times a second the display showing the
	// surface refreshes, at most, 0 when unknown.
	RefreshRate() float64
	// PresentPixels shows a frame drawn in memory: premultiplied BGRA rows
	// of stride bytes, width×height device pixels. It is called while
	// handling a SurfaceFrame event.
	PresentPixels(pix []byte, stride, width, height int)
	// SetCursor sets the pointer's shape over the surface.
	SetCursor(c Cursor)
	// SetTextInput turns text input (IME composition) on for an editable
	// element, telling input methods where its caret is and the text
	// around it, or off.
	SetTextInput(t TextInputState)
	// UpdateAccessibility gives assistive technology the content's
	// elements. The content calls it after every frame once the surface
	// sent AccessibilityOn.
	UpdateAccessibility(tree *AccessTree)
	// StartDataDrag starts a native transfer; CancelDataDrag cancels the
	// source owned by this surface. Both run on the main thread.
	StartDataDrag(DragRequest)
	CancelDataDrag()
	// SetDropFormats registers the formats the content can receive.
	SetDropFormats([]transfer.Format)
	// NewWebView creates a web view under the surface, hidden until
	// PlaceWebViews shows it. Of opts, the options of a webview apply
	// (UserScripts, Schemes, DevTools, UserAgent, Zoom, BackgroundColor,
	// Transparent); h hears of its page.
	NewWebView(opts *WindowOptions, h WindowHandler) (WebView, error)
	// PlaceWebViews shows the web views of the surface where the content's
	// last frame shows them, in the order it painted them, and hides the
	// others, which keep their pages. A press on one, which takes it,
	// comes as WebViewPress.
	PlaceWebViews(views []WebViewPlacement)
}

Surface is the drawing area of a window created with WindowOptions.Surface, which shows content MyGo draws itself (package ui) instead of a webview. Its methods run on the main thread.

type SurfaceEvent added in v0.2.0

type SurfaceEvent struct {
	Kind SurfaceEventKind
	// X and Y locate the pointer in DIPs relative to the surface.
	X, Y float64
	// Button is 0 for the primary button, 1 the secondary, 2 the middle.
	Button int
	Clicks int
	// DX and DY are scroll distances in DIPs; Precise marks touchpads and
	// other devices that scroll by pixels rather than by lines. Momentum
	// marks scrolling that continues after the fingers leave a touchpad.
	DX, DY   float64
	Precise  bool
	Momentum bool
	// Scale is PointerZoom's.
	Scale float64
	// Pointer is the device of PointerMove, PointerDown and PointerUp, as
	// Pointer Events' pointerType, and Pressure how hard a pen or a finger
	// presses, from 0 to 1, where the device tells: 0 where it does not,
	// as a mouse, which the content takes for Pointer Events' default.
	Pointer  PointerKind
	Pressure float64
	// Width and Height are the size of a finger's contact with the
	// touchscreen in DIPs, of TouchDown and TouchMove, where the device
	// tells it: 0 where it does not.
	Width, Height float64
	Key           Key
	// PhysicalKey is the key by its position on an ANSI US keyboard,
	// whatever the active layout types; KeyUnknown where the backend does
	// not report it. Key and PhysicalKey agree on a US layout.
	PhysicalKey Key
	// Code is the key by its position, on any keyboard and with the sides
	// of the modifiers told apart; CodeUnknown where the backend does not
	// report it. KeyPressed, KeyReleased and the raw keys have it.
	Code   KeyCode
	Mods   Modifiers
	Repeat bool
	Text   string
	Caret  int
	// Replace makes TextInput replace, and TextComposition compose over,
	// the runes From to To of the last TextInputState.Text, instead of the
	// selection.
	Replace  bool
	From, To int
	// Files are the paths of FileDrop's files, or original native paths
	// for DataDrop's legacy file-listener fallback.
	Files []string
	Drag  *DataDragEvent
	// ID and Action are AccessAction's; ID is also the finger of
	// TouchDown, TouchMove, TouchUp and TouchCancel.
	ID     uint64
	Action AccessActionKind
	// WebView is WebViewTabOut's and WebViewKey's.
	WebView WebView
	// Paced marks a SurfaceFrame of frames following each other at the
	// display's refreshes (PacedSurface): the content may draw it later,
	// once the display can take it, which it tells by returning true from
	// SurfaceEvent; the refreshes go on meanwhile.
	Paced bool
}

SurfaceEvent is input on a Surface, or a change of it.

type SurfaceEventKind added in v0.2.0

type SurfaceEventKind uint8

SurfaceEventKind is the kind of a SurfaceEvent.

const (
	// SurfaceFrame asks the content to draw a frame now.
	SurfaceFrame SurfaceEventKind = iota
	// SurfaceResize reports a new Size; a frame follows.
	SurfaceResize
	// PointerMove reports the pointer at X, Y.
	PointerMove
	// PointerDown and PointerUp report Button pressed or released at X,
	// Y; Clicks counts quick successive presses (2 for a double click),
	// by the system's double-click settings. A release may leave it 0, for
	// its press's.
	PointerDown
	PointerUp
	// PointerCancel reports that the system ended the pointer's press
	// without a release, as Pointer Events' pointercancel: every button
	// held is let go of, and no PointerUp follows for them. The content
	// commits nothing a release would. Backends send it when they lose the
	// press to the system (a browser's pointercancel, a window losing the
	// mouse capture or a pointer grab while a button is down, a menu's
	// loop taking the release), and the content ignores one while nothing
	// is pressed.
	PointerCancel
	// PointerLeave reports the pointer left the surface.
	PointerLeave
	// PointerScroll scrolls by DX, DY DIPs at X, Y: positive DY moves the
	// view down the content, as dragging a scroll bar's thumb down does.
	PointerScroll
	// PointerZoom zooms by Scale at X, Y, as pinching a touchpad does: 2
	// shows the content twice as large as it was.
	PointerZoom
	// KeyPressed and KeyReleased report Key with Mods; Repeat marks
	// auto-repeat.
	KeyPressed
	KeyReleased
	// ModifiersChanged reports the modifier keys held, Mods, as one of
	// them goes down or up on its own.
	ModifiersChanged
	// RawKeyPressed and RawKeyReleased report a key by its position, Code,
	// that KeyPressed and KeyReleased leave out: a modifier, a lock key, or
	// one the layout types no Key for. PhysicalKey is set where it can be,
	// Key never is. The content reports whether it took the press or the
	// release, which then goes no further in the system, as Alt opening
	// the window's menu bar.
	RawKeyPressed
	RawKeyReleased
	// TextInput inserts Text, typed or committed by an input method.
	TextInput
	// TextComposition shows Text as the input method's composition, its
	// caret at rune Caret; an empty Text ends the composition.
	TextComposition
	// SurfaceFocus and SurfaceBlur report the surface gaining or losing
	// the keyboard.
	SurfaceFocus
	SurfaceBlur
	// SurfaceCommand performs the edit command Text: "copy", "cut",
	// "paste", "pasteAndMatchStyle", "selectAll", "undo", "redo" or
	// "delete" (Edit menu roles), or a Format menu role's: "bold",
	// "italic", "underline", "strikethrough", "alignLeft", "alignCenter"
	// or "alignRight".
	SurfaceCommand
	// SurfaceCommandEnabled asks whether SurfaceCommand with Text would
	// act now, for a menu to enable its item: WindowHandler.SurfaceEvent
	// reports it.
	SurfaceCommandEnabled
	// FileDragOver reports files of another app dragged over X, Y, and
	// FileDragLeave that they left. FileDrop drops Files at X, Y.
	// WindowHandler.SurfaceEvent returns whether the content takes them
	// there.
	FileDragOver
	FileDragLeave
	FileDrop
	// AccessibilityOn reports that assistive technology asked about the
	// surface: the content calls UpdateAccessibility at once and after
	// every frame from then on.
	AccessibilityOn
	// AccessAction performs Action on the element ID of the accessibility
	// tree, with Text the value of AccessSetValue.
	AccessAction
	// SurfaceShown reports that some of an OccludableSurface shows again
	// after none did, and SurfaceHidden that none of it shows any more.
	SurfaceShown
	SurfaceHidden
	// DataDragOver queries a destination; DataDrop commits a transfer.
	// DataDragLeave clears its hover state. Drag carries the query/result.
	DataDragOver
	DataDragLeave
	DataDrop
	// SurfaceRenew reports that the native objects a GPU renderer draws
	// into changed (Surface.Native), as a window of Windows composes its
	// frames once it has web views: the content makes its renderer again.
	SurfaceRenew
	// WebViewPress reports that Button went down at X, Y on a web view
	// the content shows there (Surface.PlaceWebViews), which takes the
	// press and what follows: the content notes it, as popovers close for
	// a press outside them, but handles none of it.
	WebViewPress
	// WebViewTabOut reports that Tab moved the keyboard out of WebView
	// past its page's last element, or Shift+Tab (Mods) past its first:
	// the surface has the keyboard again, and the content moves the focus
	// on from the web view's element.
	WebViewTabOut
	// WebViewKey reports Key with Mods, pressed in the page of WebView,
	// which has the keyboard, and which the page left unhandled: it did
	// not cancel it, type it into an editable element or compose with it,
	// and it is neither Tab nor a modifier key on its own. The content
	// takes it as if the web view's element had the focus, and the
	// keyboard stays with the page.
	WebViewKey
	// TouchDown, TouchMove, TouchUp and TouchCancel report a finger on a
	// touchscreen landing, moving, lifting or taken by the system (as for
	// an edge's gesture, where no TouchUp follows) at X, Y, with Pressure
	// and the size of its contact (Width, Height) where the device tells
	// them. ID tells the fingers down at once apart
	// from the TouchDown to the TouchUp or TouchCancel; it may be used
	// again after. They come besides the pointer events a backend makes of
	// the fingers (taps, scrolls, pinches), which they leave as they are:
	// the content tracks them only for elements that ask (ui.Element.Touches).
	// Windows (WM_POINTER), Linux (GDK's touch sequences) and browsers
	// (Pointer Events of pointerType touch) send them; macOS has no
	// touchscreen, and a trackpad's fingers are not points on the screen.
	TouchDown
	TouchMove
	TouchUp
	TouchCancel
)

type SurfaceNative added in v0.2.0

type SurfaceNative struct {
	// HWND is the surface's child window (Windows).
	HWND uintptr
	// Composed tells that the window has no redirection bitmap, which
	// would hide its material (Windows): a GPU renderer presents through
	// DirectComposition, with the frames' alpha, which the material shows
	// through.
	Composed bool
	// View is the surface's NSView and Layer its layer (macOS).
	View, Layer uintptr
	// Widget is the surface's GtkGLArea or GtkDrawingArea, and GLArea the
	// GtkGLArea while its render signal draws a frame with OpenGL, in the
	// context it made current (Linux).
	Widget, GLArea uintptr
	// Canvas is the number of the canvas's WebGL 2 context (package gl's
	// Context.ID), current while SurfaceFrame events are handled
	// (browsers).
	Canvas uintptr
}

SurfaceNative holds the native objects of a Surface.

type TextContext added in v0.2.17

type TextContext struct {
	Text       string
	Start, End int
	Caret      int
	Base       int
	// contains filtered or unexported fields
}

TextContext is a bounded window of a client document, with preedit removed as GTK and IMM32 surrounding-text protocols expect. Positions in Text are UTF-16 units; Range maps them back to the client's document.

func ClientTextContext added in v0.2.17

func ClientTextContext(client TextInputClient) TextContext

func (TextContext) DeleteRange added in v0.2.17

func (c TextContext) DeleteRange(offset, count int) TextRange

DeleteRange maps GTK character offsets around the selection's end, rather than confusing Unicode characters with UTF-16 or UTF-8 offsets.

func (TextContext) Range added in v0.2.17

func (c TextContext) Range(r TextRange) TextRange

Range maps a range of the surrounding text to the actual document. A collapsed position at preedit stays collapsed; an explicit range crossing it includes preedit, so replacement remains one client operation.

type TextInputClient added in v0.2.17

type TextInputClient interface {
	TextForRange(TextRange) (string, TextRange)
	Selection() TextSelection
	MarkedRange() (TextRange, bool)
	ReplaceText(*TextRange, string)
	SetMarkedText(*TextRange, string, TextRange)
	UnmarkText()
	BoundsForRange(TextRange) (RectF, TextRange, bool)
	IndexForPoint(x, y float64) (int, bool)
}

TextInputClient supplies a focused custom element's text to native input methods. All calls are synchronous on the main thread. Ranges are absolute UTF-16 document offsets, including marked text. Nil replacement ranges mean the marked range, if present, otherwise the selection.

type TextInputState added in v0.2.0

type TextInputState struct {
	// Active is true while an editable element has the keyboard.
	Active bool
	// Caret is the caret's rectangle, in DIPs relative to the surface.
	Caret RectF
	// Text is the input's text around the caret, and Start and End are the
	// selection in it, in runes: both the caret when nothing is selected.
	// Input methods read it to edit what was typed before, as the accents
	// of macOS's press and hold replace the letter they decorate.
	Text       string
	Start, End int
	// Client supplies full text and geometry for a custom text element. The
	// Text/Start/End snapshot remains the plain-widget and TextCaret fallback.
	Client TextInputClient
	// NoInputMethod keeps input methods out while Active: keys type the
	// characters of the keyboard's layout as TextInput, and nothing is
	// composed, as winit's set_ime_allowed(false). Browsers cannot turn
	// input methods off, and ignore it.
	NoInputMethod bool
}

TextInputState is the state of the text input that has the keyboard, for input methods.

type TextRange added in v0.2.17

type TextRange struct{ Start, End int }

TextRange is a half-open range in UTF-16 code units of a text client's document. Native input protocols use these units, independently of UTF-8 storage or the client's choice of buffer.

func ClientDeleteRange added in v0.2.17

func ClientDeleteRange(client TextInputClient, offset, count int) TextRange

ClientDeleteRange can query beyond the usual surrounding window when an input method asks to replace more text. GTK offsets count Unicode runes.

func NormalizeTextRange added in v0.2.17

func NormalizeTextRange(r TextRange) TextRange

type TextSelection added in v0.2.17

type TextSelection struct {
	Range    TextRange
	Reversed bool
}

TextSelection is the primary selection exposed to input methods. A client may own additional selections. Reversed puts the caret at Range.Start.

func (TextSelection) Caret added in v0.2.17

func (s TextSelection) Caret() int

type TextSelectionChange added in v0.9.1

type TextSelectionChange struct {
	Type, Direction, Granularity int
}

TextSelectionChange is how the selection of a text field moved, as WebKit tells VoiceOver in the userInfo of AXSelectedTextChanged (AXTextStateChangeType, AXTextSelectionDirection and AXTextSelectionGranularity), which it reads out by: the new line for a move by line, the character passed for a move by character.

func SelectionChange added in v0.9.1

func SelectionChange(value string, oldStart, oldEnd, start, end int) TextSelectionChange

SelectionChange returns how the selection of value moved from the runes oldStart to oldEnd to those from start to end, as the keys move it: by a character, a word or a line, to the beginning or the end of a line or of the text, or elsewhere (discontiguous), judged from where its moving end went. A selection that holds runes extends, an empty one moves.

type Texts added in v0.5.0

type Texts struct {
	OK, Cancel, Open, Save, SelectFolder string
	// About is the title of the about panel with "\x00" for the app's
	// name: "About \x00".
	About string
}

Texts are the words backends say of their own, in the language the app shows, as package mygo sets them (SetTexts): the buttons of the panels of pages' alert, confirm and prompt, the titles and buttons of file dialogs, and the title of the about panel. Backends read them with CurrentTexts from any thread.

func CurrentTexts added in v0.5.0

func CurrentTexts() Texts

CurrentTexts returns the texts backends say.

type Theme

type Theme interface {
	IsDark() bool
	// SetSource is "system", "light" or "dark".
	SetSource(source string)
	// UIFont returns the family of the desktop's interface font where the
	// system's text stack does not know it, as on Linux, else "".
	UIFont() string
	// FontRendering returns how the desktop's settings say to rasterize
	// text where the system's text stack does not know them, as on Linux.
	FontRendering() FontRendering
	// Preferences returns the settings of the desktop that the system's
	// controls follow. A change of any of them calls Handler.ThemeChanged.
	Preferences() Preferences
}

Theme reads and overrides the system appearance.

type TitleBar added in v0.1.11

type TitleBar struct{ Height, Left, Right, Bottom int }

TitleBar is the room the window controls take at the top of a window with a hidden title bar, in DIPs: they sit in a band of Height along the top edge, Left wide from the left edge and Right wide from the right, and end Bottom below the top edge, which is Height where they fill the band.

type Tray

type Tray interface {
	// SetID names the icon across launches (macOS's autosave name).
	SetID(id string)
	// Dark reports whether the bar the icon shows on is dark.
	Dark() bool
	SetImage(png []byte, template bool) error
	SetTitle(title string)
	// SetTitleMonospaced draws the title in the system's monospaced font,
	// every character as wide as the others, where the icon has a title
	// (macOS).
	SetTitleMonospaced(on bool)
	SetToolTip(tip string)
	SetMenu(m *Menu)
	PopUpMenu(m *Menu)
	// SetActivatable tells the panel whether the icon answers activation,
	// so that it can tell a single click from a double one. Platforms that
	// report clicks themselves ignore it.
	SetActivatable(on bool)
	Bounds() Rect
	Destroy()
}

Tray is a status bar / notification area icon.

type TrayHandler

type TrayHandler interface {
	Clicked()
	RightClicked()
	// AppearanceChanged tells that the bar the icon shows on turned dark
	// or light.
	AppearanceChanged()
}

TrayHandler receives tray icon events.

type UserScript

type UserScript struct {
	Source string
	// AtDocumentEnd injects after the DOM is parsed instead of before any
	// page script runs.
	AtDocumentEnd bool
	// AllFrames injects into iframes too.
	AllFrames bool
}

UserScript is JavaScript injected into pages.

type ViewSurface added in v0.8.2

type ViewSurface interface {
	// EmbedView puts view, an NSView on macOS, under the surface, hidden
	// until PlaceWebViews shows it as it shows a web view. The WebView it
	// returns stands for it there; of its Page, only what concerns a view
	// applies (Focus, TabInto, Close, which takes the view out of the
	// window and lets go of it). The surface keeps view while it shows it.
	EmbedView(view uintptr) (WebView, error)
}

ViewSurface is a Surface that shows views of the platform's own under it, as it shows web views: those of native modules (package native), shown with ui.NativeView. macOS's surfaces are.

type WebView added in v0.4.0

type WebView interface {
	Page
	// Focus gives the web view the keyboard.
	Focus()
	// TabInto gives the web view the keyboard as Tab does: at its page's
	// first element taking the focus, or its last when back, as Shift+Tab
	// does. Tab past the other end comes back as WebViewTabOut.
	TabInto(back bool)
	// SetBackgroundColor paints the web view before its page does.
	SetBackgroundColor(c Color)
	// Close destroys the web view; its handler hears no more of it.
	// Backends close the web views of a window that closes before telling
	// its WindowHandler.Closed, and Close does nothing then.
	Close()
}

WebView is a web view in a window showing a Surface, which its content places (Surface.NewWebView, Surface.PlaceWebViews): under the surface, which shows it where its frames are transparent, as holes (scene.OpHole) make them. Its page reports to the WindowHandler it was made with, which hears nothing of the window.

type WebViewPlacement added in v0.4.0

type WebViewPlacement struct {
	WebView WebView
	// Frame is the web view's box as it shows; Clip the part of it that
	// shows, which the frames leave transparent but where the content
	// painted over it.
	Frame, Clip RectF
	// Width and Height are the size the page lays out at, in its own
	// DIPs: the element's content box before a scale of the transforms
	// around it, which shows the page in Frame scaled as a picture of it,
	// its viewport the same (Scale). Zero is Frame's size.
	Width, Height float64
	// Radii are those of the page's corners, in its DIPs, from its
	// top-left clockwise, as the hole showing it has: the page shows, and
	// takes the pointer, inside them.
	Radii [4]float64
	// Opacity is how opaque the page shows, 0 to 1. Where the content
	// painted a background under the element, opaque or through, the
	// frames' own hole blends the page with it, and this is 1. Where none
	// is, as in a transparent window, this is the element's opacity, and
	// the platform fades the page itself by it, over what is behind the
	// window, as over a parent window a flyout leaves live. A platform
	// that cannot fades nothing (the page then shows whole).
	Opacity float64
	// Covers are the boxes, within Clip, of what the content painted over
	// the web view that takes the pointer: there the pointer is the
	// surface's, elsewhere in Clip the web view's.
	Covers []RectF
}

WebViewPlacement is where the content of a surface shows a web view (Surface.PlaceWebViews), in DIPs relative to the surface.

func (*WebViewPlacement) At added in v0.4.0

func (p *WebViewPlacement) At(x, y float64) bool

At reports whether the pointer at x, y is the web view's.

func (*WebViewPlacement) Rounded added in v0.8.0

func (p *WebViewPlacement) Rounded() bool

Rounded reports whether the page's corners are rounded.

func (*WebViewPlacement) Scale added in v0.8.0

func (p *WebViewPlacement) Scale() (x, y float64)

Scale returns how much Frame scales the page: 1, 1 unless a transform scales it.

func (*WebViewPlacement) Size added in v0.8.0

func (p *WebViewPlacement) Size() (w, h float64)

Size returns the size the page lays out at, in its DIPs.

func (*WebViewPlacement) ToPage added in v0.8.0

func (p *WebViewPlacement) ToPage(x, y float64) (float64, float64)

ToPage converts a point of the surface to the page's DIPs.

type WideGamutSurface added in v0.2.15

type WideGamutSurface interface {
	// WideGamut reports whether the screen showing most of the window
	// shows colors outside the sRGB gamut, as Display P3 screens do.
	WideGamut() bool
}

WideGamutSurface is a Surface that tells whether its window's screen shows colors outside the sRGB gamut (macOS's).

type Window

type Window interface {
	// Handle returns the native window (NSWindow*, GtkWindow*, HWND).
	Handle() uintptr
	// Surface returns the drawing surface of a window created with
	// WindowOptions.Surface, nil for others.
	Surface() Surface

	SetTitle(title string)
	Title() string
	// SetRepresentedFile shows the file a window shows, "" for none: the
	// proxy icon of the title bar and its menu of folders (macOS). Other
	// platforms do nothing.
	SetRepresentedFile(path string)
	// SetDocumentEdited shows that the window's document has unsaved
	// changes: the dot of the close button (macOS). Other platforms do
	// nothing; the core marks the title there.
	SetDocumentEdited(edited bool)
	SetBounds(r Rect)
	Bounds() Rect
	SetContentBounds(r Rect)
	ContentBounds() Rect
	SetMinimumSize(s Size)
	SetMaximumSize(s Size)
	SetResizable(v bool)
	IsResizable() bool
	SetMovable(v bool)
	IsMovable() bool
	SetMinimizable(v bool)
	IsMinimizable() bool
	SetMaximizable(v bool)
	IsMaximizable() bool
	SetClosable(v bool)
	IsClosable() bool
	SetAlwaysOnTop(v bool)
	IsAlwaysOnTop() bool
	Show()
	ShowInactive()
	Hide()
	// IsVisible reports whether Show showed the window and Hide did not
	// hide it since: a minimized window is visible (#1542).
	IsVisible() bool
	Focus()
	Blur()
	IsFocused() bool
	// CornerRadius is the radius, in DIPs, the window's corners are
	// rounded to on screen, or 0 when they are square or the system
	// does not tell it.
	CornerRadius() float64
	Minimize()
	IsMinimized() bool
	Maximize()
	Unmaximize()
	IsMaximized() bool
	Restore()
	SetFullScreen(v bool)
	IsFullScreen() bool
	Center()
	SetBackgroundColor(c Color)
	SetOpacity(v float64)
	Opacity() float64
	SetHasShadow(v bool)
	HasShadow() bool
	SetIgnoreMouseEvents(v bool)
	IgnoresMouseEvents() bool
	SetContentProtection(v bool)
	SetVibrancy(material string)
	// SetVibrancyTint tints the window's material, where it takes one
	// (macOS 26's Liquid Glass); nil removes the tint. Other materials and
	// platforms ignore it.
	SetVibrancyTint(c *Color)
	// SetActiveAppearance keeps the window drawn as active, as the key
	// window of the app in front, while it is not (macOS).
	SetActiveAppearance(v bool)
	// SetWindowButtonsTheme draws the controls of a hidden title bar for a
	// "light" or "dark" background whatever the app's appearance, or
	// follows it again with "system" (Windows).
	SetWindowButtonsTheme(source string)
	// SetProgressBar shows progress on the taskbar button, Dock icon or
	// launcher entry: state is "" (none), "normal", "indeterminate",
	// "paused" or "error", value between 0 and 1.
	SetProgressBar(state string, value float64)
	FlashFrame(flash bool)
	SetSkipTaskbar(v bool)
	SetVisibleOnAllWorkspaces(v bool)
	// SetIcon sets the window icon from a PNG image; nil restores the
	// application's.
	SetIcon(png []byte) error
	// SetMenu sets a per-window menu bar (Linux/Windows). No-op on macOS.
	SetMenu(m *Menu)
	// SetAutoHideMenu hides the menu bar until Alt or F10 brings the
	// keyboard to it (Linux/Windows). No-op on macOS.
	SetAutoHideMenu(v bool)
	// TitleBar returns the room the window controls of a window with a
	// hidden title bar take, which WindowHandler.TitleBarChanged reports
	// changes of. It is zero for other windows and while the controls are
	// hidden, in full screen.
	TitleBar() TitleBar
	// StartDrag moves the window with the mouse (frameless drag regions).
	StartDrag()
	// TitleBarDoubleClicked performs the platform action for a double click
	// on a custom title bar (zoom/minimize on macOS).
	TitleBarDoubleClicked()
	// PlaceFlyout places a flyout (WindowOptions.Flyout) of the given
	// size next to its anchor again, as Flyout.Place resolves it in the
	// work area of a display, after the anchor, the size or the parent
	// changed. It does nothing for other windows.
	PlaceFlyout(f Flyout, size Size)
	// Close destroys the window without asking WindowHandler.ShouldClose.
	Close()

	Page
}

Window is a native window hosting a webview.

type WindowButtonsBackend added in v0.8.0

type WindowButtonsBackend interface {
	WindowButtons() (start, end []string)
}

WindowButtonsBackend reports the window buttons the desktop puts at the start and at the end of title bars (Linux): "minimize", "maximize" and "close", in their order, none where the desktop wants none. Main thread only.

type WindowHandler

type WindowHandler interface {
	// ShouldClose is called when the user tries to close the window.
	ShouldClose() bool
	// Closed is called after the native window has been destroyed.
	Closed()
	Focused()
	Blurred()
	// MenuItemClicked reports an item chosen from this window's menu bar
	// or context menu, even while the menu has focus instead of the window.
	MenuItemClicked(id int)
	Resized()
	Moved()
	Minimized()
	Restored()
	Maximized()
	Unmaximized()
	EnteredFullScreen()
	LeftFullScreen()
	// TitleBarChanged is called when Window.TitleBar changes, e.g. when the
	// window enters full screen or the desktop's button layout changes.
	TitleBarChanged()

	// Message delivers a message posted by the renderer bridge.
	Message(msg string)
	// WillNavigate is called before a navigation; returning false cancels it.
	WillNavigate(nav Navigation) bool
	NavigationStarted(url string)
	NavigationCommitted(url string)
	LoadFinished()
	LoadFailed(url string, code int, description string)
	TitleChanged(title string)
	// NewWindow is called for window.open() and target=_blank links. It
	// returns the window that should host the new page or nil to deny it.
	NewWindow(req NewWindowRequest) Window
	// ClosedByPage is called when the page calls window.close().
	ClosedByPage()
	RenderProcessGone(reason string)
	// AudibleChanged is called when Page.IsAudible changes.
	AudibleChanged(audible bool)
	// CaptureStateChanged is called when Page.CaptureState of kind may
	// have changed, with its state.
	CaptureStateChanged(kind CaptureKind, state CaptureState)
	SchemeRequest(req *SchemeRequest)
	// DownloadStarted returns where to save a download, "" to cancel it;
	// DownloadFinished reports how it ended.
	DownloadStarted(url, suggestedName string) string
	DownloadFinished(url, path string, err error)
	// SchemeDownload downloads a URL of a custom scheme, which the engine
	// cannot turn into a download, by serving it again.
	SchemeDownload(url string)
	// PermissionRequested asks whether the page at origin may use kinds:
	// "camera", "microphone", "geolocation" or "notifications".
	PermissionRequested(kinds []string, origin string) bool
	// AuthRequested answers an HTTP authentication challenge of the page,
	// or of what it loads.
	AuthRequested(req AuthRequest) AuthResponse
	// ClientCertificateRequested asks which client certificate to give a
	// server that asks for one, of the page or of what it loads.
	ClientCertificateRequested(req ClientCertificateRequest) ClientCertificateResponse
	// HandlesClientCertificates tells whether the app answers client
	// certificate challenges at all: a backend that lists certificates
	// (macOS, whose keychain asks the user for them) lists them only
	// while it does, and leaves the challenge to the web view otherwise.
	HandlesClientCertificates() bool
	// CertificateError asks whether to load what a server sent with a
	// certificate that does not verify: false fails it, as without the
	// call. A backend that verifies certificates itself to tell (macOS)
	// does so only while HandlesCertificateErrors reports true, and
	// leaves them to the web view otherwise.
	CertificateError(e CertificateError) bool
	HandlesCertificateErrors() bool
	// ContextMenu asks what the page's context menu shows, as it is
	// about to open, and HandlesContextMenu whether to ask at all: a
	// backend describes its menu only while it does.
	ContextMenu(m *ContextMenu) ContextMenuResponse
	HandlesContextMenu() bool

	// SurfaceEvent delivers input on the window's Surface, and changes of
	// it. For FileDragOver and FileDrop it reports whether the content
	// takes the files where they are, for KeyPressed whether it took
	// the key itself, which the system then leaves alone (Windows opens no
	// menu for Alt and the key), for TextComposition whether it took the
	// composition, which the input method gives up otherwise (macOS), and
	// for SurfaceCommandEnabled whether the command would act; it returns
	// false for other events.
	SurfaceEvent(ev SurfaceEvent) bool
}

WindowHandler receives window and webview events from the backend.

type WindowOptions

type WindowOptions struct {
	Title          string
	X, Y           int
	Width, Height  int
	Center         bool
	UseContentSize bool
	MinSize        Size
	MaxSize        Size
	// StateBounds is the window's restored normal rectangle in the
	// screen's pixels, set by WindowStateBackend. It overrides X, Y,
	// Width and Height.
	StateBounds *Rect

	Resizable      bool
	Movable        bool
	Minimizable    bool
	Maximizable    bool
	Closable       bool
	Focusable      bool
	Fullscreenable bool
	AlwaysOnTop    bool
	FullScreen     bool
	Maximized      bool
	SkipTaskbar    bool
	AutoHideMenu   bool
	HasShadow      bool
	Frameless      bool
	Transparent    bool
	// BackgroundColor is painted before the page renders; nil keeps the
	// platform default.
	BackgroundColor *Color
	// TitleBarStyle is "default", "hidden" or "hiddenInset". A hidden title
	// bar gives the page the whole window, under the window controls:
	// AppKit's traffic lights on macOS, and on Linux and Windows controls
	// the backend puts over the page (see Window.TitleBar).
	TitleBarStyle string
	// TitleBarHeight is the height of a hidden title bar in DIPs (Linux,
	// Windows); 0 is the backend's own.
	TitleBarHeight int
	// HideWindowButtons hides the window controls of a hidden title bar,
	// which the page draws itself: TitleBar is then zero.
	HideWindowButtons    bool
	TrafficLightPosition *Point
	Vibrancy             string
	// VibrancyTint tints the material, where the platform's material takes
	// one (macOS 26's Liquid Glass): nil for none.
	VibrancyTint *Color
	// CornerRadius rounds a frameless window's corners, in DIPs: its
	// content and material are cut to them (macOS), or the system rounds
	// it with its own corners (Windows 11).
	CornerRadius int
	Opacity      float64
	Parent       Window
	Modal        bool
	// Flyout makes the window a flyout of its Parent, placed next to an
	// anchor (Window.PlaceFlyout), at Width and Height: borderless,
	// transparent, out of the taskbar, with Focusable telling whether it
	// takes the keyboard. Show of a flyout that is not focusable shows it
	// without the keyboard, as ShowInactive.
	Flyout *Flyout
	// Panel makes the window a panel (mygo.WindowOptions.Panel): it floats
	// above the windows of all apps on the current workspace, full-screen
	// ones included, out of the taskbar and the app switcher, and on macOS
	// takes the keyboard without activating the app.
	Panel bool

	// UserScripts are injected into every page, in order.
	UserScripts []UserScript
	// Schemes lists the custom protocols the webview must route to
	// WindowHandler.SchemeRequest.
	Schemes  []string
	DevTools bool
	// UserAgent overrides the user agent of the webview.
	UserAgent string
	// UserAgentSuffix is appended to UserAgent, or to the webview's own
	// user agent, after a space. The public package trims it.
	UserAgentSuffix string
	Zoom            float64
	// TabFocusesLinks makes Tab reach links and form controls that are not
	// text fields (macOS, WKPreferences.tabFocusesLinks); the other
	// platforms reach them already.
	TabFocusesLinks bool
	// NoBackgroundThrottling keeps the page running at full speed while
	// its window is hidden, minimized or covered
	// (mygo.PageOptions.BackgroundThrottling): its timers unthrottled, its
	// process at the priority of a visible one.
	NoBackgroundThrottling bool
	// Autoplay lets the page play audible media without a user gesture
	// (mygo.PageOptions.Autoplay).
	Autoplay bool
	// PictureInPicture lets the page's videos go into picture in picture
	// (macOS, WebKit's private _allowsPictureInPictureMediaPlayback);
	// WebView2 lets them already, and WebKitGTK has none.
	PictureInPicture bool
	// SwipeNavigation lets a swipe go back and forward through the page's
	// history (mygo.PageOptions.SwipeNavigation).
	SwipeNavigation bool
	// PinchZoom lets a pinch magnify the page; the backends turn it off
	// where their webview has it on by default (mygo.PageOptions.PinchZoom).
	PinchZoom bool
	// DataStore is the website data store of the page, one of
	// AppController.NewDataStore; nil is the default store. A window
	// opened by window.open has its opener's.
	DataStore DataStore
	// Native carries backend specific state, e.g. the WKWebViewConfiguration
	// WebKit hands us for window.open().
	Native uintptr

	// ScrollToContainer scrolls the native container around an embedded web
	// view instead of its page. Ordinary pages keep their own wheel input.
	ScrollToContainer bool
	// Surface creates the window with a Surface, which content MyGo draws
	// itself fills, instead of a webview: Window.Surface returns it, the
	// webview methods do nothing and the webview options are ignored.
	Surface bool
}

WindowOptions configures a native window and its webview. The public package fills in all defaults before calling NewWindow.

type WindowStateBackend added in v0.8.0

type WindowStateBackend interface {
	RestoreWindowState(opts *WindowOptions, pixels Rect) bool
}

WindowStateBackend restores windows at their pixels (Windows): RestoreWindowState sets opts.StateBounds and returns true when pixels, zero for none, would show on a connected display. Otherwise the core restores the state's DIPs where every display has the same scale, and centers the window where they have not.

type WindowStateWindow added in v0.8.0

type WindowStateWindow interface {
	WindowStateBounds() Rect
}

WindowStateWindow is a window whose bounds in DIPs change with the scales of the displays where they differ (Windows). WindowStateBounds is its rectangle in the screen's pixels, which window states keep with them.

Jump to

Keyboard shortcuts

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