Documentation
¶
Overview ¶
Package platform defines the contract between Tango's core (the root tango package) and each native backend (darwin, windows, linux, ios, android, fake).
Rules every backend follows:
- Every method on Backend and Surface is called on the main (UI) thread, except Backend.Wake, which is safe from any goroutine, and — on mobile — Init and Run (see below).
- Mobile (round 3, documenting what ios / android do): the native host owns the main thread and starts main.main on a goroutine of its own, so Init and Run are called on the goroutine that called App.Run, not on the UI thread. Init only records the Host; Run blocks that goroutine until the app terminates. LifecycleStarted, and later LifecycleTerminating, are delivered on the main thread like every other Host call; Run returns only after Terminating was delivered.
- Every Host method is called by the backend on the main thread.
- Backends translate; they hold no policy. Queues, ID allocation, message routing and lifecycle state machines live in the core.
- Desktop backends never use cgo (purego / syscall only). Mobile backends may use cgo and live behind ios / android build tags.
This file is the shared contract. Backends must not change it; propose changes instead.
Index ¶
- Constants
- Variables
- func DamageRects(dirty []image.Rectangle, bounds image.Rectangle, maxRects int) (rects []image.Rectangle, full bool)
- func DamageToLogical(r image.Rectangle, scale float64) image.Rectangle
- func DeliverCanvasKey(sink CanvasSink, ev input.KeyEvent, synthetic bool)
- func EnvLocales() []string
- func FilterCanvasKey(sink CanvasSink, ev input.KeyEvent) bool
- func IsDownloadPending(h WebHost, sid SurfaceID, id uint64) bool
- func LocaleSource() func() []string
- func LocaleWatch() func(fn func()) (cancel func())
- func PosixToBCP47(v string) string
- func ReportActivity(h Host, id SurfaceID)
- func ReportWebNavigation(h Host, id SurfaceID, token uint64, kind WebNavigationKind, page WebPageState, ...)
- func SetLocaleSource(fn func() []string)
- func SetLocaleWatch(watch func(fn func()) (cancel func()))
- func ValidWebProfile(s string) bool
- func WebJSONExpression(expression string) string
- func WebKeyRune(key input.Key, mods input.Modifiers) rune
- func WebProfileKey(name string) string
- type AppAppearance
- type AppControl
- type AppControlOp
- type AppEvent
- type AppEventKind
- type AppMenu
- type AppOptions
- type AppShortcuts
- type Appearance
- type AttachedCanvas
- type AuthAction
- type AuthChallenge
- type AuthResponse
- type Backend
- type BackgroundKind
- type BackgroundRequest
- type BackgroundTask
- type BackgroundTasks
- type BinaryLane
- type BiometricOptions
- type Biometrics
- type BiometryKind
- type BrowsingData
- type Camera
- type Canvas
- type CanvasAccessible
- type CanvasAccessibleSink
- type CanvasAnchor
- type CanvasAttacher
- type CanvasBackHandler
- type CanvasCoreGraphics
- type CanvasCreator
- type CanvasDamagePresenter
- type CanvasDropTarget
- type CanvasGL
- type CanvasHWND
- type CanvasInsets
- type CanvasKeySink
- type CanvasLayer
- type CanvasMetal
- type CanvasNativeWindow
- type CanvasShortcutCapture
- type CanvasSink
- type CanvasTextInputState
- type CanvasThreaded
- type CanvasThreadedRelease
- type CanvasThreadedSink
- type CanvasWebViewEmbedder
- type Clipboard
- type ClipboardRich
- type ContrastPreference
- type CreatorEx
- type Dialogs
- type Display
- type Displays
- type DocumentPrinter
- type DownloadEvent
- type DownloadRequest
- type DownloadState
- type DragOperation
- type Dragger
- type EdgeResizer
- type EmbedGeometry
- type EmbeddedNativeView
- type EmbeddedWebView
- type FileDragger
- type FileFilter
- type FileOptions
- type FindOptions
- type FindResult
- type Geometry
- type HapticKind
- type Haptics
- type Host
- type HostEx
- type HostQuit
- type Hotkeys
- type IMECandidate
- type IMEKey
- type IMEMenuItem
- type IMEModifierKey
- type InputMethodCandidateSink
- type InputMethodCandidates
- type InputMethodMenus
- type InputMethodModeSink
- type InputMethodModes
- type InputMethodModifiers
- type InputMethodSink
- type InputMethods
- type Insets
- type Keyboard
- type LaneGenerations
- type LaneHost
- type LifecycleEvent
- type LocaleListeners
- type LocaleWatcher
- type Locales
- type Location
- type LocationAccuracy
- type LocationOptions
- type Locator
- type Material
- type MediaPicker
- type MediaType
- type MenuItem
- type MessageKind
- type MessageOptions
- type MotionPreference
- type NativeViewEmbedder
- type NativeViewOptions
- type NavigationRequest
- type NestedLoop
- type Network
- type NetworkKind
- type NetworkStatus
- type NewWindowRequest
- type Notification
- type NotificationRemover
- type Notifier
- type Orientation
- type OrientationMask
- type Orientations
- type OverlaySupport
- type PDFOptions
- type PageControl
- type PagePrinter
- type Permission
- type PermissionDecision
- type PermissionRequest
- type PermissionStatus
- type Permissions
- type PickMediaOptions
- type PopupMenu
- type Power
- type PowerEvent
- type PowerSource
- type PowerStatus
- type PrintOptions
- type Product
- type ProductKind
- type Purchases
- type Push
- type PushEvent
- type PushPayload
- type RecentDocuments
- type Rect
- type RectF
- type SafeArea
- type ScreenControl
- type SecureStore
- type SettingsOpener
- type ShareOptions
- type Sharer
- type Shell
- type ShortcutItem
- type SleepBlock
- type Stateful
- type StatusBar
- type StatusBarControl
- type StatusBarStyle
- type StoreReview
- type Styled
- type Surface
- type SurfaceEvent
- type SurfaceEventKind
- type SurfaceExtras
- type SurfaceID
- type SurfaceKind
- type SurfaceOptions
- type SurfaceStatus
- type SystemTheme
- type Theme
- type TitleBar
- type Transaction
- type TransactionState
- type Tray
- type TrayHandlers
- type TrayMenuTrigger
- type TrayOptions
- type Trays
- type WebCookies
- type WebCreator
- type WebData
- type WebDialogKind
- type WebDialogRequest
- type WebDialogResponse
- type WebDialogs
- type WebDownloadPending
- type WebDownloads
- type WebEvaluator
- type WebFileChooserRequest
- type WebFinder
- type WebHeaders
- type WebHistory
- type WebHost
- type WebInput
- type WebInputKind
- type WebInputSink
- type WebInspector
- type WebInteractionHost
- type WebKeySink
- type WebNavigationHost
- type WebNavigationKind
- type WebOptions
- type WebPDF
- type WebPageState
- type WebPermission
- type WebPlacement
- type WebProfileSupport
- type WebSnapshot
- type WebUserAgent
- type WebViewEmbedder
- type WebViewInfo
- type WidgetContent
- type Widgets
- type WindowState
Constants ¶
const ShortcutArgPrefix = "--tango-shortcut="
ShortcutArgPrefix is the command-line argument a Windows Jump List task launches the executable with: ShortcutArgPrefix + ShortcutItem.ID. Clicks on such tasks arrive as a new process (forwarded to the primary instance by sys/single when the app uses it); sys/jumplist turns them into click callbacks.
Variables ¶
var ( // ErrNotAvailable: the capability exists on the platform but cannot be // used now (no biometric hardware, no camera, location services off). ErrNotAvailable = errors.New("tango: not available on this device") // ErrNotEnrolled: biometric hardware without enrolled faces/fingers. ErrNotEnrolled = errors.New("tango: no biometrics enrolled") // ErrLockedOut: too many failed biometric attempts. ErrLockedOut = errors.New("tango: biometrics locked out") // ErrAuthFailed: the user was not recognised. ErrAuthFailed = errors.New("tango: authentication failed") // ErrPermissionDenied: the user (or policy) denied the permission the // operation needs. ErrPermissionDenied = errors.New("tango: permission denied") // ErrNotFound: no such item (secure storage key). ErrNotFound = errors.New("tango: not found") // ErrNotConfigured: the app bundle lacks a declaration the OS requires // (an Info.plist usage description, a manifest permission, an // entitlement). The error text names it; see docs/mobile-permissions.md. ErrNotConfigured = errors.New("tango: app is not configured for this") )
var ErrCanceled = errors.New("tango: canceled")
ErrCanceled is returned by dialogs the user dismissed.
var ErrResponseFinished = errors.New("tango: asset response already finished")
ErrResponseFinished is the error a backend's asset response writer (the http.ResponseWriter handed to Host.ServeAsset) returns from Write and FlushError once the response is complete: the handler returned and the end of the response was queued for the WebView. darwin and ios use it, so a late write fails the same way on both.
var ErrUnsupported = errors.New("tango: not supported on this platform")
ErrUnsupported is returned by core feature packages when the backend does not implement the capability interface.
var ErrWebViewClosed = errors.New("tango: surface closed")
ErrWebViewClosed indicates a WebView closed before an operation finished.
Functions ¶
func DamageRects ¶
func DamageRects(dirty []image.Rectangle, bounds image.Rectangle, maxRects int) (rects []image.Rectangle, full bool)
DamageRects prepares the dirty list of a PresentDamage call for a canvas: rectangles are clipped to bounds and empty ones dropped. full is true when updating the parts would not pay off (more than maxRects rectangles, or their total area above half of bounds): the caller then presents the whole frame.
func DamageToLogical ¶
DamageToLogical converts a device-pixel rectangle to the smallest logical-pixel rectangle (integer coordinates) covering it at scale, for platforms whose invalidation APIs take logical units.
func DeliverCanvasKey ¶
func DeliverCanvasKey(sink CanvasSink, ev input.KeyEvent, synthetic bool)
func EnvLocales ¶
func EnvLocales() []string
EnvLocales reads the POSIX locale variables in gettext priority order: LANGUAGE (a colon-separated list) first, then the first non-empty of LC_ALL, LC_MESSAGES and LANG. Values are converted to BCP 47 ("zh_CN.UTF-8" -> "zh-CN"); "C" and "POSIX" are skipped. As in gettext, LANGUAGE is ignored when the locale is explicitly set to "C" or "POSIX".
func FilterCanvasKey ¶
func FilterCanvasKey(sink CanvasSink, ev input.KeyEvent) bool
func LocaleSource ¶
func LocaleSource() func() []string
LocaleSource returns the registered source, or nil.
func LocaleWatch ¶
func LocaleWatch() func(fn func()) (cancel func())
LocaleWatch returns the registered watcher, or nil.
func PosixToBCP47 ¶
PosixToBCP47 converts a POSIX locale name ("zh_TW.UTF-8@euro") to a BCP 47 tag ("zh-TW"). It returns "" for "C", "POSIX" and empty input.
func ReportActivity ¶
ReportActivity records input at native dispatch, before it is consumed by a menu, canvas or child view. Hosts that do not track activity ignore it.
func ReportWebNavigation ¶
func ReportWebNavigation(h Host, id SurfaceID, token uint64, kind WebNavigationKind, page WebPageState, err string)
func SetLocaleSource ¶
func SetLocaleSource(fn func() []string)
SetLocaleSource registers the system-language source used when no Backend value is at hand. The last registration wins.
func SetLocaleWatch ¶
func SetLocaleWatch(watch func(fn func()) (cancel func()))
SetLocaleWatch registers the watcher used when no Backend value is at hand (the WatchLocales of a LocaleWatcher). The last registration wins.
func ValidWebProfile ¶
func WebJSONExpression ¶
WebJSONExpression wraps a synchronous expression in a JSON conversion for native APIs that return JavaScript values.
func WebKeyRune ¶
WebKeyRune is the printable character for a WebView chord on the US layout.
func WebProfileKey ¶
WebProfileKey maps a case-sensitive name to a filesystem-safe key.
Types ¶
type AppAppearance ¶
type AppAppearance interface {
SetAppAppearance(mode string)
}
AppAppearance is an optional Backend capability: force the light or dark look of the whole app — window chrome, menus, system controls and the pages' prefers-color-scheme — or follow the system again. mode is "light", "dark" or "" (follow the system). While forced, SystemTheme reports the forced look and AppThemeChanged fires for it, as for a system switch. Main thread.
type AppControl ¶
type AppControl interface {
// AppControlOps reports which operations the platform performs. It may
// be called from any goroutine and must not change while the app runs.
AppControlOps() AppControlOp
HideApp()
ShowApp()
// SetBadge sets the dock/taskbar badge; "" clears.
SetBadge(text string)
// SetProgress shows dock/taskbar progress in [0,1]; negative hides.
SetProgress(p float64)
RequestAttention(critical bool)
// SetDockVisible false makes a tray-only (accessory) app on macOS.
SetDockVisible(visible bool)
}
AppControl is app-wide window-manager integration. Methods for operations not in AppControlOps are no-ops; capability packages check AppControlOps first and report ErrUnsupported (round 3: replaces the duck-typed AppControlSupports(op string)).
type AppControlOp ¶
type AppControlOp uint32
AppControlOp is a set of AppControl operations.
const ( CtlHide AppControlOp = 1 << iota // HideApp / ShowApp CtlBadge // SetBadge with counts ("3", "99+") CtlBadgeText // SetBadge with any text CtlProgress // SetProgress CtlAttention // RequestAttention CtlDock // SetDockVisible CtlAll = CtlHide | CtlBadge | CtlBadgeText | CtlProgress | CtlAttention | CtlDock )
type AppEvent ¶
type AppEvent struct {
Kind AppEventKind
URL string // AppOpenURL; AppWebViewRestored: the URL reloaded
Paths []string // AppOpenFiles
Theme Theme // AppThemeChanged
Surface SurfaceID // AppWebViewRestored: the surface whose page was reloaded
Insets Insets // AppSafeAreaChanged: the new insets
Orientation Orientation // AppOrientationChanged: the new orientation
Push PushEvent // AppPushToken, AppPushReceived, AppPushOpened
Notification string // AppNotificationOpened: the notification's ID
NotificationData string // AppNotificationOpened: application data when the backend can recover it
}
AppEvent is one app-level event. Which fields are set depends on Kind (documented with each kind); the others are zero. Round 3 added typed payloads for the mobile kinds (mobile_ext.go), which used to borrow URL and Paths.
type AppEventKind ¶
type AppEventKind int
const ( AppOpenURL AppEventKind = iota + 1 // URL set (deep link / custom scheme) AppOpenFiles // Paths set (file association, dock drop, "Open With") AppThemeChanged // Theme set AppDisplaysChanged // display added/removed/rearranged/rescaled AppReopen // macOS dock icon clicked with no visible windows // AppNotificationOpened (round 3): the user clicked a notification // for which the backend has no live Notifier.Notify onClick — one sent // by an earlier run of the app, typically the click that launched it. // Notification is set to its Notification.ID. AppNotificationOpened )
const ( // AppSafeAreaChanged: the safe area insets changed (rotation, status // bar, split view). Insets = the new insets. AppSafeAreaChanged AppEventKind = 100 + iota // AppOrientationChanged: the interface orientation changed. // Orientation = the new orientation. AppOrientationChanged // AppPushToken: the push token was issued or changed. Push.Token = the // token. AppPushToken // AppPushReceived: a remote notification arrived while the app runs. // Push.Payload = the notification. AppPushReceived // AppPushOpened: the user tapped a remote notification (also the one // that launched the app). Push.Payload as for AppPushReceived, with // Action set. AppPushOpened // AppWebViewRestored: the system killed a page's web content process // and the backend reloaded the page. Surface = the surface, URL = the // URL being reloaded. The backend reports SurfaceNavigating before the // reload, so messages are held until the page has loaded again. AppWebViewRestored )
const ( // AppKeyboardChanged: the software keyboard appeared, disappeared or // changed height. Insets.Bottom = the height of the part of the screen // the keyboard covers, in CSS pixels; 0 means hidden. AppKeyboardChanged AppEventKind = AppWebViewRestored + 1 + iota // 106 // AppBackgroundTask: the system started (or expired) background tasks. // A signal without payload: the listener takes the updates with // BackgroundTasks.TakeBackgroundTasks (on the main thread). AppBackgroundTask // 107 // AppPurchaseUpdated: in-app purchase transactions changed state. A // signal: take them with Purchases.TakePurchaseUpdates. AppPurchaseUpdated // 108 )
const AppContrastChanged AppEventKind = 201
AppContrastChanged: the system high-contrast preference changed (ContrastPreference). A signal without payload: read the new value with ContrastPreference.HighContrast. Next to AppReduceMotionChanged, outside the desktop (1...) and mobile (100...) ranges.
const AppMemoryWarning AppEventKind = 203
AppMemoryWarning: the system is low on memory (iOS memory warning, Android onTrimMemory at TRIM_MEMORY_RUNNING_LOW or above). No payload. Receivers release caches they can rebuild (GPU atlases and textures, glyph caches). 201 is AppContrastChanged, 202 is reserved for a future AppTextScaleChanged (docs/specs/mobile-canvas.md §3.3–3.4).
const AppReduceMotionChanged AppEventKind = 200
AppReduceMotionChanged: the system "reduce motion" preference changed (MotionPreference). A signal without payload: read the new value with MotionPreference.ReduceMotion. Its value lies outside the desktop (1...) and mobile (100...) ranges.
type AppMenu ¶
AppMenu sets the application menu bar (macOS) or the given surface's window menu (Windows/Linux; parent==0 means all current and future surfaces). Clicks call onClick(id) on the main thread.
type AppOptions ¶
type AppOptions struct {
Name string // display name, e.g. "My App"
ID string // reverse-DNS identifier, e.g. "com.example.myapp"
StartAccessory bool // macOS initial activation policy
}
func (AppOptions) DefaultIMEConnection ¶
func (o AppOptions) DefaultIMEConnection() string
DefaultIMEConnection uses the same ID fallback as tango.App.ID.
type AppShortcuts ¶
type AppShortcuts interface {
SetAppShortcuts(items []ShortcutItem, onClick func(id string)) error
}
AppShortcuts sets the app's shortcut menu: the Dock icon's menu on macOS (items above the system's own), the Jump List "Tasks" category on Windows. items == nil clears it. On macOS a click calls onClick(id) in this process; on Windows the system relaunches the executable instead (see ShortcutArgPrefix) and onClick is not called by the backend. Linux has no runtime API (Desktop Actions are written into the .desktop file at packaging time) and does not implement it.
type Appearance ¶
type Appearance struct {
TitleBar TitleBar
Transparent bool // WebView and window background transparent
Background uint32 // 0xRRGGBBAA, used when !Transparent; 0 = platform default
Material Material
AlwaysOnTop bool
Opacity float64 // 0 means 1.0
NoShadow bool // drop the window shadow; only meaningful for TitleBarNone
NoClose bool // disable the close button / close command
NoMinimize bool // disable minimizing
NoMaximize bool // disable maximizing / zoom
// AllSpaces shows the window on every desktop: every macOS Space,
// including beside full-screen windows, and every Linux workspace
// (sticky). Windows has no API for it and ignores it.
AllSpaces bool
}
Appearance is applied as a whole: the core always sends the full desired state, backends diff against what they have. Unsupported fields are ignored.
The zero value is an ordinary window (revised round 3: the switches are negative, so a zero Appearance no longer means "no close button, no shadow").
type AttachedCanvas ¶
type AttachedCanvas interface {
Canvas
// SetLayer moves the canvas: new bounds, stacking or pass-through. A
// size change reports CanvasResized and asks for a frame.
SetLayer(layer CanvasLayer) error
// Detach removes the canvas from its surface. Afterwards the sink is
// never called again, Invalidate does nothing and Present returns an
// error. Closing the surface detaches its canvases implicitly (the
// core learns of it from SurfaceClosed). Detach is idempotent.
Detach()
}
AttachedCanvas is implemented by the Canvas that CanvasAttacher returns when the backend can move or remove it later. Both methods run on the main thread.
type AuthAction ¶
type AuthAction int
AuthAction is what to do with an AuthChallenge.
const ( AuthDefault AuthAction = iota // platform default (usually: fail with 401, or its own dialog) AuthCredentials // answer with User / Password AuthCancel // cancel the request )
type AuthChallenge ¶
type AuthChallenge struct {
URL string // the request that was challenged, where the platform tells
Host string
Port int
Realm string
Scheme string // "basic", "digest", "ntlm", "negotiate" or "" when unknown
Proxy bool // a proxy asked
// Retry is the number of failed attempts before this one, where the
// platform tells (0 otherwise).
Retry int
}
AuthChallenge is an HTTP authentication challenge.
type AuthResponse ¶
type AuthResponse struct {
Action AuthAction
User string
Password string
}
type Backend ¶
type Backend interface {
// Init prepares the native application object. Called once on the main
// thread before Run. The backend keeps h and calls it on the main thread.
Init(h Host, opts AppOptions) error
// Run blocks on the main thread running the native event loop until Quit
// is called or the platform terminates the app. Before returning it calls
// h.OnLifecycle(LifecycleTerminating).
Run() error
// Quit asks the native loop to stop. Main thread only.
Quit()
// Wake schedules h.Drain() to run soon on the main thread. Safe from any
// goroutine, may be called many times; coalescing is allowed but at least
// one Drain must follow every Wake.
Wake()
// Step processes native events once. If block is true it waits for at
// least one event (or a Wake). Returns false once the loop is quitting.
// Used by the core to keep the UI responsive while the main thread waits
// on something (nested loops). Main thread only.
Step(block bool) bool
// NewSurface creates a native surface (a desktop window or a mobile
// page) hosting a WebView. It is created hidden unless opts.Visible.
NewSurface(id SurfaceID, opts SurfaceOptions) (Surface, error)
// AssetOrigin is the origin the backend serves Host.ServeAsset under,
// without trailing slash, e.g. "tango://app" (WebKit custom scheme) or
// "https://tango.localhost" (WebView2 / Android request interception).
AssetOrigin() string
}
Backend is the minimum a platform must implement to run a Tango app. Optional features (menus, dialogs, clipboard, ...) are separate interfaces in caps.go that a backend may additionally implement.
type BackgroundKind ¶
type BackgroundKind int
BackgroundKind is the kind of a background task. Each kind has at most one pending request: scheduling again replaces it.
const ( // BackgroundRefresh: short work (about 30 s on iOS) to refresh content, // run when the system sees fit (BGAppRefreshTask; Android JobScheduler). BackgroundRefresh BackgroundKind = iota + 1 // BackgroundProcessing: longer maintenance work (minutes), typically // while the device is idle (BGProcessingTask; Android JobScheduler). BackgroundProcessing )
type BackgroundRequest ¶
type BackgroundRequest struct {
Kind BackgroundKind
// Earliest delays the task: not before now+Earliest. 0 = whenever the
// system decides. It is a lower bound; the system picks the time.
Earliest time.Duration
RequiresNetwork bool
RequiresCharging bool // BackgroundProcessing on iOS; any kind on Android
}
type BackgroundTask ¶
type BackgroundTask struct {
ID int64
Kind BackgroundKind
Deadline time.Time // latest end the backend knows of; zero when unknown
Expired bool
}
BackgroundTask is one update in the queue TakeBackgroundTasks drains: a task the system started (Expired false), or the system asking a running task to stop now (Expired true, same ID).
type BackgroundTasks ¶
type BackgroundTasks interface {
ScheduleBackground(r BackgroundRequest) error
CancelBackground(k BackgroundKind) error
TakeBackgroundTasks() []BackgroundTask
FinishBackgroundTask(id int64, success bool)
}
BackgroundTasks schedules work the system runs while the app is in the background, possibly after launching it for that (main.main and App.Run then run without a visible page). Every started task must be finished with FinishBackgroundTask, at the latest when it expired.
type BinaryLane ¶
type BinaryLane interface {
// LaneCaps returns the lanes the surface's current page can use, by
// name: "down:poll" when the asset scheme handler can hold a request
// open and answer it later (the core's short polls), "up:post" when it
// can read request bodies, platform lanes such as
// "down:android" or "down:shm" when the backend has them. Nil or empty
// means none. The core offers them to the page only when the page
// comes from the asset origin.
LaneCaps() []string
// SendLanePacket sends one packet to the page on the backend's own
// downstream lane (down:android, down:shm; never called for
// down:poll, which the core serves). It must not block: false means
// the packet was not taken (the lane is busy or gone) and the frames
// go as messages instead. On true the backend owns p; on false it must
// neither keep nor modify it.
//
// gen is the lane generation (the page's hello) p was sent in. The
// call is made without the core's lane lock, so the generation may
// have ended by now: the backend delivers p only while the page lane
// of generation gen is still valid, and drops it otherwise. It must
// not call back into the core's lane state.
SendLanePacket(gen uint64, p []byte) bool
}
BinaryLane is implemented by surfaces whose page can use IPC fast lanes: side channels that carry stream byte frames as binary packets next to the message channel (ipc package comment, "Fast lanes"; lane names and state in internal/lane). Both methods are called from any goroutine (ipc's stream writers), never only the main thread, and must be safe there.
type BiometricOptions ¶
type BiometricOptions struct {
Reason string // shown in the prompt (iOS: localizedReason; Android: subtitle)
Title string // Android prompt title; macOS/iOS ignore it
CancelTitle string // label of the cancel button; "" = system default
AllowPasscode bool // fall back to the device passcode / PIN
}
type Biometrics ¶
type Biometrics interface {
// BiometryKind reports what the device has; err explains BiometryNone
// (ErrNotAvailable, ErrNotEnrolled, ErrLockedOut).
BiometryKind() (BiometryKind, error)
Authenticate(opts BiometricOptions, done func(err error))
}
Biometrics authenticates the device owner. done(nil) on success; otherwise ErrCanceled, ErrAuthFailed, ErrNotEnrolled, ErrLockedOut, ErrNotAvailable or ErrNotConfigured (iOS without NSFaceIDUsageDescription).
type BiometryKind ¶
type BiometryKind int
const ( BiometryNone BiometryKind = iota BiometryTouchID // also Android fingerprint BiometryFaceID // also Android face BiometryOpticID // Vision Pro BiometryOther // available, kind not reported (Android) )
type BrowsingData ¶
type BrowsingData uint32
BrowsingData selects kinds of website data.
const ( DataCookies BrowsingData = 1 << iota DataCache // memory and disk cache DataStorage // localStorage, sessionStorage, IndexedDB, service workers, WebSQL, cache storage DataAll = DataCookies | DataCache | DataStorage )
type Camera ¶
Camera takes a photo with the system camera UI. done receives the path of a JPEG in the app's cache directory.
type Canvas ¶
type Canvas interface {
// Size is the drawable content size in logical pixels.
Size() (w, h float32)
// Scale is the device-pixel ratio.
Scale() float32
// Invalidate schedules one CanvasFrame soon (next vsync if possible).
// Callable from any goroutine; calls coalesce.
Invalidate()
// InvalidateAt schedules a CanvasFrame no later than t. Callable from
// any goroutine; an earlier pending time wins.
InvalidateAt(t time.Time)
// SetCursor sets the pointer shape over the canvas. Main thread.
SetCursor(c input.Cursor)
// SetTextInput enables or disables the platform text-input client (IME)
// and positions its candidate window at caret (logical pixels). While
// enabled, text arrives as input.TextInput / input.Composition. Main
// thread.
SetTextInput(enabled bool, caret geom.Rect)
// Present displays a finished frame. img is premultiplied RGBA of
// Size()*Scale() device pixels and is only valid during the call: copy
// or upload it before returning. Main thread.
Present(img *image.RGBA) error
}
Canvas is a drawing target supplied by a backend.
type CanvasAccessible ¶
type CanvasAccessible interface {
// AccessibilityActive reports whether an assistive technology uses
// the canvas. Called at the start of every frame from the UI thread;
// must be cheap (an atomic load).
AccessibilityActive() bool
// SetAccessibilityTree replaces the whole tree: the first tree after
// activation (every node is new), or nil to drop all native objects
// after deactivation.
SetAccessibilityTree(tree *a11y.Tree)
// UpdateAccessibilityNodes delivers the next snapshot. changed lists
// added and modified nodes in depth-first order, then removed ones
// (tree.Node returns nil for those), as ui.AccessibilityHost does. The
// backend compares with the snapshot it kept to choose notifications
// (value, name, selection, structure, destroyed).
UpdateAccessibilityNodes(tree *a11y.Tree, changed []a11y.NodeID)
// AccessibilityFocusChanged reports the node that now has keyboard
// focus in the last tree: tree.Focus, or its ActiveDescendant when it
// has one (already resolved). 0 means no node of the canvas has
// focus. Backends post their focus notification only while the canvas
// itself has keyboard focus.
AccessibilityFocusChanged(id a11y.NodeID)
// AccessibilityAnnounce asks for text to be spoken once. source is 0
// for ui.Context.Announce and the root of a live region whose content
// changed otherwise (the core computes live-region changes; it skips
// them in the first tree after activation). live is the politeness:
// LiveAssertive interrupts, LivePolite waits. Backends with native
// live regions (UIA LiveRegionChanged) may raise that event on source
// instead of speaking text.
AccessibilityAnnounce(text string, live a11y.Live, source a11y.NodeID)
}
CanvasAccessible is implemented by a Canvas (from CanvasCreator or CanvasAttacher) whose backend can expose an a11y.Tree.
Activation. The core builds no tree while AccessibilityActive is false. When the backend detects an assistive technology (macOS: the view is first asked for its accessibility children, hit test or focused element; Windows: WM_GETOBJECT with UiaRootObjectId; AT-SPI: org.a11y.Status IsEnabled) it makes AccessibilityActive return true and invalidates the canvas; the next frame calls SetAccessibilityTree with the full tree, later frames that change it call UpdateAccessibilityNodes. When the backend decides the technology left it returns false again; the next frame calls SetAccessibilityTree(nil). Until the first tree arrives the backend answers queries with the canvas alone (no children) and announces the layout change when it does.
Order and threading. All methods except AccessibilityActive run on the main thread, from inside CanvasFrame before Present. One frame calls, in this order: SetAccessibilityTree or UpdateAccessibilityNodes, then AccessibilityFocusChanged if the effective focus moved, then AccessibilityAnnounce zero or more times. The methods must not call the sink; native notifications may be posted at once or after the frame. After the surface closes or the canvas is detached the core calls none of them; the backend releases its native objects in its own teardown.
Snapshots. A tree is immutable and stays valid after the call (the runner builds a new one every frame): keep it as the data source of the native objects and answer queries from it, never by calling back into the core. Node.Bounds are logical pixels relative to the canvas's top-left; convert them to screen coordinates when a query asks (window moves and scale changes then need no new tree). NodeIDs are unique within one canvas only: key native objects by (canvas, NodeID).
type CanvasAccessibleSink ¶
type CanvasAccessibleSink interface {
// AccessibilityAction performs act on node id of the last tree for
// an assistive technology (press, increment, setValue with arg, ...).
// It fails when the node is not in that tree or does not declare the
// action; nil means accepted, not done: the widget handles it in a
// following frame, which the sink requests. For a11y.Focus the backend
// first gives the canvas keyboard focus (first responder, SetFocus,
// gtk_widget_grab_focus).
AccessibilityAction(id a11y.NodeID, act a11y.Action, arg string) error
}
CanvasAccessibleSink is optionally implemented by a CanvasSink (package uihost implements it) that serves CanvasAccessible. Backends call it on the main thread only, never from inside CanvasFrame; a request that arrives on another thread (a UIA or D-Bus worker) is posted to the main thread first.
type CanvasAnchor ¶
type CanvasAnchor uint8
CanvasAnchor chooses which part of the content area non-zero CanvasLayer.Bounds stay attached to on resize.
const ( AnchorTopLeft CanvasAnchor = iota // zero value: offsets from the top-left stay fixed AnchorTopRight AnchorBottomLeft AnchorBottomRight AnchorCenter // the centre offset from the content area's centre stays fixed )
type CanvasAttacher ¶
type CanvasAttacher interface {
AttachCanvas(id SurfaceID, layer CanvasLayer, sink CanvasSink) (Canvas, error)
}
CanvasAttacher is implemented by backends that can mix a canvas with a WebView in one window (step D of the canvas spec).
type CanvasBackHandler ¶
type CanvasBackHandler interface {
SetBackHandling(on bool)
}
CanvasBackHandler is implemented by canvases on platforms with a system Back action (Android's back button and back gesture). The core calls SetBackHandling(true) while the UI has something Back should close (an overlay, a drawer, a dialog: ui.Context.WantBack) and false otherwise. While handling is on, the platform intercepts Back and delivers it to the canvas as an input.KeyEvent for input.KeyEscape (down then up) instead of closing the page. Main thread.
type CanvasCoreGraphics ¶
CanvasCoreGraphics provides a retained content layer on macOS/arm64. Main thread only. The view owns the returned CALayer until close or a switch to Metal; callers retaining it may finish releasing their content afterward. Acquisition is idempotent and schedules a frame without calling the sink.
type CanvasCreator ¶
type CanvasCreator interface {
NewCanvasSurface(id SurfaceID, opts SurfaceOptions, ex SurfaceExtras, sink CanvasSink) (Surface, Canvas, error)
}
CanvasCreator is implemented by backends that can create a Surface whose content is a Canvas. The returned Surface is a normal window: WebView-only methods (Navigate, Eval, OpenDevTools) are no-ops and the Surface's other optional interfaces (Geometry, Stateful, Styled, ...) behave as for a WebView surface. Host.OnSurfaceEvent and Host.ShouldClose are reported for id exactly as for NewSurface.
type CanvasDamagePresenter ¶
type CanvasDamagePresenter interface {
PresentDamage(img *image.RGBA, dirty []image.Rectangle) error
}
CanvasDamagePresenter is optionally implemented by a Canvas that can show a CPU frame by updating only the parts that changed since the last frame it presented (ui.DamagePresenter on the platform side; package uihost discovers it with a type assertion).
img is the complete frame, with the same ownership and layout as for Present. dirty lists device-pixel rectangles within img.Bounds() that differ from the previous frame presented on this canvas (by Present or PresentDamage); an empty list means nothing changed. The canvas must keep its copy of the last frame for this to be correct: when it cannot (no previous frame, a different size, a GPU or fallback mode, a mode where retained content is not reliable) it presents img whole, exactly as Present does. Main thread. On error nothing may be on screen: the caller presents the whole frame with Present.
type CanvasDropTarget ¶
type CanvasDropTarget interface {
// CanvasDragOver reports files dragged over the canvas at (x, y),
// logical pixels relative to the canvas's top-left; called when the
// drag enters and as it moves.
CanvasDragOver(x, y float32)
// CanvasDragLeave reports that the drag left the canvas, was
// cancelled or was dropped (it precedes SurfaceFilesDropped).
CanvasDragLeave()
}
CanvasDropTarget is optionally implemented by a CanvasSink that wants drop feedback (a highlight) while files are dragged over its canvas. Backends call it only for canvases of surfaces created with SurfaceExtras.AcceptFiles, on the main thread. The drop itself is reported to the Host as SurfaceFilesDropped (X/Y in the surface's content coordinates), as for WebView surfaces.
type CanvasGL ¶
type CanvasGL interface {
// UseGLArea switches the canvas to GPU presentation once and returns
// the GtkGLArea* (owned by the surface: valid until it closes; the
// caller must release its GL objects before or when the surface
// closes). Calling it again returns the same area. Main thread; it
// never calls the sink itself but schedules one CanvasFrame, so the
// first GPU frame follows without an Invalidate.
//
// The area is realized before return and requires OpenGL 3.3 core.
// When GTK reports a GL error (gtk_gl_area_get_error after realize,
// e.g. no GL 3.3 or GL disabled) the area is destroyed, the error is
// returned and the canvas stays on cairo, unchanged. Auto-render is
// off (the presenter queues each render), no alpha, no depth or
// stencil buffer; the presenter connects the area's "render" signal
// and makes its context current itself.
//
// Frame scheduling is unchanged: CanvasFrame still comes only after
// Invalidate/InvalidateAt, a size or scale change (reported as
// CanvasResized and followed by a frame synchronously from the size
// allocation, on the main thread; the presenter adapts to the
// GLArea's buffer size, the allocation in device pixels, in its
// render callback), or the switch itself, at most once per display
// refresh, and a still window costs no frames. Input, IME, cursor,
// focus and scale behave as before: the GLArea sits in a GtkOverlay
// above the drawing area with pass-through input, so the drawing area
// keeps receiving every event.
//
// After a successful call, Present(nil) means "the GPU presented
// already" and returns nil. Present(img) still works as a CPU fallback
// (the presenter cannot start, a frame beyond a device limit, a lost
// device): the GLArea is hidden and the drawing area shows img with
// cairo until the next Present(nil) shows the GLArea again. Partial
// presentation (CanvasDamagePresenter) presents whole frames.
//
// Returns ErrUnsupported for attached (CanvasAttacher) canvases,
// layered ones and so PassThrough layers, and for transparent canvases
// (Appearance.Transparent), and an error off the main thread or after
// the surface closed.
UseGLArea() (glarea uintptr, err error)
// ReleaseGLArea undoes a successful UseGLArea for good, for a caller
// that will not present with the area (its presenter could not
// start, or was rejected): it destroys the GtkGLArea, so it never
// shows a buffer nobody renders, and returns the canvas to the plain
// cairo path — Present(nil) is an error again, Present(img) and
// partial presentation (CanvasDamagePresenter) work as before the
// switch, frames run as on the cairo path — and schedules one
// CanvasFrame. The caller must have closed any presenter on the area
// first. Later UseGLArea calls return ErrUnsupported. Main thread; a
// no-op before UseGLArea succeeded, when called again and after the
// surface closed.
ReleaseGLArea()
}
CanvasGL is implemented by Linux canvases that can present with OpenGL through a GtkGLArea. Discover it with a type assertion on the Canvas from CanvasCreator.NewCanvasSurface; it parallels CanvasMetal and CanvasHWND.
type CanvasHWND ¶
type CanvasHWND interface {
// UseGPUWindow switches the canvas to GPU presentation once and
// returns the canvas's own child HWND, which keeps receiving input,
// IME, focus and accessibility queries. The HWND is owned by the
// surface: valid until it closes; the caller must release its swap
// chain before or when the surface closes. Calling it again returns
// the same HWND. Main thread; it never calls the sink itself but
// schedules one CanvasFrame, so the first GPU frame follows without an
// Invalidate.
//
// Frame scheduling is unchanged: CanvasFrame still comes only after
// Invalidate/InvalidateAt, a size or scale change (WM_SIZE and
// WM_DPICHANGED_AFTERPARENT report CanvasResized and produce a frame
// synchronously, so the presenter resizes its buffers at the start of
// present, on the main thread), or the switch itself, at most once
// per display refresh, and a still window costs no frames. Input,
// IME, cursor, focus and DPI behave as before.
//
// After a successful call nothing is drawn with GDI on the HWND any
// more: WM_PAINT only validates the window (BeginPaint/EndPaint) and
// runs a CanvasFrame when one is due, never blitting a CPU frame.
// Present(nil) means "the GPU presented already" and returns nil.
// Present(img) still works as a CPU fallback (the GPU presenter cannot
// start, a frame beyond a device limit, a lost device): the image is
// shown in a sibling child window placed above the HWND, which passes
// pointer input through to the canvas and never takes focus, and the
// next Present(nil) hides it again.
//
// Returns ErrUnsupported for attached (CanvasAttacher) canvases,
// layered ones and so PassThrough layers, and for transparent
// canvases (Appearance.Transparent or a Material), and an error off
// the main thread or after the surface closed.
UseGPUWindow() (hwnd uintptr, err error)
}
CanvasHWND is implemented by Windows canvases that can hand their child HWND to a GPU presenter (a DXGI flip-model swap chain). Discover it with a type assertion on the Canvas from CanvasCreator.NewCanvasSurface; it parallels CanvasMetal.
type CanvasInsets ¶
type CanvasInsets interface {
// SafeAreaInsets returns the parts of the content area covered by the
// status bar, a notch or camera cut-out, rounded corners, the home
// indicator or the navigation bar.
SafeAreaInsets() geom.Insets
// KeyboardInset returns the part covered by the soft keyboard, usually
// only Bottom; zero while the keyboard is hidden. The keyboard is not
// part of the safe area.
KeyboardInset() geom.Insets
}
CanvasInsets is implemented by canvases that fill the screen behind system UI. The core polls it every frame, so both methods return cached values and must be cheap. When a value changes the platform calls Invalidate (or reports CanvasResized when the size changed too). Logical pixels; main thread.
type CanvasKeySink ¶
type CanvasKeySink interface {
CanvasFilterKey(input.KeyEvent) bool
CanvasKeyInput(ev input.KeyEvent, synthetic bool)
}
CanvasKeySink is the optional synchronous key filter of a canvas sink. Backends call it after native menu handling, before translating a key to text. Any key events subsequently emitted for that hardware event go through CanvasKeyInput, so the filter is not called twice.
type CanvasLayer ¶
type CanvasLayer struct {
Bounds Rect // relative to the content area, logical pixels; zero = fill
Above bool // above the WebView (true) or below it (false; the page must be transparent)
PassThrough bool // pointer events over transparent pixels go to the layer below
// HitAlpha is the pass-through threshold: with PassThrough, a pixel
// of the last presented frame takes pointer input only if its alpha
// is at least HitAlpha. 0 means 1 (any non-transparent pixel); 32
// lets soft shadows and anti-aliased fringes pass clicks through.
HitAlpha uint8
// Anchor keeps non-zero Bounds at a fixed distance from a corner (or
// the centre) of the content area when the window is resized; X/Y of
// Bounds are still given from the top-left for the current size.
// Ignored for zero Bounds (fill).
Anchor CanvasAnchor
}
CanvasLayer places a canvas inside an existing WebView surface.
func (CanvasLayer) AnchoredBounds ¶
func (l CanvasLayer) AnchoredBounds(oldW, oldH, newW, newH int) Rect
AnchoredBounds returns where Bounds (given for a content area of oldW×oldH) sit in a content area of newW×newH under Anchor. Zero Bounds stay zero (fill).
func (CanvasLayer) HitThreshold ¶
func (l CanvasLayer) HitThreshold() uint8
HitThreshold returns the effective HitAlpha (at least 1).
type CanvasMetal ¶
type CanvasMetal interface {
// UseMetalLayer replaces the view's backing layer with a CAMetalLayer
// once and returns it (a CAMetalLayer*, owned by the view: valid until
// the surface closes; retain it to keep it longer). Calling it again
// returns the same layer. Main thread; it never calls the sink itself
// but schedules one CanvasFrame, so the first GPU frame follows without
// an Invalidate.
//
// Frame scheduling is unchanged: CanvasFrame still comes only after
// Invalidate/InvalidateAt, a size or scale change, or the switch
// itself, at most once per display refresh, and a still window costs
// no frames. Input, IME, cursor and focus behave as before.
//
// The platform keeps the layer's frame on the view's bounds, its
// contentsScale on the backing scale factor (updated before
// CanvasResized is reported), opaque set and implicit animations off.
// Everything else is the caller's (the GPU presenter's): device,
// pixelFormat, framebufferOnly, colorspace and drawableSize, which it
// must set to Size()*Scale() device pixels on CanvasResized or at the
// start of each CanvasFrame.
//
// After a successful call, Present(nil) means "the GPU presented
// already" and returns nil. Present(img) still works as a CPU fallback
// (e.g. when the GPU presenter cannot start): the image is shown in a
// sublayer above the drawables, not blitted through Metal, and hidden
// again by the next Present(nil).
//
// Returns ErrUnsupported for attached (CanvasAttacher) canvases, for
// transparent canvases (Appearance.Transparent or a Material) and so
// for PassThrough layers, and an error off the main thread or after
// the surface closed.
UseMetalLayer() (layer uintptr, err error)
}
CanvasMetal is implemented by macOS canvases that can switch to a CAMetalLayer for GPU presentation. Discover it with a type assertion on the Canvas from CanvasCreator.NewCanvasSurface.
type CanvasNativeWindow ¶
CanvasNativeWindow is implemented by canvases that can be drawn by a GPU API bound to a native window (Android EGL). UseNativeWindow switches the canvas to GPU presentation and returns a stable platform handle to the window holder, not the window itself: the native window is recreated whenever the app returns from the background, so the presenter reads the current window from the holder on every present and skips the frame while there is none. After it succeeds, Present(nil) means the GPU presented the frame. It returns ErrUnsupported when the canvas cannot do it (for example canvases placed inside a WebView surface). Main thread.
type CanvasShortcutCapture ¶
type CanvasShortcutCapture interface {
SetShortcutCapture(on bool)
}
CanvasShortcutCapture is an optional capability for shortcut recording. While enabled, menu accelerators yield to this canvas when it owns native keyboard focus. Other controls/windows and OS-level hotkeys are unaffected. It does not enable text input/IME. Main thread.
type CanvasSink ¶
type CanvasSink interface {
// CanvasFrame asks for a frame now: after Invalidate/InvalidateAt fire,
// after a size or scale change, and when the canvas is first shown. The
// sink renders and calls Canvas.Present before returning.
CanvasFrame()
// CanvasInput delivers input in logical pixels relative to the top-left
// of the content area (see ui/window.go for event conventions).
CanvasInput(ev input.Event)
// CanvasResized reports a new logical size or device scale.
CanvasResized(w, h, scale float32)
// CanvasFocus reports keyboard focus gained or lost by the canvas.
CanvasFocus(focused bool)
}
CanvasSink receives canvas callbacks. It is implemented by the core (package uihost); backends call it on the main thread only.
type CanvasTextInputState ¶
type CanvasTextInputState interface {
SetTextInputState(st input.TextInputState)
}
CanvasTextInputState is implemented by canvases whose input method can use the text around the caret (autocorrection, prediction, surrounding text deletion). The core calls SetTextInputState after SetTextInput whenever the focused field's state changes. Without it, or until the first call, the platform runs its input method on a shadow document that holds only the composition. Main thread.
type CanvasThreaded ¶
type CanvasThreaded interface {
// StartFrameClock starts per-refresh callbacks on the calling thread
// (the window's UI thread); request asks for a callback at the next
// refresh (frameAtOnce semantics apply). tick runs on that thread.
StartFrameClock(tick func()) (request func(), stop func(), err error)
// MainGeometry returns the latest size and scale as set on the main
// thread; safe from any thread. Update it before dispatching resize
// callbacks; uihost uses it to reject stale, reentrant CanvasResized
// notifications as well as to seed the initial frame geometry.
MainGeometry() (w, h, scale float32)
}
CanvasThreaded is implemented by a Canvas whose frames may be drawn and presented on a thread other than the main thread.
Package uihost discovers it with a type assertion on the Canvas from CanvasCreator.NewCanvasSurface (never for attached canvases) and then drives the window from its own UI thread: frames come from the clock, not from CanvasSink.CanvasFrame, and Present and PresentDamage are called there; request replaces Invalidate. The sink callbacks still arrive on the main thread, and the GPU switch calls (UseMetalLayer, UseCoreGraphicsLayer) stay main-thread calls: uihost makes them on the main thread while it opens the window, and a UI thread that needs one later asks the main thread for it and waits (tango.Await marks that wait). The main thread may be waiting for StartFrameClock to return, so StartFrameClock must not wait for the main thread. request may be called from any goroutine; stop is called once, on the UI thread. Experimental.
type CanvasThreadedRelease ¶
type CanvasThreadedRelease interface {
ReleaseThreadedOnMain()
}
CanvasThreadedRelease is optional on a CanvasThreaded. Once a threaded window starts closing, the backend stops delivering its callbacks but keeps the canvas and any native objects a frame can still use alive. uihost calls ReleaseThreadedOnMain once, on main after stopping the clock, closing the renderer and observing that the UI thread exited. This also applies on app quit (even without a native close event); it must not need a running native loop or block. If the thread misses the quit deadline, this method is not called. A canvas that fell back to the main thread still uses its ordinary native teardown path.
type CanvasThreadedSink ¶
type CanvasThreadedSink interface {
WantsUIThread() bool
}
CanvasThreadedSink is optionally implemented by a CanvasSink that can drive a CanvasThreaded canvas from its own UI thread. A backend that supports threaded canvases returns one from CanvasCreator.NewCanvasSurface only when the sink implements this interface and WantsUIThread reports true. Every other sink (the tan dev host's windows, for example) gets an ordinary main-thread canvas, because a threaded canvas does not draw until a UI thread starts its frame clock. Experimental.
type CanvasWebViewEmbedder ¶
type CanvasWebViewEmbedder interface {
NewCanvasWebView(id SurfaceID, opts SurfaceOptions, web WebOptions) (EmbeddedWebView, error)
}
CanvasWebViewEmbedder is implemented by attached canvases that can host WebViews in their own coordinate system and stacking layer.
type ClipboardRich ¶
type ClipboardRich interface {
ClipboardReadImage() ([]byte, error)
ClipboardWriteImage(png []byte) error
ClipboardReadFiles() ([]string, error)
// ClipboardWriteFiles puts absolute paths on the clipboard as a file
// list (Finder / Explorer / file manager copy). Round 3.
ClipboardWriteFiles(paths []string) error
}
ClipboardRich extends Clipboard with images (PNG bytes) and file lists.
Reading a clipboard that holds no item of the kind asked for (empty, or only text) returns (nil, nil), not an error; errors are for clipboards that could not be read or converted. Writing replaces the whole clipboard content.
type ContrastPreference ¶
type ContrastPreference interface {
HighContrast() bool
}
ContrastPreference is an optional Backend capability: the system "increase contrast" / high-contrast accessibility preference (macOS accessibilityDisplayShouldIncreaseContrast, Windows SPI_GETHIGHCONTRAST with HCF_HIGHCONTRASTON — the contrast themes —, the XDG settings portal's org.freedesktop.appearance contrast or a GTK theme named like "HighContrast" on Linux). false also means the platform does not say. When it changes the backend reports AppContrastChanged through HostEx.OnAppEvent, as AppReduceMotionChanged for MotionPreference. Any goroutine.
type CreatorEx ¶
type CreatorEx interface {
NewSurfaceEx(id SurfaceID, opts SurfaceOptions, ex SurfaceExtras) (Surface, error)
}
type Dialogs ¶
type Dialogs interface {
MessageDialog(parent SurfaceID, opts MessageOptions, done func(button int, err error))
OpenFileDialog(parent SurfaceID, opts FileOptions, done func(paths []string, err error))
SaveFileDialog(parent SurfaceID, opts FileOptions, done func(path string, err error))
}
Dialogs are asynchronous: the backend shows the dialog and calls done on the main thread exactly once. It must not block the main thread.
type DocumentPrinter ¶
type DocumentPrinter interface {
PrintDocument(parent SurfaceID, pdf []byte, opts PrintOptions, done func(error))
}
DocumentPrinter prints a PDF document through the system print dialog. pdf is a complete PDF file (the core checks the %PDF- header and turns images into PDF before calling). The dialog is attached to parent where the platform attaches dialogs to windows; parent 0 or an unknown id shows it on its own. done reports as for PagePrinter.
The backend must not keep pdf after done; it copies what it needs (to a temporary file, for example) and removes such copies itself.
type DownloadEvent ¶
type DownloadEvent struct {
ID uint64
State DownloadState
Received int64 // bytes written so far
Total int64 // expected total, -1 when unknown
Path string // destination
Error string // DownloadFailed
}
DownloadEvent reports progress or the end of an accepted download.
type DownloadRequest ¶
type DownloadRequest struct {
CannotDefer bool // engine requires a synchronous destination
ID uint64 // allocated by the backend, unique for the app's run, never 0
URL string
Filename string // suggested file name (no directory); may be ""
MIME string // may be ""
Size int64 // expected size in bytes, -1 when unknown
}
DownloadRequest describes a download asking for a destination.
type DownloadState ¶
type DownloadState int
const ( DownloadProgress DownloadState = iota + 1 DownloadDone DownloadFailed DownloadCanceled )
type DragOperation ¶
type DragOperation int
DragOperation is what the drop target did with dragged files.
const ( DragNone DragOperation = iota // canceled, or the target refused DragCopy DragMove DragLink )
type Dragger ¶
type Dragger interface {
StartMove()
StartResize(edge string) // "n","s","e","w","ne","nw","se","sw"
}
Dragger lets frameless windows be moved/resized from page content. The core injects JS that detects elements with CSS `--tango-drag: drag` (or `app-region: drag`) and asks the backend to start a native drag on the current mouse-down. Backends that can detect drag regions natively may ignore these calls.
type EdgeResizer ¶
type EdgeResizer interface {
HandlesEdgeResize() bool
}
EdgeResizer is implemented by surfaces that tell the core whether their frameless (TitleBarNone) resizable windows keep native resize borders. When HandlesEdgeResize reports true the core does not turn the page's edges into resize handles (Dragger.StartResize is then never called). Surfaces without it are treated as reporting false. (Round 3.)
type EmbedGeometry ¶
type EmbedGeometry struct {
// Visible is false when nothing of the view shows (empty clip or
// hidden); the other fields are then zero.
Visible bool
// Clip is the container rectangle relative to the parent's content
// area, in the units requested (device pixels for DeviceGeometry).
Clip image.Rectangle
// Frame is the web view rectangle relative to the container's
// top-left corner (its origin is usually ≤ 0).
Frame image.Rectangle
}
EmbedGeometry is a placement converted for a "clip container" implementation: a native container sized to the visible part, whose child — the web view — is offset so that only the visible part shows.
type EmbeddedNativeView ¶
type EmbeddedNativeView interface {
// SetPlacement moves, resizes and clips the view, exactly like
// EmbeddedWebView.SetPlacement. Main thread; cheap when unchanged.
SetPlacement(p WebPlacement)
// Close removes the view from its parent and hides it, leaving it to
// the application. Main thread.
Close()
}
EmbeddedNativeView is an application's native view placed in a canvas surface.
type EmbeddedWebView ¶
type EmbeddedWebView interface {
Surface
// SetPlacement moves, resizes and clips the view. Main thread; cheap
// when nothing changed, so callers may call it every frame.
SetPlacement(p WebPlacement)
// FocusWeb gives keyboard focus to the web view (first responder,
// MoveFocus, gtk_widget_grab_focus).
FocusWeb()
// BlurWeb gives keyboard focus back to the parent's content view
// (the canvas) if the web view has it; otherwise it does nothing.
BlurWeb()
}
EmbeddedWebView is a WebView living inside another surface.
Its Surface methods: Navigate, Eval and OpenDevTools work as for a WebView surface. Show and Hide set an application-level hidden flag that combines with the placement (hidden wins). Close removes and destroys the view and reports SurfaceClosed. SetTitle and SetSize do nothing. Size reports the frame size of the last placement, rounded. Focus is FocusWeb. Native returns the platform web view object (WKWebView*, ICoreWebView2Controller*, WebKitWebView*).
The value also implements the optional WebView interfaces (webview_ext.go: WebFinder, WebSnapshot, WebCookies, ...) that the backend's WebView surfaces implement, but none of the window interfaces (Geometry, Stateful, Styled, ...).
type FileDragger ¶
type FileDragger interface {
StartFileDrag(paths []string, icon []byte, done func(op DragOperation)) error
}
FileDragger is implemented by surfaces that can start a native drag of files to other apps (Finder, Explorer, file managers, mail clients).
StartFileDrag must be called while a mouse button is held over the surface — typically from the page's mousedown / dragstart, relayed to Go — because the platforms tie a drag session to the press that started it; without a press the drag ends at once with DragNone. paths are absolute and must exist. icon is an optional PNG for the drag image (nil: the system's file icon). done runs once on the main thread when the drag ends. Where the platform's drag loop is modal (Windows DoDragDrop) StartFileDrag returns after done has run.
Backends offer the target copy and link only, never move: the dragged files are the app's own, and a file manager would otherwise take them away on a same-volume drop. DragMove is reported only if a target moves anyway. icon may be ignored where the system builds the drag image itself (Windows shell data object).
type FileFilter ¶
type FileOptions ¶
type FileOptions struct {
Title string
Directory string // initial directory
Filename string // save dialog default name
Filters []FileFilter
Multiple bool // open: allow multiple selection
PickFolders bool // open: choose directories instead of files
CanCreateDirs bool // open/save: allow "New Folder"
ShowHidden bool
}
type FindOptions ¶
type FindOptions struct {
MatchCase bool
Backward bool // search towards the start of the page
NoWrap bool // stop at the end (start) instead of wrapping around
}
FindOptions configures a find-in-page search.
type FindResult ¶
type FindResult struct {
// Matches is the number of matches in the page, -1 when the platform
// does not count them.
Matches int
// Active is the 1-based index of the highlighted match, 0 when nothing
// is highlighted or the platform does not tell.
Active int
// Found reports whether a match is highlighted.
Found bool
}
FindResult reports a find-in-page search.
type Geometry ¶
type Geometry interface {
Bounds() Rect
SetBounds(r Rect)
Center()
SetSizeLimits(minW, minH, maxW, maxH int) // 0 = no limit
}
Geometry is implemented by surfaces that are free-floating windows.
type HapticKind ¶
type HapticKind int
const ( HapticLight HapticKind = iota + 1 // impact HapticMedium HapticHeavy HapticSelection // selection changed (picker tick) HapticSuccess // notification feedback HapticWarning HapticError )
type Haptics ¶
type Haptics interface {
Haptic(k HapticKind) error
}
type Host ¶
type Host interface {
// Drain runs work queued with App.Post. Called after Wake.
Drain()
OnLifecycle(ev LifecycleEvent)
// ShouldClose is asked when the user tries to close a surface (window
// close button, Android back on the root page). Returning false keeps it
// open. If true the backend closes it and emits SurfaceClosed.
ShouldClose(id SurfaceID) bool
OnSurfaceEvent(id SurfaceID, ev SurfaceEvent)
// OnMessage delivers a string the page sent with
// window.__tangoNative.post(str). origin is the page origin as reported by
// the WebView (scheme://host[:port]) so the core can reject untrusted
// frames. Only main-frame messages are delivered. Where the platform
// cannot tell which frame sent a message (WebKitGTK 4.1, Android
// JavascriptInterface), the backend reports the main frame's current
// origin and the bridge shim must refuse to post from sub-frames.
OnMessage(id SurfaceID, origin string, msg string)
// ServeAsset serves a request made to AssetOrigin. Backends adapt their
// native scheme handler / request interception to net/http. id is the
// surface that issued the request, or 0 if unknown.
//
// EXCEPTION to the main-thread rule (revised round 2): ServeAsset may be
// called from any goroutine/thread, and backends SHOULD call it off the
// main thread so slow or streaming handlers never block the UI. Writes to
// w may happen after ServeAsset returns only if the backend documents
// it; by default the response is complete when ServeAsset returns.
ServeAsset(id SurfaceID, w http.ResponseWriter, r *http.Request)
}
Host is implemented by the core. Backends call it on the main thread.
type HostEx ¶
type HostEx interface {
Host
OnAppEvent(ev AppEvent)
// ShouldQuit is asked when the user quits the app (Cmd+Q, Quit menu role,
// last-window policy is the core's business). Return false to cancel.
ShouldQuit() bool
}
HostEx is implemented by the core's Host. Backends type-assert their Host to HostEx (always succeeds for the real core; fake hosts may not).
type HostQuit ¶
type HostQuit interface {
OnQuitStarted()
}
--------------------------------------------------------------------------- HostQuit is notified on main when the backend commits to exit, before aborting modal loops or completing requests canceled by the exit. It is not a veto and can be called repeatedly. Backends that support threaded windows must notify it even if their event loop ends without Quit.
type Hotkeys ¶
type Hotkeys interface {
RegisterHotkey(id uint32, accelerator string, fire func()) error
UnregisterHotkey(id uint32)
}
Hotkeys are system-wide shortcuts that fire even when the app is inactive.
type IMECandidate ¶
type IMECandidate struct {
Text, Comment string
}
type IMEMenuItem ¶
type IMEModifierKey ¶
type InputMethodCandidateSink ¶
InputMethodCandidateSink reports a selection by zero-based list index.
type InputMethodCandidates ¶
type InputMethodCandidates interface {
IMESetCandidates(session uint64, list []IMECandidate, selected int)
}
InputMethodCandidates sends a session's candidates to a native panel.
type InputMethodMenus ¶
type InputMethodMenus interface {
IMEMenu() []IMEMenuItem
IMEMenuClicked(id string)
}
InputMethodMenus is the optional menu event sink.
type InputMethodModeSink ¶
type InputMethodModeSink interface {
IMEModeChanged(id string)
}
InputMethodModeSink is notified after a system-initiated mode change.
type InputMethodModes ¶
InputMethodModes controls the backend's process-wide input mode.
type InputMethodModifiers ¶
type InputMethodModifiers interface {
IMEWantsModifiers() bool
IMEModifier(session uint64, key IMEModifierKey) bool
}
InputMethodModifiers is the optional modifier event sink.
type InputMethodSink ¶
type InputMethodSink interface {
IMEKey(session uint64, k IMEKey) bool
IMEActivate(session uint64)
IMEDeactivate(session uint64)
IMECommitComposition(session uint64)
IMEEnd(session uint64)
}
InputMethodSink receives events for the lifetime of each input session.
type InputMethods ¶
type InputMethods interface {
// An empty connection selects the platform default.
ServeInputMethod(connection string, sink InputMethodSink) error
IMESetComposition(session uint64, text string, cursor int) // cursor counts runes
IMECommit(session uint64, text string)
IMECaret(session uint64) Rect
IMEClientApp(session uint64) string
}
InputMethods is implemented by backends that can host a system input method.
type Insets ¶
type Insets struct {
Top, Bottom, Left, Right float64
}
Insets are in CSS pixels (points / dp), measured from the edges of the page's web view: the parts of the page covered by system UI (status bar, notch, home indicator, navigation bar). Where the host already keeps the web view clear of system UI they are zero.
type Keyboard ¶
type Keyboard interface {
// KeyboardHeight is the covered height in CSS pixels, 0 when hidden.
KeyboardHeight() float64
HideKeyboard() error
}
Keyboard reports the software keyboard. Changes arrive as AppKeyboardChanged.
type LaneGenerations ¶
type LaneGenerations interface {
// LaneGeneration is called after the core started lane generation gen
// for the page's hello, with the lanes it offered (nil: none, the
// generation has no lanes). Any goroutine; must not block and must
// not call back into the core's lane state.
LaneGeneration(gen uint64, lanes []string)
}
LaneGenerations is optionally implemented by a BinaryLane whose lanes need setting up for each page generation (Windows shared buffers).
type LaneHost ¶
LaneHost is implemented by the core's Host. Backends type-assert their Host to LaneHost to deliver packets their upstream lanes (up:android, up:shm) received from surface id's page at origin, sent in lane generation gen. OnLanePacket may be called from any goroutine and does not keep p. It reports whether p was handed to the OnBinary handlers; false means it was dropped (the surface is gone, origin is not the asset origin, gen is not the current generation or the upstream lane is not usable), and the backend may tell the page its upstream lane refused.
type LifecycleEvent ¶
type LifecycleEvent int
const ( LifecycleStarted LifecycleEvent = iota + 1 // native app finished launching LifecycleForeground // app became active / visible LifecycleBackground // app resigned active / went to background LifecycleTerminating // about to exit; last chance to save )
type LocaleListeners ¶
type LocaleListeners struct {
// contains filtered or unexported fields
}
LocaleListeners is a set of change callbacks for backends implementing LocaleWatcher: Add registers one, Notify calls them all. The zero value is ready to use and safe for concurrent use.
func (*LocaleListeners) Add ¶
func (l *LocaleListeners) Add(fn func()) (cancel func(), first bool)
Add registers fn and returns its cancel function. first reports whether fn is the first listener ever added, so a backend can start observing lazily.
func (*LocaleListeners) Notify ¶
func (l *LocaleListeners) Notify()
Notify calls every registered fn, outside the lock, on the calling goroutine.
type LocaleWatcher ¶
type LocaleWatcher interface {
WatchLocales(fn func()) (cancel func())
}
LocaleWatcher is an optional Backend capability: WatchLocales calls fn after the system language list may have changed (fn may also run for changes that leave the list as it was). fn runs on the main thread when the backend knows one, otherwise on any goroutine. cancel stops the calls; it may be called more than once.
Like Locales, a desktop backend package can also register a backend-independent watcher with SetLocaleWatch from its init function. Backends whose system has no change notification (Linux) implement neither, and apps call i18n.Refresh themselves.
type Locales ¶
type Locales interface {
PreferredLocales() []string
}
Locales is an optional Backend capability: the user's preferred UI languages as BCP 47 tags ("zh-Hans-CN", "en-US"), most preferred first. Unlike the other capabilities it may be called from any goroutine.
type Location ¶
type Location struct {
Latitude, Longitude float64
Altitude float64 // metres; valid when AltitudeAccuracy > 0
Accuracy float64 // horizontal, metres
AltitudeAccuracy float64
Speed float64 // m/s; negative when unknown
Heading float64 // course in degrees from north; negative when unknown
Time time.Time
}
type LocationAccuracy ¶
type LocationAccuracy int
const ( AccuracyBalanced LocationAccuracy = iota // ~100 m, network-assisted AccuracyHigh // best available (GPS) AccuracyLow // ~1-3 km, battery friendly )
type LocationOptions ¶
type LocationOptions struct {
Accuracy LocationAccuracy
// DistanceFilter (metres) for updates: only report moves at least this
// far; 0 reports every update.
DistanceFilter float64
}
type Locator ¶
type Locator interface {
// CurrentLocation delivers one fix.
CurrentLocation(opts LocationOptions, done func(Location, error))
// StartLocationUpdates delivers fixes to fn until StopLocationUpdates.
// One session at a time: starting again replaces opts and fn. An error
// passed to fn ends the session.
StartLocationUpdates(opts LocationOptions, fn func(Location, error))
StopLocationUpdates()
}
Locator reads the device location. Both ask for when-in-use permission first if the user has not been asked; ErrPermissionDenied if refused.
type MediaPicker ¶
type MediaPicker interface {
PickMedia(opts PickMediaOptions, done func(paths []string, err error))
}
MediaPicker lets the user choose from the photo library (PHPicker, Android Photo Picker) without a library permission. done receives paths of copies in the app's cache directory, ErrCanceled when dismissed.
type MenuItem ¶
type MenuItem struct {
ID uint32 // core-allocated, nonzero for clickable items
Label string
Accelerator string // "CmdOrCtrl+Shift+N"
Role string // "", "quit", "about", "hide", "copy", "paste", "cut", "selectAll", "undo", "redo", "minimize", "close", "appMenu", "editMenu", "windowMenu"
Separator bool
Disabled bool
Checked bool
Checkable bool // render as a check item even when !Checked
RadioGroup string // non-empty: radio item; items sharing a group are exclusive
Icon []byte // PNG, optional; ignored where unsupported
}
MenuItem describes a menu tree. Role items are platform standard items (Quit, Copy, Paste, ...) whose label/action the backend supplies.
type MessageKind ¶
type MessageKind int
const ( MessageInfo MessageKind = iota MessageWarning MessageError MessageQuestion )
type MessageOptions ¶
type MessageOptions struct {
Kind MessageKind
Title string
Message string
Buttons []string // empty means a single "OK"
}
type MotionPreference ¶
type MotionPreference interface {
ReduceMotion() bool
}
MotionPreference is an optional Backend capability: the system "reduce motion" accessibility preference (macOS accessibilityDisplayShouldReduceMotion, Windows SPI_GETCLIENTAREAANIMATION off, GTK gtk-enable-animations off). When it changes the backend reports AppReduceMotionChanged through HostEx.OnAppEvent, as AppThemeChanged for the theme. Any goroutine.
type NativeViewEmbedder ¶
type NativeViewEmbedder interface {
// NewEmbeddedNativeView puts view into parent's content area above
// the canvas; views embedded later stack above earlier ones (WebViews
// included). It is hidden until a SetPlacement with a non-empty Clip.
// The application keeps owning view: the backend never destroys it.
// closed runs on the main thread when the backend removes the view
// itself because parent closed; it does not run after Close. Main
// thread.
NewEmbeddedNativeView(parent SurfaceID, view uintptr, opts NativeViewOptions, closed func()) (EmbeddedNativeView, error)
}
NativeViewEmbedder is implemented by backends that can place a native view created by the application (an NSView* on macOS, a child HWND on Windows, a GtkWidget* on Linux) inside the content area of a canvas surface, in the same layer as embedded WebViews.
type NativeViewOptions ¶
type NativeViewOptions struct {
// PassInput lets mouse events over the view reach the canvas below,
// as if the view were not there; the view never takes keyboard focus
// from the canvas.
PassInput bool
}
NativeViewOptions configure an embedded native view.
type NavigationRequest ¶
type NavigationRequest struct {
}
NavigationRequest is a main-frame navigation about to start.
type NestedLoop ¶
type NestedLoop interface {
NestedLoopSupported() bool
}
NestedLoop is implemented by backends to say whether Step(true), called from inside a main-thread callback, processes native events (input, dialogs, the callbacks that would call done). Where it cannot (Android: the Looper cannot be re-entered), waiting there would never end, so the core refuses AwaitAsync on the main thread at once with an error instead. Backends without it are treated as supporting nested loops.
type Network ¶
type Network interface {
NetworkStatus() (NetworkStatus, error)
// SetNetworkHandler starts (fn != nil) or stops (nil) delivering
// changes to fn on the main thread. Repeated identical states may be
// coalesced by the backend; the core coalesces them too.
SetNetworkHandler(fn func(NetworkStatus)) error
}
Network reports connectivity and its changes.
type NetworkKind ¶
type NetworkKind int
NetworkKind is the interface type the default route uses.
const ( NetworkUnknown NetworkKind = iota NetworkNone // offline NetworkWired // Ethernet (and Thunderbolt / USB Ethernet) NetworkWiFi // 802.11 NetworkCellular // mobile broadband / tethered modem NetworkOther // VPN-only, loopback, unknown kinds )
type NetworkStatus ¶
type NetworkStatus struct {
Online bool // a route to the internet is believed to exist
Kind NetworkKind
// Metered is the system's "expensive" flag: cellular, a personal
// hotspot, or a connection the user marked as metered.
Metered bool
// Constrained is Low Data Mode (macOS) / an approaching data limit
// (Windows); false elsewhere.
Constrained bool
}
NetworkStatus is a snapshot of connectivity.
type NewWindowRequest ¶
type NewWindowRequest struct {
URL string // absolute; "" for window.open() without URL
UserInitiated bool // a user gesture caused it, where the platform tells
// Width and Height are the window features the page asked for in
// logical pixels, 0 when not given or not reported.
Width, Height int
}
NewWindowRequest is a request of the page to open a new window.
type Notification ¶
type NotificationRemover ¶
type NotificationRemover interface {
RemoveDeliveredNotification(id string) error
RemoveAllDeliveredNotifications() error
}
NotificationRemover is the optional delivered-notification removal capability.
type Notifier ¶
type Notifier interface {
// RequestNotifyPermission resolves to whether notifications may be shown.
RequestNotifyPermission(done func(granted bool, err error))
Notify(n Notification, onClick func()) error
}
Notifier shows notifications. Clicks on a notification sent in this run call its onClick. A click the backend cannot route to an onClick — on a notification an earlier run sent, including the click that launched the app — is reported as an AppNotificationOpened event with the notification's ID, where the platform tells (macOS). Backends keep such a launch click until LifecycleStarted, like other launch events.
type Orientation ¶
type Orientation int
Orientation is the interface orientation, named by where the device's top edge points: OrientationLandscapeLeft is the device turned 90° counter-clockwise from portrait (UIInterfaceOrientationLandscapeRight, Android ROTATION_90 on phones).
const ( OrientationUnknown Orientation = iota OrientationPortrait OrientationPortraitUpsideDown OrientationLandscapeLeft OrientationLandscapeRight )
type OrientationMask ¶
type OrientationMask int
OrientationMask is a set of orientations; 0 means "no lock" (whatever the app declares as supported).
const ( MaskPortrait OrientationMask = 1 << iota MaskPortraitUpsideDown // phones without a home button do not support it MaskLandscapeLeft MaskLandscapeRight MaskLandscape = MaskLandscapeLeft | MaskLandscapeRight MaskAll = MaskPortrait | MaskPortraitUpsideDown | MaskLandscape )
type Orientations ¶
type Orientations interface {
Orientation() Orientation
// LockOrientation restricts the interface to m (0 unlocks) and rotates
// to an allowed orientation if needed.
LockOrientation(m OrientationMask) error
}
type OverlaySupport ¶
type OverlaySupport interface {
SupportsOverlay() bool
}
OverlaySupport is implemented by backends that can create KindOverlay windows.
type PDFOptions ¶
type PDFOptions struct {
Landscape bool
NoBackground bool // omit background colours and images
PageWidth float64 // inches; 0 = platform default (A4 or Letter)
PageHeight float64 // inches; 0 = platform default
}
PDFOptions configures PrintToPDF. Fields a platform cannot honour are ignored.
type PageControl ¶
type PageControl interface {
Reload()
SetZoom(factor float64) // 1.0 = 100%
Zoom() float64
Print()
}
PageControl covers WebView-level controls.
type PagePrinter ¶
type PagePrinter interface {
PrintPage(surface SurfaceID, opts PrintOptions, done func(error))
}
PagePrinter prints the page shown in a WebView surface through the system print dialog.
done receives nil once the job was handed to the printing system (not when paper comes out), ErrCanceled if the user dismissed the dialog and the platform tells, or another error. Canvas surfaces, closed and unknown surfaces get ErrUnsupported.
type Permission ¶
type Permission string
Permission names. They match the permission names of tan.json.
const ( PermCamera Permission = "camera" PermPhotos Permission = "photos" PermLocation Permission = "location" // when in use PermLocationAlways Permission = "location-always" // background PermNotifications Permission = "notifications" PermMicrophone Permission = "microphone" )
type PermissionDecision ¶
type PermissionDecision int
PermissionDecision answers a PermissionRequest.
const ( PermissionDefault PermissionDecision = iota // no decision: the platform default (same as Prompt) PermissionPrompt // ask the user (platform prompt, or the backend's own) PermissionAllow PermissionDeny )
type PermissionRequest ¶
type PermissionRequest struct {
Origin string // scheme://host[:port] of the requesting frame; "" if unknown
Kinds []WebPermission
}
PermissionRequest is one page permission request. A request may name several kinds at once (camera and microphone for one getUserMedia call); the decision covers all of them.
type PermissionStatus ¶
type PermissionStatus string
const ( StatusNotDetermined PermissionStatus = "notDetermined" // never asked; Request will prompt StatusGranted PermissionStatus = "granted" StatusDenied PermissionStatus = "denied" // refused, restricted by policy, or "don't ask again" StatusLimited PermissionStatus = "limited" // partial (selected photos, approximate location, provisional notifications) )
type Permissions ¶
type Permissions interface {
CheckPermission(p Permission, done func(PermissionStatus, error))
RequestPermission(p Permission, done func(PermissionStatus, error))
}
Permissions queries and requests runtime permissions. Unknown names give ErrUnsupported. Request does not prompt again once the user decided; it then reports the current status.
type PickMediaOptions ¶
type PopupMenu ¶
type PopupMenu interface {
PopupMenu(surface SurfaceID, x, y int, items []MenuItem, onClick func(id uint32), onClose func())
}
PopupMenu shows a context menu at (x,y) in the surface's content coordinates (logical px). onClick(id) is called on the main thread if an item is chosen; onClose always follows.
type Power ¶
type Power interface {
PowerStatus() (PowerStatus, error)
// SetPowerHandler starts (fn != nil) or stops (nil) delivering power
// events to fn on the main thread. PowerSuspending is delivered on a
// best-effort basis before the system sleeps; handlers must be quick.
SetPowerHandler(fn func(PowerEvent)) error
// BlockSleep starts one sleep block and returns a nonzero token.
// reason is shown by the system where it shows one (pmset -g
// assertions, powercfg /requests, systemd-inhibit --list).
BlockSleep(kind SleepBlock, reason string) (token uint64, err error)
// UnblockSleep ends a block; unknown tokens are ignored.
UnblockSleep(token uint64)
}
Power reports the power state, suspend/resume, and keeps the machine awake. A system sleep the user asks for (lid closed, Sleep menu) is not blocked by BlockSleep on any platform.
type PowerEvent ¶
type PowerEvent int
PowerEvent is a change reported to the PowerEvents handler.
const ( PowerSuspending PowerEvent = iota + 1 // the system is about to sleep PowerResumed // the system woke up PowerStatusChanged // PowerStatus changed (source, charge, low-power mode) )
type PowerSource ¶
type PowerSource int
PowerSource is where the machine draws power from.
const ( PowerSourceUnknown PowerSource = iota PowerSourceAC // mains (or a UPS reporting AC) PowerSourceBattery // running on the internal battery )
type PowerStatus ¶
type PowerStatus struct {
Source PowerSource
HasBattery bool // the machine has an internal battery
Battery float64 // charge in [0,1]; -1 when unknown or no battery
Charging bool
// LowPower is the system's power-saving mode: Low Power Mode (macOS
// 12+), Battery / Energy Saver (Windows 10+), the "power-saver" power
// profile (Linux power-profiles-daemon).
LowPower bool
}
PowerStatus is a snapshot of the machine's power state.
type PrintOptions ¶
type PrintOptions struct {
// Title names the print job (the print queue, "Print to File" default
// name). "" keeps the platform's choice: the page title or app name.
Title string
// Copies is the initial number of copies; 0 keeps the system default.
Copies int
}
PrintOptions are the initial values of the system print dialog. The user can change them there. Fields a platform cannot preset are ignored.
type ProductKind ¶
type ProductKind int
const ( ProductUnknown ProductKind = iota ProductConsumable ProductNonConsumable ProductSubscription )
type Purchases ¶
type Purchases interface {
CanMakePayments() bool
// QueryProducts looks products up; invalid lists unknown ids.
QueryProducts(ids []string, done func(products []Product, invalid []string, err error))
// Purchase buys a product queried before; done receives the final
// state (TxPurchased, TxFailed, TxDeferred). ErrCanceled when the user
// canceled.
Purchase(productID string, quantity int, done func(Transaction, error))
// RestorePurchases re-delivers completed non-consumable and
// subscription transactions as TxRestored updates; done when finished.
RestorePurchases(done func(error))
TakePurchaseUpdates() []Transaction
FinishTransaction(id string) error
// PurchaseReceipt returns the app's store receipt for server-side
// validation (iOS: the App Store receipt), ErrNotFound without one.
PurchaseReceipt() ([]byte, error)
}
Purchases is the platform store. Transactions in TxPurchased or TxRestored state stay queued in the store until FinishTransaction (after the app delivered the content); the backend finishes failed ones itself. Updates for every transaction (also from purchases made outside the app or interrupted earlier) arrive as AppPurchaseUpdated.
type Push ¶
Push registers the app with the platform's push service. done receives the token to send to your server: the APNs device token as lowercase hex on iOS; the FCM token on Android when the app wired Firebase in (see docs/mobile-permissions.md), else ErrUnsupported. Incoming and opened notifications arrive as AppPushReceived / AppPushOpened events.
type PushEvent ¶
type PushEvent struct {
Token string // AppPushToken
Payload PushPayload // AppPushReceived, AppPushOpened
}
PushEvent is the payload of the push app events.
type PushPayload ¶
type PushPayload struct {
ID string `json:"id,omitempty"` // notification identifier, when the platform gives one
Title string `json:"title,omitempty"`
Body string `json:"body,omitempty"`
Action string `json:"action,omitempty"` // opened: the action identifier, "" for the default tap
Data map[string]any `json:"data,omitempty"`
}
PushPayload is a remote notification. Data holds the platform payload: the APNs userInfo dictionary on iOS (including "aps"), the FCM data map on Android. It is also the JSON object the native hosts hand to the backends.
func ParsePushPayload ¶
func ParsePushPayload(s string) PushPayload
ParsePushPayload decodes the JSON a native host reports for a push notification. Input that is not a PushPayload object ends up raw in Data["raw"], so nothing the host sent is lost.
type RecentDocuments ¶
type RecentDocuments interface {
NoteRecentDocument(path string) // path is absolute
ClearRecentDocuments()
}
RecentDocuments is the system's list of recently opened documents (the Dock menu's Open Recent on macOS). Main thread.
type Rect ¶
type Rect struct{ X, Y, Width, Height int }
Rect is a rectangle in logical (DIP) pixels on the desktop.
Coordinates (revised round 3, all desktop backends): the origin is the top-left corner of the primary display, X grows right and Y grows down, so displays left of or above the primary have negative coordinates. For a window (Geometry.Bounds/SetBounds, SurfaceExtras.Bounds, SurfaceMoved), X/Y is the top-left corner of the window's outer frame — title bar and borders included — and Width/Height is the content size, the same size SurfaceOptions, SetSize and Size use. Display.Bounds, Display.WorkArea and Tray.Bounds use the same space. Backends whose native coordinates differ (AppKit's bottom-left origin, GDK's origin at the top-left of the whole screen layout) convert.
type ScreenControl ¶
type ScreenControl interface {
SetKeepScreenOn(on bool) error
Brightness() (float64, error)
SetBrightness(v float64) error
}
ScreenControl keeps the screen on and reads/sets its brightness (0-1). SetBrightness(-1) gives brightness back to the system (Android; iOS keeps the last value, the system restores its own when the device locks).
type SecureStore ¶
type SecureStore interface {
SecureSet(key string, value []byte) error
SecureGet(key string) ([]byte, error) // ErrNotFound when absent
SecureDelete(key string) error // nil when absent
}
SecureStore keeps small secrets (tokens, keys) in the platform's protected store: the Keychain (iOS, macOS), Android Keystore-encrypted SharedPreferences. Items belong to the app and are not synced.
EXCEPTION to the main-thread rule: SecureStore methods may be called from any goroutine (the stores are thread-safe and can be slow).
type SettingsOpener ¶
type SettingsOpener interface {
OpenAppSettings() error
}
SettingsOpener opens the app's page in the system settings.
type ShareOptions ¶
type ShareOptions struct {
}
type Sharer ¶
type Sharer interface {
}
Sharer shows the system share sheet. done(nil) means shared (iOS, macOS) or the chooser was shown (Android cannot tell); ErrCanceled means the user dismissed it.
type Shell ¶
type Shell interface {
OpenURL(url string) error
OpenPath(path string) error // open file/folder with default app
RevealPath(path string) error // show in Finder / Explorer / file manager
}
Shell opens things with the OS default handler.
type ShortcutItem ¶
type ShortcutItem struct {
ID string // stable identifier, reported on click; nonempty unless Separator
Label string
Description string // tooltip (Windows); ignored elsewhere
// IconPath is an icon resource for the item: an .ico/.exe/.dll path,
// optionally ",index" (Windows). Ignored elsewhere; empty uses the
// executable's icon.
IconPath string
Separator bool
Disabled bool // macOS only; Windows tasks cannot be disabled
}
ShortcutItem is one entry of the app shortcut menu.
type SleepBlock ¶
type SleepBlock int
SleepBlock is what BlockSleep keeps awake.
const ( // BlockSystemSleep keeps the system from idle-sleeping (long tasks, // downloads); the display may still turn off. BlockSystemSleep SleepBlock = iota + 1 // BlockDisplaySleep keeps the display on as well (video playback, // presentations). It implies BlockSystemSleep. BlockDisplaySleep )
type Stateful ¶
type Stateful interface {
State() WindowState
SetState(s WindowState)
}
Stateful is implemented by surfaces that can be minimized / maximized / fullscreen. Changes made by the user are reported with SurfaceStateChanged.
type StatusBar ¶
type StatusBar struct {
Style StatusBarStyle
Hidden bool
// Color is the background behind the status bar as "#rrggbb" or
// "#aarrggbb"; "" = unchanged. Android only (iOS pages draw under the
// status bar themselves); iOS returns ErrUnsupported for a color.
Color string
}
type StatusBarControl ¶
type StatusBarStyle ¶
type StatusBarStyle int
const ( StatusBarDefault StatusBarStyle = iota // follows light/dark mode StatusBarLight // light (white) content, for dark backgrounds StatusBarDark // dark content, for light backgrounds )
type StoreReview ¶
type StoreReview interface {
RequestReview() error
}
StoreReview asks for an App Store / Play rating. iOS may show nothing (the system limits prompts); Android opens the store page.
type Styled ¶
type Styled interface {
SetAppearance(a Appearance)
}
type Surface ¶
type Surface interface {
Show()
Hide()
// Close destroys the surface without asking Host.ShouldClose. The backend
// then emits SurfaceClosed.
Close()
SetTitle(title string)
SetSize(width, height int) // logical (DIP) pixels
Size() (width, height int)
Focus()
// against AssetOrigin before calling this.
Navigate(url string)
// Eval runs JavaScript in the page's main frame, fire-and-forget.
Eval(js string)
// OpenDevTools opens the inspector if the platform supports it; no-op
// otherwise.
OpenDevTools()
// Native returns the native handle (NSWindow*, HWND, GtkWindow*, ...).
Native() uintptr
}
Surface is one native window/page containing a WebView.
type SurfaceEvent ¶
type SurfaceEvent struct {
Kind SurfaceEventKind
Width, Height int
X, Y int
URL string
Error string
State WindowState
Paths []string
}
type SurfaceEventKind ¶
type SurfaceEventKind int
const ( SurfaceClosed SurfaceEventKind = iota + 1 // native surface destroyed; see above SurfaceResized // Width/Height set SurfaceFocused // the window became the key / foreground window SurfaceBlurred // the window stopped being the key window SurfaceLoaded // main frame finished loading (DOM ready); URL set // Round 2 (ext.go). Backends emit these when they can. SurfaceLoadFailed // main frame navigation failed; URL and Error set SurfaceMoved // X/Y set SurfaceStateChanged // State set SurfaceFilesDropped // Paths, X/Y set (only when SurfaceExtras.AcceptFiles) )
SurfaceClosed timing (round 3): emitted exactly once per surface, when the native surface has been destroyed — after Surface.Close, after a user close that Host.ShouldClose allowed, or when the platform tore it down (an Android activity finishing, a window destroyed by the system). It may be emitted from inside Surface.Close. It is not emitted while Backend.NewSurface has not returned, nor for surfaces still open when Run returns (the core treats those as closed without the event). No other event for the id follows it, and the core no longer calls the Surface's methods.
type SurfaceExtras ¶
type SurfaceExtras struct {
Kind SurfaceKind
Parent SurfaceID
Bounds Rect // zero Width/Height = use SurfaceOptions size; X/Y ignored when Centered
Centered bool
MaxWidth int
MaxHeight int
State WindowState
Appearance Appearance
AcceptFiles bool // report SurfaceFilesDropped instead of letting the page navigate to dropped files
}
SurfaceExtras carries round-2 creation options. The core passes it to backends implementing CreatorEx; others get the plain SurfaceOptions.
type SurfaceID ¶
type SurfaceID uint64
SurfaceID is allocated by the core, unique for the app's lifetime, never 0.
type SurfaceKind ¶
type SurfaceKind int
SurfaceKind selects the native window type.
const ( KindWindow SurfaceKind = iota KindPanel // floating utility panel, does not activate the app (NSPanel / WS_EX_TOOLWINDOW) KindModal // modal to Parent; Parent must be set KindSheet // macOS sheet attached to Parent; other platforms: KindModal KindOverlay // non-activating, non-focusable overlay )
type SurfaceOptions ¶
type SurfaceOptions struct {
Title string
Width, Height int // logical pixels; 0 means backend default (1024x768)
MinWidth int
MinHeight int
Resizable bool
Visible bool // show immediately after creation
URL string // absolute; empty means about:blank
Debug bool // allow devtools / inspector
// BridgeScript is injected at document start in every frame-0 navigation,
// AFTER the backend's own shim. The backend's shim must define, before
// any page script runs:
//
// window.__tangoNative = { post(str) { /* native postMessage */ } }
//
// The core supplies the rest of the JS runtime through BridgeScript.
// Go→JS messages are delivered by the core with Eval.
BridgeScript string
}
type SurfaceStatus ¶
SurfaceStatus is implemented by surfaces that can report their window's visibility and keyboard focus as the window system sees it (hidden together with the app, minimized windows still count as visible). The core falls back to its own bookkeeping (Show/Hide, SurfaceFocused / SurfaceBlurred) for surfaces without it. (Round 3.)
type SystemTheme ¶
type SystemTheme interface {
SystemTheme() Theme
}
type Transaction ¶
type TransactionState ¶
type TransactionState int
const ( TxPurchasing TransactionState = iota + 1 TxPurchased TxFailed TxRestored TxDeferred // waiting for approval (Ask to Buy) or pending payment )
type Tray ¶
type Tray interface {
SetOptions(o TrayOptions)
SetMenu(items []MenuItem) // nil removes menu
// Bounds is the icon rect on screen if the platform knows it. Linux
// StatusNotifierItem knows only where the last Activate click was and
// reports that as a 1x1 rect (sysx).
Bounds() (Rect, bool)
Remove()
}
type TrayHandlers ¶
type TrayHandlers struct {
OnClick func() // primary click, unless it opens the menu (see TrayMenuTrigger)
OnRightClick func()
OnDoubleClick func()
OnMenu func(id uint32) // menu item chosen
}
type TrayMenuTrigger ¶
type TrayMenuTrigger int
TrayMenuTrigger chooses which click opens a tray icon's menu.
const ( // TrayMenuDefault follows the platform: primary click on macOS and // Linux, secondary click on Windows. TrayMenuDefault TrayMenuTrigger = iota // TrayMenuPrimary opens the menu on a primary (left) click; OnClick // does not fire while a menu is set. TrayMenuPrimary // TrayMenuSecondary opens the menu on a secondary (right) click and // reports primary clicks with OnClick. TrayMenuSecondary )
type TrayOptions ¶
type TrayOptions struct {
Icon []byte // PNG
Template bool // macOS template image (adapts to light/dark menu bar)
Tooltip string
Title string // text next to the icon (macOS only)
// MenuOn chooses the click that opens the menu (round 3). Linux
// StatusNotifierItem honours it (sysx); the AppIndicator fallback
// always opens the menu on any click and ignores it.
MenuOn TrayMenuTrigger
}
type Trays ¶
type Trays interface {
NewTray(o TrayOptions, h TrayHandlers) (Tray, error)
}
type WebCookies ¶
type WebCookies interface {
// Cookies lists the cookies that would be sent to url, or all cookies
// when url is "". Backends that cannot enumerate every cookie report
// ErrUnsupported for "". A backend may return more cookies than match
// url; the core filters.
Cookies(url string, done func([]*http.Cookie, error))
// SetCookie adds or replaces a cookie. Domain must be set.
SetCookie(c *http.Cookie, done func(error))
// DeleteCookie deletes the cookie matching c's Name, Domain and Path.
DeleteCookie(c *http.Cookie, done func(error))
// ClearCookies deletes every cookie whose domain is domain or a
// subdomain of it; "" deletes all cookies.
ClearCookies(domain string, done func(error))
}
WebCookies manages the cookies of the surface's website data store. Surfaces of one app share one store on every platform, so changes are seen by all of them.
Cookies are net/http cookies: Expires zero means a session cookie; SameSite is mapped where the platform has it. Domain without a leading dot is a host-only cookie where the platform distinguishes.
type WebCreator ¶
type WebCreator interface {
NewSurfaceWeb(id SurfaceID, opts SurfaceOptions, ex SurfaceExtras, web WebOptions) (Surface, error)
}
WebCreator is implemented by backends that take WebOptions at creation. ex is as for CreatorEx.
type WebData ¶
type WebData interface {
ClearBrowsingData(kinds BrowsingData, done func(error))
}
WebData clears website data of the surface's store (all sites).
type WebDialogKind ¶
type WebDialogKind uint8
const ( WebDialogAlert WebDialogKind = iota WebDialogConfirm WebDialogPrompt WebDialogBeforeUnload )
type WebDialogRequest ¶
type WebDialogRequest struct {
ID uint64
Kind WebDialogKind
URL, Message, DefaultText string
}
type WebDialogResponse ¶
type WebDialogs ¶
type WebDialogs interface {
SetWebDialogs(bool)
}
type WebDownloadPending ¶
WebDownloadPending reports a destination that the core is waiting for.
type WebDownloads ¶
type WebDownloads interface {
CancelDownload(id uint64)
}
WebDownloads cancels an accepted download (unknown ids are ignored); the backend then reports DownloadCanceled.
type WebEvaluator ¶
type WebFileChooserRequest ¶
type WebFinder ¶
type WebFinder interface {
Find(text string, opts FindOptions, done func(FindResult, error))
FindNext(backward bool, done func(FindResult, error))
StopFind()
}
WebFinder is find in page. Find starts a new search (and highlights the first match); FindNext moves to the next (backward: previous) match of the current search; StopFind clears the highlight. done of FindNext without a current search receives FindResult{} and no error.
type WebHeaders ¶
WebHeaders adds headers to every request the WebView makes (navigations and subresources, every origin). nil or empty removes them. Requests to the asset origin get the core's own extra headers on every platform (see the root package), so only backends that can change every request implement this.
type WebHistory ¶
WebHistory controls the native back-forward list. GoInHistory reports whether there was an entry in the requested direction.
type WebHost ¶
type WebHost interface {
// OnPermissionRequest asks whether the page may use a device or
// feature. done receives the decision; PermissionPrompt (and
// PermissionDefault) mean "do what the platform does without an
// embedder decision", which is asking the user where the platform has
// a prompt. Backends without a native prompt show their own simple
// allow/deny question or deny.
OnPermissionRequest(id SurfaceID, req PermissionRequest, done func(PermissionDecision))
// platform lets the embedder decide on (links, form submissions,
// location changes, redirects; on most platforms also Surface.Navigate
// and reloads — the core always allows the navigations it started
// itself). Returning false cancels it; the backend then emits neither
// SurfaceNavigating nor SurfaceLoadFailed for it.
ShouldNavigate(id SurfaceID, nav NavigationRequest) bool
// OnNewWindow reports a request to open a new window (window.open,
// target=_blank links and forms). The backend always suppresses the
// platform's own popup (the page's window.open returns null); the core
// decides what to do with the URL: open it in the system browser, in a
// new surface, in this surface, or nothing.
OnNewWindow(id SurfaceID, req NewWindowRequest)
// OnAuthChallenge reports an HTTP authentication challenge (Basic,
// Digest, NTLM, Negotiate — not TLS client certificates or server
// trust, which keep the platform default). done receives the answer.
OnAuthChallenge(id SurfaceID, ch AuthChallenge, done func(AuthResponse))
// OnDownloadStarted asks where to save a download the page started
// (a download attribute, Content-Disposition: attachment, or a
// response the WebView cannot show). done receives an absolute file
// path, or "" to cancel the download. The backend creates missing
// parent directories only if the platform does; the core passes paths
// whose directory exists. Existing files at path are replaced.
OnDownloadStarted(id SurfaceID, d DownloadRequest, done func(path string))
// OnDownloadEvent reports progress of a download accepted with a
// non-empty path. Every accepted download ends with exactly one event
// whose State is DownloadDone, DownloadFailed or DownloadCanceled.
// Progress events are throttled by the backend (at most a few per
// second) and are optional where the platform does not report bytes.
OnDownloadEvent(id SurfaceID, ev DownloadEvent)
}
WebHost is implemented by the core's Host in addition to Host and HostEx.
type WebInput ¶
type WebInput struct {
Kind WebInputKind
X, Y float64
DeltaX, DeltaY float64
Text string
}
type WebInputKind ¶
type WebInputKind uint8
const ( WebClick WebInputKind = iota + 1 WebType WebScroll )
type WebInputSink ¶
type WebInspector ¶
WebInspector controls a native inspector window.
type WebInteractionHost ¶
type WebInteractionHost interface {
HasWebDialogHandler(SurfaceID) bool
OnWebDialog(SurfaceID, WebDialogRequest, func(WebDialogResponse)) bool
OnWebFileChooser(SurfaceID, WebFileChooserRequest, func([]string)) bool
OnWebPopup(SurfaceID, NewWindowRequest, func(SurfaceID, SurfaceID, SurfaceOptions) (Surface, error)) bool
}
type WebKeySink ¶
WebKeySink dispatches a key chord in a development build. Called on the main thread. done fires once, once native dispatch has completed.
type WebNavigationHost ¶
type WebNavigationHost interface {
}
WebNavigationHost receives main-frame events. The native token stays the same through redirects. Metadata changes have no token.
type WebNavigationKind ¶
type WebNavigationKind uint8
WebNavigationKind is a main-frame load phase or a page metadata change.
const ( WebPageChanged )
type WebOptions ¶
type WebOptions struct {
Profile string // optional isolated website data store
UserAgent string // "" keeps the platform's
Headers http.Header // extra headers for every request; see WebHeaders
}
WebOptions are WebView settings that must be in place before the first request. The core passes them to backends implementing WebCreator; for others it applies them right after creation through WebUserAgent / WebHeaders, which may miss the first request.
type WebPDF ¶
type WebPDF interface {
PrintToPDF(opts PDFOptions, done func(pdf []byte, err error))
}
WebPDF renders the current page as a PDF document.
type WebPageState ¶
WebPageState is metadata read from a native WebView.
type WebPermission ¶
type WebPermission string
WebPermission names a feature a page asks for. Backends report the names below; anything else is reported as WebPermOther.
const ( WebPermCamera WebPermission = "camera" WebPermMicrophone WebPermission = "microphone" WebPermGeolocation WebPermission = "geolocation" WebPermNotifications WebPermission = "notifications" WebPermClipboardRead WebPermission = "clipboard-read" WebPermMIDI WebPermission = "midi" // Web MIDI with system exclusive messages WebPermScreen WebPermission = "screen" // display capture (getDisplayMedia) WebPermMotion WebPermission = "device-motion" // device orientation and motion (iOS) WebPermStorage WebPermission = "storage-access" // Storage Access API WebPermMedia WebPermission = "protected-media" // EME / protected media identifier WebPermOther WebPermission = "other" )
type WebPlacement ¶
type WebPlacement struct {
// Frame is the whole web view: the page's viewport has Frame's size.
Frame RectF
// Clip is the visible part of Frame (ancestors clipping, scrolling);
// it is intersected with Frame. An empty Clip hides the view.
Clip RectF
}
WebPlacement places an embedded WebView. Coordinates are logical pixels relative to the top-left corner of the parent's content area.
func (WebPlacement) Geometry ¶
func (p WebPlacement) Geometry(scale float64, hidden bool) EmbedGeometry
Geometry converts p for a clip container at scale (device pixels per logical pixel; 1 for platforms that position in logical units). Edges are rounded to the nearest unit independently, so neighbouring views stay seamless. hidden forces Visible false.
func (WebPlacement) Size ¶
func (p WebPlacement) Size() (w, h int)
Size returns the frame size rounded to whole logical pixels, for Surface.Size.
type WebProfileSupport ¶
type WebProfileSupport interface {
SupportsWebProfiles() bool
}
WebProfileSupport reports whether the backend supports isolated stores.
type WebSnapshot ¶
WebSnapshot captures the visible part of the page as a PNG image.
type WebUserAgent ¶
type WebUserAgent interface {
SetUserAgent(ua string)
}
WebUserAgent changes the User-Agent of later requests; "" restores the platform default.
type WebViewEmbedder ¶
type WebViewEmbedder interface {
// NewEmbeddedWebView creates a WebView inside the content area of
// parent. id is a new SurfaceID allocated by the core: messages
// (Host.OnMessage), asset requests (Host.ServeAsset), surface events
// (SurfaceLoaded, SurfaceLoadFailed, SurfaceClosed, and
// SurfaceFocused / SurfaceBlurred when the web view gains or loses
// keyboard focus inside its window) and the WebHost decisions are
// reported for id exactly as for a WebView surface.
//
// opts.URL, Debug and BridgeScript apply as for NewSurface; the
// window fields (title, size, visibility, ...) are ignored. web
// carries the creation-time user agent and headers (WebCreator).
//
// The view is created hidden: it shows only after a SetPlacement
// with a non-empty Clip. It stacks above the parent's content (the
// canvas); views created later stack above earlier ones. Closing the
// parent closes its embedded views first, each reporting
// SurfaceClosed. Main thread.
NewEmbeddedWebView(id, parent SurfaceID, opts SurfaceOptions, web WebOptions) (EmbeddedWebView, error)
}
WebViewEmbedder is implemented by backends that can place a WebView as a child view inside the content area of another surface (a canvas surface from CanvasCreator), so that a self-drawn layout can host it.
type WebViewInfo ¶
type WebViewInfo interface {
WebViewVersion() (engine, version string)
}
WebViewInfo reports the page engine and its version, e.g. ("WebKit", "20621.1.15"), ("WebView2", "131.0.2903.70"), ("WebKitGTK", "2.46.5"). version may be "" when unknown. Any goroutine.
type WidgetContent ¶
type Widgets ¶
type Widgets interface {
UpdateWidget(c WidgetContent) error
}
Widgets updates the app's home-screen widget (Android AppWidget declared with the tan.json "widget" capability). The content persists across app launches; tapping the widget opens the app.
type WindowState ¶
type WindowState int
const ( StateNormal WindowState = iota StateMinimized StateMaximized StateFullscreen )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package a11ybridge holds the platform-neutral parts of the accessibility bridges of the desktop backends (docs/specs/a11y-bridge.md): role and state translation from ui/a11y to NSAccessibility, UI Automation and AT-SPI2, focus and live-region computation, hit testing and coordinate conversion.
|
Package a11ybridge holds the platform-neutral parts of the accessibility bridges of the desktop backends (docs/specs/a11y-bridge.md): role and state translation from ui/a11y to NSAccessibility, UI Automation and AT-SPI2, focus and live-region computation, hit testing and coordinate conversion. |
|
Package android is Tango's Android backend: one Activity (the Java host in mobile/android) whose content is a stack of full-screen pages, WebViews or self-drawn canvases, driven over JNI.
|
Package android is Tango's Android backend: one Activity (the Java host in mobile/android) whose content is a stack of full-screen pages, WebViews or self-drawn canvases, driven over JNI. |
|
internal/smoke
command
Command smoke drives the macOS backend end to end without the root tango package: a window, an asset page served through tango://, a JS→Go message, an Eval round trip, a fetch POST and a streamed response, a sheet dialog, the clipboard and the app menu.
|
Command smoke drives the macOS backend end to end without the root tango package: a window, an asset page served through tango://, a JS→Go message, an Eval round trip, a fetch POST and a streamed response, a sheet dialog, the clipboard and the app menu. |
|
internal/smokeattach
command
Command smokeattach drives a canvas attached to a WebView surface of the macOS backend (docs/specs/canvas-surface.md, step D) without the root tango package.
|
Command smokeattach drives a canvas attached to a WebView surface of the macOS backend (docs/specs/canvas-surface.md, step D) without the root tango package. |
|
internal/smokecanvas
command
Command smokecanvas drives a canvas surface of the macOS backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package.
|
Command smokecanvas drives a canvas surface of the macOS backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package. |
|
internal/smokeext
command
Command smokeext checks the window capabilities (contract round 2) on the real macOS backend through the root tango package: a frameless transparent window and a normal one; SetBounds, Maximize, Restore, SetZoom, Reload, a failed navigation, a sheet and the events they cause.
|
Command smokeext checks the window capabilities (contract round 2) on the real macOS backend through the root tango package: a frameless transparent window and a normal one; SetBounds, Maximize, Restore, SetZoom, Reload, a failed navigation, a sheet and the events they cause. |
|
internal/smokemetal
command
Command smokemetal checks the GPU presentation path of the macOS canvas (platform.CanvasMetal) with the smallest possible Metal client: it calls UseMetalLayer on a canvas surface, then on every CanvasFrame takes the layer's next drawable, clears it to a colour that changes per frame, blits a white marker into the top-left quarter (width/2 × height/4) and presents it.
|
Command smokemetal checks the GPU presentation path of the macOS canvas (platform.CanvasMetal) with the smallest possible Metal client: it calls UseMetalLayer on a canvas surface, then on every CanvasFrame takes the layer's next drawable, clears it to a colour that changes per frame, blits a white marker into the top-left quarter (width/2 × height/4) and presents it. |
|
internal/smoketray
command
Command smoketray checks menus, context menus and the tray icon on the real macOS backend through the public tango, menu and tray packages: it creates a tray icon with a menu, updates it, clicks tray menu items, opens a context menu with menu.Popup and one from the page (data-tango-menu), each closed programmatically.
|
Command smoketray checks menus, context menus and the tray icon on the real macOS backend through the public tango, menu and tray packages: it creates a tray icon with a menu, updates it, clicks tray menu items, opens a context menu with menu.Popup and one from the page (data-tango-menu), each closed programmatically. |
|
internal/smokewebdrop
command
Command smokewebdrop checks file drags over a WebView surface created with AcceptFiles on the real macOS backend: the page sees the hover (dragenter / dragover / dragleave, with "Files" in the types) so it can highlight a drop target, the drop goes to OnFilesDropped (paths and point) instead of to the page or a navigation, and a drag without files is left to WebKit.
|
Command smokewebdrop checks file drags over a WebView surface created with AcceptFiles on the real macOS backend: the page sees the hover (dragenter / dragover / dragleave, with "Files" in the types) so it can highlight a drop target, the drop goes to OnFilesDropped (paths and point) instead of to the page or a navigation, and a drag without files is left to WebKit. |
|
Package fake is a headless platform.Backend for testing Tango's core.
|
Package fake is a headless platform.Backend for testing Tango's core. |
|
apphook
Package apphook lets test helpers build a tango.App on an injected Backend without the root package exporting a constructor for it.
|
Package apphook lets test helpers build a tango.App on an injected Backend without the root package exporting a constructor for it. |
|
faketest
Package faketest runs a tango.App on the fake backend for tests of packages built on tango (capability packages, ipc, bind, ...).
|
Package faketest runs a tango.App on the fake backend for tests of packages built on tango (capability packages, ipc, bind, ...). |
|
Package imesession routes system input method sessions on the app thread.
|
Package imesession routes system input method sessions on the app thread. |
|
Package linux is Tango's Linux desktop backend: GTK 3 windows hosting WebKitGTK 4.1 web views, loaded at run time with purego (no cgo).
|
Package linux is Tango's Linux desktop backend: GTK 3 windows hosting WebKitGTK 4.1 web views, loaded at run time with purego (no cgo). |
|
internal/smoke
command
Command smoke is a manual check of the Linux backend on a real desktop:
|
Command smoke is a manual check of the Linux backend on a real desktop: |
|
internal/smokeattach
command
Command smokeattach drives canvases attached to a WebView surface of the Linux backend (docs/specs/canvas-surface.md, step D) without the root tango package.
|
Command smokeattach drives canvases attached to a WebView surface of the Linux backend (docs/specs/canvas-surface.md, step D) without the root tango package. |
|
internal/smokecanvas
command
Command smokecanvas drives a canvas surface of the Linux backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package.
|
Command smokecanvas drives a canvas surface of the Linux backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package. |
|
Package mobilecanvas holds the platform-independent logic of the iOS and Android canvas backends (docs/specs/mobile-canvas.md): the frame scheduler, touch bookkeeping, the input-method shadow document, UTF-16 offsets and inset arithmetic.
|
Package mobilecanvas holds the platform-independent logic of the iOS and Android canvas backends (docs/specs/mobile-canvas.md): the frame scheduler, touch bookkeeping, the input-method shadow document, UTF-16 offsets and inset arithmetic. |
|
Package native picks the platform backend for the GOOS being built and holds the per-platform main-thread rules the core follows.
|
Package native picks the platform backend for the GOOS being built and holds the per-platform main-thread rules the core follows. |
|
Package rolenames holds the localized labels of the native menu roles and the default dialog buttons the desktop backends supply themselves, in the wording of each platform (Apple, Microsoft and GNOME style guides).
|
Package rolenames holds the localized labels of the native menu roles and the default dialog buttons the desktop backends supply themselves, in the wording of each platform (Apple, Microsoft and GNOME style guides). |
|
Package windows is Tango's Windows backend: Win32 windows hosting Microsoft Edge WebView2, called through package syscall and COM vtables (no cgo).
|
Package windows is Tango's Windows backend: Win32 windows hosting Microsoft Edge WebView2, called through package syscall and COM vtables (no cgo). |
|
internal/smoke
command
Command smoke exercises the Windows backend without the tango root package: it opens a window, serves a page through ServeAsset, exchanges messages with it, sets a menu, and quits once the page has loaded and its message round-tripped (or after a 30-second timeout).
|
Command smoke exercises the Windows backend without the tango root package: it opens a window, serves a page through ServeAsset, exchanges messages with it, sets a menu, and quits once the page has loaded and its message round-tripped (or after a 30-second timeout). |
|
internal/smokeattach
command
Command smokeattach drives canvases attached to a WebView surface of the Windows backend (docs/specs/canvas-surface.md, step D) without the root tango package.
|
Command smokeattach drives canvases attached to a WebView surface of the Windows backend (docs/specs/canvas-surface.md, step D) without the root tango package. |
|
internal/smokecanvas
command
Command smokecanvas drives a canvas surface of the Windows backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package.
|
Command smokecanvas drives a canvas surface of the Windows backend (the self-drawn UI window, docs/specs/canvas-surface.md) without the root tango package. |