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
- Variables
- func ContentRulesIdentifier(id, rules string) string
- func CookieMatchesURL(c Cookie, u *url.URL) bool
- func FitIcon(w, h, box int) (int, int)
- func InsideCorners(w, h float64, radii [4]float64, x, y float64) bool
- func KeyByPosition(key, physical Key, mods Modifiers) bool
- func ParseAuthChallenge(challenge string) (scheme, realm string)
- func SetTexts(t Texts)
- func StaleContentRules(id, current, identifier string) bool
- func UTF16ByteOffset(s string, offset int) int
- func UTF16Len(s string) (n int)
- type AboutPanelOptions
- type AccessActionKind
- type AccessActions
- type AccessAutoComplete
- type AccessCurrent
- type AccessNode
- type AccessPopup
- type AccessRole
- type AccessStates
- type AccessTextRun
- type AccessTree
- type Align
- type AppController
- type AppHandler
- type AppOptions
- type Application
- type AuthRequest
- type AuthResponse
- type Backend
- type BackgroundSurface
- type CaptureKind
- type CaptureState
- type CertificateError
- type ClickCounter
- type Clipboard
- type Color
- type ContextMenu
- type ContextMenuResponse
- type ContextMenuTarget
- type Cookie
- type CookieKey
- type Cursor
- type DamageSurface
- type DataDragEvent
- type DataStore
- type DataStoreOptions
- type Dialogs
- type Display
- type DoubleClick
- type DragRequest
- type FileFilter
- type FileWatch
- type FileWatchKind
- type FileWatchNotice
- type FileWatchTarget
- type FirstFrameSurface
- type Flyout
- type FontRendering
- type FrameRateSurface
- type GlassPlacement
- type GlassSurface
- type Gravity
- type HeldKeys
- type IdleSurface
- type ImmediateFrameSurface
- type InputComposition
- type JumpList
- type JumpListTask
- type Key
- type KeyCode
- type LaterClipboard
- type MaterialSurface
- type MaximizeButtonSurface
- type MediaCommand
- type Menu
- type MenuIcon
- type MenuItem
- type MenuItemType
- type MessageBoxOptions
- type MessageBoxResult
- type Modifiers
- type Navigation
- type Network
- type NetworkStatus
- type NewWindowRequest
- type Notification
- type NotificationSender
- type NowPlaying
- type NowPlayingInfo
- type OccludableSurface
- type OpenDialogOptions
- type PDFOptions
- type PacedSurface
- type PackageInfo
- type Page
- type Point
- type PointerAccuracy
- type PointerKind
- type Power
- type Preferences
- type Rect
- type RectF
- type RefreshSurface
- type Region
- type SaveDialogOptions
- type SchemeBodyWriter
- type SchemeRequest
- type SchemeResponder
- type Screen
- type Secrets
- type Shell
- type Side
- type SiteData
- type Size
- type StyleBackend
- type Surface
- type SurfaceEvent
- type SurfaceEventKind
- type SurfaceNative
- type TextContext
- type TextInputClient
- type TextInputState
- type TextRange
- type TextSelection
- type Texts
- type Theme
- type TitleBar
- type Tray
- type TrayHandler
- type UserScript
- type WebView
- type WebViewPlacement
- type WideGamutSurface
- type Window
- type WindowButtonsBackend
- type WindowHandler
- type WindowOptions
- type WindowStateBackend
- type WindowStateWindow
Constants ¶
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.
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.
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".
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 ¶
var DefaultDoubleClick = DoubleClick{Time: 500 * time.Millisecond, DX: 5, DY: 5}
DefaultDoubleClick is the double click where the system tells none.
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.
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.
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.
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).
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.
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.
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.
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 ContentRulesIdentifier ¶
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 ¶
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 ¶
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 InsideCorners ¶
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 ¶
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 ParseAuthChallenge ¶
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 StaleContentRules ¶
StaleContentRules reports whether identifier names a list compiled for id from other rules than current, which is ContentRulesIdentifier's.
func UTF16ByteOffset ¶
UTF16ByteOffset rounds an offset inside a surrogate pair down to its rune.
Types ¶
type AboutPanelOptions ¶
type AboutPanelOptions struct {
ApplicationName string
ApplicationVersion string
Version string
Copyright string
Credits string
}
AboutPanelOptions configures the standard about panel.
type AccessActionKind ¶
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 ¶
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 ¶
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 ¶
func (a AccessAutoComplete) String() string
String returns the value of aria-autocomplete that a is, "" for AutoCompleteNone.
type AccessCurrent ¶
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 ¶
func (c AccessCurrent) String() string
String returns the value of aria-current that c is, "" for CurrentNone.
type AccessNode ¶
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
}
AccessNode is an element of an AccessTree.
type AccessPopup ¶
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 ¶
func (p AccessPopup) String() string
String returns the value of aria-haspopup that p is, "" for PopupNone.
type AccessRole ¶
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 // 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 )
func (AccessRole) Live ¶
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 ¶
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 ¶
func (r AccessRole) Tabular() bool
Tabular reports whether nodes of a role hold rows of cells: tables, grids and tree grids.
type AccessStates ¶
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 ¶
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 ¶
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 ¶
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).
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.
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)
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
}
AppOptions configures Backend.Init.
type Application ¶
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 ¶
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 ¶
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(h TrayHandler) (Tray, error)
RegisterHotkey(id int, accelerator 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 ¶
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 CaptureKind ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Clipboard ¶
type Clipboard interface {
// 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;
// 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, 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 ContextMenu ¶
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 ¶
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 ¶
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 ¶
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 ¶
type CookieKey struct{ Name, Domain, Path string }
CookieKey identifies a cookie without request URL matching.
type Cursor ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DoubleClick is how far apart in time and on each axis two presses make a double click.
type DragRequest ¶
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 FileFilter ¶
FileFilter restricts the files shown in file dialogs: those of its Extensions, and of its MIMETypes, which may be "kind/*".
type FileWatch ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (c *InputComposition) End(client TextInputClient)
func (*InputComposition) Replace ¶
func (c *InputComposition) Replace(client TextInputClient, r *TextRange, text string)
func (*InputComposition) Reset ¶
func (c *InputComposition) Reset()
type JumpList ¶
type JumpList struct {
Tasks []JumpListTask
}
JumpList is the whole jump list of the app: Windows replaces all of it at each commit.
type JumpListTask ¶
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 ¶
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 ¶
KeyForRune returns the key typing r unshifted, KeyUnknown for others.
func KeyForScancode ¶
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 ¶
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 )
func KeyCodeForDOM ¶
KeyCodeForDOM returns the key of a KeyboardEvent's code, CodeUnknown for one it does not map.
func KeyCodeForEvdev ¶
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 ¶
KeyCodeForMac returns the key of a macOS virtual key code, CodeUnknown for one it does not map, as Fn.
func KeyCodeForXT ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 )
type Menu ¶
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 (*Menu) Apply ¶
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 (*Menu) TidySeparators ¶
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 ¶
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 (*MenuIcon) Native ¶
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 ¶
type MenuItem struct {
ID int
Type MenuItemType
Label string
Subtitle string
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
// 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 (*MenuItem) LabelWithSubtitle ¶
LabelWithSubtitle is the label of a backend that can't show the subtitle on a line of its own.
type MenuItemType ¶
type MenuItemType int
MenuItemType is the kind of a menu item.
const ( MenuItemNormal MenuItemType = iota MenuItemSeparator 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 ¶
MessageBoxResult is the outcome of a message box.
type Navigation ¶
type Navigation struct {
// (OnWillNavigate): reloads, history navigations and the loads the app
// starts.
Unasked bool
// started it: Reload, the page's location.reload(), the web view's own
// menus.
Reload bool
}
Navigation describes a pending navigation.
type Network ¶
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 ¶
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 ¶
NotificationSender describes an incoming direct message's sender.
type NowPlaying ¶
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 ¶
type NowPlayingInfo struct {
Title, Artist, Album 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 ¶
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 ¶
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 ¶
PackageInfo is metadata of a packaged application.
type Page ¶
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 ¶
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 ¶
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())
OnBattery() bool
IdleTime() time.Duration
}
Power reports power and session events and keeps the computer awake.
type Preferences ¶
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 ¶
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 ¶
PrimaryWorkArea returns the work area of the primary display.
func WorkAreaFor ¶
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 ¶
type RectF struct{ X, Y, W, H float64 }
RectF is a rectangle in DIPs with fractional coordinates.
type RefreshSurface ¶
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 ¶
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 ¶
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 Secrets ¶
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
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
}
Shell integrates with the desktop environment.
type SiteData ¶
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 )
type StyleBackend ¶
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 ¶
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 ¶
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
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 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 ¶
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 )
type SurfaceNative ¶
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 ¶
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 ¶
func ClientTextContext(client TextInputClient) TextContext
func (TextContext) DeleteRange ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
type TextSelection ¶
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 ¶
func (s TextSelection) Caret() int
type Texts ¶
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.
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 ¶
type TitleBar struct{ Height, Left, Right 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.
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)
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 WebView ¶
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 ¶
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
// 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 ¶
func (p *WebViewPlacement) At(x, y float64) bool
At reports whether the pointer at x, y is the web view's.
func (*WebViewPlacement) Rounded ¶
func (p *WebViewPlacement) Rounded() bool
Rounded reports whether the page's corners are rounded.
func (*WebViewPlacement) Scale ¶
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 ¶
func (p *WebViewPlacement) Size() (w, h float64)
Size returns the size the page lays out at, in its DIPs.
type WideGamutSurface ¶
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() bool
Focus()
Blur()
IsFocused() bool
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)
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 ¶
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.
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
// 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
// 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 ¶
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 ¶
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.