// Package platform defines the contract between the public mygo API and the // native backends (WKWebView on macOS, WebKitGTK on Linux, WebView2 on // Windows). // // Threading rules: unless a method says otherwise it must be called on the // main (UI) thread, and every handler callback is invoked on the main thread. // The public package is responsible for hopping onto the main thread. package platform import ( "context" "errors" "io" "time" "github.com/egoist/mygo/transfer" ) // ErrUnsupported is returned by features the current backend cannot provide. // It is errors.ErrUnsupported too (errors.Is), which apps check. var ErrUnsupported error = unsupportedError{} type unsupportedError struct{} func (unsupportedError) Error() string { return "not supported on this platform" } func (unsupportedError) Is(target error) bool { return target == errors.ErrUnsupported } // ErrNotificationsDenied is what ShowNotification fails with when the user // does not allow the app to show notifications. var ErrNotificationsDenied = errors.New("mygo: the user does not allow notifications") // Point is a position in screen coordinates (DIPs, origin top-left of the // primary display). type Point struct{ X, Y int } // Size is a width and height in DIPs. type Size struct{ Width, Height int } // Rect is a rectangle in screen coordinates (DIPs). type Rect struct{ X, Y, Width, Height int } // TitleBar is the room the window controls take at the top of a window // with a hidden title bar, in DIPs: they sit in a band of Height along the // top edge, Left wide from the left edge and Right wide from the right, // and end Bottom below the top edge, which is Height where they fill the // band. type TitleBar struct{ Height, Left, Right, Bottom int } // Color is an 8-bit RGBA color. type Color struct{ R, G, B, A uint8 } // Backend is implemented by every native backend. type Backend interface { // Name identifies the backend, for example "darwin/wkwebview". Name() string // Init prepares the native application. It is called once, on the main // thread, before Run. Init(h AppHandler, opts AppOptions) error // Run runs the native event loop until Quit is called. h.Ready is // invoked once the application has finished launching. Run() error // Quit makes Run return. Quit() // IsMainThread reports whether the caller runs on the UI thread. Safe // to call from any goroutine. IsMainThread() bool // Signal asks the backend to invoke AppHandler.Dispatch on the main // thread as soon as possible. Safe to call from any goroutine. Signal() // Step blocks until at least one native event has been processed or // Wake has been called. Main thread only; used for nested waits. Step() // Wake unblocks a pending Step. Safe to call from any goroutine. Wake() NewWindow(opts *WindowOptions, h WindowHandler) (Window, error) SetApplicationMenu(m *Menu) // PopupMenu shows a context menu. pos is relative to the window's // content area; nil means the current mouse location. It blocks until // the menu is dismissed. PopupMenu(m *Menu, w Window, pos *Point) // UpdateMenuItem refreshes label/state of every native item created // for item.ID. UpdateMenuItem(item *MenuItem) App() AppController Dialogs() Dialogs Clipboard() Clipboard Shell() Shell Screen() Screen Theme() Theme Power() Power Network() Network NowPlaying() NowPlaying // Secrets may be called before Init, from any goroutine. Secrets() Secrets // Applications lists the applications installed on the computer. // Unlike other methods it may be called from any goroutine once Init // returned: it reads the disk, which the core does off the main thread. Applications() ([]Application, error) // NewFileWatch starts watching files, with no target yet. notify is // called on a goroutine of the backend, one notice at a time. // NewFileWatch may be called before Init, from any goroutine. NewFileWatch(notify func(FileWatchNotice)) (FileWatch, error) // ReplaceFile replaces the file at target with the file at // replacement, in the same directory, keeping what the system keeps of // the target's metadata (permissions, owner, extended attributes, // creation date); replacement is gone afterwards. It may be called // before Init, from any goroutine. ReplaceFile(target, replacement string) error // NewTray makes a tray icon. id is TrayOptions.ID, which Linux needs // as the icon is made; the other backends take it through Tray.SetID. NewTray(id string, h TrayHandler) (Tray, error) // RegisterHotkey makes accelerator a global shortcut. description says // what it does, for desktops that show the app's shortcuts to the // user; such desktops tell the keys they bound with HotkeyBound. RegisterHotkey(id int, accelerator, description string) error UnregisterHotkey(id int) NotificationsSupported() bool // ShowNotification shows n; done runs on the main thread once the // system has it, or with why it could not. ShowNotification(n *Notification, done func(error)) RemoveNotification(id string) // RemoveAllNotifications removes the app's notifications, on macOS // those of earlier runs too. RemoveAllNotifications() // WebViewAvailable reports whether the system webview is there, and so // whether windows showing web pages can work: WKWebView on macOS, // WebKitGTK on Linux, the WebView2 Runtime on Windows. A window showing // native UI needs none, so an app whose windows all do runs without one. // It may be called before Init, from any goroutine. WebViewAvailable() bool } // WindowStateWindow is a window whose bounds in DIPs change with the // scales of the displays where they differ (Windows). // WindowStateBounds is its rectangle in the screen's pixels, which window // states keep with them. type WindowStateWindow interface { WindowStateBounds() Rect } // InputRegionWindow is a window that takes the mouse only where its input // region is (macOS, Linux, Windows): SetInputRegion limits it to region, // in DIPs from the top-left corner of the content, and lets the mouse // through elsewhere; nil gives it all of the window, an empty region // none. SetIgnoreMouseEvents(true) wins over it. Apart from Window, so // that only apps setting a region link it. type InputRegionWindow interface { SetInputRegion(region []Rect) } // WindowStateBackend restores windows at their pixels (Windows): // RestoreWindowState sets opts.StateBounds and returns true when pixels, // zero for none, would show on a connected display. Otherwise the core // restores the state's DIPs where every display has the same scale, and // centers the window where they have not. type WindowStateBackend interface { RestoreWindowState(opts *WindowOptions, pixels Rect) bool } // StyleBackend styles the widgets the toolkit draws for the app with the // app's own style sheet (Linux: GTK's CSS, Theme.SetGTKCSS). SetStyleSheet // replaces the sheet set before, or removes it for "", and keeps that one // when css does not parse, returning why. type StyleBackend interface { SetStyleSheet(css string) error } // WindowButtonsBackend reports the window buttons the desktop puts at the // start and at the end of title bars (Linux): "minimize", "maximize" and // "close", in their order, none where the desktop wants none. Main thread // only. type WindowButtonsBackend interface { WindowButtons() (start, end []string) } // ExitBackend releases what the native application must not take into the // process's exit (Windows: its windows, whose window procedure is Go's and // cannot run once the process exits). The app calls Exiting once, on the // main thread, when it has finished and is about to exit; nothing native // is used after it. type ExitBackend interface { Exiting() } // AppOptions configures Backend.Init. type AppOptions struct { Name string // ActivationPolicy is "regular" (default), "accessory" or "prohibited". // Only meaningful on macOS. ActivationPolicy string // DMABUFRenderer is "off" (or ""), "on" or "auto": whether WebKitGTK // may draw with its DMA-BUF renderer. Only meaningful on Linux. DMABUFRenderer string // Background starts the app without bringing it to the front, as // `mygo dev -background` asks. Only meaningful on macOS, where an // executable that is no bundle is brought there as it starts; the // core shows the windows without the focus everywhere. Background bool } // AppHandler receives application level events from the backend. type AppHandler interface { Ready() // Dispatch drains the queue of functions scheduled for the main thread. Dispatch() // QuitRequested is called when the user or the OS asks the application // to quit (Cmd+Q, Dock > Quit, logout). Returning true lets the quit // proceed. QuitRequested() bool // Terminating is called right before the process is terminated by the // OS (logout/shutdown); Run will not return. The core runs the quit // listeners then, unless a quit ran them, and finishes the app. Terminating() // Activated is called when the application is re-activated, e.g. by // clicking its Dock icon. Activated(hasVisibleWindows bool) DidBecomeActive() DidResignActive() OpenURLs(urls []string) OpenFiles(paths []string) MenuItemClicked(id int) ThemeChanged() DisplaysChanged() // LocaleChanged is called when the languages the user prefers, or the // regional formats, may have changed, on the systems that report it. LocaleChanged() // PowerEvent is "suspend", "resume", "lock-screen" or "unlock-screen". PowerEvent(event string) // NetworkChanged reports the network's status, once Network.Watch was // called, when it may have changed. NetworkChanged(status NetworkStatus) HotkeyPressed(id int) // HotkeyBound reports the keys a desktop that binds global shortcuts // for apps has for one, as it writes them, "" when it bound none. HotkeyBound(id int, keys string) NotificationClicked(id string) // MediaCommand reports a media key or a remote command for what // NowPlaying shows; position is where MediaSeek asks to go. MediaCommand(cmd MediaCommand, position time.Duration) // MemoryWarning reports that the system is short of memory, on the // systems that say: phones end apps that keep too much. MemoryWarning() } // AppController exposes application level native features. type AppController interface { SetActivationPolicy(policy string) Activate() // AllowForeground lets the next process to ask bring its windows to // the front, which Windows only lets the process in front do. AllowForeground() // WithActivationToken runs fn with the startup notification or XDG // activation token of the launch that caused it, which the window fn // shows or focuses first may need to take the focus (Wayland). WithActivationToken(token string, fn func()) Hide() Unhide() IsHidden() bool // IsActive reports whether the app is the active one: in front on // macOS, with a window that has the keyboard elsewhere. IsActive() bool SetBadge(label string) Badge() string // Bounce requests user attention and returns an id for CancelBounce. Bounce(critical bool) int CancelBounce(id int) SetDockIcon(png []byte) error // SetDockMenu sets the menu of the Dock icon (macOS); nil removes it. SetDockMenu(m *Menu) // NewDataStore makes a website data store other than the default one // (mygo.Session), which WindowOptions.DataStore and the calls below // take. The core makes one store per session and closes it with // DataStore.Close. NewDataStore(opts DataStoreOptions) (DataStore, error) // ClearBrowsingData deletes the data of types pages stored in store, // nil for the default one; done runs on the main thread. ClearBrowsingData(store DataStore, types SiteData, done func(error)) // Cookie operations address store, nil for the default page store. // Calls and exactly-once completions run on main; ListCookies returns // independent Go values: every cookie, or with an http or https url // the cookies a request to it sends (CookieMatchesURL where the engine // cannot tell). ListCookies(store DataStore, url string, done func([]Cookie, error)) SetCookie(store DataStore, cookie Cookie, done func(error)) DeleteCookie(store DataStore, key CookieKey, done func(error)) ClearCookies(store DataStore, done func(error)) // CompileContentRules makes a content rule list of rules, in WebKit's // content blocker JSON format: it loads the list kept as identifier // (ContentRulesIdentifier) where the engine keeps compiled lists, // else compiles rules, keeps the list as identifier and removes the // lists kept for id under other identifiers (StaleContentRules). // done runs on the main thread exactly once, with a handle // Page.SetContentRules takes. CompileContentRules(id, identifier, rules string, done func(list any, err error)) ShowAboutPanel(opts AboutPanelOptions) // PreferredLanguages returns the languages the user reads, most // preferred first, as the system's settings list them, in the forms // the system writes them (the core normalizes them): never what the // app chose for itself (SaveLocale). Safe before Init. PreferredLanguages() []string // Region returns the user's regional formats. Safe before Init. Region() Region // SavedLocale returns the language the app chose for itself, as the // system keeps it, and whether the system keeps one at all (macOS: // AppleLanguages in the app's own defaults, which System Settings // shows as the app's language; browsers: localStorage). Where it // keeps none, the core keeps it in a file. Safe before Init. SavedLocale() (tag string, kept bool) // SaveLocale keeps tag where SavedLocale reads it, "" to forget it, // and reports whether the system keeps one at all. SaveLocale(tag string) bool // SetLanguages tells the backend the languages the app shows, its // own language first, and whether it is laid out right to left, for // what shows text the core does not draw: the web views it creates // later and, where it can change, those it created, and the system's // own texts and widgets. SetLanguages(tags []string, rtl bool) // RegisterURLScheme makes the app, identified by id (its identifier) // and named name, the handler of the URLs of scheme for the user. RegisterURLScheme(scheme, id, name string) error UnregisterURLScheme(scheme, id, name string) error IsURLSchemeRegistered(scheme, id, name string) bool // SetOpenAtLogin makes the app start at login, passing arg where the // start command takes arguments; OpenedAtLogin reports whether the // system started it so without one (macOS login items). SetOpenAtLogin(open bool, id, name, arg string) error OpenAtLogin(id, name, arg string) bool OpenedAtLogin() bool // Package describes the application bundle the process runs from; ok // is false for a plain executable (e.g. `go run`). Safe to call from // any goroutine, before Init too. Package() (info PackageInfo, ok bool) // AddRecentDocument records the absolute path of a document the user // opened in the system's recent documents; ClearRecentDocuments // removes the ones the app recorded. AddRecentDocument(path string) error ClearRecentDocuments() error // SetJumpList commits the app's whole jump list (Windows); elsewhere // it does nothing. SetJumpList(list JumpList) error } // Region is the user's regional formats, as the system's settings have // them with the user's changes. type Region struct { // Locale is the locale of the formats, in the form the system writes // it, "" when unknown. Locale string // FirstWeekday is the first day of the week, 0 for Sunday to 6 for // Saturday, or -1 when the system does not say. FirstWeekday int // HourCycle is 12 or 24, or 0 when the system does not say. HourCycle int } // PackageInfo is metadata of a packaged application. type PackageInfo struct { Name string Version string Identifier string } // AboutPanelOptions configures the standard about panel. type AboutPanelOptions struct { ApplicationName string ApplicationVersion string Version string Copyright string Credits string } // JumpList is the whole jump list of the app: Windows replaces all of it // at each commit. type JumpList struct { Tasks []JumpListTask } // JumpListTask is a task of a jump list: a program to run with its // arguments, unquoted, its label, tooltip and icon. type JumpListTask struct { Title string Description string Path string Args []string WorkingDir string IconPath string IconIndex int } // WindowOptions configures a native window and its webview. The public // package fills in all defaults before calling NewWindow. type WindowOptions struct { Title string X, Y int Width, Height int Center bool UseContentSize bool MinSize Size MaxSize Size // StateBounds is the window's restored normal rectangle in the // screen's pixels, set by WindowStateBackend. It overrides X, Y, // Width and Height. StateBounds *Rect Resizable bool Movable bool Minimizable bool Maximizable bool Closable bool Focusable bool Fullscreenable bool AlwaysOnTop bool FullScreen bool Maximized bool SkipTaskbar bool AutoHideMenu bool HasShadow bool Frameless bool Transparent bool // BackgroundColor is painted before the page renders; nil keeps the // platform default. BackgroundColor *Color // TitleBarStyle is "default", "hidden" or "hiddenInset". A hidden title // bar gives the page the whole window, under the window controls: // AppKit's traffic lights on macOS, and on Linux and Windows controls // the backend puts over the page (see Window.TitleBar). TitleBarStyle string // TitleBarHeight is the height of a hidden title bar in DIPs (Linux, // Windows); 0 is the backend's own. TitleBarHeight int // HideWindowButtons hides the window controls of a hidden title bar, // which the page draws itself: TitleBar is then zero. HideWindowButtons bool TrafficLightPosition *Point Vibrancy string // VibrancyTint tints the material, where the platform's material takes // one (macOS 26's Liquid Glass): nil for none. VibrancyTint *Color // CornerRadius rounds a frameless window's corners, in DIPs: its // content and material are cut to them (macOS), or the system rounds // it with its own corners (Windows 11). CornerRadius int Opacity float64 Parent Window Modal bool // Flyout makes the window a flyout of its Parent, placed next to an // anchor (Window.PlaceFlyout), at Width and Height: borderless, // transparent, out of the taskbar, with Focusable telling whether it // takes the keyboard. Show of a flyout that is not focusable shows it // without the keyboard, as ShowInactive. Flyout *Flyout // Panel makes the window a panel (mygo.WindowOptions.Panel): it floats // above the windows of all apps on the current workspace, full-screen // ones included, out of the taskbar and the app switcher, and on macOS // takes the keyboard without activating the app. Panel bool // UserScripts are injected into every page, in order. UserScripts []UserScript // Schemes lists the custom protocols the webview must route to // WindowHandler.SchemeRequest. Schemes []string DevTools bool // UserAgent overrides the user agent of the webview. UserAgent string // UserAgentSuffix is appended to UserAgent, or to the webview's own // user agent, after a space. The public package trims it. UserAgentSuffix string Zoom float64 // TabFocusesLinks makes Tab reach links and form controls that are not // text fields (macOS, WKPreferences.tabFocusesLinks); the other // platforms reach them already. TabFocusesLinks bool // NoBackgroundThrottling keeps the page running at full speed while // its window is hidden, minimized or covered // (mygo.PageOptions.BackgroundThrottling): its timers unthrottled, its // process at the priority of a visible one. NoBackgroundThrottling bool // Autoplay lets the page play audible media without a user gesture // (mygo.PageOptions.Autoplay). Autoplay bool // PictureInPicture lets the page's videos go into picture in picture // (macOS, WebKit's private _allowsPictureInPictureMediaPlayback); // WebView2 lets them already, and WebKitGTK has none. PictureInPicture bool // SwipeNavigation lets a swipe go back and forward through the page's // history (mygo.PageOptions.SwipeNavigation). SwipeNavigation bool // PinchZoom lets a pinch magnify the page; the backends turn it off // where their webview has it on by default (mygo.PageOptions.PinchZoom). PinchZoom bool // DataStore is the website data store of the page, one of // AppController.NewDataStore; nil is the default store. A window // opened by window.open has its opener's. DataStore DataStore // Native carries backend specific state, e.g. the WKWebViewConfiguration // WebKit hands us for window.open(). Native uintptr // ScrollToContainer scrolls the native container around an embedded web // view instead of its page. Ordinary pages keep their own wheel input. ScrollToContainer bool // Surface creates the window with a Surface, which content MyGo draws // itself fills, instead of a webview: Window.Surface returns it, the // webview methods do nothing and the webview options are ignored. Surface bool // OwnScene opens the window as a window of the system's own, on iPad. OwnScene bool } // DataStoreOptions describe a website data store (AppController.NewDataStore). type DataStoreOptions struct { // ID identifies a persistent store from one run to the next: a UUID // in lowercase hex with dashes, which the core derives from the // session's name. It is empty for an ephemeral store. ID string // Ephemeral keeps the store's data in memory, where it goes with the // store. Ephemeral bool // DataDir and CacheDir are where a persistent store keeps its data and // its caches, for the backends that choose (Linux). DataDir, CacheDir string } // DataStore is a website data store a backend made: cookies, local and // session storage, IndexedDB, caches and service workers that the pages // using it share, apart from those of other stores. type DataStore interface { // Close lets the store go once the backend no longer needs it: the // core calls it when no page uses an ephemeral store, whose data then // goes, and makes another store for the session's next page. Calls // under way finish. Close() } // SiteData are kinds of data pages store, for ClearBrowsingData. type SiteData uint const ( SiteDataCookies SiteData = 1 << iota // SiteDataLocalStorage is localStorage and sessionStorage. SiteDataLocalStorage // SiteDataIndexedDB is IndexedDB, and WebSQL where the engine has it. SiteDataIndexedDB // SiteDataCaches is the HTTP caches, and Cache Storage. SiteDataCaches SiteDataServiceWorkers // SiteDataAll is all the data the engine keeps for sites, the kinds // above and the others (HSTS, media keys, …). SiteDataAll SiteData = 1<