Documentation
¶
Overview ¶
Package platform defines the contract between the public golet 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 CookieMatchesURL(c Cookie, u *url.URL) bool
- func KeyByPosition(key, physical Key, mods Modifiers) bool
- func SetTexts(t Texts)
- func UTF16ByteOffset(s string, offset int) int
- func UTF16Len(s string) (n int)
- type AboutPanelOptions
- type AccessActionKind
- type AccessActions
- type AccessNode
- type AccessRole
- type AccessStates
- type AccessTextRun
- type AccessTree
- type Align
- type AppController
- type AppHandler
- type AppOptions
- type Application
- type Backend
- type ClickCounter
- type Clipboard
- type Color
- type Cookie
- type CookieKey
- type Cursor
- type DamageSurface
- type DataDragEvent
- type Dialogs
- type Display
- type DoubleClick
- type DragRequest
- type FileFilter
- type FileWatch
- type FileWatchKind
- type FileWatchNotice
- type FileWatchTarget
- type Flyout
- type FontRendering
- type Gravity
- type IdleSurface
- type InputComposition
- type JumpList
- type JumpListTask
- type Key
- type MaterialSurface
- type Menu
- type MenuItem
- type MenuItemType
- type MessageBoxOptions
- type MessageBoxResult
- type Modifiers
- type Navigation
- type Network
- type NetworkStatus
- type NewWindowRequest
- type Notification
- type NotificationSender
- type OccludableSurface
- type OpenDialogOptions
- type PDFOptions
- type PacedSurface
- type PackageInfo
- type Page
- type Point
- type Power
- type Preferences
- type Rect
- type RectF
- type Region
- type SaveDialogOptions
- type SchemeBodyWriter
- type SchemeRequest
- type SchemeResponder
- type Screen
- type Secrets
- type Shell
- type Side
- type Size
- 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 WindowHandler
- type WindowOptions
Constants ¶
const DragSessionFormat transfer.Format = "application/x-golet-drag-session"
DragSessionFormat carries an unguessable, process-local registry key. It never contains a pointer. Only the core resolves it while a drag lives.
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 golet sets others.
var ErrClipboardChanged = errors.New("golet: 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("golet: 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("golet: 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("golet: 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 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 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 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 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
// Level is how deep an item of a tree is, or the rank of a heading,
// from 1; 0 for other nodes.
Level int
// 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
// Actions are the actions the element takes in AccessAction events.
Actions AccessActions
// 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 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 )
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).
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 or a table whose user // chooses several rows. 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. AccessVertical )
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
}
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()
Hide()
Unhide()
IsHidden() 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)
// ClearBrowsingData deletes the data pages stored; done runs on the
// main thread.
ClearBrowsingData(done func(error))
// Cookie operations address 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(url string, done func([]Cookie, error))
SetCookie(cookie Cookie, done func(error))
DeleteCookie(key CookieKey, done func(error))
ClearCookies(done func(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)
}
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
}
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 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
// 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 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 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 the default 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 )
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 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.
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 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 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 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 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) 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, and the keys of keyboards that have them. 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 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 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.
type MenuItem ¶
type MenuItem struct {
ID int
Type MenuItemType
Label string
Role string
Accelerator string
Enabled bool
Visible bool
Checked bool
ToolTip string
}
MenuItem is a snapshot of a menu item. ID identifies the public item the native item was built from.
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
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
// 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
Sender *NotificationSender
}
Notification is a desktop notification.
type NotificationSender ¶
NotificationSender describes an incoming direct message's sender.
type OccludableSurface ¶
type OccludableSurface interface {
// Occluded reports whether nothing of the surface shows on screen. The
// surface sends 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)
// 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
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 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
}
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 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)
// OpenApplication starts the application at Application.Path, or
// brings it to the front.
OpenApplication(path string) error
}
Shell integrates with the desktop environment.
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 Golet 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.
DX, DY float64
Precise bool
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
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.
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 // 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 // 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 // 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 // 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. SurfaceShown // 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 )
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 golet 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)
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; Clip the part of it that shows, which
// the frames leave transparent but where the content painted over it.
Frame, Clip RectF
// 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.
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)
// 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 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)
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
// 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, and for KeyPressed whether it took
// the key itself, which the system then leaves alone (Windows opens no
// menu for Alt and the key); 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
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
TrafficLightPosition *Point
Vibrancy string
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 (golet.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
// Native carries backend specific state, e.g. the WKWebViewConfiguration
// WebKit hands us for window.open().
Native uintptr
// Surface creates the window with a Surface, which content Golet 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.