# MyGo documentation Build desktop apps in Go. Windows draw native UI that MyGo paints on the GPU, written in Go alone with package ui, or show a web frontend in the system webview that calls Go through a TypeScript client generated from your code. Pure Go with no cgo, and a few megabytes per app. --- Source: https://mygo.egoist.dev/docs.md # MyGo documentation MyGo builds desktop apps in Go. Each window shows one of two kinds of interface, and one app can have windows of both: * **A web page**, in the webview of the operating system (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows) instead of a bundled browser. The frontend is HTML, CSS and JavaScript built with any tools, and calls your Go code through a TypeScript client that MyGo generates from it, with the types of your Go structs and the documentation of your methods. * **Native UI**, which MyGo draws itself on the GPU, written in Go alone with package `ui`: there is no HTML, no JavaScript and no webview to start, so the window opens at once and takes little memory. Windows of both kinds share the window options and events, the menus and the desktop APIs, and the app is a single Go program of a few megabytes. A window with a web page, whose frontend calls a Go service: ```go type Greeter struct{} // Greet returns a greeting. func (Greeter) Greet(name string) string { return "Hello, " + name } func main() { mygo.Bind(Greeter{}) mygo.App.WhenReady(func() { mygo.NewWindow(mygo.WindowOptions{Title: "Hello", URL: "/"}) }) if err := mygo.App.Run(); err != nil { log.Fatal(err) } } ``` ```ts import { Greeter } from "./mygo"; // generated document.body.textContent = await Greeter.greet("Ada"); ``` A window with native UI, whose view is a Go function of the app's state: ```go type counter struct{ n int } func (s *counter) view(c *ui.Context) { ui.Column(c).Fill().Center().Gap(12).Children(func() { ui.Text(c, fmt.Sprint(s.n)).FontSize(40).Bold() if ui.PrimaryButton(c, "Increment").Clicked() { s.n++ } }) } func main() { s := &counter{} mygo.App.WhenReady(func() { mygo.NewWindow(mygo.WindowOptions{ Title: "Counter", Content: ui.View(s.view), }) }) if err := mygo.App.Run(); err != nil { log.Fatal(err) } } ``` Web pages suit rich documents, existing web code and what only a browser does; native UI suits tools, settings, inspectors and utilities, and apps that must start instantly. ## Getting started * [Getting started](https://mygo.egoist.dev/docs/getting-started.md): install the tools, then create, develop and build an app, with native UI or a web frontend. ## Building the app What every app has, whether its windows show native UI or web pages. * [Windows](https://mygo.egoist.dev/docs/windows.md): creating and arranging windows of both kinds, their events, and what windows showing web pages do with them: navigation, downloads, permissions, printing. * [The application](https://mygo.egoist.dev/docs/app.md): the lifecycle, quitting, a single instance, deep links, file associations, recent documents, starting at login, well-known directories, the jump list, drawing web pages on Linux, browsing data, cookies and sessions. * [Menus and the tray](https://mygo.egoist.dev/docs/menus.md): application, context and Dock menus, keyboard shortcuts and tray icons. * [Documents](https://mygo.egoist.dev/docs/documents.md): document-based apps, a window per file, with the File menu, autosave, recovery after a crash, asking to save before closing and quitting, and files changed by other apps. * [Languages](https://mygo.egoist.dev/docs/i18n.md): the app's messages in the languages it ships, with catalogs of ICU messages, typed Go and TypeScript functions, plural forms, MyGo's own strings, and pseudo locales to test layouts. * [Desktop APIs](https://mygo.egoist.dev/docs/native.md): dialogs, notifications, the clipboard, the shell, displays, dark mode, power, the network status, secrets, watching files and global shortcuts. * [Native modules](https://mygo.egoist.dev/docs/native-modules.md) (experimental): Go interfaces implemented in Swift, Kotlin, Rust or Zig, without cgo, for the frameworks and views of macOS, iOS and Android, Rust crates and Zig and C libraries, which the CLI builds, puts into apps and publishes for the users of your Go packages. * [Clipboard and drag data](https://mygo.egoist.dev/docs/data-transfer.md): multiple representations, file lists, custom formats, lazy providers, and clipboard persistence. * [Audio](https://mygo.egoist.dev/docs/audio.md): sound effects, streamed music and sound an app makes itself, mixed in Go, with WAV, Ogg Vorbis and MP3. * [Launchers](https://mygo.egoist.dev/docs/launchers.md): apps in the manner of Spotlight and Raycast, summoned by a shortcut over every app, which find and open the apps installed. ## Native UI [Native UI](https://mygo.egoist.dev/docs/ui.md) has documentation of its own: guides to views, layout, input, navigation and accessibility, and a page for each of its components, from buttons to tables. ## Web pages * [The frontend](https://mygo.egoist.dev/docs/frontend.md): how pages load during development and in builds, the `mygo-runtime` package, custom protocols, custom title bars and dropped files. * [Calling Go from the frontend](https://mygo.egoist.dev/docs/bindings.md): bound services, channels, typed events and the generated TypeScript client. * [Plugins](https://mygo.egoist.dev/docs/plugins.md): features that come in a Go package and an npm package, such as the official plugins, and writing your own. ## Phones and tablets * [Phones and tablets](https://mygo.egoist.dev/docs/mobile.md): the same app on iOS and Android, what you need, developing on a simulator, an emulator or a device, and how apps behave on phones. * [Building and publishing for phones](https://mygo.egoist.dev/docs/mobile/building.md): signed `.ipa`, `.apk` and `.aab` files, App Store Connect and Google Play, links, icons and launch screens. * [Interfaces on phones](https://mygo.egoist.dev/docs/mobile/interface.md): the system's tabs and stacks, fingers, the keyboard, the widgets of phones, and testing. * [Device APIs and plugins](https://mygo.egoist.dev/docs/mobile/plugins.md): haptics, sharing, the battery, the official plugins for maps, the camera, location and more, and writing your own in Swift and Kotlin. ## Shipping * [Building and distributing](https://mygo.egoist.dev/docs/distribution.md): packaged apps for macOS, Windows and Linux, signing, installers and disk images. * [Auto-updates](https://mygo.egoist.dev/docs/updates.md): signed updates from GitHub releases, an S3 bucket, your own server or the app's own update service, delta updates, and an update window in the manner of Sparkle. * [GitHub Actions](https://mygo.egoist.dev/docs/github-actions.md): a workflow that builds, signs and notarizes the apps of every platform, and publishes them with their updates, when you push a tag. ## Official plugins * [Fetch](https://mygo.egoist.dev/docs/plugins/fetch.md): a `fetch` that makes HTTP requests from Go, with no CORS, any header, streamed bodies and cancellation. * [WebSocket](https://mygo.egoist.dev/docs/plugins/websocket.md): a `WebSocket` whose connections Go makes, with headers on the handshake. * [SQLite](https://mygo.egoist.dev/docs/plugins/sqlite.md): local databases with parameterized queries and atomic transactions, without cgo. * [Watch](https://mygo.egoist.dev/docs/plugins/watch.md): changes to files, in the directories the app lets pages watch. * [Updater](https://mygo.egoist.dev/docs/plugins/updater.md): an update window in the manner of Sparkle, which checks for updates and offers to install them. * [Terminal](https://mygo.egoist.dev/docs/plugins/terminal.md): a terminal for native UI, which runs the shell or any program with Ghostty's terminal emulator. * [Glass](https://mygo.egoist.dev/docs/plugins/glass.md): Liquid Glass for native UI, as macOS draws it, on every platform, with macOS's scroll edges and backdrop blurs. * [Game](https://mygo.egoist.dev/docs/plugins/game.md): what games need beyond what apps do, opt-in: a game loop in fixed steps with its input, a camera, and gamepads in one standard layout. * [Loading](https://mygo.egoist.dev/docs/plugins/loading.md): loading.dev's 29 loading indicators for native UI. * [SF Symbols](https://mygo.egoist.dev/docs/plugins/sfsymbols.md): Apple's SF Symbols for native UI on macOS, drawn by the system. * [Automation](https://mygo.egoist.dev/docs/plugins/automation.md): drive a running app from another process, as end-to-end test runners and agents do: its windows, elements, input, menus and screenshots, and `mygo-automation`, its command line client for agents. * [PermissionFlow](https://mygo.egoist.dev/docs/plugins/permissionflow.md): the system's permissions, such as Accessibility and Screen Recording, checked and asked for, and a guide to System Settings with the app to drag into its list. * [Render](https://mygo.egoist.dev/docs/plugins/render.md): videos of native UI, its frames drawn on the GPU and encoded with the system's encoders, with sound. ## Reference * [Configuration](https://mygo.egoist.dev/docs/configuration.md): `mygo.config.ts`, or `mygo.json`. * [The mygo CLI](https://mygo.egoist.dev/docs/cli.md): its commands and flags. * The Go API: `go doc -all github.com/egoist/mygo`, with the documentation of every type and method. * [Architecture](https://mygo.egoist.dev/docs/architecture.md): how MyGo works inside, for contributors, with a table of the differences between platforms. ## Requirements To develop apps you need [Go](https://go.dev/dl/) 1.27 or later and, for the frontend tooling of projects with a web frontend, [Bun](https://bun.sh); projects of native UI need Go alone. MyGo uses no cgo, so there is no C toolchain to install, and any machine can compile the apps of every platform; signing and disk images of macOS apps need a Mac. Apps run on: | Platform | Windows with web pages need | Windows of native UI need | | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | | macOS 12 or later | nothing: WKWebView is part of macOS | nothing: they draw with Metal | | Linux (x64, arm64) | GTK 3 and WebKitGTK 4.1 (or 4.0): `libwebkit2gtk-4.1-0` on Debian and Ubuntu, `webkit2gtk4.1` on Fedora, `webkit2gtk-4.1` on Arch Linux | GTK 3 alone | | Windows 10 and 11 (x64, arm64) | the [WebView2 Runtime](https://developer.microsoft.com/microsoft-edge/webview2/), which Windows 11 includes | nothing: they draw with Direct3D 11 | An app whose windows all show native UI needs neither WebKitGTK nor the WebView2 Runtime. Tray icons on Linux also need `libayatana-appindicator3`. On Linux, MyGo turns WebKitGTK's DMA-BUF renderer off unless the app opts in, see [drawing web pages on Linux](https://mygo.egoist.dev/docs/app.md#drawing-web-pages-on-linux). An app that shows web pages can ask whether the machine has a webview with `mygo.WebViewAvailable()`, also before `App.Run`, and open a window of native UI where it has none, as the table's last column describes. `mygo doctor` checks a development machine. --- Source: https://mygo.egoist.dev/docs/app.md # The application `mygo.App` is the application: its lifecycle, its identity, and how it meets the rest of the system. ## The main function ```go func main() { mygo.Bind(&Notes{}) // services the frontend calls mygo.App.WhenReady(func() { // once the app has launched mygo.NewWindow(mygo.WindowOptions{URL: "/"}) }) if err := mygo.App.Run(); err != nil { // the event loop, until the app quits log.Fatal(err) } } ``` `App.Run` runs the native event loop and returns when the app quits. It must be called from the main goroutine, because the UI toolkits of every platform must run on the thread that started the process; MyGo keeps the main goroutine on it. Windows exist only once the app is ready: create them in `WhenReady`, or from any goroutine after that. Before `Run`, `main` sets the app up: it binds services, handles protocols, adds listeners, and makes settings such as `App.SetName`, `App.SetMenu`, `App.Dock.SetMenu`, `Theme.SetSource` and `Theme.SetGTKCSS`, which take effect when the app starts. It may also read what needs no running app, such as `App.Path`, `App.Locale` or `Power.IsOnBattery`, and register the app with the system (`App.SetOpenAtLogin`, `App.RegisterURLScheme`). Everything else needs the running app: when `main` calls the clipboard, displays, dialogs, notifications, global shortcuts, trays, Dock badges, `Theme.IsDark`, `Theme.Preferences` and the like before `Run`, they panic with a message naming the call, on every platform. Use them from `WhenReady` on; other goroutines may call them earlier, and wait for the app to start. ## Threads Every function and method of MyGo is safe to call from any goroutine: calls made off the main thread are sent to it and wait for the result. What runs where: * Event listeners, such as `OnClose` or `OnActivate`, menu item clicks and global shortcuts run on the main thread, which also draws the UI: keep them short, and start goroutines for slow work. * Bound methods run on goroutines of their own, one per call: they may block. * `mygo.RunOnMain(fn)` runs `fn` on the main thread, for native APIs called through `Window.NativeHandle`. ## Lifecycle | Event | When | | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `OnReady` | the app has launched; `WhenReady` also runs its function right away when the app is already ready | | `OnActivate(func(hasVisibleWindows bool))` | the app was activated again, e.g. by a click on its Dock icon (macOS) | | `OnDidBecomeActive`, `OnDidResignActive` | the app became, or stopped being, the active app | | `OnWindowCreated(func(w *mygo.Window))` | a window was created | | `OnWindowAllClosed` | the last window closed, unless the app is quitting | | `OnBeforeQuit(func(e *mygo.QuitEvent))` | a quit started, before the windows close; `e.PreventDefault()` cancels it, unless the OS ends the session (`e.SessionEnding`) | | `OnWillQuit(func(e *mygo.QuitEvent))` | every window has closed and the app is about to quit; it can still be canceled, unless the OS ends the session | | `OnQuitCanceled` | a quit that started was canceled by a listener or a window; the app keeps running | | `OnQuit` | the event loop stopped, right before `Run` returns | Each returns a function that removes the listener. ### Quitting When its last window closes, an app quits, unless `OnWindowAllClosed` has a listener. On macOS apps usually keep running with their Dock icon, and open a window again when it is clicked: ```go mygo.App.OnWindowAllClosed(func() { if runtime.GOOS != "darwin" { mygo.App.Quit() } }) mygo.App.OnActivate(func(hasVisibleWindows bool) { if !hasVisibleWindows { openMainWindow() } }) ``` * `App.Quit()` closes every window, which `OnClose` listeners can refuse, then quits; `OnBeforeQuit` and `OnWillQuit` listeners can cancel it too. Cmd+Q, the Quit menu item and Ctrl+C in the terminal (SIGINT and SIGTERM) quit the same way; a second signal exits at once. * When one of them cancels the quit, `OnQuitCanceled` runs: an app that set its own quitting state in `OnBeforeQuit` clears it there, or it would go on running with that state set. The windows a canceled `OnWillQuit` had already closed stay closed. * When the OS ends the session (logout, restart, shutdown) on Windows and macOS, the quit listeners and the windows' `OnClose` run all the same, in that order and before `OnQuit`, but can't cancel it: the `QuitEvent`'s `SessionEnding` is set, and the process may end as soon as they and `OnQuit` return. Save what must survive synchronously there, without dialogs or goroutines to wait for. A quit that already ran them only finishes. Linux tells MyGo of no session end: shutdown, and a logout that stops the user's processes, send SIGTERM, which quits like `App.Quit()`. * `App.Exit(code)` exits right away, without events. * `App.Relaunch()` quits, then starts the app again with the same arguments, for example after a setting that needs a restart. `App.Relaunch(args...)` passes other arguments instead, which replace those the app started with, so that the new instance knows why it starts, without a file the two would share: ```go mygo.App.Relaunch("--safe-mode") ``` They reach the new instance on macOS (through Launch Services, also after an update), Linux and Windows, and under `mygo dev`. In browsers `Relaunch` only quits. ## A single instance Most desktop apps run once: starting them again brings the running instance to the front. `RequestSingleInstanceLock` returns false in a second instance, after passing its command line to the first: ```go func main() { if !mygo.App.RequestSingleInstanceLock() { return // the running instance takes over } mygo.App.OnSecondInstance(func(args []string, workingDir string) { if w := mainWindow(); w != nil { w.Restore() w.Focus() } }) // ... } ``` The lock is held until the process exits, so the work an app does after `Run` returns (stopping the processes it started, writing its files) never overlaps with a new instance. From quit on, the instance takes no more command lines: a launch meanwhile, such as `Relaunch`'s or an update's, waits for it to exit, however long that takes, and then runs. The system releases the lock when the process ends, also when it crashes or is killed, and the processes the app started don't keep it. ## Deep links Apps open URLs of their own schemes, such as `myapp://open?note=42`. List the schemes in mygo.config.ts, which registers them with the system when the app is installed: ```ts export default defineConfig({ urlSchemes: ["myapp"], }); ``` and handle the URLs with `OnOpenURL`, registered before `Run` so it also gets the URL the app was started with: ```go mygo.App.OnOpenURL(func(rawURL string) { u, err := url.Parse(rawURL) if err != nil { return } openNote(u.Query().Get("note")) }) ``` On Windows and Linux a URL starts a new instance of the app: request the [single instance lock](#a-single-instance), and the URLs of later instances reach `OnOpenURL` in the first one. Apps that are not installed with the package `mygo build` makes, a portable executable for example, register their schemes at run time with `App.RegisterURLScheme("myapp")`, which is cheap to call at every launch; `UnregisterURLScheme` and `IsURLSchemeRegistered` go with it. On macOS schemes must be listed in the configuration. ## File associations Apps open files of their types from the file manager. Declare the types in mygo.config.ts: ```ts export default defineConfig({ fileAssociations: [ { ext: ["md", "markdown"], name: "Markdown Document", mimeType: "text/markdown", }, ], }); ``` and open them with `OnOpenFile`, registered before `Run` so it also gets the files the app was started with: ```go mygo.App.OnOpenFile(func(path string) { openDocument(path) }) ``` It also gets files dropped on the app's Dock icon (macOS) and files passed on the command line. As with deep links, the single instance lock makes the first instance get the files of later ones on Windows and Linux. Apps whose windows each show a file get this and the rest of what document-based apps do from [documents](https://mygo.egoist.dev/docs/documents.md). ## Recent documents Record the documents the user opens, so that the app and the system offer them again: ```go if err := mygo.App.AddRecentDocument(path); err != nil { log.Println(err) } ``` `App.RecentDocuments()` returns them, newest first, ten at most, also those of earlier runs, without the files that no longer exist; the Open Recent menu (`RoleOpenRecent`, see [menus](https://mygo.egoist.dev/docs/menus.md)) lists them. macOS lists them in the app's Dock menu too, Linux in the user's recently used files (`~/.local/share/recently-used.xbel`, the Recent of file choosers and file managers), and Windows in the Recent category of the app's [jump list](#jump-lists), for the file types the app is registered to open (see [file associations](#file-associations)). Choosing one of them, in the Open Recent menu, the Dock menu or the jump list, opens the file with the app, which gets it through `OnOpenFile`. [Documents](https://mygo.egoist.dev/docs/documents.md) record the files they open and save, and open those chosen themselves; other apps, such as those that open folders, record what they open. `ClearRecentDocuments` removes them all, for example when the user asks to clear the app's history, as the Open Recent menu's Clear Menu does. On Linux the user's other recent files stay. ## Start at login ```go if err := mygo.App.SetOpenAtLogin(true); err != nil { log.Println(err) } enabled := mygo.App.OpenAtLogin() ``` Offer it as a setting. The app becomes a login item of the user on macOS 13 and later (which needs the packaged app), a launch agent on macOS 12, an XDG autostart entry on Linux and a Run entry of the user on Windows, which the system's settings list and can turn off. `WasOpenedAtLogin` tells a launch at login apart, to start in the background: ```go mygo.NewWindow(mygo.WindowOptions{URL: "/", Hidden: mygo.App.WasOpenedAtLogin()}) ``` On Windows the Run entry starts the app with the user's normal (unelevated) token, even when the user is an administrator: the app cannot create network adapters, change the system's proxy or write to protected folders. An app that needs administrator rights registers a logon task in Task Scheduler with the run level `HighestAvailable` instead (`schtasks /Create /SC ONLOGON /RL HIGHEST`, or the Task Scheduler API), which starts it elevated without asking, and does not call `SetOpenAtLogin`. Creating the task needs administrator rights itself, so the app asks for them once, as the user turns the setting on. `WasOpenedAtLogin` does not tell such a launch apart: give the task's command an argument of the app's own for that. ## Directories `App.Path` returns well-known directories: | Name | Directory | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | | `PathUserData` | the app's data: `~/Library/Application Support/`, `~/.config/` (`$XDG_CONFIG_HOME`) or `%AppData%\`; created on first use | | `PathCache` | the app's cache: `~/Library/Caches/`, `~/.cache/` or `%LocalAppData%\`; created on first use | | `PathLogs` | where to write logs: `~/Library/Logs/`, else `logs` in the user data directory; created on first use | | `PathResources` | the files the app ships with, see [resources](https://mygo.egoist.dev/docs/distribution.md#resources) | | `PathAppData` | the per-user configuration directory, without the app's name | | `PathHome`, `PathTemp`, `PathExe` | the home directory, the temporary directory, the executable | | `PathDesktop`, `PathDocuments`, `PathDownloads`, `PathMusic`, `PathPictures`, `PathVideos` | the user's folders | ```go dir, err := mygo.App.Path(mygo.PathUserData) db := filepath.Join(dir, "notes.db") ``` `App.SetPath` overrides a directory, for example to keep test data apart. ## Name and version A packaged app knows its name and version from its configuration, which `mygo build` links into it: `App.Name()` and `App.Version()`. A program run with `go run` has the executable's name and no version, unless it calls `App.SetName` and `App.SetVersion`, before `Run`. The name sets the user data, cache and log directories and the single instance lock. Development builds of `mygo dev` are named ` Dev`, so that they keep their data apart from the installed app's; calling `SetName` ties them together again. `mygo.IsDev()` reports whether the app is a development build: `go run`, `go build` and `mygo dev` builds are, `mygo build` builds are not, and `MYGO_ENV=production` makes any build behave like one. `App.IsPackaged()` reports whether it runs from an app bundle. `App.Locale()` returns the language the app shows, such as `"zh-Hans"`, of those it is written in, `App.PreferredLanguages()` the languages the user reads, as the system lists them, and `App.ChosenLocale()` the language `App.SetLocale` chose, `""` while the app follows the user's; see [the language the app shows](https://mygo.egoist.dev/docs/i18n.md#the-language-the-app-shows). Before 0.5, `App.Locale()` returned the user's first preferred language whatever the app is written in. ## The Dock and the taskbar * `App.SetBadgeCount(n)` shows a count on the app's icon: the Dock (macOS) or the launcher entry (Linux docks that support it); zero clears it. * `App.Dock` controls the Dock icon on macOS: `SetBadge` shows any text, `Bounce` asks for attention, `SetIcon` replaces the icon, `SetMenu` adds items to its menu (see [the Dock menu](https://mygo.egoist.dev/docs/menus.md#the-dock-menu)), and `Hide` and `Show` remove and restore it. * `App.SetActivationPolicy(mygo.ActivationPolicyAccessory)` removes the Dock icon of an app that lives in the menu bar, see [tray icons](https://mygo.egoist.dev/docs/menus.md#tray-icons); its windows can still show. `App.ActivationPolicy` returns the policy. * `App.Focus` brings the app to the front, and `App.IsActive` reports whether it is there: the active app, or the one with the focused window on Windows and Linux. On macOS, `App.Hide` and `App.Show` hide and show all its windows, and `App.ShowAboutPanel` shows the standard about panel. ### Jump lists On Windows, right-clicking the app's taskbar button shows its jump list: the documents the user opened recently (see [recent documents](#recent-documents)) and tasks, programs to run with arguments, often the app itself, such as a text editor's "New note". `App.JumpList.SetTasks` sets the tasks; Windows keeps them after the app quits, so setting them once at startup is enough: ```go mygo.App.OnOpenURL(func(rawURL string) { if rawURL == "myapp://new-note" { newNote() } }) // ... once the app is ready: if err := mygo.App.JumpList.SetTasks([]mygo.JumpListTask{ {Title: "New note", Description: "Write a new note", Args: []string{"myapp://new-note"}}, {Title: "Notepad", Path: `C:\Windows\notepad.exe`}, }); err != nil { log.Println(err) } ``` A task that runs the app starts it again with `Args`: when the app is not running, the new instance gets them; when it is, with [a single instance](#a-single-instance) the running one does. A URL of one of the app's [schemes](#deep-links) reaches `OnOpenURL` either way, and a file of its types `OnOpenFile`, so tasks are best made of them. Other arguments go to the new instance's `os.Args`, and to the running one's `OnSecondInstance`: handle them in both places. Each argument is passed as it is, and MyGo quotes them for the command line. `Path` is the app's own executable unless set, `WorkingDir` the directory it runs in, `Description` the tooltip, and the icon is the program's own unless `IconPath` (with `IconIndex`) names another. No tasks removes them. Windows replaces the whole jump list whenever the app changes a part of it, so `App.JumpList` keeps the parts and commits them together. Its methods do nothing on macOS and Linux. ## Drawing web pages on Linux WebKitGTK draws pages on the GPU with its DMA-BUF renderer where it can, and that renderer shows blank windows with NVIDIA's driver, in virtual machines and in containers. So MyGo turns it off by default: before GTK starts, `App.Run` sets `WEBKIT_DISABLE_DMABUF_RENDERER=1` unless the environment already has the variable. Pages then draw on the CPU, which costs frame rate where the renderer would have worked: on a Wayland desktop with Intel's GPU, a long page (a chat transcript of 4,600 elements) scrolls at 11–19 frames per second with a core busy, against 56 with the renderer and half the CPU. An app that knows where it runs can leave the renderer on, before `App.Run`: ```go mygo.App.SetDMABUFRenderer(mygo.DMABUFRendererAuto) ``` | Setting | The renderer | | --------------------------------- | --------------------------------------------------------- | | `DMABUFRendererOff` (the default) | off | | `DMABUFRendererAuto` | on where the host is known to draw with it, off elsewhere | | `DMABUFRendererOn` | left to WebKitGTK, which uses it wherever it can | `DMABUFRendererAuto` leaves it on when GTK will open a Wayland display (`WAYLAND_DISPLAY` names a socket that exists, and `GDK_BACKEND` does not put another backend first) and the system has a GPU with a Mesa driver (a render node of a driver with 3D): not NVIDIA's driver (`/sys/module/nvidia`, `/proc/driver/nvidia/version`), not software OpenGL (`LIBGL_ALWAYS_SOFTWARE`, `GALLIUM_DRIVER=llvmpipe`), not in a container (`/.dockerenv`, `/run/.containerenv`), WSL or a virtual machine (the firmware's `product_name` or `sys_vendor` names VirtualBox, VMware, QEMU, KVM, Hyper-V and others). Use `DMABUFRendererOn` only where you know the machines, as in a kiosk. `WEBKIT_DISABLE_DMABUF_RENDERER`, set by the user, always wins, whatever the app chose: `0` turns the renderer on, `1` off. Other systems ignore the setting. ## Browsing data `App.ClearBrowsingData()` deletes what the app's pages stored: cookies, local and session storage, IndexedDB, service workers and caches, for example when the user signs out. Open pages keep what they hold in memory until they reload. It clears the default session; `Session.ClearData` clears another, or some kinds of data only. ### Cookies `mygo.Cookies` reads and changes the cookies of the app's pages, `HttpOnly` ones included: the default cookie store, which all windows share and which the system webview keeps from one run to the next. Set one, for example, to sign the pages in with a token the backend got, before the first page loads, or read the session a page's sign-in set: ```go err := mygo.Cookies.Set(mygo.Cookie{ Name: "session", Value: token, Domain: "example.com", Secure: true, HTTPOnly: true, Expires: time.Now().Add(30 * 24 * time.Hour), }) // The cookies a request to the URL sends. sent, err := mygo.Cookies.List(mygo.CookieFilter{URL: "https://example.com/account"}) // Those named session of example.com and its subdomains. sessions, err := mygo.Cookies.List(mygo.CookieFilter{Name: "session", Domain: "example.com"}) // Every cookie, sorted by domain, path and name. all, err := mygo.Cookies.List(mygo.CookieFilter{}) err = mygo.Cookies.Delete(mygo.Cookie{Name: "session", Domain: "example.com"}) err = mygo.Cookies.Clear() // every cookie, but not the pages' storage ``` A cookie's name, domain and path identify it: `Set` replaces the cookie of the same name, domain and path, and `Delete` deletes it, whatever its other fields, so it deletes a cookie `List` returned. A domain without a leading dot is a host's, sent to that host only; with one, `.example.com`, the cookie goes to its subdomains too. Domains are ASCII (punycode for others) and an empty path is `/`. An empty `SameSite` is `Lax`, and `None` needs `Secure`. Names and values take what browsers take: anything but control characters, `;`, and spaces at either end, and names no `=`. A zero `Expires` makes a cookie that lasts until the app quits, and one in the past deletes the cookie. A filter's fields narrow the list: `URL`, an http or https URL, keeps the cookies a request to it sends, matched by the engine where it can (by domain, path and `Secure` as RFC 6265 says on macOS); `Name` keeps those of a name; `Domain` those of a domain and its subdomains, with or without a leading dot; `Path` those of exactly a path. The methods are safe from any goroutine once the app is running, and on the main thread the app keeps handling events while they wait. Cookies may carry the user's credentials: rather than binding the module to the pages, bind a backend method that does what the page needs. On Windows, WebView2 gives cookies only through a web view: while no window or web view in native UI shows a page, the methods, and `App.ClearBrowsingData`, make a hidden one, which also makes the WebView2 browser process start, and a window's first page waits for the calls under way when its web view is made. The hidden web view closes once a page shows, or, in an app showing none, a few seconds after the last call, and WebView2's processes exit with it; it stays while the session has cookies that WebView2 keeps only while they run: those with a zero `Expires`, and any of an ephemeral session. WebView2 applies changes after its calls return, so the methods wait until the change shows, and fail when it does not within two seconds, as when the engine refuses a cookie. On Linux they need WebKitGTK 2.42 or newer, and `Set` libsoup 2.70 or newer; WebKitGTK keeps the cookies in `cookies.sqlite` of the app's user data directory (`~/.config/`). ### Sessions Every page shows in the default session unless `PageOptions.Session` names another: a store of cookies, local and session storage, IndexedDB, caches and service workers of its own, which the pages of other sessions don't see, as Electron's partitions. Two accounts of a service side by side, a private window, a preview that must not see the user's sign-ins, or a third-party page kept away from the app's own storage each take one: ```go work := mygo.NewSession("work") // kept on disk from one run to the next private := mygo.NewEphemeralSession() // in memory only win := mygo.NewWindow(mygo.WindowOptions{ URL: "https://mail.example.com", Page: mygo.PageOptions{Session: work}, }) list, err := work.Cookies.List(mygo.CookieFilter{}) err = work.Cookies.Set(mygo.Cookie{Name: "session", Value: token, Domain: "example.com"}) err = work.ClearData(mygo.SiteDataAll) // signing out err = work.ClearData(mygo.SiteDataCookies | mygo.SiteDataCaches) // some kinds ``` `NewSession` returns the same session for the same name, whose data stays on disk as the default session's does. `NewEphemeralSession` returns a new session every time, which writes nothing to disk: its data goes when the last page using it closes, and its next page starts with none. A cookie set before its first page opens goes to that page. `mygo.Cookies` and `App.ClearBrowsingData` are the default session's, which `mygo.DefaultSession()` returns too. A window a page opens with `window.open` or a `target="_blank"` link is in its opener's session, whatever the `Session` of the options the open handler returns. Custom protocols (`mygo.Protocol`) serve the pages of every session, and a web view in [native UI](https://mygo.egoist.dev/docs/ui/web-view.md) takes a session in its `PageOptions` too. `ClearData` takes `SiteDataCookies`, `SiteDataLocalStorage` (with session storage), `SiteDataIndexedDB` (with WebSQL), `SiteDataCaches` (the HTTP cache and Cache Storage), `SiteDataServiceWorkers`, or `SiteDataAll`: all the data the engine keeps for sites, those kinds and the others it has. | | persistent session | ephemeral session | | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | | macOS | `WKWebsiteDataStore dataStoreForIdentifier:` with a UUID made of the name, from macOS 14; before, an in-memory store that lasts until the app quits | `nonPersistentDataStore` | | Linux | a web context of its own, with its data in `Sessions/` of the user data directory and its caches in that of the cache directory; WebKitGTK 2.16 or newer | a web context with an ephemeral website data manager | | Windows | a WebView2 profile, `mygo-`, in the app's WebView2 user data; WebView2 Runtime 1.0.1185 or newer | an InPrivate profile, `mygo-private-`, which WebView2 drops with its last web view | On Windows, the cookies of a session come from a web view of its profile, as the default session's do: before one of its windows shows a page, the calls make a hidden one. --- Source: https://mygo.egoist.dev/docs/architecture.md # MyGo architecture This guide explains how MyGo is put together: the layers, the threading model, how Go talks to the native toolkits without cgo, how pages and Go exchange typed messages, how MyGo draws native UI, and how to extend the framework safely. Read it before changing anything under `internal/`. ## Goals and constraints * **Low overhead.** A hello-world app is a \~7 MB binary with a \~35 MB physical footprint on macOS (mostly AppKit/WebKit), \~62 MB with the processes WKWebView runs for its page, GPU and network, and idles at 0% CPU. A window of native UI starts no webview process: idle, a small one takes 44 MB on macOS, and the counter example 65 to 67 MB on Linux, tiled to half of a 4K display at scale 2, 15 MB of it the window's buffer, without loading Mesa (122 to 155 MB with it). Nothing polls: all work is driven by native events or explicit wake-ups. A window of native UI whose content settled asks for no frame and arms no timer (`TestSettledWindowSleeps`): the display link pauses, Go's scheduler sleeps, and the counter example idles at about 0.005% of a core on macOS (an AppKit window, 0.002%) and wakes no thread under X11. The one exception is opt-in: while an app observes the clipboard on macOS, which tells no one of changes, a timer reads the pasteboard's change count every 250 ms (`Clipboard.OnChanged`). * **No cgo.** Everything builds with `CGO_ENABLED=0`, so any platform can be cross-compiled from any machine. Native APIs are called at run time through [purego](https://github.com/ebitengine/purego) (`dlopen` + assembly trampolines) on macOS and Linux and through the `syscall` package on Windows, never through `import "C"`. Phones are the exception Go makes: iOS and Android link with their own toolchains, with cgo (see [Phones](#phones-internalmobile)). * **Two kinds of windows.** Web pages show in the system webview: WKWebView on macOS, WebKitGTK 4.1 (4.0 as a fallback) on Linux, WebView2 on Windows (amd64 and arm64); no browser engine is bundled. Native UI is drawn by MyGo itself, in Go, with Metal, Direct3D 11 or OpenGL, or on the CPU, and text from the system's own engines (see [Native UI](#native-ui-ui)); an app whose windows all show it needs no webview at all, and runs in browsers too, compiled to WebAssembly, on canvases drawn with WebGL 2 (see [Browsers](#browsers-internalweb)). On unsupported platforms, 32-bit Windows and Linux among them, the `internal/unsupported` backend makes `App.Run` fail with a clear error while everything still compiles, so every file of a backend, and of the text engine it pairs with, names the backend's architectures in its build constraint. * **Bun is dev tooling only.** It builds and tests the TypeScript bridge, and installs and runs the web template's tools (Vite, TypeScript, the mygo-cli package); projects of native UI need none. Nothing Bun-related ships in an app. * **Great DX over API parity.** The API has the feel of Electron (app lifecycle, windows, menus, dialogs) but is Go-first: typed IPC with a generated TypeScript client, `http.Handler` for custom protocols, typed event structs, blocking calls that are safe from any goroutine, and native UI written in Go alone. ## Repository layout ``` . package mygo: the public API ├── app.go lifecycle, quit sequence, Dock, paths (paths.go) ├── window.go Window: the native window, its options, state and events ├── flyout.go NewFlyout: windows owned by a parent, placed next to an anchor ├── page.go Page: the web page a window shows, its loading, Eval and events ├── content.go Content: windows showing native UI instead of a page ├── webview.go WebView: web pages in windows of native UI, under it ├── ipc.go Bind/BindAs, method calls, Event[T], CallerWindow ├── plugin.go Plugin and Use: services bound as "plugin:" ├── channel.go Channel[T]: values streamed to a call's page ├── typescript.go GenerateTypeScript / WriteTypeScript (uses internal/tsgen) ├── protocol.go custom schemes served by http.Handler, FileServer ├── frontend.go the app's frontend: relative URLs, devUrl, mygo://localhost ├── menu.go Menu/MenuItem model, roles, native item updates ├── cookies.go Cookies: the pages' cookies, checked, keyed by name, domain and path, filtered by CookieFilter ├── session.go Session: website data stores chosen per page (PageOptions.Session), ClearData by kind ├── recent_docs.go jumplist.go: recent documents (Open Recent and the system's lists), the jump list ├── dialog.go modules.go clipboard.go: shell, clipboard, screen, theme, tray, shortcuts, notifications ├── watch.go watch_scan.go: WatchFiles, and what a watch saw of its directory ├── document*.go NewDocuments: documents, their saving, recovery copies, watches, menus ├── loop.go main-thread queue: postMain / onMain / await ├── events.go listener lists and the Preventable event types ├── single_instance.go RequestSingleInstanceLock: a lock file, command lines over a Unix socket ├── dev.go signal_*.go IsDev, the `mygo dev` ready signal, quitting on SIGINT/SIGTERM ├── backend_*.go picks the backend per GOOS ├── internal/ │ ├── platform/ the contract every backend implements │ ├── darwin/ macOS: AppKit + WKWebView through the Objective-C runtime │ ├── linux/ Linux: GTK 3 + WebKitGTK through dlopen │ ├── windows/ Windows: Win32 + WebView2 through syscall and COM │ ├── schemehost/ maps custom scheme URLs to the http://*.localhost URLs WebView2 serves them at │ ├── schemestream/ the bounded pipe custom scheme bodies stream to WebView2 through, and media ranges narrowed │ ├── web/ browsers (js/wasm): native UI on canvases, through syscall/js │ ├── mobile/ iOS and Android: one backend; wire/ its messages; ios/ the │ │ Swift host, android/ the Kotlin host (a Gradle project) │ ├── unsupported/ stub for other platforms │ ├── fake/ in-memory backend for unit tests │ ├── automationcli/ mygo-automation, the command line client of plugins/automation's socket │ ├── watchdriver/ the goroutine that runs a backend's file watcher │ ├── bridge/ embeds bridge.js, built from packages/bridge │ ├── surface/ the connection between a window and its native UI │ ├── pacing/ whether frames wait for the display (MYGO_UNCAPPED) │ ├── scene/ display lists and glyph atlases, what renderers draw │ ├── media/ the contract between ui's VideoPlayer and ui/video's engines │ ├── text/ fonts, shaping, line breaking, editing, glyph rasterization │ ├── rope/ the persistent tree of text chunks text buffers keep │ ├── diff/ line and word diffs: histogram, Myers, git's indent heuristic │ ├── vec/ the coverage rasterizer of glyphs and paths │ ├── raster/ the CPU renderer of scenes │ ├── gpu/ the instances GPU renderers draw, and gputest/ for their tests │ ├── gpu/d3d11/ the Direct3D 11 renderer of scenes, and device/ for its devices │ ├── gpu/metal/ the Metal renderer of scenes │ ├── gpu/gl/ the OpenGL and WebGL 2 renderer of scenes │ ├── shader/ the compiler of shaders in Go's syntax, forked from Ebitengine's Kage │ ├── shaderir/ its IR; glsl/, hlsl/ and msl/ write it for the GPU renderers, interp/ runs it on the CPU │ ├── svg/ SVG parsing and drawing, for icons and images │ ├── tsgen/ TypeScript client generator │ ├── nativegen/ native modules: reads their Go interfaces, writes their Go, Swift, Kotlin, Rust and Zig │ ├── i18ngen/ checks catalogs of messages, writes their Go and TypeScript functions │ ├── i18nlink/ what package i18n gives MyGo's own catalog only: a catalog that links no dates │ ├── l10n/ MyGo's own strings: the catalog of the controls and menu roles │ ├── nativelib/ mygo-plugin.json, libraries' file names, where they are built and cached │ ├── accelerator/ parses "CmdOrCtrl+Shift+K" │ ├── menuicon/ menu items' PNG icons as premultiplied, scaled pixels (Windows) │ ├── update/ update manifests, signatures, archives and delta updates │ ├── idlemem/ measures apps' memory once idle, for the benchmarks │ ├── inputlatency/ measures how long input takes to reach the screen in native UI (macOS) │ └── e2e/ GUI tests and benchmarks against the real backend (MYGO_E2E=1) ├── packages/ Bun workspace (with the examples' frontends): │ ├── bridge/ the runtime injected into pages (→ internal/bridge/bridge.js) │ ├── runtime/ mygo-runtime, the npm package apps and generated clients import │ └── cli/ mygo-cli, the npm package of the CLI, and in npm/ its │ per-platform binary packages ├── plugins/ official plugins, each a Go package and its npm │ package (@mygo-plugins/) side by side: fetch, │ websocket, sqlite, watch; and Go only: updater, the │ update window, a web page or native UI (updater/native), │ terminal, a view of native UI running programs with │ libghostty-vt, glass, game, what games need │ beyond what apps do (game/gamepad), loading, │ loading.dev's indicators for native UI, │ automation, a socket other processes drive the │ app through, for end-to-end tests, with its │ command line client for agents │ (automation/cmd/mygo-automation), and │ permissionflow, the system's permissions and a │ guide to System Settings, after PermissionFlow, │ and render, videos of native UI drawn on the GPU │ and encoded with the system's encoders ├── ui/ native UI: views, layout, widgets, text editing, Tester; │ ui/chart: charts without a look, on ui's public API; │ ui/editor: the code editor and the diff viewer; │ ui/shader: shaders in Go's syntax, on every renderer; │ ui/video: video with the system's media framework ├── i18n/ languages: matching, CLDR plural rules and parent locales, │ formatting of numbers and dates (generated by │ i18n/internal/gen), ICU MessageFormat, catalogs ├── ffi/ native libraries (Rust, Zig, C) that packages name in │ mygo-plugin.json: finding, loading and binding them ├── transfer/ immutable data items, representations, lazy providers and drag effects ├── netproxy/ the proxy of the system's settings, for Go's HTTP clients ├── native/ the runtime of native modules: Go interfaces implemented in Swift, Kotlin, Rust or Zig ├── audio/ sound: players, the mixer, the output of each platform, WAV; │ audio/vorbis and audio/mp3 decode Ogg Vorbis and MP3, │ audio/mp4 MP4 (fragmented too) with ALAC, audio/aac │ AAC, audio/flac FLAC ├── cmd/mygo/ the CLI: init, generate, dev, build, native build, doctor ├── examples/ hello, todo, frameless, native; counter-native, vibrancy, │ effort-slider, flyout, menubar-flyout, piano, farm │ and mayoi (games), code-editor and gallery (native │ UI), timeline (motion on one playhead); webview (web │ views in native UI); launcher (a Spotlight-like panel, │ native UI); wind (a texture of glyphs lit by a │ wind, two shaders of ui/shader); loading (the │ loading plugin's indicators); video (a GIF │ looping behind a window's content, a trailer │ with controls over it); permissionflow │ (the permissions, asked for and guided to); │ render (a promo video of native UI, and its preview); │ native-module (native modules in Swift, called from native UI); │ rust-native (a Rust crate the CLI builds, called │ through ffi) ├── docs/ the user guides, the official plugins' pages │ (plugins/), and this architecture guide └── website/ the website, with these docs: TanStack Start, prerendered and served by Cloudflare Workers as static assets ``` ## Layers ``` user code ──► package mygo ──► platform.Backend ──► darwin | linux | windows | web | unsupported ▲ │ ▲ │ │ └─ handlers ────┘ (AppHandler, └─ purego ─► AppKit/WebKit, GTK/WebKitGTK │ WindowHandler) page (JS) ◄── bridge.js ◄── Eval (batched) ─┘ └──── postMessage(JSON) ──► WindowHandler.Message ``` * **`package mygo`** owns all behavior that is not platform specific: option defaults, the window registry, event listeners, the quit sequence, IPC routing and encoding, menus, protocol handling, trust checks. It never calls a native API directly. * **`internal/platform`** is a small, synchronous contract: a `Backend` (event loop, window factory, menus, dialogs, clipboard, …), a `Window` (chrome + webview), and two handler interfaces the core implements to receive events (`AppHandler`, `WindowHandler`). Options arrive fully defaulted; backends never invent policy. * **Backends** translate the contract to native calls. They keep native objects alive, map native callbacks back to Go objects and report events. Keeping policy in the core is what lets `internal/fake` test almost all behavior without a GUI, and keeps each backend a thin translation layer. ## Threading model Cocoa and GTK must be driven from the thread that started the process. The rules are: 1. **The main goroutine is locked to the main thread** (`runtime.LockOSThread` in `mygo.go`'s `init`), and `App.Run` must be called from it. `Run` initializes the backend and blocks in the native event loop. Before that no backend is initialized (the Linux one has not even loaded GTK), yet `main` already runs on the main thread, where `onMain` calls functions directly, and generate mode never initializes it. So a public method that reaches the backend either keeps its value in the core until the backend can take it, for settings (`SetActivationPolicy` through `AppOptions`, `SetMenu` once ready, `Theme.SetSource`, `Theme.SetGTKCSS` and `Dock.SetMenu` right after `Init`), or starts with `needsApp`, which panics on the main thread before `Run` with the name of the call, rather than letting it crash on Linux, hang in `await` or answer wrong on macOS. Only calls that work before `Init` on every backend (`Locale`, packaging info, login items, URL schemes, `IsOnBattery`) do neither. 2. **Every `platform` method is called on the main thread, and every handler callback runs there.** The backend never needs locks for its own state. 3. **Every public method is safe from any goroutine.** `loop.go` provides: * `postMain(fn)` appends to a FIFO queue and calls `Backend.Signal`, which makes the backend call `AppHandler.Dispatch` (→ `loop.drain`) on the main thread. macOS uses a `CFRunLoopSource` added in all common modes (so it fires while menus track, windows resize and modal panels run); Linux uses `g_idle_add`, deduplicated with an atomic flag. * `onMain(fn)` runs `fn` directly when already on the main thread, else posts it and waits. After shutdown posted work is dropped instead of deadlocking. * `await(ch)` waits for an asynchronous native result. Off the main thread it is a plain channel receive. **On the main thread it pumps native events with `Backend.Step`** until the value arrives; whoever produces the value calls `deliver`, which sends and then `Backend.Wake`s the loop. This is what makes `Page.Eval`, `CapturePage` and dialogs usable from event listeners without deadlocking. Nested runs of the dispatch source are expected and safe. A nested loop started inside a run loop observer is not: CFRunLoop never runs that observer again meanwhile, and in the one AppKit displays views and Core Animation commits in, no window, panel or sheet would show. So native UI's frames, whose handlers (`Clicked`) may show a dialog, draw outside it on macOS, but those AppKit asks for, as a resize's (`drawSoon` in `internal/darwin/surface.go`). 4. **Event listeners run on the main thread**, synchronously, so cancelable events (`OnClose`, `OnBeforeQuit`, `OnWillNavigate`, …) can answer the native toolkit immediately. **IPC calls run on their own goroutines**, so bound methods may block. 5. **Validate in the caller's goroutine.** Anything that can panic on bad input (for example `WindowOptions.BackgroundColor`) is checked before hopping to the main thread, so the panic points at the user's call. Main-thread-only fields are marked as such in comments (for example `Window.native`, `Window.trusted`). Fields shared with other goroutines are guarded by a mutex or atomic. File watches (`watch.go`) don't use the main thread: each runs on a goroutine of its own, and the backend's watcher on another (see [Watching files](#watching-files-watchgo)). ## Native interop without cgo purego gives three primitives, used everywhere: * `purego.SyscallN(fn, args...)` for integer/pointer arguments. Fast, no reflection; it allocates only the array of its arguments, which escapes. Floats cannot be passed this way, nor structs, but for those C passes in integer registers, as Core Foundation's `CFRange`, which goes as its two fields, and comes back as `r1` and `r2`. * `purego.RegisterFunc(&typedFn, addr)` for signatures with floats or structs (`NSRect`, `CGFloat`, `GdkRGBA*` …). These are created once at startup; calling them uses reflection, so they are kept off hot paths. * `purego.NewCallback(fn)` turns a Go function into a C function pointer. At most \~2000 callbacks can exist per process and they are never freed, so **callbacks are created once per signature at startup** and user data (a window id, a request id) identifies the target. Never create callbacks per window, per request or per call. Package `ffi` gives apps and plugins the same for their own libraries (a Rust crate, a Zig package, C): `ffi.New(name, manifest)` finds the library of the package's embedded `mygo-plugin.json` (`$MYGO_NATIVE_`, the app's resources, the executable's directory and, outside packaged apps, the CLI's builds in `.mygo/native/-` of the working directory's module, then the published file in the user's cache, downloaded when missing), loads it once (`dlopen` with `RTLD_LOCAL`, `LoadLibrary` on Windows), and `Bind` sets a struct's function fields with `purego.RegisterFunc`, by tag or by the field's name in snake case, turning purego's panics on unsupported signatures into errors. `Bind` and `BindFunc` bind a pointer once, under the library's mutex, and remember the result in a `sync.Map`, so that functions can call `Bind` before each use from any goroutine without locking. The terminal and SQLite plugins find their libraries through it. Elsewhere than macOS, Linux and Windows on amd64 and arm64 it reports `errors.ErrUnsupported`. Apps that do not import it link none of it, and production builds (`mygo_nodownload`, set by `mygo build` with `mygo_noinspector`) leave out its downloader and `net/http` with it, about 1.9 MB, as packaged apps never download. ### macOS (`internal/darwin`) * `objc.go` loads the frameworks, caches selectors and classes, and wraps `objc_msgSend`: `send(obj, "selector:", args...)` for integer arguments and pre-registered typed variants (`msgRect`, `msgSetFloat`, `msgInitWindow`, …) for the rest. On amd64, methods returning structs larger than 16 bytes go through `objc_msgSend_stret`. * Classes are defined at run time with `objc.RegisterClass`: `MyGoWindow` (borderless-friendly `NSWindow`), `MyGoWebView` (records the last `mouseDown:` for drag regions; `window_drag.go` follows the press with a local event monitor: `StartDrag` asks the window server (`performWindowDragWithEvent:`) while the pointer has not moved, and moves the window itself when it has, or when the window server did not begin, which `windowWillMove:` tells, not the window's frame: it lags), `MyGoWindowDelegate` (window, navigation, UI and script-message delegate in one object per window), the app delegate, scheme handler, menu and tray targets. Only protocols that exist at run time are adopted (`WKScriptMessageHandler` is not registered, and WebKit does not need it). * **Overrides call super with `sendSuper`** (`sendSuperSize` for an `NSSize`), naming the class they are defined in, never purego's `objc.ID.SendSuper`: that resolves super from the object's class, which key-value observing replaces with a generated subclass, so the override would call itself until the stack overflows. `TestSuperFromDefinedClass` rejects it. * **The web view is not the content view.** A plain `NSView` is, holding the web view and, with vibrancy, an `NSVisualEffectView` behind it. WebKit docks the inspector next to the web view in its superview; were that the window's frame view, AppKit would draw a broken legacy title bar from then on. Liquid Glass is an `NSGlassEffectView` there instead, which shows what is under it in the window rather than behind it: an opaque window is made clear while it shows one, and so is the content view a rounded window's color went to (`clearForGlass`), the color given back once the glass goes. * **Memory is managed by hand.** Objects created with `alloc`/`init` are owned (+1) and must be released; convenience constructors return autoreleased objects. Code that creates temporary objects runs inside `withPool`, which keeps the goroutine on its thread until it pops the pool: a pool belongs to the thread that pushed it, and a goroutine other than the main one, as those reading the bundle for `App.Name`, may otherwise resume on another thread, where popping it crashes. Delegates and windows are released with `autorelease` from `windowWillClose:` because AppKit still uses them while closing. * **Blocks.** Completion handlers passed to Apple APIs are created with `objc.NewBlock` and released right after the call (the callee copies them). Blocks received from Apple (decision and completion handlers) are invoked with `callBlock`; when they are called later they are `_Block_copy`d first and released after use. * **Coordinates.** AppKit's origin is the bottom-left of the primary screen; MyGo's is the top-left. `rectToMac`/`rectFromMac` convert. * **Quitting.** Cmd+Q ends in `applicationShouldTerminate:`, which runs the core quit sequence and then stops the run loop so `App.Run` returns (the reply is `NSTerminateCancel`; AppKit never calls `exit`). Quit Apple Events (Dock > Quit, AppleScript, logout) are handled by our own handler installed in `applicationWillFinishLaunching:`, so senders get a success reply, or error -128 when a listener cancels. ### Linux (`internal/linux`) * `ffi.go` `dlopen`s GLib, GObject, GIO, GDK, GTK 3, cairo, GdkPixbuf and, when installed, AppIndicator. WebKitGTK 4.1 (4.0), JavaScriptCore and libsoup 3 (2.4), which only windows showing web pages need, load with the first such window (`webKit`), or to clear browsing data: an app that shows only native UI never maps them and the 75 or so libraries they bring, some 7 MB and 20 ms of startup. Without them, `errWebKit` says what to install when such a window is created. Symbols from newer WebKitGTK versions are bound optionally and feature-detected (`webkitWebViewCallAsyncJavascriptFunction != nil`). * Signals are connected with `g_signal_connect_data`, passing the window id as user data; `Backend.window(data)` resolves it and ignores closed windows. GDK event structs are read at fixed 64-bit offsets (`field[T]`). * The main thread is the one that called `gtk_init_check`; `IsMainThread` compares `gettid`. `Step` is `g_main_context_iteration(NULL, TRUE)` and `Wake` is `g_main_context_wakeup`. * `Init` names the program after its executable (`g_set_prgname`) before `gtk_init_check`, which would name it after `argv[0]`: GTK names the class of the windows and the app id after the program, as the desktop entry does (`StartupWMClass`), and WebKitGTK the directories of the pages' data. Started through a link of another name, as `linux.command` puts in `/usr/bin`, the app is then the same program. An app that named the program itself before `Run` (`g_set_prgname`), as one does to give its windows the reverse-DNS ID of its desktop entry, keeps its name: GLib leaves the name unset until `gtk_init_check`, so `Init` names the program only while `g_get_prgname` is `NULL`. * `Bounds` are those of the frame a reparenting X11 window manager puts around the window (`gdk_window_get_frame_extents`): GTK positions the frame (NORTH_WEST gravity) and sizes the window inside it, without the frame. `ContentBounds` are where the content widget is (`gdk_window_get_origin` plus its offset below the menu bar). The frame's extents are known once the window manager framed the window that shows, which its first synthetic configure report tells; until then a window expects the frame it had, or the one seen last around a decorated window that is resizable or not as it is (openbox: 1, 20, 1 and 5 px at the bottom, or 1). Wayland has no frame in `Bounds`. * GTK geometry changes are asynchronous: `SetBounds` remembers the requested rectangle, within the sizes GTK gives the window (`constrain`), with the frame it expects, as does a window about to show, which X has where GTK created it, or where it was, until the window manager places it; `Center` moves that rectangle along. `Bounds` reports that rectangle until a configure event reports its size and, on X11, its position, or the window manager's own (synthetic) report of the size comes, or another size, which the window manager or the user chose. A window being placed waits for the window manager's report: a reparenting one first puts its frame where it created it. If the frame is not the one expected, the rectangle grows with it around the size asked for inside it (`SetContentBounds`, `UseContentSize`, a window that showed before), or GTK is asked for the size inside the new frame. A report of the previous size was sent before the window manager took the request (openbox sends one when the size hints change); GTK would ask for that size again from it, so the backend asks for the new one again. * On Wayland, the configure event that activates a window can carry the size of the last buffer it drew, from before a resize GTK already took (Mutter sends one when native UI drawing with GL resizes from its first frames), and GTK goes back to that size. So a window drawing with GL keeps the latest bounds asked for while it is not focused, and once it is, an idle callback asks for them again if the window went back to the size it had, unless it is maximized, full screen or tiled. GTK skips a request for the size it asked for last: the callback first takes the configure and asks for the size the window has. * A window the user cannot resize is never smaller than its default size, which `SetBounds` sets too, and `SetResizable(false)` to the size it has, or than its natural size, which GTK makes 200x200 when the window's child has none, as the web view: the box around the web view asks for 1x1. * On Wayland, GTK decorates a frameless window, or one with a hidden title bar, itself (`useCSD`): `gtk_window_set_titlebar` with a `GtkBox` that never shows gives it client-side decorations without a title bar, so GTK draws its shadow and border around the page, resizes the window from them, and drops them while the window is maximized or in full screen. GTK sizes the window without them (`gtk_window_get_size`, the default size, the geometry hints), so the page keeps the size asked for, and Wayland has no positions they would shift. A window with `DisableShadow`, a transparent one (the decorations would outline the rectangle around a page that shows its own shape; GTK draws them on an app-paintable window too), panels and flyouts, a hidden title bar on a compositor that decorates windows itself, and every window on X11 stay undecorated (`gtk_window_set_decorated`): an X11 window that decorates itself has its shadow inside its X window, which the frame extents that `Bounds` counts do not tell, and Mutter puts its own shadow around opaque undecorated windows there. GTK styles the decorations once, so the shadow comes with the window: `SetHasShadow` changes nothing on Linux. * GTK gives windows without decorations no resize borders, so the outer 5 px of the page of an undecorated frameless window, or one with a hidden title bar, resize it (16 px along the edges from a corner resize the corner). The web view's `motion-notify-event` shows a resize cursor there, keeping WebKit's cursor to restore, and its `button-press-event` calls `gtk_window_begin_resize_drag` with the press, as a Wayland compositor requires; neither event reaches WebKit. Nothing resizes a maximized or full screen window, and a tiled one only resizes at the edges the window manager allows, as with GTK's own decorations. * `gtk_window_realize` announces server-side decorations to a Wayland compositor that speaks `org_kde_kwin_server_decoration` (KWin, COSMIC, Sway) for every window GTK does not decorate itself, one without decorations too, and the compositor draws its title bar on it. A frameless window GTK does not decorate itself is realized before it shows and announced client-side instead (`gdk_wayland_window_announce_csd`, looked up at startup): GDK keeps that for the `GdkWindow` and requests it again whenever the window maps or the compositor answers with another mode, so the window gets no title bar unless the compositor decorates every window. Without the protocol (Mutter), or on X11, which reads the hint of `gtk_window_set_decorated`, nothing decorates the window anyway. * A hidden title bar (`titlebar.go`) is a window without decorations whose web view is in a `GtkOverlay`, under a `GtkHeaderBar` for each side of `gtk-decoration-layout` that names window buttons. Each bar shows only that side's minimize, maximize and close (`decoration-layout`), and CSS clears its background and, with `TitleBarHeight`, its minimum height. GTK makes the buttons (they need the bar inside a `GtkWindow`) and hides those the window cannot use, and they act as a header bar's: iconify, toggle maximized, close. The bars are measured before the web view exists, from their natural size, for the script that tells the first page, then from their allocations; a change of the layout setting rebuilds them. A Wayland compositor that decorates windows itself (`gdk_wayland_display_prefers_ssd`: the default mode of `org_kde_kwin_server_decoration_manager`, server on KWin, Hyprland and Sway) gets no bars: such a window keeps GTK's announcement of server-side decorations, unlike a frameless one, so the compositor's title bar, or a tiling compositor's lack of one, stands for the buttons, whatever the layout says. * The app's GTK style sheet (`Theme.SetGTKCSS`, `style.go`) is a `GtkCssProvider` of its own for the default screen, at `GTK_STYLE_PROVIDER_PRIORITY_USER`: GTK 3 looks providers up from the highest priority, and among equal ones from the last added, so it wins over the theme, MyGo's own provider (600) and the user's `gtk.css`. Each sheet loads into a new provider, which replaces the one before only once it parsed (`gtk_css_provider_load_from_data` with a `GError`, which takes GTK's first parse error instead of a warning). The core reaches it through `platform.StyleBackend`, which only Linux and the fake backend implement, so apps that never set a sheet do not link it; one set on the main goroutine before `Run` waits in `pendingGTKCSS` until `Init`. * `WEBKIT_DISABLE_DMABUF_RENDERER=1` is set before GTK starts unless the user set it, which avoids blank webviews on NVIDIA drivers, VMs and containers, at the cost of drawing pages on the CPU. `App.SetDMABUFRenderer` (`AppOptions.DMABUFRenderer`) leaves it unset: always (`on`), or where `dmabufSafe` (`dmabuf.go`) finds Wayland and a GPU of Mesa's outside containers and virtual machines (`auto`, whose call links that probe in with `LinkDMABUFProbe`). * XDG desktop portal calls go through `portalCall` (`portal.go`), which first registers the app's ID, the name of its desktop entry, with `org.freedesktop.host.portal.Registry`: the portal only accepts that before any other call, and needs it for apps outside a sandbox that the desktop did not launch. Methods that may involve the user answer with a `Response` signal on a request object; `portalRequest` routes it to a callback by the object's path. * On Wayland, where apps grab no keys, global shortcuts go through the `GlobalShortcuts` portal (`hotkey_portal.go`), and under XWayland too when the desktop offers it (`portalOnX11`): GNOME sends XWayland no key presses meant for Wayland windows, so a grab there fires only while a window of the app has the focus. A session binds its shortcuts once, so every change closes the session and creates one that binds them all; the ids are canonical accelerators and the session token is named after the app, so desktops keep the keys the user picked. The portal may ask the user to confirm new shortcuts and needs the app's ID (portals from 1.21 refuse without it), so the app must be installed. KDE Plasma 5 binds the shortcuts listed in `CreateSession`'s options, as the portal's drafts had it: portals before 1.17 pass them on, later ones drop them and Plasma 5 then binds nothing; MyGo logs the shortcuts the desktop bound no keys to. The desktop shows each shortcut's description (`GlobalShortcutOptions.Description`, else the accelerator) where it asks and in its settings, and the keys it answers with, in `BindShortcuts`'s response and in later `ShortcutsChanged` signals, go to the shortcut's `OnKeys` (`HotkeyBound`): none when the user declined it, which KDE remembers without asking again. Under X11 (XWayland) `BindShortcuts` names the app's focused window, else its first shown one, as the parent of the desktop's dialog (`x11:XID`), which GNOME otherwise opens behind the windows in front; a Wayland window would need exporting first. The activation token of an `Activated` signal becomes the display's startup notification id while the callback runs, so the window it shows or focuses may take the focus. Under XWayland there is no Wayland display to give it to, and GNOME does not take the token as an X11 window's startup id (`_NET_STARTUP_ID`): the window shows without the focus. #### Why not GTK 4 The backend uses GTK 3 because a GTK 4 backend would do less, run on fewer systems and give apps nothing they lack on GTK 3, at the cost of rewriting most of `internal/linux`. **It would do less.** Some of what MyGo's API promises has no GTK 4 counterpart, not even a renamed one: * **Window placement.** GTK 4 has no `gtk_window_move`, `gtk_window_get_position`, `gtk_window_set_position` or `gdk_window_get_frame_extents`, on X11 too: an app cannot put a window anywhere or ask where it is. `Bounds`, `SetBounds`, `Center` and the frame handling above rest on them, and flyouts are anchored to a rectangle with `gdk_window_move_to_rect`, of a `GdkWindow` GTK 4 has no more. * **Window hints.** `gtk_window_set_keep_above`, `gtk_window_set_skip_taskbar_hint` and `gtk_window_set_type_hint` are gone: no always on top, no windows kept out of the taskbar, no utility or popup menu windows for flyouts and panels. * **Tray icons.** AppIndicator, which draws them, takes a `GtkMenu`, which GTK 4 removed with `GtkMenuBar`, and has no GTK 4 version: the backend would serve StatusNotifierItem and dbusmenu over D-Bus itself. Only X11 could get placement and hints back, through Xlib and EWMH beside GTK (`XMoveWindow`, `_NET_WM_STATE_ABOVE`, `_NET_WM_STATE_SKIP_TASKBAR`), and GTK 4.18 deprecated its X11 backend, to be removed in GTK 5: a GTK 4 backend would rest those features on what GTK is dropping. Wayland is no reason to move either: no GTK version places windows there. **It would run on fewer systems.** GTK 4 replaced ATK, which native UI's accessible tree implements (`surface_access.go`) and GTK 3 bridges to AT-SPI, with `GtkAccessible`, and only GTK 4.14 lets an app expose text it draws itself (`GtkAccessibleText`), which screen readers need to read native UI's text fields and editors. Ubuntu 22.04 ships GTK 4.6 and Debian 12 GTK 4.8, both still supported, where GTK 3 gives native UI the same accessibility as everywhere else. GTK 4 also means WebKitGTK 6.0, which replaces 4.1 and 4.0 rather than adding to them, so apps could no longer fall back to the WebKitGTK 4.0 of older distributions. **It would give apps nothing.** A MyGo window shows a web page or native UI, which MyGo draws itself; GTK's own widgets show only in title bar buttons, menus and dialogs. WebKitGTK 6.0 is the same WebKit as 4.1, built from the same releases, so pages render and behave the same. **And it would cost the rewrite.** Beyond the above, GTK 4 replaced the `button-press-event`, `motion-notify-event`, `key-press-event` and `configure-event` signals with event controllers and made `GdkEvent` opaque, where the backend reads its fields at fixed offsets (`field[T]`); removed `gtk_widget_event`, which hands Tab to the web view, and `GtkLayout`, which holds the web views over native UI; turned `GtkClipboard` and `gtk_drag_*` into `GdkClipboard` and `GtkDragSource`/`GtkDropTarget`; made menus `GMenuModel`s in popovers; and removed `gtk_dialog_run` and `gtk_native_dialog_run`, which run the main loop until a message or file dialog is answered so that the call that opened it returns the answer. The window manager quirks the bounds handling above works around would have to be found again on GTK 4, across the same X11 window managers and Wayland compositors. GTK 3 is still maintained, installed on every desktop MyGo targets, and what WebKitGTK 4.1, AppIndicator and gtk-layer-shell are built against. The trade turns once WebKitGTK stops releasing 4.1, GTK 3 leaves the distributions apps ship to, or those that are still supported all have GTK 4.14: then a GTK 4 backend loses nothing GTK 3 still gives, and the features GTK 4 lacks become X11-only code beside it. ### Windows (`internal/windows`) * Win32 is called through `syscall` (`LazyDLL` procs; system DLLs are loaded by absolute path from the system directory). `IsMainThread` compares the thread id recorded during package initialization. The loop is `GetMessageW`; `Signal` and `Wake` post messages to a hidden top-level application window, which also receives tray, hot key, theme (`WM_SETTINGCHANGE`) and display broadcasts. `Quit` posts `WM_QUIT`, which modal loops (dialogs, menus) forward, so quitting works while they run. * **COM.** `comCall` calls vtable methods; its indices come from `WebView2.h` (constants in `webview2.go`). Handler objects (event and completion handlers) share one vtable whose callbacks are created once and route `Invoke` to a Go function per object; the objects live in a map until COM releases them. Call wrappers are `go:uintptrescapes`, so `uintptr(unsafe.Pointer(&x))` arguments stay valid. * **WebView2 without a loader DLL.** `createEnvironment` finds the Evergreen runtime in the registry (`EdgeUpdate\ClientState\\EBWebView`) and calls `CreateWebViewEnvironmentWithOptionsInternal` of its `EmbeddedBrowserWebView.dll`, as `WebView2Loader.dll` does; a loader next to the executable wins. `internal/webview2` finds the runtime, for the backend and for `mygo doctor`: a directory holding that library for this architecture and the browser process `msedgewebview2.exe` at its root (the library alone is the Edge browser's, whose environments fail with `ERROR_NOT_SUPPORTED`), and EdgeUpdate's record of a runtime outlives its files. The first window that shows a web page starts the environment (`startEnvironment`), and fails without a runtime: windows that show native UI need none, so an app whose windows all do runs without WebView2. The environment and each controller are created asynchronously: window methods that need the webview wait in `pending`. A creation that fails is tried again, three times in all, a second then two apart, as Microsoft advises unless it failed with `ERROR_INVALID_STATE`: under load, WebView2 fails some with `ERROR_BUSY` or `CO_E_SERVER_EXEC_FAILURE`. When the webview never comes, the calls that report a result (Eval, CapturePage, PrintToPDF) get the reason, as later ones do: the window closed, or WebView2 could not create it. User data lives in `%LOCALAPPDATA%\\WebView2`. The direct path applies `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS` and `WEBVIEW2_USER_DATA_FOLDER` as the loader does; it does not read the channel variables or policy keys. * **Without WebView2 (`mygo_nowebview`).** What creates the environment (`startEnvironment`, `createEnvironment`, the loader and the runtime's lookup, `WebViewAvailable`) is in `webview2_env.go`, the only file that imports `internal/webview2`. The tag `mygo_nowebview` builds `webview2_env_off.go` instead: `startEnvironment` returns `errBuiltWithoutWebView`, so `NewWindow` of a page fails (and `mygo.NewWindow` panics with it), as do `NewWebView` and the cookie calls, and `WebViewAvailable` is false. Every call of `createWebView` is behind the constant `webViewBuilt`, false there, so the compiler drops it, and the linker the code that creates and drives web views (some 500 KB of `examples/counter-native`) and the strings antivirus heuristics flag (`WebView2Loader.dll`, `msedgewebview2.exe`, `CreateCoreWebView2EnvironmentWithOptions`, `WEBVIEW2_USER_DATA_FOLDER`). A new path to a web view goes behind `webViewBuilt` too. For native-UI-only apps, which pass it in `GOFLAGS` (`mygo build` adds those tags to its own); CI vets the backend with it. * **Custom schemes** load from `http://.localhost/`, and their other hosts from `http://..localhost/` (`internal/schemehost`: hosts of DNS labels, lower-cased, without a port), which WebView2 lets the app answer through `WebResourceRequested`. Its filters are added with `ICoreWebView2_22`'s `AddWebResourceRequestedFilterWithRequestSourceKinds` for documents (iframes of every origin, and their dedicated workers), or, on runtimes without it, `AddWebResourceRequestedFilter`, which reaches only the main frame and its same-origin iframes. Service and shared workers are left out: their requests reach every web view of the profile that filters them. Chromium treats `*.localhost` as a secure origin, and unlike `https`, `http` blocks no mixed content, so pages reach `ws://` and `http://` URLs as with the custom schemes of the other backends. The backend maps URLs both ways, so the core only sees `:///`. See "Custom protocols" for how responses reach WebView2. `LoadHTML` with a base URL serves the document from that URL the same way. * **Eval** goes through the DevTools protocol (`Runtime.evaluate` with `awaitPromise`), which reports syntax errors and ignores the page's CSP. Edit roles run `document.execCommand` with a user gesture, except Paste: `Input.dispatchKeyEvent` carries Chromium's `paste` command on an `Unidentified` raw key-down, followed by key-up once it completes. The page sees these events without modifiers, avoiding its Ctrl+V handlers, and a paste event with the clipboard's formats. The controller gets focus first, after the menu closes. Paste and Match Style still inserts the clipboard's text with `Input.insertText`. * Scripts injected at document creation run in every frame, so the main-frame-only ones (the bridge) are wrapped in `window === window.top`. Iframes get no `chrome.webview` handler. * **ABI.** On x64, structs over 8 bytes are passed by reference and Go mirrors the first integer arguments into the XMM registers, so doubles can be passed as bits. On ARM64, 16-byte structs travel in two registers and `syscall` cannot pass floats, so zoom falls back to CSS (`abi_*.go`); `comCallFloat` calls methods taking a double through purego instead, as `put_Expires` of cookies. Go callbacks read only integer registers: the two methods of UI Automation that take doubles enter through thunks in assembly (`uia_*.s`), which move the doubles' bits to the integer registers of their positions, touching only registers a call may change, and jump to the callbacks. * DPI: the process is per-monitor aware (v2); the backend converts sizes between pixels and DIPs with the window's or monitor's DPI, and points and rectangles of the screen (windows' bounds, the displays, the cursor, tray icons) through one space of DIPs in which displays never overlap and a point names one display (`dipSpace`, in `dips.go`, which builds on every platform for its tests): a display's DIPs start at its top-left pixel scaled by the smallest scale of the displays, as Qt anchors them at that pixel, and go on in its own scale. The primary display's DIPs, and those of displays that all have one scale, are the screen's pixels at that scale. A window takes the scale of the display it is the most on, whose DPI Windows gives it; it is created on its display, at its rectangle, and `place` moves it, keeping its rectangle in `WM_DPICHANGED`, whose suggested one would scale the size, already in the new display's scale, a second time (#1039). Frameless windows, and those with a hidden title bar, drop the caption in `WM_NCCALCSIZE` but keep the side and bottom borders, which Windows 10+ draws invisibly outside the window, so they still resize. On Windows 11 a hidden title bar keeps one pixel of its top, under the window's border, without which the maximize button opens no snap layouts while the window is not maximized. Windows 10, which has no snap layouts, keeps none: over a window that keeps any of its top it draws its whole title bar. A resizable frameless window on Windows 10 takes the visible pixel of its borders into its client area too, where the content covers the line DWM draws there, white whatever the content (#916), and its frame is not extended for the shadow, which its invisible borders cast: extended, it shows as a white line along the top. Other windows without a caption extend it by a pixel, without which a window with no borders has no shadow. The build comes from `RtlGetVersion`, which no manifest changes. * The top edge of a window without a caption (`topedge.go`), which `WM_NCCALCSIZE` gives to the client area, where the webview's or the surface's window answers `HTCLIENT`, is a child window above them: a layered window without a bitmap (`WS_EX_NOREDIRECTIONBITMAP`), as tall as the sizing frame, that answers `HTTOP`, and `HTTOPLEFT` and `HTTOPRIGHT` near the corners it reaches, and sends the window's presses on, so it resizes; Windows Terminal's caption works the same way. Below it, `--app-region: drag` still moves the window. It spans a frameless window and stops at a hidden title bar's buttons, and hides while the window is maximized, in full screen or not resizable. * A hidden title bar (`titlebar.go`) gets its controls from a child window above the webview's, beside the top edge. The buttons are a layered window (`UpdateLayeredWindow`, premultiplied BGRA): Segoe Fluent Icons glyphs (Segoe MDL2 Assets on Windows 10) drawn white on black with GDI give their coverage, over backplates of Chromium's alphas. It answers `WM_NCHITTEST` with `HTMINBUTTON`, `HTMAXBUTTON` and `HTCLOSE`, passes `WM_NCMOUSEMOVE` to `DefWindowProc`, which opens Windows 11's snap layouts over maximize, and runs the buttons itself from the non-client button messages, sending the window `WM_SYSCOMMAND`. The webview's window is created later, so the controls and the top edge go back to the top of the z-order when it appears. A window without a caption has no room for its menu bar: Alt and F10 open a popup holding the bar's own submenus. * **Menus** are Win32's (`menu.go`). Popup menus follow the appearance through uxtheme's preferred app mode (ordinal 135); the menu bar follows nothing, so the window draws it, and covers the light line below it when dark, from the UAH messages menus send their window (`darkmenu.go`). Windows 11 still draws Win32 menus as Windows 10 did, so there MyGo draws the items in the style of its own menus (WinUI's `MenuFlyout`, File Explorer's), in either appearance (`menudraw.go`): popup items are owner-drawn (`MFT_OWNERDRAW`, measured and drawn in `WM_MEASUREITEM` and `WM_DRAWITEM` of the window the menu shows for, or of the application window for trays), each into a bitmap with its highlight's rounded corners antialiased, then copied, and excluded from the DC after, which keeps Windows from drawing the submenus' arrows over the chevrons; `WM_INITMENUPOPUP` gives the menu the background of the items. Windows widens every owner-drawn item past the width it asks for, by as much as it doesn't tell (not `SM_CXMENUCHECK`, #922): items ask for all they need until one draws, whose width less the widest asked for in its menu is that widening at the DPI, and for that much less after. Labels are measured by their advance and drawn unclipped (`DT_NOCLIP`), into the item's padding where their ink reaches past it (Microsoft YaHei UI, Chinese Windows' menu font, by a pixel, #1028). The items keep their strings, which mnemonics, screen readers and the tests read. A menu with owner-drawn items loses Windows 11's frame, its window square under its class's drop shadow (`CS_DROPSHADOW`) along two sides: while menus show (`WM_ENTERMENULOOP` to `WM_EXITMENULOOP`, and around `TrackPopupMenuEx`, which creates its window before), a `WH_CALLWNDPROC` hook of the main thread rounds the windows of class `#32768` in their `WM_CREATE` (`DWMWCP_ROUND`, WinUI's 8 pixels), gives them one outline (`DWMWA_BORDER_COLOR`: a pixel of WinUI's `SurfaceStrokeColorFlyout` over the menu's background, `#00000019` in the light appearance and `#FFFFFF19` in the dark, a color of its own rather than the accent) and takes the shadow off the class, for DWM's around the window. It also subclasses them: on Windows 11 22H2 with transparency effects on, no contrast theme, energy saver off, outside remote sessions and with a GPU (`glassConditions`: DWM draws no material when the first DXGI adapter is Microsoft's Basic Render Driver or a software one, unless its `ForceEffectMode` policy is 2), a window that says (`MN_GETHMENU`, before it shows or paints) that it shows a menu MyGo draws gets Acrylic (`DWMSBT_TRANSIENTWINDOW`, in the appearance through `DWMWA_USE_IMMERSIVE_DARK_MODE`) with the frame extended over all of it, and is framed active (`WM_NCACTIVATE` to `DefWindowProc` as active with an lParam of -1, again once shown and whatever it is told after, as Firefox's popups with Acrylic are): DWM draws a system backdrop as a flat grey in a window it frames inactive, as a menu's window, never activated, otherwise is. Its background brush turns black, which DWM shows as transparent, its border too (`WM_NCPAINT`, and `WM_PRINT` for animations), and its items wear the veil of WinUI's Acrylic tint over the material: the fallback color at the opacity of its luminosity layer (`acrylicLuminosity`, 85% in either appearance), so that a menu is as light as the shell's flyouts over a dark desktop, the material showing a seventh of the way through, and the highlights and separators are WinUI's translucent fills over it, their rounded corners leaving DWM's window to show. The labels, the shortcuts and the icons go over the veil's own color, opaque, and once: what shows is the text as GDI draws it on the color the shell's menus draw theirs on, its ClearType blending with it, rather than the grayscale antialiasing of text drawn over black and over white for unblend to tell its alpha, and the pixels GDI leaves no alpha to take the item's. A window that shows another menu, as Windows' window menu, stays as it is, and so do its items. Elsewhere a menu MyGo draws has WinUI's solid background, the fallback of its Acrylic (`#F9F9F9`, dark `#2C2C2C`), its window's own border painted in it, for that one outline to be the menu's only border. Tray menus open on Windows 11 as the system's do, centered on the icon 12 DIPs from the taskbar (`ABM_GETTASKBARPOS`, aligned by `TrackPopupMenuEx` and kept off the taskbar by its `rcExclude`), and at the pointer on Windows 10 or for an icon not on the taskbar. The bar grows from `WM_UAHMEASUREMENUITEM` and its items get inset backplates with rounded corners. A contrast theme keeps the system's colors: the bar is Windows' again, the popup items take the system's. Windows 10 keeps its menus. * **Vibrancy** sets `DWMWA_SYSTEMBACKDROP_TYPE` (Windows 11 22H2) and extends the frame over the client area, behind a transparent webview or native UI. The material shows only in a window created without a redirection bitmap (`WS_EX_NOREDIRECTIONBITMAP`, which Windows neither adds nor removes later), whose opaque surface would cover it, so `SetVibrancy` shows one only in windows created with `Vibrancy`. A transparent window of native UI (`Transparent` with `Content`) is created without one too, as a flyout is, where DirectComposition is available: what its frames leave transparent shows what is behind the window. Such a window shows nothing GDI draws: it has no menu bar, like a window without a caption, and the buttons of its hidden title bar, layered without a bitmap too, show their pixels through DirectComposition (`compositor.go`), on a Direct3D 11 device the windows share (`internal/gpu/d3d11/device`, which links none of the renderer). A device found invalid after a failed draw, or whose GPU device signals its removed event (`ID3D11Device4::RegisterDeviceRemovedEvent`, waited for by a goroutine), is made again, and every window's buttons draw again; buttons that could not draw retry on a timer of the application window, a second later and longer after each failure in a row. Without DirectComposition, a window with a hidden title bar or native UI keeps its bitmap: what it draws shows, and the material does not. Native UI there draws on the GPU into a swap chain for composition, premultiplied by its alpha (`d3d11.NewComposed`), on a DirectComposition device of the renderer's own, and its frames drawn in memory show as the window controls do. A renderer about to draw takes the surface's window over from those (`Surface.Native`): a window has one DirectComposition target at most. `ui.Context.Vibrancy` tells the view whether the material shows (`platform.MaterialSurface`). * Message boxes are task dialogs (comctl32 v6, activated from shell32's manifest for executables without one); their structs are packed and laid out by hand. Notifications are notification-area balloons, which Windows 10+ shows as toasts. ### Browsers (`internal/web`) With `GOOS=js GOARCH=wasm`, `backend_js.go` picks `internal/web`, which shows windows of native UI (`WindowOptions.Surface`) on a page; windows of web pages, menus, trays, notifications, global shortcuts and file dialogs report `errUnsupported` or do nothing, as the browser has nothing to stand for them. Building for browsers adds nothing to desktop builds: the backend, `load_js.go` and `canvas_js.go` are `js` only, and the contract gained one field, `SurfaceNative.Canvas`. * **Size.** What only web pages use would make most of a build for browsers, which servers send whole (Cloudflare's static files are at most 25 MiB): the root's files for pages leave it out. `ipc.go`, `channel.go`, `bridge.go` (what windows say to the bridge: its script, messages, `Eval`), `protocol.go` (custom schemes, the frontend's, their downloads), `typescript.go`, `updater.go` (and `relaunchNow`), `single_instance.go`, `window_state.go` and `random.go` have twins (`_js.go`) that keep their API and do nothing, or report that there is no page, without the packages they need: net/http, net, crypto, encoding/json, internal/tsgen with go/parser, internal/update. Only `Protocol.Handle`, `HandleFunc` and `FileServer`, which take net/http's types, are missing there. `Bind` binds nothing, so nothing calls `reflect.Value.Method`, which would make the linker keep every exported method of every type in an interface. `internal/platform` takes an `http.Header` as its type, `map[string][]string`, so that ui does not import net/http either (importing it alone adds 2.3 MB), and `gpu.SourceSum`, for shaders compiled ahead of time, is not built for browsers, with crypto/sha256. The root's tests and `internal/e2e` are for desktops. What stays is mostly the runtime, ui and its packages, and the image codecs (`ui.Image`): `website/docs-demo` comes to about 9.8 MB (2.6 MB with gzip). * **Threading.** Go's main goroutine, which calls `Run`, is the main thread, told by its goroutine ID as `internal/fake` does. JavaScript calls Go's functions (`js.FuncOf`) on goroutines of their own, while the browser's event loop waits: `Backend.sync` hands the event to the main goroutine through `tasks` and waits for it, so that a handler can still call `preventDefault`. A callback that a call from Go to JavaScript sets off (a `focus()` firing `focus`) runs on the calling goroutine, the main one, and so runs at once. `Step`, for nested loops (`await`, `PopupMenu`), takes tasks as `Run` does, so the browser's events go on meanwhile; a nested loop must not start in a task, whose callback holds the browser's event loop, but from `Dispatch`. * **Windows** are elements of class `mygo-window` filling the element with the ID `mygo`, or else the page, each holding a canvas and a textarea. The page sets their size; `Bounds` reads the element's. The surface's size is the canvas's CSS size (DIPs) and `devicePixelRatio`, which a `ResizeObserver` and the window's `resize` watch; its backing store is set before each frame to the frame's size, `ceil(width × scale)` as package ui computes it. `RequestFrame` asks `requestAnimationFrame`; `Occluded` is `document.hidden`, where browsers give no frames, and `visibilitychange` brings `SurfaceShown`, or `SurfaceHidden`. * **Drawing.** The canvas's WebGL 2 context (`gl.NewContext`: premultiplied alpha, no depth, stencil or antialiasing) is current while a frame is handled, as a GtkGLArea's is in its render signal, and `SurfaceNative.Canvas` names it for `ui/gpu_js.go`. WebGL names its objects by JavaScript objects and GL by numbers: `load_js.go` numbers them (the number also a property of the object, which reads `FRAMEBUFFER_BINDING` back) and implements the GL functions `gl.go` calls on the current context, copying Go's bytes into one reused `Uint8Array` for uploads, which the pixel store's unpacking (tracked from `glPixelStorei`) sizes. With `WEBGL_blend_func_extended` the shader writes the second color as on desktops; without it (one color blended) subpixel glyphs could not draw, which browsers' text never has. A lost context is kept (`preventDefault`) and, once restored, renumbered (`Context.Renew`), which makes the renderer start over. Where the browser has no WebGL 2, the canvas takes a 2D context and `PresentPixels` puts the frames drawn in memory into an `ImageData`. * **Text** (`internal/text/canvas_js.go`) is the browser's: a 2D context measures and draws it, so that it finds fonts, falls back and shapes as for pages. Canvases give widths, not glyphs: the engine's glyphs are grapheme clusters (go-text's segmenter), each ending where the text of its word through it ends and starting its own width before, so that the word's kerning moves the cluster it applies to; they are drawn alone, with the font at the size they were measured at and the canvas scaled (at the pixels' size the system's font may take another optical size, as SF Pro Display for Text, whose glyphs the advances would not fit), their coverage read back (`getImageData` of a `willReadFrequently` context) and cropped to the ink. A line of text draws as the browser's `fillText` draws it whole, pixel for pixel. Fonts are shaded: a glyph is drawn in a gray of its text's shade, as Chrome's text, like AppKit's, is bolder the lighter its color (dark text drawn with white glyphs looks too bold), Thick in white; emoji take an unshaded twin of their font. Runs of scripts whose letters join or reorder (Arabic, the scripts of India, Thai, …) are one glyph each, shaped whole. Lines break at UAX #14's opportunities, and go-text's bidi package gives runs' levels, which the engine reorders (UAX #9's L2). Glyph IDs number the clusters' texts. Glyphs blend in turn (`join` false), at quarter-pixel positions, as Skia draws them. Chrome picks the optical size of the system font inconsistently between pages and canvases, so text of native UI can be wider or narrower than a page's in the same font. * **Input.** Pointer events (captured on press) are the pointer, with clicks counted from presses close in time and place, buttons 3 and 4 the back and forward keys. Those of a pointer that is not the primary one (`isPrimary`), as a second finger, are left out, as no second finger presses on the desktops; a button going down or up while another is held, which comes as a `pointermove` with its `button`, is a `PointerDown` or `PointerUp` as on the desktops (`chord`); their `pointerType` and `pressure` are the device and the pressure (`device`). `pointercancel`, the browser taking the pointer, as a touch it scrolls the page with, is a `PointerCancel`, not a release. `wheel` events scroll, lines and pages turned into DIPs, notches of 120 not `Precise`. The textarea, out of sight at the caret (`SetTextInput`), has the keyboard: `keydown` and `keyup` are keys, by what they type (`key`) and else by where they are (`code`); `beforeinput` brings typed text, which it cancels so that the textarea stays empty; composition events are the input method's. The browser keeps its defaults for keys that type, its own keys (F5, F11, F12) and those copying and pasting: the content copies on the key and the `copy` event that follows carries its text (the backend's clipboard) to the system's, while the clipboard's text comes with `paste`, which then sends the paste command. On a Mac, Command is `ModCtrl` and Control `ModSuper`, as package ui takes browsers for another system than macOS. * **Files dropped** (`files.go`): `dragover` on the canvas, with files, is `FileDragOver`, whose answer is the `dropEffect`, and the browser's default (opening the file, leaving the app) is always prevented; a `drop` reads the files' bytes (`arrayBuffer`, settled together; folders have none) before `FileDrop` gives their paths, `/mygo-drop//`. Go's syscall package calls the `fs` object of `wasm_exec.js`, whose functions fail in browsers: the backend wraps `open`, `read`, `fstat`, `close`, `stat`, `lstat` and `readdir` to answer for those paths, synchronously, as an app reads a drop in its handler, while the browser waits on the callback that sent the drop, and passes other paths on. * **Context menus** (`PopupMenu`) are HTML, styled as macOS's, in a nested loop until an item is chosen, a press lands elsewhere, Escape is pressed or the page loses focus; the choice goes to `MenuItemClicked`. * **Themes**: `IsDark` and `Preferences` read `matchMedia`, whose changes call `ThemeChanged`; the root's `data-mygo-theme` (watched by a `MutationObserver`) chooses the appearance over the media's. `ShowMessageBox` uses `alert` and `confirm`. * **History** (`ui/router_js.go`): the first `ui.Router` a window (not a `Tester`) shows claims the tab's history, through hooks the router calls (`browserHistory`, nil elsewhere). Its location goes in the URL's fragment and the number of its entry (`Router.base + at`, `base` counting the entries dropped past `maxHistory`) in `history.state`: `Push` is `pushState`, `Replace` `replaceState`, `Go` `history.go`, whose `popstate` finds the router there already. A `popstate` of the browser's own buttons goes to the entry of its number; one just before the router's first or after its last, as after a reload (which takes the number of the browser's entry for the router's), becomes the router's; a fragment typed in, without a state, is pushed. ### Phones (`internal/mobile`) With `GOOS=ios` or `GOOS=android`, `backend_mobile.go` picks `internal/mobile`, one backend for both: Go and the system meet in a host written in the system's language, Swift with UIKit on iOS (`internal/mobile/ios`), Kotlin with Android's views on Android (`internal/mobile/android`), which owns the process's UI thread and does what only it does well: the views, the web view and its delegates, the keyboard, accessibility, the system's dialogs and Swift-only or Java-only APIs. Phones' build modes need cgo to link (`c-archive` linked into the Swift host by swiftc, `c-shared` loaded by the Kotlin one), the only cgo of MyGo, in `glue_ios.go` and `glue_android.go` (with `jni_android.c`); the rest of the backend builds anywhere, and its tests run on desktops with a fake host. Desktop files of `darwin` and `linux` exclude `ios` and `android`, which their constraints otherwise include. * **Threads.** Go runs on a thread of its own, the core's main thread: the host's `mygo_start` (once the app launched) runs the app's `main` there, found with `go:linkname` as the build modes compile but don't run it, and `App.Run` loops over the host's events, as the browser backend does. Go's calls of the host run on the UI thread (`transport`): queued, then drained when the host runs `mygo_drain` (Go asks with `post`: a `DispatchQueue.main` block on iOS, a pipe the main `ALooper` watches on Android, so that no thread of Go's attaches to the JVM), or at once while the UI thread waits for Go's answer to an event it sent: a handler of `WillNavigate` may call the host. Neither side ever waits for the other without serving it, and `Step` waits for events without the UI thread, which goes on. * **Messages** (`internal/mobile/wire`) are numbered and binary, their fields in the order of `gen/spec.go`, from which `go generate` writes the Go side and the Swift and Kotlin ones (`Wire.swift`, `Wire.kt`): a `HostCalls` protocol the hosts implement and the encoders of events. A call without a reply is not waited for, so most cost Go a queue append; answers that come later (a dialog's, `CallAsync`'s) are events carrying the request's number. * **Windows** fill the screen, the one shown last in front. Their size is the root view's, and the insets of what covers it (the system's bars, the cutout, the keyboard) come with it (`Resized`): native UI lays out inside them (`platform.InsetSurface`, `ui`'s `padInsets`), pages inside the bars on Android and as WKWebView insets them on iOS. * **Pages.** WKWebView takes the app's schemes as `WKURLSchemeHandler`s and the bridge's messages through `messageHandlers.mygo`, as on macOS. Android's WebView loads no custom scheme: as WebView2, it is served the app's at `https://.localhost` (`schemehost.WebURLOf`, mapped back for the core), answered from `shouldInterceptRequest` with a stream Go writes. Android gives that no request's body, so a document-start script (`Schemes.bodyScript`) puts the bodies of `fetch` and XHR to those hosts aside through the host (`putBody`) and tags their requests with `X-MyGo-Body`, which the host looks them up by; a form's post still comes without one. The bridge posts through the host's JavaScript interface (`mygoAndroid`), and document-start scripts come from androidx.webkit. Android starts a page as it commits it (`onPageStarted`), when the core takes its URL to trust it, before its scripts run. * **Navigation** (`navigation.go`, `platform.NavigationBackend`, which only phones implement: desktops show the windows as windows). `Tabs` are UIKit's `UITabBarController` and Material's `BottomNavigationView`, a stack in each tab; `Window.Push` puts a window on its stack, a `UINavigationController` on iOS and a page with a `MaterialToolbar` on Android, and the user's back (the bar's button, iOS's edge swipe, Android's back) pops it, which the host reports (`Popped`) and the core takes as a close. A `ui.Router` with `SystemStack` shows its history as a window's stack (`platform.StackSurface`, `ui/router_stack.go`): before the frame that shows a new page presents, the core sends the stack (`SetStack`, waited for). iOS gives each page past the first a `RouteController`, moves the window's one surface into the screen shown, leaving a snapshot of the page going (`snapshotView`) in the screen it leaves, and flushes the transaction before answering, as Metal's frames show without waiting for UIKit's commit. A screen the user pops (`StackPopped`) takes the router back; the surface hides under the snapshot until the core presented the page there (`StackShown`). The router shows each page at once there, the system moving the screens; on Android the toolbar alone follows the stack and the router slides the pages. Each screen of native UI on iOS holds an empty scroll view over the surface (`ScreenController.titles`, clear, taking no touches), which UIKit takes for the page's content (`setContentScrollView`): iOS 26 draws a large title in it, and moves it with the page under the one a finger takes back, beneath it, as for a table; without one, it shows the title at once over that page. The surface's top inset is the scroll view's (`adjustedContentInset`), which counts the large title. Each window's insets come from where layout put it (Android: its position in the root, ignoring the translation of a page sliding in), so a window under a toolbar has no top inset and one above the tab bar no bottom one. iOS 26's bars float over the content: a scroll container flush with the root's padded bottom goes on under the bottom inset with as much more to scroll (`extendUnderBottom`), so lists pass under the tab bar's glass. Android colors its bars with the window's background (`SetBackground`), which a `SurfaceView` can't take itself, as it would hide the frames. * **Native UI.** iOS draws with the Metal renderer and Core Text, through purego as on macOS, on Go's thread: frames present through the command buffer (no transaction to present with, which needs a run loop) and Core Animation's transactions are flushed (`flushTransactions`); the renderer adds its CAMetalLayer to the view's layer, sizes it each frame, and uses shared storage, as iOS has no managed textures. Core Text's system font takes its weight from its descriptor, as there is no NSFont, and smooths nothing. Android draws with the GL renderer, OpenGL ES 3 in an EGL context of its own (`gl.NewWindow`) on the surface's ANativeWindow; the host waits for Go to let go of it before Android does (`SurfaceDestroyed`). Android's text is Minikin's and Skia's, through the host's `Paint` (`internal/text/paint_android.go`): an engine sharing the browsers' layout of grapheme clusters (`clusters.go`), whose words the host measures (`getTextRunAdvances`) and whose clusters it draws. These calls go straight to the host on the caller's thread (`callHere`, which joins the JVM), a screen of new text being hundreds of them. Frames come at the display's refreshes (CADisplayLink, Choreographer) when asked. * **Input.** A finger is the pointer while it touches (`SurfaceEvent.Touch`, the first one; two pinch), and `ui` pans what scrolls under one that moves and flings it on (`ui/touch.go`, reached only where touches come: `touch_mobile.go`, or a Tester touching). A finger on what scrolls presses only after `pressDelay` (Android's tap timeout, as UIKit's scroll views delay their content's touches) or as it lifts sooner, so a drag that starts at once presses nothing. Android's back goes first to the stack in front, then to the content as Escape and `KeyBack`, which `ui` reports taken when a shortcut claims it (a Router only while it can go back); untaken, the app goes to the background. `ui` tells the surface whether it takes back (`SetBackAvailable`), for Android's predictive back, which `ui.Router` follows (`ui/touch_back.go`, with iOS's edge swipe). A finger locks to an axis and a container, overscrolls and long-presses (`ui/touch.go`); all of it hangs on hooks `enableTouch` sets, for desktops not to link it. The hosts take the keyboard with `UITextInput` and an `InputConnection`, which edit the input's `TextInputClient` by UTF-16 ranges: they keep a copy of the text around the selection, and each edit's event waits for the state after it (`internal/mobile/textinput.go`), as keyboards read on at once; the content's own changes come with `SetTextInput`, checked after each frame. Selection handles draw in `ui` (`ui/touch_text.go`), the edit menu and the magnifier are the system's. VoiceOver and TalkBack ask for the accessibility tree when they read the window (`AccessibilityTree`), which turns on the content's (`AccessibilityOn`). * **Views in native UI.** A web view or a plugin's view is a window whose `Parent` is the surface's, under it in the host, in a view that clips it (`PlaceViews`), showing through the frames' holes (`scene.OpHole`) as on desktops. iOS gives the holder a `-1` z position, under the renderer's layer; Android's `SurfaceView` goes over the window (`setZOrderOnTop`, made again the first time, off the call that asked: the surface going waits for Go, which waits for the call). The hosts route fingers by the placements' boxes themselves, without asking Go. * **The background.** `Background` is waited for: on iOS the GPU is off limits once `sceneDidEnterBackground` returns, and iOS ends what uses it. `frame` draws nothing in the background, and asks again on the way back. * **Plugins' native code.** `mygo-plugin.json`'s `mobile` names Swift and Kotlin, which `cmd/mygo/mobile_plugins.go` copies into the host's sources with a generated `PluginRegistry`, and which `PluginCall` and `PluginEvent` reach (`Plugins.swift`, `Plugins.kt`, `native.go`), with JSON. Their frameworks, Info.plist keys, permissions and Gradle dependencies join the app's. * **Files** are watched with inotify on Android (`internal/inotify`, as on desktop Linux) and kqueue on iOS (`internal/kqueue`; see "Watching files"). * **Packaging** is the CLI's (`cmd/mygo/ios.go`, `android.go`): for iOS, swiftc compiles the embedded host and links it with the Go archive, actool compiles the icon, and the bundle gets the build keys App Store validation checks, a privacy manifest of the APIs the binary uses and the provisioning profile that fits; for Android, the embedded Gradle project goes into `.mygo/android` and builds with the app's libraries, manifest, icons and resources (copied out of the APK's assets on first launch, as `PathResources`). `mygo dev` installs and relaunches builds with simctl and adb, the environment of a launch passed as simctl's `SIMCTL_CHILD_` variables or an extra of Android's intent (which Go reads again as it starts, having copied the environment as its library loaded). ## IPC ### The page runtime (`packages/bridge` → `internal/bridge/bridge.js`) `packages/bridge/src/bridge.ts` is bundled by Bun into an IIFE and committed, so building an app never needs Bun. The core wraps it with the window's configuration (`bridge.Script`) and every backend injects it at document start into the main frame. It installs: * `window.mygo`: `call(method, ...args)`, `callWith(method, args, options)`, `on(event, fn)`, `once`, the `window` controls (`minimize`, `toggleMaximize`, `close`, …), `platform`, `windowId`, `version`. Frozen, so pages cannot tamper with it. * `window.__mygo.receive(messages)`, used by Go to deliver messages. * dom-ready notification and `--app-region: drag` handling for frameless windows (the mousedown is reported, the backend starts a window drag from the recorded mouse event while the button is down). * The `--mygo-titlebar-*` CSS variables of a window with a hidden title bar, in a constructed style sheet (a ` ``` Serve the directory over HTTP, with WebAssembly as `application/wasm`, as most servers do. A window fills the element with the ID `mygo`, or else the page; a window opened later covers the earlier ones. The page sets the window's size: the size, position and title bar options do nothing, and the title of the window opened last is the page's. ## What works * **Drawing.** Frames draw with WebGL 2 at the device pixel ratio, once for each of the browser's frames that something changed in; effects, as [Liquid Glass](https://mygo.egoist.dev/docs/plugins/glass.md), draw as on the desktop. Where the browser has no WebGL 2, frames draw in memory and show through a 2D canvas. A lost WebGL context draws again once the browser restores it. * **Text** comes from the browser, which finds the fonts, falls back for what one lacks and shapes, as for its pages: `system-ui` is the system's font, as a page's. Lines break and runs order (bidi) as in package text everywhere. Text is not drawn with subpixel antialiasing. * **Input**: the pointer, with the clicks counted; the wheel and touchpads; keys; input methods, which compose in a text area out of sight at the caret; and the clipboard's text, through the browser's copy, cut and paste. On a Mac, ⌘ is Control for the view's shortcuts, which take a browser for a system other than macOS. A Mac's browsers tell of no key let go of while ⌘ is held: it goes up with ⌘ ([`c.KeyDown`](https://mygo.egoist.dev/docs/ui/input.md#keys-held)). * **Routers.** The first [router](https://mygo.egoist.dev/docs/ui/navigation.md) a window shows follows the tab's history, in the URL's fragment, as `#/notes/42`: the browser's back and forward buttons go through its pages, and a link to a page, or a reload, opens the app there. * **Files dropped** on a window: `DroppedFiles`, `FileDragOver` and `OnFileDrop` work as on desktops. Browsers give no paths, so the backend reads the files as they drop and keeps them at paths of its own, as `/mygo-drop/3/photo.png`, which `os.Open`, `os.ReadFile`, `os.Stat` and `os.ReadDir` read; the files of the last 16 drops stay. * **Context menus** show as menus of HTML on the page. * **Dark mode**, reduced motion and more contrast follow the browser's settings, and change with them. A page can choose the appearance itself with `data-mygo-theme="dark"` or `"light"` on its root element, as one framing the app does to give it its own theme (a frame's `prefers-color-scheme` follows the browser, not the page around it). * `Dialog.Message` asks with the browser's `alert` and `confirm`, and `Shell.OpenExternal` opens a tab. ## What does not Windows of web pages, application and Dock menus, trays, notifications, global shortcuts, file dialogs and the drag and drop of data other than files have nothing in a browser to stand for them, and report so. Assistive technology does not see the content yet. Of a style's OpenType features, canvases apply `kern` only. A font added with `ui.RegisterFont` needs its family, and draws once the browser loaded it. The clipboard's text comes from the system when a paste brings it: the view's own Paste command pastes what the app copied last. ## Size The counter example is 8.2 MB of WebAssembly, 2.2 MB compressed with gzip, and the previews of these docs, with every component, 9.8 MB (2.6 MB). Builds for browsers leave out what package `mygo` has for web pages, which they do not show: its IPC, custom schemes and their HTTP, the TypeScript generator, the updater, with the JSON and the cryptography they take. Their API stays, doing nothing: `Bind` binds nothing, events reach no page, `Updater.Check` reports `ErrUpdatesDisabled`. Only `Protocol.Handle`, `HandleFunc` and `FileServer`, which take net/http's types, are missing, so that code using them is for desktops (`//go:build !js`). The tag `mygo_noinspector`, which `mygo build` sets for production, leaves out the inspector of native UI too, some 350 KB. Building for browsers adds nothing to apps for desktops: the browser's code is only in `js/wasm` builds. ## Under the hood Go's main goroutine runs the event loop; the browser's events reach it through the functions JavaScript calls, which wait for it to handle them, so that they can still prevent the browser's defaults. The architecture guide's [Browsers](https://mygo.egoist.dev/docs/architecture.md#browsers-internalweb) section has the details. --- Source: https://mygo.egoist.dev/docs/ui/button.md # Button `ui.Button` creates a push button showing a label, and `ui.PrimaryButton` one in the accent color, for the main action of a window or a dialog. `Clicked` reports a click, or Enter or Space while the button has the keyboard focus: ```go ui.Row(c).Gap(8).Justify(ui.End).Children(func() { if ui.Button(c, "Cancel").Clicked() { app.editing = false } if ui.PrimaryButton(c, "Save").Clicked() { app.save() } }) ``` ## Content A button lays out its children in a row and gives them its text color. Give it other content, as an icon before the label, with `Children` and an empty label: ```go ui.PrimaryButton(c, "").Children(func() { ui.Icon(c, save) ui.Text(c, "Save").SingleLine() }) ``` A button showing only an icon needs a `Label`, which names it for assistive technology, and a `Tooltip`: ```go if ui.Button(c, "").Label("Delete").Tooltip("Delete").Children(func() { ui.Icon(c, trash) }).Clicked() { app.delete() } ``` ## States `Disabled(true)` grays a button out: it takes neither clicks nor the focus. `AccessDisabled(true)` only tells screen readers it is unavailable, while it keeps the focus and its look, for one they must still reach, as a submit button while the form is not valid: see [accessibility](https://mygo.egoist.dev/docs/ui/accessibility.md#unavailable-still-reachable). In a [toolbar](https://mygo.egoist.dev/docs/ui/toolbar.md), buttons take no face of their own until hovered. A default button that Enter presses wherever the focus is takes the key with a [shortcut](https://mygo.egoist.dev/docs/ui/input.md#shortcuts): ```go if ui.PrimaryButton(c, "Sign in").Clicked() || c.Shortcut(0, ui.KeyEnter) { app.signIn() } ``` A focused button keeps Enter and Space for itself, so the shortcut fires only when the focus is elsewhere. ## Style The button returns its element: calls after it change its look, as `ui.Button(c, "Save").Padding(10, 20).Radius(999)`. `ui.ButtonBase` is a button without a look, a row that takes the focus and reports `Clicked`, for a design of your own: see [custom widgets](https://mygo.egoist.dev/docs/ui/custom-widgets.md). ## Accessibility Assistive technology sees a button named by its text or its `Label`, which it presses as a click does. ## Click actions Use `Clicked()` for inline control flow or `OnClick` to run an action after construction: ```go ui.Button(c, "Save").Disabled(app.saving).OnClick(app.save) ``` The callback sees the final configuration and runs after bound-value input. It can change the model without interrupting a loop that is building controls. Handled input is consumed before the view rebuilds. See [Events and actions](https://mygo.egoist.dev/docs/ui/views.md#events-and-actions) for choosing between queries and callbacks. --- Source: https://mygo.egoist.dev/docs/ui/calendar.md # Calendar `ui.Calendar` creates a month's calendar choosing the day of a `*time.Time`, as SwiftUI's graphical date picker: a click chooses a day, as the arrows do while the calendar has the keyboard focus; Page Up and Page Down, or its buttons, move by months, and Home and End go to the first and the last day of the month. `Changed` reports a new date, which keeps the time of day and the location of the value. ```go ui.Calendar(c, &app.day).Label("Due date") ``` It shows six weeks from the first day of the week of the user's regional formats (`Context.Region`: Sunday in the United States, Monday in most of Europe), the days of the months around in gray, and marks today. Its title ("January 2026", "2026年1月"), the names of the weekdays and the days' names for assistive technology are CLDR's in the window's language, its days in the language's digits; the buttons' names are [MyGo's own strings](https://mygo.egoist.dev/docs/i18n.md#mygos-own-strings). For a date in a compact field, use a [date input](https://mygo.egoist.dev/docs/ui/date-input.md), which opens this calendar below it. ## Browsing without choosing `Browse` lets the user look about the calendar without choosing a day: its buttons and Page Up and Page Down only show other months, and the arrows, Home and End only move among the days, until a click, Enter or Space chooses one, as in a date input's calendar. `Changed` then reports only a day the user picked, as a calendar in a [popover](https://mygo.egoist.dev/docs/ui/popover.md) that closes when a day is picked needs: ```go chip := ui.Button(c, task.Due.Format("Jan 2")) if chip.Clicked() { app.dueOpen = !app.dueOpen } ui.Popover(c, chip, &app.dueOpen, func() { if ui.Calendar(c, &task.Due).Browse().Changed() { app.dueOpen = false } }) ``` The calendar goes back to the value's month as the app sets another date. ## Accessibility Assistive technology sees a table named by its month, whose days are buttons named by their dates, the day chosen checked, and reads the day chosen as the arrows move; with `Browse`, the day the arrows are on. --- Source: https://mygo.egoist.dev/docs/ui/chart.md # Charts Package `ui/chart` builds charts without a look of their own, as headless libraries such as visx do on the web, with the parts of Swift Charts: scales that map data onto a plot and pick round ticks, a plot with axes around it, marks that are elements you style as any other, paths of lines, areas and pie slices for `Draw` functions, stacking, and a selection that the pointer and the keyboard move. Every color, size and font is yours. ```go import "github.com/egoist/mygo/ui/chart" t := c.Theme() x := chart.NewBand(app.months...).Padding(0.3, 0.15) _, hi := chart.Extent(app.sales...) y := chart.NewLinear(0, hi).Nice(4) ticks := y.Ticks(4) chart.Plot(c, chart.Axes{Left: ticks, Bottom: x.Ticks()}, func(area ui.Element) { area.Draw(func(p *ui.Painter, r ui.Rect) { for _, tick := range ticks { // grid lines p.Line(r.X, chart.Y(r, tick.At), r.X+r.W, chart.Y(r, tick.At), 1, t.Border) } }) for i, v := range app.sales { chart.Rect(c, x.Band(i), y.Span(0, v)).Radius(4).Background(t.Accent). Tooltip(fmt.Sprintf("%s: %.0f", app.months[i], v)) } }).Label("Sales by month").Height(200).Gap(6) ``` Positions on a plot are fractions of it, from 0 to 1: along x from its left edge, and along y from its bottom up, the way values grow. Scales turn data into fractions; marks place themselves in percentages of the plot, so they are built without waiting for the layout and follow the plot as it resizes; `Draw` functions get the plot's box, and `chart.X(r, f)` and `chart.Y(r, f)` turn fractions into points in it. ## Scales * `chart.NewLinear(lo, hi)` maps numbers. `Nice(n)` rounds the domain out to the round values of about n ticks, and `Ticks(n)` returns them: 1, 2 or 5 times a power of ten apart, as d3 and Swift Charts pick them, with as many decimals as the step needs, or labeled by `Format`. `At(v)` is where a value is, `Span(a, b)` the stretch between two, as a bar's from 0 to its value, and `Invert(f)` the value at a fraction, as under the pointer. `Clamp` keeps values outside the domain at its ends; `chart.Extent(values...)` returns the smallest and the largest. * `chart.NewLog(lo, hi)` gives equal ratios equal distances: 1, 10 and 100 are equally spaced. Both ends must be positive or both negative; reversed domains work too. `Base` defaults to 10 (2 and `math.E` work too); it changes ticks and `Nice()`, not the positions. `Nice()` extends to whole powers of the base. `Ticks(n)` is a density hint: short domains with integer bases include minor multiples, whose labels are omitted when crowded. `Format` labels every tick when set. Constant domains get one tick at their value, including noninteger bases. * `chart.NewSymLog(lo, hi)` includes negative values and zero, using `sign(v) * log1p(abs(v)/c)`. `Constant` is c, 1 when zero: the size of the nearly linear region around zero; larger magnitudes are logarithmic. `Ticks(n)` and `Nice(n)` choose round numbers in the original units, placed nonlinearly. A nonpositive count, or a nice request that does not settle on a stable domain, leaves the original domain unchanged. * `chart.NewBand(labels...)` gives each label a band, as the bars of a bar chart: `Band(i)` is the i-th's stretch, `At(i)` its middle, `Width()` their width, and `Index(f)` the band at a fraction. `Padding(inner, outer)` leaves room between the bands and around them, in fractions of a band's step. Its `Ticks()` are the labels, in the middle of their bands. * `chart.NewTime(from, to)` maps times. Its ticks fall on round times in the times' location, chosen for the span as d3's are: seconds, quarters of an hour, midnights, Sundays, the firsts of months or years; and each is labeled with what changed since the last round time of the coarser unit: "2026", "Mar", "Mar 5", "14:00", ":30". Ticks are `chart.Tick` values, `At` a fraction, `Value` and `Label`: make your own for axes a scale does not mark. ### Wide ranges and signed data ```go latency := chart.NewLog(0.01, 1000) // milliseconds, five orders of magnitude position := latency.At(0.1) // 0.2 of the plot value := latency.Invert(0.5) // about 3.162 ms changes := chart.NewSymLog(-1000, 1000) changes.Constant = 10 baseline := changes.At(0) // 0.5; zero is valid bar := changes.Span(0, -100) // a signed bar around that baseline ``` Both scales have `At`, `Invert`, `Span`, `Clamp` and `Format`, as `Linear` does. Keep the domain in data units; apply `At` to each sample, then use normal marks and paths. A logarithmic bar needs a nonzero baseline: use `SymLog` for bars around zero. NaN samples propagate as missing values, which line and area paths leave as gaps. Without clamping, values of the wrong sign give NaN on a log scale and zero maps to infinity off its plot. With `Clamp`, out-of-domain values, including zero, stay at the ends. Domains must be finite. A log domain cannot touch or cross zero, its nonzero base must be finite and greater than 1, and a symlog scale's nonzero constant must be finite and positive. Invalid scales give NaN positions and no ticks; `Nice` leaves them unchanged. At the float64 limits, log `Nice` retains an edge if the next power is unrepresentable. The scales are values with no mutable caches or timers; they add no runtime dependency. The gallery's Charts page compares linear and log latencies, and lets you change the symlog linear region. ## The plot and its axes `chart.Plot` lays the plot's area out in a grid with an axis on each side that `chart.Axes` gives ticks to: `Left` and `Right` along the height, `Top` and `Bottom` along the width. The labels stay in the layout, so the axes take the room they need, and the area the rest: give the plot a height, or `Fill` its parent, and a `Gap` (or `GapX` and `GapY`) between the labels and the area. `Axes.Label` builds each label, centered on its tick; it is plain text by default. Labels sit in boxes of no width or height that center them, so keep their text on one line with `NoWrap`: ```go label := func(side chart.Side, tick chart.Tick) { ui.Text(c, tick.Label).NoWrap().FontSize(11).TextColor(t.TextMuted) } chart.Plot(c, chart.Axes{Left: y.Ticks(4), Bottom: x.Ticks(), Label: label}, build) ``` The function of `Plot` gets the area, an element to style, with a background, a border or a `Draw` function painting grid lines and lines, and to add marks to. ## Marks Marks are elements in the area, placed in percentages of it: style them, name them for assistive technology, give them tooltips, and handle their clicks, as any element. * `chart.Rect(c, x, y)` covers a stretch along x and up y: a bar, a band of a range, a cell of a heat map. * `chart.Point(c, x, y, w, h)` is w by h DIPs, centered on a point: a dot of a scatter plot, the point a selection is on. * `chart.RuleX(c, x, width)` is a vertical line across the plot, and `chart.RuleY(c, y, height)` a horizontal one: a threshold, an average. * `chart.Anchor(c, x, y, h, v, build)` places what `build` adds at a point, of any size: `ui.Center` centers it there, `ui.Start` puts its left (h) or top (v) edge there, and `ui.End` its right or bottom edge, so that `ui.Center, ui.End` shows a label above a bar. ```go for i, v := range app.sales { bar := chart.Rect(c, x.Band(i), y.Span(0, v)).Background(t.Accent) if bar.Clicked() { app.month = i } chart.Anchor(c, x.At(i), y.At(v), ui.Center, ui.End, func() { ui.Text(c, fmt.Sprint(v)).NoWrap().FontSize(11).Margin(0, 0, 4, 0) }) } ``` A mark with a [`Transition`](https://mygo.egoist.dev/docs/ui/transitions.md) moves to its new place as the data changes, as bars growing to new values: ```go chart.Rect(c, x.Band(i), y.Span(0, v)).Background(t.Accent). Transition(ui.ElementTransition{Duration: 300 * time.Millisecond}) ``` ## Lines and areas `chart.Line(r, xs, ys, curve)` returns the path of a line through points, and `chart.Area(r, xs, lo, hi, curve)` the path of the area between two lines, for a `Draw` function of the area to stroke and fill. `xs` and `ys` are fractions, as scales return; nil `lo` is the bottom of the plot, and a NaN breaks the line or the area there, for missing values. The curve joins the points: `chart.CurveLinear` with straight lines, `chart.CurveMonotone` smoothly, without going past the values of the points it joins, and `chart.CurveStepAfter`, `CurveStepBefore` and `CurveStep` in steps. ```go area.Draw(func(p *ui.Painter, r ui.Rect) { p.FillPath(chart.Area(r, xs, nil, ys, chart.CurveMonotone), t.Accent.Alpha(0.15)) p.StrokePath(chart.Line(r, xs, ys, chart.CurveMonotone), 2, t.Accent) }) ``` ### Live data A line of thousands of samples, redrawn every frame as new ones arrive, needs fewer points than it has samples: `chart.MinMax` keeps the lowest and highest sample of each pixel column, in their order, and the ends of each run, so that the line looks the same and narrow spikes still show. Its `xs` are fractions that never decrease; a NaN still breaks the line. It writes into the slices you pass, and `chart.LineInto` into the path you pass, so that a view keeping them draws without allocating once warm. Keep the samples themselves for selections and readings. `Painter.StrokePolyline` strokes points in DIPs with round joins and caps, as `StrokePath` would, faster for lines that change every frame: on a GPU it draws each segment as a rounded rectangle, rather than rasterizing the whole line into a mask on the CPU. Where segments overlap, their antialiased edges can look a little bolder than `StrokePath`'s. Translucent lines, and drawing without a GPU, take `StrokePath`'s way, since overlapping segments would show darker there; a translucent line of one segment has none to overlap, and stays fast on a GPU. ```go // bx, by and points live in the view's state, reused every frame. area.Draw(func(p *ui.Painter, r ui.Rect) { bx, by = chart.MinMax(bx, by, xs, ys, int(math.Ceil(float64(r.W*p.Scale())))) points = points[:0] for i, x := range bx { points = append(points, [2]float32{chart.X(r, x), chart.Y(r, by[i])}) } p.StrokePolyline(points, 2, t.Accent) }) ``` Ask for frames with `Context.AnimationFrame` and take in the samples that arrived since the last one, rather than invalidating per sample. `examples/chart-streaming` scrolls three waveforms of 15,000 samples, 1,000 a second each; `-mode path` and `-mode raw` draw them with `StrokePath`, to compare. ## Stacks `chart.Stack(series, how)` piles series up, as stacked bars and areas show them: `series[s][i]` is the i-th value of the s-th series, and the result's `[s][i]` the `Segment` it covers in the i-th stack. `chart.StackStandard` piles values up from 0, and negative values down from it; `chart.StackNormalized` in shares of the stack's sum, from 0 to 1; and `chart.StackCenter` around 0, as a streamgraph. ```go stacked := chart.Stack([][]float64{app.search, app.direct}, chart.StackStandard) for s, series := range stacked { for i, seg := range series { chart.Rect(c, x.Band(i), y.Span(seg.Lo, seg.Hi)).Background(colors[s]) } } ``` ## Pies and donuts `chart.Pie(values, pad)` divides a circle among values, in their order from twelve o'clock, with `pad` radians between them, and `chart.Sector(cx, cy, inner, outer, slice)` returns the path of a slice: a wedge with `inner` 0, a piece of a donut otherwise. `chart.SliceAt` finds the slice at a point, as under the pointer, and `chart.Polar` the point at an angle, where a slice's label goes: ```go slices := chart.Pie(app.shares, 0.03) ring := ui.Box(c).Size(160, 160).Label("Users by platform") hover := -1 if x, y, over := ring.PointerPosition(); over { if i, ok := chart.SliceAt(slices, x-80, y-80, 50, 80); ok { hover = i } } ring.Draw(func(p *ui.Painter, r ui.Rect) { for i, s := range slices { outer := float32(76) if i == hover { outer = 80 } p.FillPath(chart.Sector(r.X+80, r.Y+80, 50, outer, s), colors[i]) } }) ``` ## Selection `chart.Select` makes the area choose one of the points at `xs`, in ascending order, as Swift Charts' `chartXSelection`: the one nearest the pointer while it is over the area, and none (-1) once it leaves. The area takes the keyboard focus, as one stop of Tab, and the left and right arrows, Home and End move the choice while it has it, and Escape clears it. It reports a new choice. Show the choice with marks: ```go describe := func(i int) string { return fmt.Sprintf("%s: %.1f °C", hours[i], temps[i]) } chart.Select(c, area, &app.selected, xs, describe) if i := app.selected; i >= 0 { chart.RuleX(c, xs[i], 1).Background(t.TextMuted) chart.Point(c, xs[i], ys[i], 10, 10).Radius(5).Background(t.Accent) chart.Anchor(c, xs[i], 1, ui.Center, ui.Start, func() { ui.Text(c, describe(i)).NoWrap().Padding(3, 8).Radius(6).Background(t.Surface) }) } ``` For the points of a band scale, `xs` are their middles; `chart.Nearest` finds the point nearest a fraction for selections of your own, and a band's `Index` the band. ## Repeated queries of growing data `MinMax` is stateless and takes plot fractions. For large histories that mostly stay unchanged, keep a `MinMaxIndex` per series instead. `Update` borrows the full raw X and Y slices and indexes only their appended suffix; `Query` maps X to fractions for the requested viewport and leaves Y unchanged: ```go var index chart.MinMaxIndex var dx, dy []float32 // After appending samples to rawX and rawY: index.Update(rawX, rawY) // In the plot's Draw callback, with finite float32 viewport bounds lo < hi: dx, dy = index.Query(dx, dy, lo, hi, int(math.Ceil(float64(r.W*p.Scale())))) p.StrokePath(chart.LineInto(&path, r, dx, dy, chart.CurveLinear), 2, color) ``` Declare `path` as a retained `ui.Path`. `StrokePolyline` can use these same fractions after converting them with `chart.X` and `chart.Y`. Keep the raw samples for precise cursor readings; reduced points are drawing geometry. X must be nondecreasing within each finite run. NaN and infinity in either input break the line. Query uses float32 `(x-lo)/(hi-lo)`, including its rounding, before assigning pixel columns, and preserves MinMax's first equal extremum, time order and boundary neighbors. Invalid bounds, an overflowing span, or a nonpositive pixel width return empty output. Do not modify existing samples while indexed. Reallocation from appending is fine, but replacing data, editing it or removing its prefix requires `Reset` followed by `Update` of the retained history. Reset releases all borrowed slices and index memory. Bound your own history and rebuild periodically for a sliding window, as `examples/chart-streaming` does. Do not copy a populated index or access it concurrently; output must not alias input. Pan, zoom and DPI changes need only another query, without a rebuild. The index stores two original sample positions per completed 16-sample block and per completed pair of blocks above it. Construction is O(N), append amortizes to O(K) for K new samples, and storage is O(N/16 + R), where R is the finite-run count. On 64-bit systems the completed hierarchy uses about two bytes per sample before slice capacity slack, plus run bounds. Queries binary-search each run, skip whole blocks inside a pixel column, and scan blocks crossing a column boundary. Dense-query work is O(R log N + P log N + 16P), bounded by a full scan, for P occupied columns; highly fragmented input can still require visiting every run. A reusable normalization buffer handles low-density visible ranges with MinMax. For small data, a single query, frequently edited samples, or very many gaps, prefer `MinMax`: building an index may cost more than it saves. For a tiny visible fraction of sorted finite X, binary-searching the visible slice and calling MinMax may already suffice; retain one neighbor on each side and preserve gap markers. Index construction, capacity growth and explicit rebuilds allocate; warmed queries reuse their buffers. ## Accessibility Name the plot with `Label` and say what it shows with `Description`. Marks are elements: name each one assistive technology should read, as a bar's month and value. `Select` tells it about the chosen point: what `describe` returns is the area's value, which screen readers read out as the arrows come to a point. What the package leaves out: zooming and panning, legends (rows of your own, as above) and labels that avoid each other. --- Source: https://mygo.egoist.dev/docs/ui/checkbox.md # Checkbox `ui.Checkbox` creates a check box toggling a `*bool`, with a label: a click on the box or its label checks it or unchecks it, as does Space while it has the keyboard focus, and `Changed` reports a click. ```go ui.Checkbox(c, &app.settings.Sync, "Sync across devices") if ui.Checkbox(c, &app.showHidden, "Show hidden files").Changed() { app.reload() } ``` The check box changes the value itself, the moment the user clicks: read it, or ask `Changed` for work that follows. ## Groups `ui.CheckboxGroup` creates a check box over the check boxes built inside it, indented below it, as a list of permissions: it is checked when they all are, mixed when some are, and a click, or Space while it has the focus, checks them all, or none when they all are. `Changed` reports a click. ```go ui.CheckboxGroup(c, "Notifications", func() { ui.Checkbox(c, &app.mail, "Mail") ui.Checkbox(c, &app.calendar, "Calendar") ui.Checkbox(c, &app.messages, "Messages") }) ``` ## Mixed `ui.CheckboxState` is a check box that can be mixed, as a "select all" box in a table's header: checked when every row is, mixed when some are. It sets a `*ui.CheckState`, `ui.CheckOff`, `ui.CheckOn` or `ui.CheckMixed`, and shows a dash while mixed; a click, or Space while it has the focus, checks it, or unchecks it once it is checked, and `Changed` reports a click: ```go all := ui.CheckOff switch n := app.selected(); { case n == len(app.rows): all = ui.CheckOn case n > 0: all = ui.CheckMixed } if ui.CheckboxState(c, &all, "").Label("Select all").Changed() { app.selectAll(all == ui.CheckOn) } ``` `CheckboxGroup` is such a check box over the check boxes it holds. ## Without a look `ui.CheckboxBase` is a check box without a look: a row that toggles its `*bool` when clicked, which you draw from the value, and `ui.CheckboxStateBase` one that sets a `*ui.CheckState`, as `CheckboxState` does: see [custom widgets](https://mygo.egoist.dev/docs/ui/custom-widgets.md). ## Accessibility Assistive technology sees a check box named by its label, checked or not, which it toggles as a click does, and one that can be mixed checked, unchecked or mixed. A check box group is a check box, mixed while some are checked, and a group of the others named by its label. --- Source: https://mygo.egoist.dev/docs/ui/code-editor.md # Code editor Package `ui/editor` is a code editor and a [diff viewer](https://mygo.egoist.dev/docs/ui/diff-viewer.md) for native UI, designed after Zed's: syntax highlighting, several carets and selections, soft wraps, folding, finding and replacing, completions, hovers, diagnostics and inlay hints from the app or a language server, ranges shown as something else, and the commands and keys of code editors. It lays out and paints only the lines in view, so a file of a million lines scrolls and edits as one of ten. ```go import "github.com/egoist/mygo/ui/editor" // Kept by the app, as its other state. buf := editor.NewBuffer(source) buf.SetLanguage(editor.LanguageFor("main.go")) app.code = &editor.State{Buffer: buf, WrapGuides: []int{100}} // In the view: editor.View(c, app.code).Grow(1).FillWidth() ``` A `State` is the editor's state, kept across frames as a text input's string is: its buffer, its options, and what the editor keeps of its own, as its selections, folds and scroll position. Its options are fields set before the editor is built; their zero values are the defaults, those of Zed. `View` builds the editor of a state, which is a focusable element as any other: give it a size, and `AutoFocus` to type in it at once. The [code editor example](https://github.com/egoist/mygo/tree/main/examples/code-editor) edits files of several languages, with completions of the words of the file, hovers, diagnostics of TODO comments, the changes in the gutter and their diff. ## Buffers A `Buffer` is the text an editor edits, with its undo history and its language. Several editors, and both sides of a diff, can show one buffer: an edit in one shows in the others, their carets moving with the text around them, and undo takes back the buffer's last edit, whichever editor made it. ```go buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// Generated.\n"}) buf.Transact(func() { // one step of undo buf.Edit(editor.Edit{Start: a, End: b, Text: name}) buf.Edit(editor.Edit{Start: c, End: d, Text: name}) }) if buf.Modified() { _, err := buf.WriteTo(file) if err == nil { buf.MarkSaved() } } ``` Offsets count bytes of UTF-8, and a `Pos` is a line and the bytes into it, both from 0: `Pos` and `Offset` convert between them, and `Line`, `Slice` and `String` read the text. `Set` replaces the text as an edit, which undo takes back, and `Reset` as a new document, without history. `EditRemote` applies edits made elsewhere, as another device's or the result of a merge, outside the history. Undo and redo go on taking back and making again the buffer's own steps, on the text with those edits: ```go buf.Edit(editor.Edit{Start: 0, End: 0, Text: "// Mine.\n"}) buf.EditRemote(editor.Edit{Start: end, End: end, Text: "// Theirs.\n"}) buf.Undo() // takes back "// Mine.", and "// Theirs." stays ``` A step that overlaps a remote edit can no longer be taken back or made again alone: it leaves the history, the text staying as it is, and the steps around it stay. Inserting at the edge of a step's text does not overlap it, nor does replacing the text next to it. So pass the ranges that changed, from a diff of the two texts, rather than the whole text, which overlaps every step. Carets, selections, folds, diagnostics and inlays move through a remote edit as through any, and `Modified` still compares with the saved text: call `MarkSaved` when the new text is what is on disk. A remote edit moves every step of the history, around a millisecond for a full one of 10,000 steps, whatever the size of the text. Lines end in `\n`, as in Zed: a text with `\r\n` or `\r` line endings is kept with `\n` ones, and the buffer remembers the ending of each line, which `WriteTo` writes, so that a file saves as it was, mixed endings and all. An edit changes only the endings of the lines it breaks or joins: a line broken in two, as with Enter, ends both halves as it ended, deleting a line break keeps the one after it, and line breaks pasted take the endings of those they replace, then the ending of the line they go in, whatever the clipboard had; moving lines up or down moves their endings with them. A line ending in `\r` followed by an empty line ending in `\n` would be written `\r\n`, which reads back as one line break, so the empty line's break becomes `\r\n`. Undo and redo put endings back with the text. `LineEnding` says which ending most lines have, and `SetLineEnding` converts every line to one. The text is a persistent tree of chunks, as Zed's rope: an edit copies a few kilobytes and a path of the tree, whatever the size of the document, and each version shares the rest with the one before. Undo keeps the edits that take each step back, and a `Snapshot` is a version that stays as it is while the buffer changes, which other goroutines read without locks. Buffers' methods are safe from any goroutine; change them with `Window.Update` so the window shows the change. ## Editing The editor edits as Zed does, with the commands bound to the same keys (Control replaces Command on Linux and Windows, as in Visual Studio Code): * **Several carets.** Cmd+D selects the next occurrence of the selection, or the word at the caret; Cmd+Shift+L all of them; Cmd+Alt+Up and Down add a caret on the line above or below; Alt+click adds a caret, and Alt+Shift+drag selects a column. Typing, deleting and every command act at each caret, and Escape goes back to one. Cmd+U undoes a change of the selections. * **Selections by structure.** Ctrl+Shift+Right selects the word, then the string or brackets around it, and on out; Ctrl+Shift+Left goes back. * **Lines.** Alt+Up and Down move lines, Alt+Shift+Up and Down duplicate them, Cmd+Shift+K deletes them, Ctrl+J joins them, Cmd+/ comments them out, Cmd+] and Cmd+\[ indent them; Cmd+Enter opens a line below. * **Typing.** Brackets and quotes close as they are typed, and wrap the selection; Enter keeps the indentation, indents after an opening bracket and between a pair, and continues line comments; a closing bracket, or a word such as `end`, outdents its line as it is typed. Undo takes back typing a burst at a time. * **Folding.** The gutter's markers fold the lines indented under a line, up to its closing bracket, or a run of imports, with the blank lines between them; Cmd+Alt+\[ and ] fold and unfold, Cmd+K Cmd+0 folds everything and Cmd+K Cmd+J unfolds it, Cmd+K Cmd+1 to 9 by level. * **Finding.** Cmd+F opens the find bar, with case, whole words, regular expressions and finding in the selection; Cmd+Alt+F replaces. Cmd+G goes to the next match, and Ctrl+G to a line. The bar is no wider than the editor: in a narrow one it leaves out the count of matches, then the options and the buttons that go through the matches or replace them, keeping the fields, the button that shows or hides the replacement and the close button. Its field turns red for a regular expression that is not one. * **The pointer.** A double click selects a word, a triple click a line, and dragging extends by them; dragging near the edges scrolls; Cmd+click goes to a definition. `Run` runs a command, as a menu item or the app's own key does, and `Bindings` binds keys: Mods and Key, then ThenMods and ThenKey for chords such as Cmd+K Cmd+0. An app's bindings come before the defaults (`DefaultBindings`), and a binding to `NoCommand` takes a key away from the editor, for the app's own shortcut. `CommandNamed` finds a command by the name keymaps give it, as "selectNext". ```go app.code.Bindings = []editor.Binding{ {Mods: ui.Cmd, Key: ui.KeyP, Command: editor.NoCommand}, // the app's {Mods: ui.Cmd | ui.Shift, Key: ui.KeyD, Command: editor.DuplicateSelection}, } if ui.Button(c, "Format").Clicked() { app.code.Run(editor.SortLines) } ``` `Selections`, `SetSelections`, `Select`, `Cursor` and `CursorPos` read and set the carets and selections, `Insert` types at each of them, `GoTo` moves the caret to a position and `ScrollTo` shows a line. `Find` opens the find bar on a query and `FindMatches` counts its matches; `Fold`, `Unfold` and `Folded` fold lines, and `FoldImports` the first run of imports, as an editor can on opening a file; `Focused` reports whether the editor has the keyboard focus, and `VisibleLines` the first and last lines the last frame showed, as a half page of Vim's moves by. `ScrollY` and `SetScrollY` read and set how far the lines are scrolled, in DIPs, `ViewportHeight` how high the part of them in view is, and `LineTop` where a line starts, below the first, `LineTop` of the count of lines being the height of them all: editors side by side scroll together with them, an app draws what joins their lines, as the bands between the panes of a merge, and a minimap beside the editor shows where its view is. The scroll bars' thumbs show while the pointer is over the editor, or drags one, as a scroll container's do, or all the time with `KeepScrollbars`; the marks of changes, matches and diagnostics on the vertical one show all the time. `NoScrollbars` takes the bars and their marks away, and gives their room to the text. `OnInput` sees each input event before the editor does: keys, the text typed, edit commands and the pointer. Returning true takes the event, and the editor leaves it; the others go on as without it. An app's own mode of editing, as Vim's normal mode, takes keys this way while the editor still shows and moves the carets. Letters typed at the carets come as `InputText`: on some systems their keys come first as `InputKeyDown` too, and taking a key doesn't take its text, so a mode reads letters from `InputText`. What an input method composes, commits or replaces, as the accents of macOS's press and hold replace the letter before the caret, goes to the editor alone. The key after the first of a chord of `Bindings`, as Cmd+K Cmd+0, is the chord's, as VS Code resolves chords before an extension's keys. `NoInputMethod` turns the system's input methods off while the editor has the keyboard, as Neovide does in Vim's normal mode: keys type the characters of the keyboard's layout, which come to `OnInput` as `InputText`, and nothing is composed, so j is j with a Chinese input method on. Set it in the modes that read letters as commands and clear it in insert mode. Browsers cannot turn input methods off: there they compose in the text still. ```go app.code.CursorShape = editor.CursorBlock // normal mode app.code.NoInputMethod = true app.code.OnInput = func(ev ui.InputEvent) bool { if ev.Kind == ui.InputText { return app.vim.normalKeys(ev.Text) // j, k, dd, … } return false } ``` ## Options * `SoftWrap` wraps lines at the editor's width, or at `WrapColumn` columns when narrower; wrapped rows keep the line's indentation. CJK text wraps between any two characters, but closing punctuation such as `,` and `。` starts no row, and opening punctuation such as `(` and `「` ends none. * `LineNumbers` shows the gutter's numbers, absolute, relative to the caret's line, or not at all; `GutterMarks` put dots of a color by lines, as breakpoints, and `OnGutterClick` reports clicks on numbers. * `LineBackgrounds` fill lines, from `First` to `Last`, with a color under the text and the selections, as the statement a key would run; the gutter keeps its own, and lines a fold hides take no room to fill. They keep their line numbers as the text is edited, unlike diagnostics and inlays, which move with it: compute them again when the buffer's `Version` changes. * `TextBackgrounds` fill ranges of the text, bytes `Start` to `End`, with a color under the text and the selections and over line backgrounds, as the words a merge changed within its lines. They follow the editor's layout: the rows a line wraps into, tabs, wide characters and scrolling sideways; lines a fold hides show none. As line backgrounds, they stay where they are as the text is edited, cut to its end until computed again when the buffer's `Version` changes. * `TabSize` and `Indent` set indentation: tabs or spaces, as the language's files usually have them when zero (Go's tabs). * `Whitespace` shows spaces and tabs as dots and arrows: within selections by default, everywhere, at the ends of lines, or nowhere. * `WrapGuides` draws guides at columns, as 80 and 100; `NoIndentGuides` hides those of indentation. * `ReadOnly` lets the text be selected and copied, not edited. * `FitContent` makes the editor as high as its lines, rather than scrolling them, to show code in a scroll view or a list. * `KeepScrollbars` keeps the scroll bars' thumbs showing with the pointer away, as a scroll container's `KeepScrollbars`; `NoScrollbars` takes the bars away, with their room, the wheel and the keys still scrolling. * `Scrollbar` styles the scroll bars, as a theme's `ScrollbarStyle`: their track and thumb colors, widths, corners and shortest thumb. Its zero fields follow the theme's; its `TrackWidth` is 10 DIPs when 0, unless the theme's style sets one, as the editor's bar has always been. As VS Code's editor: ```go st.Scrollbar = ui.ScrollbarStyle{ TrackWidth: 14, ThumbWidth: 14, Square: true, Flush: true, MinLength: 20, Thumb: ui.RGBA(121, 121, 121, 0.4), Hover: ui.RGBA(100, 100, 100, 0.7), Active: ui.RGBA(191, 191, 191, 0.4), } ``` * `Font` and `LineHeight` set the text: the system's monospaced font of 13 DIPs, 1.5 times as high, by default. * `NoAutoClose`, `NoFolding`, `NoActiveLine` and `NoScrollPastEnd` turn those behaviors off. `Placeholder` shows while the buffer is empty. * `ScrollMargin` sets how many lines to keep above and below the caret when scrolling it into view. Zero uses three lines, a positive value sets that many lines, and a negative value removes the margin. The margin shrinks to fit the viewport and stops at the scroll limits. ```go st.ScrollMargin = -1 // no margin ``` * `CursorShape` paints carets as bars (`CursorBar`), as blocks over the character after them (`CursorBlock`), as Vim's normal mode does, translucent so that the character shows and outlined while the editor hasn't the keyboard, or as underlines (`CursorUnderline`), as its pending operators do. * `DiffBase` is the text the buffer's changes show against in the gutter, as the file in Git: bars mark the lines added and changed, and a mark where lines were deleted. Cmd+F8 goes to the next change, and Cmd+Alt+Z reverts the one at the caret. * `ContextMenu` adds items to the editor's context menu, after its own. ## Languages and highlighting `LanguageFor` finds a file's language by its name, `LanguageForText` by its name or else the `#!` line its text opens with, as `#!/usr/bin/env ruby`, and `LanguageNamed` by its own; `Languages` lists them. The editor knows Go, JavaScript, TypeScript, JSON, Python, Rust, C, C++, Java, Kotlin, Scala, Swift, Dart, C#, shell scripts, YAML, TOML, SQL, R, Ruby, Lua, PHP, CSS, HTML, ERB, Svelte, XML, Markdown, diffs, Dockerfiles, Makefiles, Protocol Buffers, GraphQL, Zig, Nix, Jinja templates and HCL (Terraform). A template's text is in the language its name gives before the template's extension: `LanguageFor` highlights `compose.yaml.j2` as Jinja in YAML, `config.json.erb` as ERB in JSON, and `notice.text.erb` as ERB in plain text. Without such a name, ERB's text is HTML and Jinja's plain text. A `Language` says how to highlight, comment, match brackets and indent its text, and with `Imports`, a pattern of a line that imports (`^import\b` for Go), which lines fold as a run: build one for another language, or copy one and change it. A language highlights its text with a `Tokenizer` by default: a function from a line, and the state the line before it ended in, to the line's tokens and the state it ends in, as TextMate grammars and Monaco's tokenizers work. The editor tokenizes the lines it shows, and after an edit only the lines below it until one starts in the state it started in before, a frame's time budget at a time. ```go // Lines starting with # are comments. lang := &editor.Language{ Name: "Notes", Extensions: []string{".notes"}, LineComment: "#", Tokenizer: editor.TokenizerFunc(func(line string, state uint64, tokens []editor.Token) ([]editor.Token, uint64) { kind := editor.TokenText if strings.HasPrefix(strings.TrimSpace(line), "#") { kind = editor.TokenComment } return append(tokens, editor.Token{End: len(line), Kind: kind}), 0 }), } ``` A token is a run of a line of one `TokenKind`, which the theme colors: keywords, types, functions, strings, comments and the others. ### Highlighters A language can instead bring a highlighter of its own, as one of a parser such as tree-sitter: `Language.Highlighter` makes the `Highlighter` of each buffer of the language, and the editor uses it in place of the tokenizer. The tokenizer itself is one (`NewTokenHighlighter`), so a highlighter plugs in without the editor changing. The text of a patch's side (`DiffState.SetPatch`) is its hunks' lines one after another: the tokenizer starts each hunk in state 0, while a highlighter of its own sees one text, and highlights it as it sees fit. ```go type Highlighter interface { // Edit follows an edit of the text, old and new its text before and // after, and changes what it replaced, in order. Edit(old, new editor.Snapshot, changes []editor.Change) // Highlight works toward the tokens of the lines up to last, for at // most budget, and reports whether they are ready. Highlight(last int, budget time.Duration) bool // Tokens appends the tokens of line i to dst, and reports whether // they are final rather than a guess made before Highlight is done. Tokens(i int, text string, dst []editor.Token) ([]editor.Token, bool) } ``` The editor calls these methods on the main thread: `Edit` as the buffer changes, `Highlight` before it paints, with the lines it shows, and again in later frames while it reports false, and `Tokens` for each line it paints. A `Change` gives the ranges an edit replaced in the old text and the new, what an incremental parser takes to edit its tree. A parser can work in the background instead: snapshots are safe to read from any goroutine, `Chunks` reads them a piece at a time, and the `invalidate` function the highlighter was made with draws the editors showing the buffer again once a parse is done. A highlighter that knows the structure of the text can tell the editor more, by implementing any of these interfaces too: * `SyntaxSelector`: `Enclosing` returns the smallest node holding more than a range, which Select Larger selects, rather than the word, string or brackets around it. * `Folder`: `FoldEnd` returns the last line folding a line hides, rather than what indentation and brackets say. * `BracketMatcher`: `EnclosingBrackets` returns the innermost pair around a range, which the editor highlights and moves between, as `do` and `end`. * `Indenter`: `IndentAfter` returns how many levels more a line Enter opens is indented. ## Completions, hovers and diagnostics The editor shows what the app or a language server knows of the code; the app answers its requests, at once or later from another goroutine through `Window.Update`: ```go app.code.OnCompletion = func(r editor.CompletionRequest) { go func() { items := app.lsp.Complete(r.Offset) // a language server's app.win.Update(func() { app.code.ShowCompletions(r.Offset-len(r.Prefix), items) }) }() } app.code.OnHover = func(r editor.HoverRequest) { if doc, start, end, ok := app.lsp.Hover(r.Offset); ok { app.code.ShowHover(start, end, doc, nil) } } app.code.SetDiagnostics(buf.Version(), app.lsp.Diagnostics()) ``` * `OnCompletion` asks for completions as a word is typed, or Ctrl+Space pressed. `ShowCompletions` lists them below the caret, filtered and ranked as typing goes on by the word typed, with their kinds, details and documentation; Enter or Tab inserts the one chosen. * `OnHover` asks what to show as the pointer rests on the text (`HoverDelay`, 600 ms by default), or for Cmd+K Cmd+I at the caret. `NoPointerHover` turns hovers from the resting pointer off, diagnostics' too, as VS Code's `editor.hover.enabled`; the keys still show one. `ShowHover` shows text in a popover over the range, or what a function builds there. The pointer can go into the hover, which stays while it is there, to select and copy its text; the hover goes a moment after the pointer leaves the text and the hover, and Escape closes it. * `SetDiagnostics` underlines problems with wavy lines of their severity, shows their messages in the hover and marks them on the scroll bar. The version is the buffer's the diagnostics are of: the editor moves them through the edits made since. * `SetInlays` shows inlay hints, text in the lines that is not theirs, as the types of variables; `SetSuggestion` shows text after the caret as a suggestion, which Tab accepts, as an AI's. * `OnDefinition` is called for Cmd+click and F12 on a word. With Cmd held, the word under the pointer shows as a link. `NoDefinitionClick` leaves Cmd+click to the editor's other clicks, link and all, and F12 and the context menu still go to the definition; `NoDefinitionLink` keeps Cmd+click but shows no link. ## Replacing ranges `SetReplacements` shows ranges of the text as something else, as Zed's folds show their placeholders: `Text`, the element `Content` builds, or nothing. The text stays the buffer's: it saves, copies, finds and undoes as it is, and assistive technology reads it. A Markdown editor's live preview hides the marks and draws check boxes, but on the lines with a caret, whose source shows to edit: ```go var rs []editor.Replacement for _, m := range marks(buf) { // the app's parser if !onCaretLine(m) { rs = append(rs, editor.Replacement{Start: m.Start, End: m.End}) } } rs = append(rs, editor.Replacement{ Start: box.Start, End: box.End, Label: "Not done", Interactive: true, Content: func(c *ui.Context, e ui.Element, r editor.Replacement) { e.Children(func() { if ui.ButtonBase(c).Fill().KeepFocus().Clicked() { buf.Edit(editor.Edit{Start: r.End - 2, End: r.End - 1, Text: "x"}) } }) }, }) app.code.SetReplacements(rs) editor.View(c, app.code).Grow(1).FillWidth() ``` Replacements move with edits, as inlays do, leaving out what is typed at their edges, and go when their text does. Set them again as the text or the selections change: laying out again only the lines whose replacements changed, this is cheap in every frame. * **Carets** step over what a replacement shows as over one character, and deleting next to it deletes all of it. A range showing nothing within a line is as if it were not there: no key press is spent on it, and Backspace takes the character before it, not the hidden text. * **`Text`** shows in the editor's font, in `Color`, else in the color of the text it replaces. * **`Content`** is given the element the editor places, `Width` DIPs wide (a square as high as a row when 0) and as high as a row, as parts are (see [Bars and popups](#bars-and-popups)). The width is the app's to say, so that soft wraps count it in lines not laid out yet. A press on it goes to the text, unless `Interactive`; `Label` names it for assistive technology. * **Ranges across lines** show on the line they start on: the lines they cover from their start through their newline take no rows, as folded ones, but the first when it shows something; the line they end in shows what follows them on a row of its own. Empty ranges, and ranges overlapping one before them, are left out. `Replacements` returns them as the edits moved them. Only the lines in view are laid out and only their elements built, so a long text may have as many as it needs. The [code editor example](https://github.com/egoist/mygo/tree/main/examples/code-editor) has a live preview of its README.md. ## Line styles `SetLineStyles` draws lines in other fonts, as a Markdown editor's headings in larger type. The text stays the buffer's; only how its lines look changes. ```go var styles []editor.LineStyle for _, h := range headings(buf) { // the app's parser styles = append(styles, editor.LineStyle{ Line: h.Line, Font: ui.Font{Size: 28 - 3*float32(h.Level), Weight: 700}, }) } app.code.SetLineStyles(styles) ``` * **`Font`**'s zero fields take the editor's, so `Size` alone keeps its family. **`LineHeight`** is a multiple of the font's size, as `State.LineHeight`; 0 takes the editor's. * **Rows** of a styled line are as high as its font makes them, and it wraps in its own font. Carets, selections, presses, find's matches and a replacement's element follow; an element without a `Width` is as wide as the line's rows are high. * **The gutter** numbers styled lines in the editor's font, on the baseline of their first row. * **Only the lines in view** are laid out still: the height of a styled line's rows comes from its font's metrics, without shaping it, and how many rows a wrapped one takes is measured as for any line. Styles move with edits, a style going with its line's text, and set again, the same styles cost nothing and a change lays out only the lines whose style changed. `LineStyles` returns them as the edits moved them. A diff's sides take none. The [code editor example](https://github.com/egoist/mygo/tree/main/examples/code-editor)'s live preview shows its README.md's headings this way. ## Code snippets A completion's `Insert` is always plain text, even with `Kind: editor.CompletionSnippet` (which chooses an icon). To insert a code template with editable placeholders, parse one and set `Snippet`: ```go snippet, err := editor.ParseSnippet("for ${1:index}, ${2:value} := range ${3:items} {\n\t$0\n}") if err != nil { // Offer a plain-text completion instead when a server uses // snippet syntax the editor does not support. return err } code.ShowCompletions(start, []editor.Completion{{ Label: "forrange", Kind: editor.CompletionSnippet, Snippet: snippet, }}) // Or insert at every current selection, outside the completion list: code.InsertSnippet(snippet) ``` Parse templates once; a `Snippet` is immutable and can be shared by editors. `Text()` returns its initial text. The parser supports `$1`, `${1}`, `${1:default}`, escaped dollars, braces and backslashes, and `$0` as the final stop (the end when omitted). Tab visits positive numbers in numeric order, with 0 last; Shift+Tab goes back, stopping at the first field. Repeated numbers share their default, including forward references, and edit together through the editor's normal multiple selections. Coincident empty stops of the same number coalesce as carets do. Scrolling and input methods follow the first occurrence at the original primary insertion site. A completion list takes Tab before the snippet's navigation, so a field can itself be completed. Escape ends the session after closing any open completion list or other editor overlay. Moving outside the active fields, editing the buffer externally, undo/redo or changing buffers ends the session too. Each field's typing is a separate undo group; undoing the insertion restores the old text and selections. Redo restores the text and selections without restarting snippet navigation. Input methods compose and commit at mirrored fields as at ordinary carets. A new snippet replaces the previous session. This is the tab-stop subset of TextMate/LSP syntax: nested placeholders, variables, choices, transformations, conflicting defaults for one number, and invalid UTF-8 return errors. Text keeps the template's indentation; CRLF is normalized to LF. `InsertSnippet` leaves a read-only editor unchanged. State methods, including snippet insertion, run on the UI thread as the rest of editor interaction does. Run `go run ./examples/code-editor`, type `funcdef` or `forrange` in a Go file, then press Tab to try it. ## Styling ### Themes `Theme` colors the editor: its background, text, gutter, selections, carets, guides, diagnostics, changes and each kind of token. Colors left zero take those of `DefaultTheme`, which follows the window's theme and appearance, light or dark. ```go th := editor.DefaultTheme(c.Theme()) th.Tokens[editor.TokenKeyword] = editor.TokenStyle{Color: ui.RGB(0xc6, 0x78, 0xdd), Bold: true} app.code.Theme = th ``` ### Bars and popups The find bar, the go to line bar, the completions and the hovers are parts the app can build itself, as it styles ui's [bases](https://mygo.egoist.dev/docs/ui/custom-widgets.md): `RenderFindBar`, `RenderGoToLine`, `RenderCompletions` and `RenderHover` are each given the element the editor places (a toolbar over its top right corner, a bar at its top, a list below the caret, a card above the text hovered), which keeps the presses from the text under it and the keyboard where the part needs it (in the editor while the completions show, in the hover as its text is selected), and a handle to what the part shows and does. Style the element and build its content; its position can change too. The find bar comes with margins that keep it inside the editor, so `bar.Right(0)` leaves it the theme's `Space(4)` from the right edge; `bar.Margin(0)` takes them off. The editor's own looks are `DefaultFindBar`, `DefaultGoToLine`, `DefaultCompletions` and `DefaultHover`, which a render function can call and then restyle. ```go app.code.RenderFindBar = func(c *ui.Context, bar ui.Element, f *editor.FindBar) { t := c.Theme() bar.Row().Gap(8).Padding(6).Background(t.Surface).Radius(12).Shadow(0, 4, 12, 0, ui.RGBA(0, 0, 0, 0.2)) bar.Children(func() { f.QueryInput(ui.TextInputBase(c, f.Query()).Placeholder("Search").Width(180)) ui.Toggle(c, f.Regexp(), ".*").KeepFocus() ui.Text(c, f.Status()).TextColor(t.TextMuted) if ui.Button(c, "Next").KeepFocus().Clicked() { f.Next() } }) } app.code.RenderHover = func(c *ui.Context, panel ui.Element, h *editor.HoverCard) { editor.DefaultHover(c, panel, h) // the editor's look, on another background panel.Background(app.hoverColor) } ``` * `FindBar` binds fields and toggles: `Query` and `Replacement`, and `CaseSensitive`, `WholeWord`, `Regexp` and `InSelection`, are pointers, and the matches follow them as they change. `QueryInput` and `ReplacementInput` give inputs the bar's keys: the query takes the focus as the bar opens, Enter and Shift+Enter go through the matches, Alt+Enter selects them all, Enter and Cmd+Enter in the replacement replace one or all, and Escape closes. `Matches` and `Status` count the matches, and `Next`, `Previous`, `SelectAll`, `Replace`, `ReplaceAll` and `Close` act; `Replacing` says whether the bar replaces too, as Cmd+Alt+F opens it. * `GoToLineBar` has `Text` for its field, which `Input` gives the bar's keys, `Cursor`, `LineCount` and `Target` to tell where it goes, and `Go` and `Close`. * `CompletionMenu` has the `Items` shown, best first, and the one `Selected`. `Item(i)` makes the row of an item, selected as the arrows move, scrolled into view and inserting the item when clicked; style it and give it content. `Font`, `LineHeight` and `Theme` show code as the editor does, and a `CompletionKind` has an `Icon` and the `Token` whose color tints it. * `HoverCard` has the `Diagnostics` of the text hovered, the `Text` the app gave `ShowHover`, and `Content`, which builds what its function builds. ## Accessibility Assistive technology sees a multi-line text field, named by `Label`, with the text of the buffer, replaced ranges among it, and the newest selection, which it moves, and where its lines in view are, so that VoiceOver moves through it line by line and outlines the line it reads; the elements of replacements are named by their `Label`; the completions are a list, and the find bar a toolbar that tells the count of matches, except in a narrow editor, where its query field still tells an invalid regular expression. The editor's menu, its find and go to line bars and their names are in the window's language ([MyGo's own strings](https://mygo.egoist.dev/docs/i18n.md#mygos-own-strings)). Input methods compose in the editor as in other text fields, with their candidate window at the caret. --- Source: https://mygo.egoist.dev/docs/ui/collapsible.md # Collapsible `ui.Collapsible` creates a disclosure, as SwiftUI's `DisclosureGroup`: a label beside an arrow, which a click opens and closes, as do Enter and Space, showing below it what its function builds while a `*bool` is true. The arrow turns and the content grows into view as it opens. `Changed` reports a click. ```go ui.Collapsible(c, "Advanced", &app.advanced, func() { ui.Checkbox(c, &app.verbose, "Verbose logging") ui.Checkbox(c, &app.experimental, "Experimental features") }) ``` With less motion asked of the desktop, the content shows at once. For several sections in a box, use an [accordion](https://mygo.egoist.dev/docs/ui/accordion.md). ## Without a look `ui.CollapsibleBase` is a collapsible without a look: a `Trigger` that shows and hides what `Panel` builds, growing and shrinking it with `Progress`, which goes from 0 closed to 1 open, for a look and a motion of your own: ```go p := ui.CollapsibleBase(c, &app.open) p.Trigger.Gap(6).Children(func() { ui.Icon(c, chevron).Rotate(90 * p.Progress()) ui.Text(c, "Details") }) p.Panel(func() { ui.Text(c, app.details) }) ``` See [custom widgets](https://mygo.egoist.dev/docs/ui/custom-widgets.md). ## Accessibility Assistive technology sees a disclosure named by its label, expanded or collapsed, which it opens and closes as a click does. --- Source: https://mygo.egoist.dev/docs/ui/color-picker.md # Color picker `ui.ColorWell` creates a swatch of a `*ui.Color` that opens a color picker below it, as AppKit's color well: a click, Enter or Space opens it, and Escape or a click outside closes it. `Changed` reports a new color. ```go ui.Field(c, "Tint", func() { ui.ColorWell(c, &app.tint) }) ``` `ui.ColorPicker` is the picker itself, to show in a panel of your own, as AppKit's color panel: a square choosing the saturation, across, and the brightness, up, of the hue its slider chooses below it, a slider of opacity, the color in hex, which the user edits, and swatches of common colors. The arrows move across the square while it has the focus, Up and Down changing the brightness and Left and Right the saturation. ```go ui.ColorPicker(c, &app.background) ``` ## Accessibility Assistive technology sees a color well whose value is the color in hex, named by its `Label` or its [field](https://mygo.egoist.dev/docs/ui/form.md). In the picker, it sees a slider of the saturation and brightness, sliders of the hue and the opacity, a text field named "Hex", and buttons named by the swatches' colors, in the window's language ([MyGo's own strings](https://mygo.egoist.dev/docs/i18n.md#mygos-own-strings)). --- Source: https://mygo.egoist.dev/docs/ui/combobox.md # Combobox `ui.Combobox` creates a combobox choosing a `*string` among options: a field showing the choice, whose text filters the options below it as the user types, those starting with it first, while a click or Down shows them all; a click showing them selects the choice, for typing to replace. Up and Down move among them and Enter chooses, as does a click; Escape closes them, and the text goes back to the choice when the field loses the focus. `Changed` reports a new choice. ```go ui.Combobox(c, &app.font, fonts).Label("Font") ``` The field keeps the keyboard focus while the user types and picks. `Placeholder` shows a text in it while its text is empty. For a text that may be anything, with suggestions, use [autocomplete](https://mygo.egoist.dev/docs/ui/autocomplete.md); for a short list without typing, a [select](https://mygo.egoist.dev/docs/ui/select.md). ## Without a look `ui.ComboboxBase` is a combobox without a look: an `Input` whose text filters the `Item`s of a `Popup` below it, which the arrows highlight and Enter or a click chooses (`Chosen`): see [custom widgets](https://mygo.egoist.dev/docs/ui/custom-widgets.md). When the options are those matching what was typed, as here, tell assistive technology with [`cb.Input.AutoComplete(ui.AutoCompleteList)`](https://mygo.egoist.dev/docs/ui/accessibility.md#suggestions). A popup without options hides, unless it holds something else to read, as a row saying that nothing matches, which then shows in their place: ```go cb.Popup(func(panel ui.Element) { panel.Padding(4).Background(t.Background).Border(1, t.Border) matches := app.matching(app.query) for _, f := range matches { cb.Item(f).Padding(6, 10).Children(func() { ui.Text(c, f) }) } if len(matches) == 0 { ui.Text(c, "No matches found").Padding(6, 10).TextColor(t.TextMuted) } }) ``` ## Accessibility Assistive technology sees a combo box named by its `Label`, editable as a text field, which expands, and whose options complete what was typed (`aria-autocomplete="list"`); the option the arrows are on has the focus for it, and reads as which of how many it is. With no options, the focus stays in the field, and a popup showing a row in their place is read out as it appears. --- Source: https://mygo.egoist.dev/docs/ui/context-menu.md # Context menu `ContextMenu` gives an element a menu of the system's, which opens where the element is right-clicked (Control-clicked on macOS), and below it when the menu key or Shift+F10 is pressed while it or one inside it has the focus, or, in a list, while the list has the focus and its row is chosen. The function builds the items when the menu opens, and runs again in the frame after one was chosen, where its `Chosen` reports it: ```go row.ContextMenu(func(m *ui.Menu) { if m.Item("Rename").Shortcut(0, ui.KeyF2).Chosen() { app.renaming = i } if m.Item("Pinned").Checked(note.pinned).Chosen() { note.pinned = !note.pinned } m.Submenu("Move to", func(m *ui.Menu) { for _, f := range app.folders { if m.Item(f.name).Chosen() { moveTo, moved = f, i } } }) m.Separator() if m.Item("Delete").Disabled(note.locked).Chosen() { deleted = i } }) ``` The function runs as the element builds, in the loop building the rows: a choice that takes the row out of the notes, as moving or deleting it, notes it, for the change once the loop is done (see [views](https://mygo.egoist.dev/docs/ui/views.md#events-and-actions)). ## Items * `Item(label)` adds an item; `Chosen` reports whether it was chosen. * `Checked(on)` shows a check mark by it, as for a setting that choosing the item toggles, and `Radio(on)` shows it as one of a group choosing one setting, marked as the one chosen when on is true. * `Disabled(d)` grays it out: it cannot be chosen. * `Tooltip(s)` shows `s` as the pointer rests on it, to say what it does. The system's menus show it on macOS and Linux, and `PopoverMenu` on every platform, also as the keys rest on it. * `Icon(icon)` shows an image beside its label, made once with [`mygo.NewMenuIcon`](https://mygo.egoist.dev/docs/menus.md#icons) of a PNG image, or `mygo.NewMenuIconSVG` of an SVG. The system's menus show it as they show the icons of `mygo.MenuItem`, browsers show none, and `PopoverMenu` draws it on every platform. * `IconColor(color)` draws its template icon in `color` instead of the text's, as a red trash can by Delete; on the highlight it takes the highlight's text color, as the label does. Only drawn menus (`PopoverMenu`, `PopoverMenuButton`, and every menu of a window that [draws them](#every-menu-of-a-window)) show it: the system's tint template icons in the color of their text. * `Shortcut(mods, key)` shows a key by it, as the shortcut that does the same. It only shows the key: handle it with `Shortcut` on the context or an element. * `Subtitle(s)` shows a second, smaller line under its label, as [`mygo.MenuItem`'s](https://mygo.egoist.dev/docs/menus.md) does: under the label on macOS 14 and in browsers, after it elsewhere (`Label — Subtitle`), and under it in `PopoverMenu` on every platform. Assistive technology reads it as the item's description. * `ID(id)` gives it an identity of its own, which `Chosen` matches instead of its place and label: a label that changes while the menu shows, as `Sync 3 Files`, or items before it that come and go, keep the choice on it. * `Separator()` adds a line between groups of items, and `Submenu(label, build)` an item opening a submenu, which `build` fills. ## Which element The innermost element with a menu gets the click, as a row's button with a menu of its own inside a row with another. [Text inputs](https://mygo.egoist.dev/docs/ui/text-input.md) have the editing commands of their platform's text fields, and selectable [text](https://mygo.egoist.dev/docs/ui/text.md) has Copy and Select All. `ContextMenu` on the input, the text, or the `Selectable` container replaces that menu, and `EditItems` adds those commands to a menu of one's own, acting on the text that was clicked, as a chat message's text offers Reply above Copy: ```go message.Selectable().ContextMenu(func(m *ui.Menu) { if m.Item("Reply").Chosen() { app.reply(msg) } m.Separator() m.EditItems() }) ``` An element within text, as a link in a paragraph, opens its menu on that text: `EditItems` in the link's `ContextMenu` adds the paragraph's Copy and Select All, which act on the selection. The same menu opens below a button with `Element.Menu`: see [menu button](https://mygo.egoist.dev/docs/ui/menu-button.md). In tests, `tt.RightClick` opens a context menu, which `tt.Menu` lists and `tt.ChooseMenuItem` chooses from. ## Drawn in the window `PopoverMenu` takes the same function, and MyGo draws the menu in the window with the theme's look, as a [popover](https://mygo.egoist.dev/docs/ui/popover.md), where the system would show its own: beside the popovers and buttons of an app's own design, the system's menu is the one that looks out of place. ```go card.PopoverMenu(func(m *ui.Menu) { if m.Item("Play Next").Chosen() { app.playNext(album) } if m.Item("Pinned").Checked(album.pinned).Chosen() { album.pinned = !album.pinned } m.Submenu("Sort by", func(m *ui.Menu) { for _, by := range []string{"Title", "Artist", "Year"} { if m.Item(by).Radio(app.sort == by).Chosen() { app.sort = by } } }) m.Separator() if m.Item("Remove").Shortcut(0, ui.KeyDelete).Disabled(album.locked).Chosen() { app.remove(album) } }) ``` It opens as the system's would, where the element is right-clicked, or below it for the menu key or Shift+F10, after that point, or before it where the window has no room, and follows the element as the window scrolls. It takes the focus as it opens and gives it back as it closes to the element that had it, and has the keys of the system's menus: * Up and Down move among the items, past separators and those disabled, and round; Home and End go to the first and the last, and typing the first letters of an item goes to it. * Right opens the submenu of the item, and Left closes it, the other way round [right to left](https://mygo.egoist.dev/docs/ui/right-to-left.md); the pointer opens it as it moves onto the item. Heading for a submenu that shows, the pointer can cross the items between, diagonally: while it moves toward the submenu, the items it crosses take no highlight and the submenu stays open, until it rests on one for 300 ms, as in the system's menus. * Enter and Space choose the item, as a click does; Escape closes the submenu on top, then the menu, and Tab closes the menu. * A press outside the menu closes it, and goes on to what is under the pointer. Its items show their `Shortcut` after their label, with a check mark or a dot by those `Checked` or `Radio` marks. Assistive technology sees a menu of menu items, check box items and radio items, checked or not, as it sees the system's. A drawn menu's items are elements: in tests, `tt.RightClick` opens it, `tt.HasText` finds its items and `tt.Click` chooses one. `tt.Menu`, `tt.ChooseMenuItem` and `tt.CloseMenu` work on it as on the system's, so a test passes with either. `PopoverMenuButton` draws the menu of a [menu button](https://mygo.egoist.dev/docs/ui/menu-button.md#drawn-in-the-window) so, below the button, and takes the same function: a row's right-click and its ⋯ button can share one menu, drawn alike. `PopoverMenuOptions` style the menu as `PopoverMenuButtonOptions` style a menu button's: `Panel` the panel of the menu and of each submenu, after the theme's look, and `Item` the row of each item. A right-click menu then unfolds as the app's ⋯ menus do: ```go text.PopoverMenu(app.messageMenu, ui.PopoverMenuOptions{ Panel: func(panel ui.Element) { panel.Background(app.menuColor).Radius(12) }, }) ``` ### Richer items A drawn menu's items take more than the system's do, without a menu of one's own ([without a look](#without-a-look)); the system's menus show those items with their label alone: ```go more.PopoverMenuButton(func(m *ui.Menu) { m.MaxWidth(320) for _, f := range app.files { if m.Item(f.Name).ID(f.Path).Trailing(f.Size).Chosen() { app.open(f) } } m.Separator() item := m.Item("Download").ID("download") item.Content(func(x ui.MenuItemContent) { ui.Text(x.Context, "Downloading "+app.download.Name) ui.Progress(x.Context, app.download.Progress) }) m.Separator() if m.Item("Delete…").Danger().Chosen() { app.confirmDelete() } }) ``` * `Danger()` shows the item in the theme's `Danger` color, as one that deletes or discards. Highlighted, it keeps the theme's highlight, its label in `Danger` where that is legible on the highlight, else in `AccentText`. Assistive technology hears no color: let the label say what the item does. * `Trailing(s)` shows a value at the item's end, before its shortcut, as a file's size; assistive technology reads it in the item's description. * `Content(fn)` builds what the item shows in place of its label and subtitle, between its mark and icon and its trailing text and shortcut. `fn` gets the context, whether the item is highlighted or disabled, and the colors of its text (`MenuItemContent`); text in it takes the item's color. The item keeps its label, which assistive technology reads as its name and typing goes to. The content stays part of the item: a press on it chooses the item. A control in it, as a text input filtering the items after it, takes its own presses and keeps the focus while the pointer moves over its item, with the keys it handles (the text typed, Space, Enter, Home and End); Up and Down move the highlight and give the menu the focus back, and Escape closes the menu. * `Highlighted()` reports, as the function builds, whether the item is the one the pointer or the keys are on, or leads to it through a submenu, as the menu's last pass built it: the function builds again as the highlight moves, so that it can show what goes with the item, as a preview of the theme highlighted. Call `ID` first, and give the items IDs when the items built change with the highlight: a drawn item's ID also keys its row, whose highlight then stays on it. * `Menu.MaxWidth(w)` keeps the menu at most `w` wide, its submenus too unless they set their own: labels, subtitles and trailing texts too long for it end with an ellipsis, while shortcuts, icons and marks keep their room. Assistive technology, `tt.Menu` and typing see each label whole, and a `Tooltip` can show it. ### Every menu of a window `Context.SetMenuPresentation(ui.PopoverMenus)` draws every popup menu of the window so, not only those given with `PopoverMenu`: the menus of `ContextMenu` and `Menu`, the ones MyGo's widgets build with them (a [table](https://mygo.egoist.dev/docs/ui/table.md)'s header and cell menus, a toolbar's overflow menu, the code editor's), and the editing menu of text inputs and selectable text. An app with a look of its own then shows no menu of the desktop's beside its own, and its menu functions do not change. It stays until set again, so the view can follow a setting of the app's: ```go func (app *App) View(c *ui.Context) { if app.settings.systemMenus { c.SetMenuPresentation(ui.SystemMenus) // the default } else { c.SetMenuPresentation(ui.PopoverMenus) } // ... } ``` `PopoverMenu` and `PopoverMenuButton` draw their menus in the window whatever it is. Only the menus MyGo builds follow it: the menu bar, the tray's menu and the Dock's stay the system's, and a [web view](https://mygo.egoist.dev/docs/ui/web-view.md)'s are the web view's own. ## Without a look `ui.ContextMenuBase` gives an element a context menu without a look, shown while a `*bool` is true: it opens as `PopoverMenu`'s does, where the element is right-clicked or below it for the menu key, and has its keys, and its `Popup` builds the menu as [`MenuBase`](https://mygo.egoist.dev/docs/ui/menu-button.md#without-a-look)'s does, with items of your own layout: ```go m := ui.ContextMenuBase(c, row, &app.rowMenu) m.Popup(func(panel ui.Element) { panel.Padding(4).Radius(10).Background(t.Background).Border(1, t.Border) for _, label := range app.labels { item := m.CheckItem(note.has(label)).Gap(8).Padding(6, 10).Radius(6) if item.Highlighted() { item.Background(t.SurfaceHover) } item.Children(func() { ui.Box(c).Size(10, 10).Radius(5).Background(label.Color) ui.Text(c, label.Name) }) if item.Clicked() { note.toggle(label) } } }) ``` --- Source: https://mygo.egoist.dev/docs/ui/custom-widgets.md # Custom widgets Every widget is built on a base, the same widget without a look: the base handles the pointer, the keyboard and the focus, and tells assistive technology what it is, and leaves every color, size and shape to the elements it returns, which you style as any other. Build a design of your own on them, as headless component libraries do on the web. | Base | What it does | | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ButtonBase` | a row that takes the focus, and reports `Clicked` for the pointer, Enter and Space | | `CheckboxBase`, `SwitchBase`, `ToggleBase` | a row that toggles a `*bool` | | `CheckboxStateBase` | a check box that can be mixed, setting a `*ui.CheckState` (`CheckOff`, `CheckOn`, `CheckMixed`), which a press checks, or unchecks once checked ([Checkbox](https://mygo.egoist.dev/docs/ui/checkbox.md#without-a-look)) | | `RadioBase` | a row that selects its value into a `*T` | | `SliderBase` | sets a `*float64` from where the pointer is across its content box, inside its padding, or up it (`Vertical`), and with the arrows, Page Up and Down, Home and End, by its `Step` | | `TabsBase` | the tab `List`, whose `Tab`s choose a `*int`, with the arrows moving the choice and the focus past those disabled | | `SegmentedBase` | a `Track` of `Segment`s, a radio group choosing a `*int` | | `CollapsibleBase` | a `Trigger` that shows and hides what `Panel` builds, growing and shrinking it with `Progress`, which goes from 0 closed to 1 open | | `AccordionBase` | a `Root` of sections, each `Item` a `CollapsibleBase` whose triggers the arrows, Home and End move the focus between ([Accordion](https://mygo.egoist.dev/docs/ui/accordion.md#without-a-look)) | | `TreeBase` | a `Root` of `Item`s, each a `Row` and a `Group` of the items inside it while its `*bool` is true, with the arrows, Home, End and typing moving the focus and opening and closing them ([Tree](https://mygo.egoist.dev/docs/ui/tree.md#without-a-look)) | | `SelectBase` | a `Trigger` opening a `Popup` of `Item`s choosing a `*T`, which the arrows highlight (`Highlighted`) and Enter chooses; `SetOpen` opens and closes it, and `SelectBaseOpen` takes the open flag from you | | `ComboboxBase` | an `Input` whose text filters the `Item`s of a `Popup` below it, which the arrows highlight and Enter or a click chooses (`Chosen`), or shows a row of yours when none match ([Combobox](https://mygo.egoist.dev/docs/ui/combobox.md#without-a-look)) | | `PopoverBase`, `DialogBase` | a panel beside an anchor, or over a backdrop covering the window, that a press outside or Escape closes | | `MenuBase`, `ContextMenuBase` | a menu button's `Trigger`, or an element's context menu, opening a `Popup` of `Item`s, `CheckItem`s, `RadioItem`s and `SubmenuItem`s with their `Submenu`s, which the pointer and the keys highlight (`Highlighted`) and choose (`Clicked`), closing the menu unless `KeepOpen`, and `Group`s of items the keys take as one stop ([Menu button](https://mygo.egoist.dev/docs/ui/menu-button.md#without-a-look)) | | `TooltipBase` | a tip beside an anchor while the pointer rests on it or the keyboard focus is on it, which a press or Escape hides ([Tooltip](https://mygo.egoist.dev/docs/ui/tooltip.md#without-a-look)) | | `ToastViewportBase`, `ToastBase` | the window's toasts in a viewport of your own, each a status with an `ActionButton` and a `CloseButton`, their time stopping while the pointer or the focus is on them ([Toast](https://mygo.egoist.dev/docs/ui/toast.md#without-a-look)) | | `TextInputBase`, `TextAreaBase` | text inputs without padding, background, border or corners, `ReadOnly` or not | Charts have bases of their own: [package `ui/chart`](https://mygo.egoist.dev/docs/ui/chart.md) has scales, axes, marks and a selection without a look. Base constructors return value parts with the same build lifetime as other elements. Give stateful bases a key with `Context.Key` before construction. A segmented control on `SegmentedBase`, and a select on `SelectBase`: ```go t := c.Theme() view := ui.SegmentedBase(c.Key("period"), &app.view, 3) view.Track.Padding(3).Radius(999).Background(t.Surface).Children(func() { for i, name := range []string{"Day", "Week", "Month"} { seg := view.Segment(i).Padding(5, 14).Radius(999) if i == app.view { seg.Background(t.Background).Shadow(0, 1, 2, 0, ui.RGBA(0, 0, 0, 0.15)) } seg.Children(func() { ui.Text(c, name) }) } }) sel := ui.SelectBase(c.Key("size"), &app.size) sel.Trigger.Gap(6).Padding(6, 10).Radius(8).Border(1, t.Border).Children(func() { ui.Text(c, app.size) ui.Icon(c, chevron) }) sel.Popup(func(panel ui.Element) { panel.Margin(4, 0, 0, 0).Padding(4).Radius(10).Background(t.Background).Border(1, t.Border) for _, size := range sizes { item := sel.Item(size).Padding(6, 10).Radius(6) if item.Highlighted() { item.Background(t.Accent).TextColor(t.AccentText) } item.Children(func() { ui.Text(c, size) }) } }) ``` Bases ring the element with the keyboard focus, as every element taking the focus is, with the theme's ring: `FocusRingWidth` wide, `FocusRingOffset` outside the element's edge, in `Focus` (see [the focus ring](https://mygo.egoist.dev/docs/ui/styling.md#the-focus-ring)). `FocusRingOffset(d)` moves an element's ring, inside it for a negative `d`, as for a header in a box that clips what goes past it, and `FocusRingColor` colors it. `FocusRing(false)` turns the ring off for a widget that draws its own, with `Painter.FocusRing` while `FocusVisible`. A disabled element shows at half its opacity, with what is inside it, bases too. `DimDisabled(false)` leaves that to you, for a widget that shows being disabled in a look of its own: a card that stays readable with the reason it is unavailable, or a select's options grayed your way. Style it while `IsDisabled`: ```go card := ui.RadioBase(c, &app.plan, p.ID).Disabled(!p.Available).DimDisabled(false) card.Column().Gap(4).Padding(12).Radius(8).Border(1, t.Border).Children(func() { name := ui.Text(c, p.Name) if card.IsDisabled() { name.TextColor(t.TextMuted) ui.Text(c, p.DisabledReason).FontSize(12) } }) ``` A widget that must stay focusable while it is unavailable, for screen readers to reach it, tells them with [`AccessDisabled`](https://mygo.egoist.dev/docs/ui/accessibility.md#unavailable-still-reachable) instead of `Disabled`, and styles itself while it is. ## Widgets of your own For text controls with their own buffer or selection model, use [`HandleTextInput` and retained text geometry](https://mygo.egoist.dev/docs/ui/text-input-client.md). Build your own widgets from elements. An element keeps state of its own from frame to frame with `ui.Local`: ```go // Spoiler hides text until clicked. func Spoiler(c *ui.Context, text string) { t := c.Theme() box := ui.Box(c).Padding(2, 6).Radius(4).Focusable() shown := ui.Local(box, "shown", func() bool { return false }) if box.Clicked() { *shown = !*shown } if *shown { box.Background(t.Surface) } else { box.Background(t.Text) // the color of the text, hiding it } box.Children(func() { ui.Text(c, text) }) } ``` ### Stopping what a widget started What `Local`'s `init` makes is the element's. When a frame no longer builds the element, its state goes, and a value that is an `io.Closer` (`T` or `*T` has `Close() error`) is closed, as the web aborts an `AbortController` when an element is removed. A widget that starts work in the background, a streaming request, a ticker or a subscription, stops it in `Close`: ```go type stream struct{ cancel context.CancelFunc } func (s *stream) Close() error { s.cancel(); return nil } // Feed shows the lines read from url while it is in the view. func Feed(c *ui.Context, win *mygo.Window, app *App, url string) { e := ui.Column(c) ui.Local(e, "stream", func() *stream { ctx, cancel := context.WithCancel(context.Background()) go read(ctx, url, func(line string) { win.Update(func() { app.lines = append(app.lines, line) }) }) return &stream{cancel} }) e.Children(func() { for _, line := range app.lines { ui.Text(c, line) } }) } ``` * `Close` runs once, on the main thread, after the frame that no longer built the element; an element's last `Local` made closes first, as deferred calls run. The window waits for it: cancel the work and return, rather than wait for the work to stop. * `Close` may change the app's state, on the main thread; ask for the frame that shows it with `Window.Invalidate`, or `Invalidate` of the `c.Services()` the widget kept. * An element leaving with an exit [transition](https://mygo.egoist.dev/docs/ui/transitions.md#coming-and-going) closes its values, and its children's, once the exit ended, as its copy is gone: the copy paints what the element had until then. Built again before that, the element starts anew, with `init`, and the values of the copy close. * A [list](https://mygo.egoist.dev/docs/ui/list.md) builds only the rows in view: a row scrolled out of view closes its values, and makes them anew with `init` as it comes back. Keep what outlives a row in the app's state, by its item. * The pages a [router](https://mygo.egoist.dev/docs/ui/navigation.md#pages-keep-their-state) keeps in its history keep their elements' values, which close as it lets the pages go. * Every element's values close as its window closes, and so as the app quits. * A `Close` that panics panics out of the frame, as the view would; the values left close after the next frame. * A nil value is not closed, as a `*stream` that `init` left nil to start later, and `Close`'s error is ignored. * A value the element must not close, as one the app shares, belongs in the app's state rather than in a `Local`. * A widget that only needs to run a function as its element goes, as `cancel`, gives it to the element's `OnUnmount`, which runs it as `Close` would, without a type of its own ([state of an element](https://mygo.egoist.dev/docs/ui/views.md#state-of-an-element)). A widget whose input changes what it edits reports it with `SetChanged` on its element, as it builds: `Changed` then returns true for it, as for the widgets' own. The [rich text editor](https://mygo.egoist.dev/docs/ui/rich-text-editor.md) does so. Give a widget a [role](https://mygo.egoist.dev/docs/ui/accessibility.md#roles), a name and its [states](https://mygo.egoist.dev/docs/ui/accessibility.md#states) for assistive technology, take the keys it needs with `Shortcut` on its element, or every key as it comes with [`HandleInput`](https://mygo.egoist.dev/docs/ui/input.md#every-key-as-it-comes), and paint what elements do not with [`Draw`](https://mygo.egoist.dev/docs/ui/drawing.md). Overlays of your own, as drawers, hover cards and menus, are placed with `AttachTo` and close with `PressedOutside` and `OverlayShortcut`; `Modal` keeps the focus in one: see [overlays](https://mygo.egoist.dev/docs/ui/overlays.md#your-own-overlays). --- Source: https://mygo.egoist.dev/docs/ui/date-input.md # Date input `ui.DateInput` creates a field showing a `*time.Time` as the user's regional formats write a date in numbers, as 1/5/2026 in the United States, 05/01/2026 in the United Kingdom or 2026/1/5 in China, which a [calendar](https://mygo.egoist.dev/docs/ui/calendar.md) below it changes. A click, Enter or Space opens the calendar, where a click chooses a day, as do the arrows and Enter; Page Up and Page Down, or its buttons, move by months, and Escape closes it. `Changed` reports a new date, which keeps the time of day and the location of the value. ```go ui.Field(c, "Birthday", func() { ui.DateInput(c, &app.birthday) }) ``` With a [time input](https://mygo.egoist.dev/docs/ui/time-input.md) beside it, the two edit one `time.Time`: ```go ui.Row(c).Gap(8).Children(func() { ui.DateInput(c, &app.meeting).Label("Date") ui.TimeInput(c, &app.meeting).Label("Time") }) ``` ## Accessibility Assistive technology sees a pop-up button whose value is the date, named by its `Label` or its [field](https://mygo.egoist.dev/docs/ui/form.md), and the calendar while it is open. --- Source: https://mygo.egoist.dev/docs/ui/decimal-input.md # Decimal input `ui.DecimalInput` is a [number input](https://mygo.egoist.dev/docs/ui/number-input.md) for amounts of money: it edits a `*string` holding an exact decimal between two bounds, which Up and Down, and the buttons beside it, change by a step. The value is written with exactly the decimals of the step, as `"1234.50"`; the bounds are written the same way, `""` for no limit. Inside, it counts in `math/big` integers of units of the step's last decimal, so no amount is ever held in binary floating point. ```go ui.Field(c, "Amount", func() { if ui.DecimalInput(c, &app.amount, "0", "", "0.01").Changed() { app.save() } }) ``` What is typed applies as soon as it is a number in range, with `.` before its decimals, `,` between groups of three digits, and an optional `-`: `1,234.5` sets `"1234.50"`, and shows so once the input loses the focus. Text and amounts in `*string` convert to whatever decimal type the app uses (`shopspring/decimal`, `apd`, `big.Rat`), and fit a database's TEXT columns. ## Nothing is rounded At a step of `0.01`, `1.500` is `1.50`, but `1.005` is not a number the input takes: rather than round it, it keeps the value as it was and marks the input with `Error`, whose message a [field](https://mygo.egoist.dev/docs/ui/form.md) around it shows below, until the text is corrected. Text that is not a number, or out of range, is marked the same way, and stays when the input loses the focus, so that a typo is never silently replaced. Emptying the input leaves the value as it was, and shows it again once the input loses the focus. A value the app sets replaces what was typed, a mistake included. A value the app sets with more decimals than the step's, or out of range, shows as it is, marked. `Changed` reports a new value: one written another way, as `1.5` for `1.50`, is not. As `NumberInput`, it reads `.` and `,` the same way in every language the window shows: `1,50` is not one and a half, but text that is not a number, which the input marks rather than read as 150. ## Accessibility Assistive technology sees a spin button of the value, named by its `Label` or its field, which it increments and decrements by the step, and reads the value as the input's text, exactly. An error's message describes the input, which it reads as invalid. --- Source: https://mygo.egoist.dev/docs/ui/dialog.md # Dialog `ui.Modal` shows a dialog its function builds over the dimmed window while a `*bool` is true; clicking outside it or pressing Escape sets it to false. ```go if ui.Button(c, "Rename…").Clicked() { app.renaming = true } ui.Modal(c, &app.renaming, func() { ui.Text(c, "Rename").Bold() if ui.TextInput(c, &app.name).AutoFocus().Submitted() { app.renaming = false } ui.Row(c).Gap(8).Justify(ui.End).Children(func() { if ui.Button(c, "Cancel").Clicked() { app.renaming = false } if ui.PrimaryButton(c, "Rename").Clicked() { app.rename() app.renaming = false } }) }) ``` ## The keyboard A dialog keeps the keyboard: it takes the focus as it opens, on its first element that takes it unless one in it asked for it (`AutoFocus`), Tab goes round its elements, and the window's shortcuts built outside it wait, as what is behind it is inert. As it closes, it gives the focus back to the element that had it, the button that opened it say. See [overlays](https://mygo.egoist.dev/docs/ui/overlays.md). ## Keeping it open `Dismissed` reports the frame Escape or a click outside closed the dialog; one that must stay open, with changes to save say, sets the `*bool` back to true then: ```go if ui.Modal(c, &app.editing, app.editor).Dismissed() && app.unsaved { app.editing = true } ``` To ask about something important, with buttons and no closing by a click outside, use an [alert dialog](https://mygo.egoist.dev/docs/ui/alert-dialog.md). ## Beyond the window A dialog draws in its window, cut to its edges: one a flyout asks for, as a tray's flyout, is no wider than the flyout. Open a window modal to the flyout instead, which shows over it and closes with it (see [a dialog over a flyout](https://mygo.egoist.dev/docs/windows.md#a-dialog-over-a-flyout)). ## Without a look `ui.DialogBase` is a dialog without a look: its function styles the backdrop covering the window, which centers the panel, and the panel, and builds the panel's content: ```go ui.DialogBase(c, &app.open, func(backdrop, panel ui.Element) { backdrop.Background(ui.RGBA(0, 0, 0, 0.5)) panel.Width(360).Padding(24).Radius(16).Background(t.Background) ui.Text(c, "Welcome").FontSize(20).Bold() }) ``` See [custom widgets](https://mygo.egoist.dev/docs/ui/custom-widgets.md). ## Accessibility Assistive technology sees a dialog, and nothing behind it while it shows. --- Source: https://mygo.egoist.dev/docs/ui/diff-viewer.md # Diff viewer `editor.DiffView` shows the changes between two texts, as Pierre's diffs and code review tools do: side by side or one over the other, with the words changed within lines highlighted, the unchanged lines between changes collapsed, and the new text editable where it shows. It is a [code editor](https://mygo.egoist.dev/docs/ui/code-editor.md) on each side, with the editor's highlighting, selections and commands, laid out and painted only where in view. ```go import "github.com/egoist/mygo/ui/editor" lang := editor.LanguageFor("main.go") before, after := editor.NewBuffer(original), editor.NewBuffer(edited) before.SetLanguage(lang) after.SetLanguage(lang) app.diff = &editor.DiffState{Old: before, New: after, Editable: true} // In the view: editor.DiffView(c, app.diff).Grow(1).FillWidth() ``` A `DiffState` is the viewer's state, kept across frames: the buffers it compares, its options, and what it keeps of its own, as the lines expanded and its scroll position. Zero options are the defaults, those of Pierre's diffs. The diff follows the buffers: an edit in either shows at once, the viewer diffing again only the lines around it. `New` can be the buffer of an editor too, as a file's, so that the diff shows its changes as they are typed. Texts of more than 10,000 lines, or 1 MB, together are compared off the main thread once a window shows them, so that opening a large file never holds up the window: the viewer shows the texts without changes until the comparison is done, and the window draws again with them. Meanwhile `Comparing` reports it, and `Hunks` and `Stats` have none. Edits of `New` go on as usual, the diff catching up with them once it arrives; an edit of `Old` starts the comparison again. An empty text has no lines, as `git diff` counts them: the side of a file added or deleted, or emptied, shows no line numbers, and its gutter selects no line and offers no button. A text's lines end at its final newline, as git's do: a diff that isn't `Editable` leaves out the empty line an editor starts after it, which no separator counts, while an editable one shows it, as typing there adds a line. A diff that isn't `Editable` compares lines with their line feeds, as git does, so a last line that gains or loses its newline is a changed line, and the last line of a text without a final newline ends with a muted "No newline at end of file", git's `\ No newline at end of file`. `SetPatch`, whose texts hold only the patch's lines, marks the sides its `\` lines name. An editable diff compares lines without them and marks none: adding the final newline adds the empty line after it, where typing goes. ## Layout * `Layout` shows the old text on the left and the new on the right, their lines aligned (`DiffSplit`), the two scrolling together; or the new text, with the lines deleted above where they were (`DiffUnified`). * `SplitPercent` is the percentage of a split view's width the old side takes, half when 0. The user drags the line between the sides to change it, or moves it with the arrows once Tab gave it the focus, as a [split view](https://mygo.egoist.dev/docs/ui/split.md)'s divider; each side keeps its gutter and 12 columns of text, and a view too narrow for both shows halves, keeping the share for when it is wide again. Keep it in the app's settings to show the sides as the user left them: ```go app.diff.SplitPercent = app.settings.DiffSplit // 0 the first time: halves editor.DiffView(c, app.diff).Grow(1).FillWidth() app.settings.DiffSplit = app.diff.SplitPercent ``` The sides keep scrolling together and their lines aligned: sideways each scrolls as far as its own lines run past it, and with `Wrap` the side wrapping a line in fewer rows leaves the room of the others under it. * `Inline` highlights what changed within changed lines: words, joining those one character apart so that a phrase reads as one change (`DiffInlineWordAlt`, the default), each word, from the first word to the last, characters, or nothing. * `Indicators` marks changed lines with bars at the gutter's edge, striped for deletions (`DiffBars`), with + and − before them (`DiffClassic`), or by their background alone. `NoBackground` leaves out the tints of changed lines, and `NoLineNumbers` the numbers. * `ContextLines` unchanged lines show around each change, 3 by default. The others collapse into separators of "N unmodified lines", whose buttons show `ExpansionLines` more at a click (100 by default), and all of them with Shift; `ExpandUnchanged`, `ExpandAll` and `CollapseAll` show or collapse them all. * `Wrap` wraps long lines, rows of each side keeping their partners aligned; `FitContent` makes the viewer as high as its lines, as the files of a review in a scroll view. * `KeepScrollbars` and `NoScrollbars` are those of the code editor: the scroll bar stays with the pointer away, so that a diff filling the window shows how far down it is, or goes, with its room. * `ScrollPastEnd` lets the lines scroll up until the last is at the top, as the code editor's do unless `NoScrollPastEnd`, so that `GoToHunk` can bring a change near the end to the middle of the view; it has no effect with `FitContent`. Off, the view stops at the last line. * `Font`, `LineHeight`, `TabSize` and `Theme` are those of the code editor. Changes are tinted with the theme's `Added`, `Deleted` and `Modified` colors, mixed with the background in a perceptual color space so that they read alike in light and dark. Lines are compared as git's histogram diff compares them, with Myers' for what it cannot split, and changes slide to where git's indent heuristic puts them, so that a function added shows as that function rather than its last lines and the next one's first. Changed lines are paired with those most like them for highlighting words, rather than in order. ## Editing and review With `Editable`, the new side edits as the code editor does: typing, several carets, undo, finding and every command, the diff following each keystroke. Cmd+F8 and Shift+Cmd+F8 go to the next and previous changes (Alt+F5 and Shift+Alt+F5 elsewhere), and `GoToHunk` goes to one. * `HunkActions` shows Revert and Keep on the change under the pointer, or the caret's: Revert puts the old lines back in `New`, Keep makes the new lines `Old`'s, as an agent's changes are reviewed one at a time. `Revert` and `Accept` do the same from the app; `Hunks` lists the changes, and `Stats` counts the lines added and deleted. * `LineSelection` lets the numbers of lines be clicked, and dragged or Shift-clicked, to select lines, which `OnLineSelection` reports and `SelectedLines` and `SetSelectedLines` read and set, as a link to lines of a review does. * `OnGutterButton` shows a + on the gutter of the line under the pointer, as to comment on it, and is called with the line when it is clicked. * `Annotations` leave room under lines for what `RenderAnnotation` builds there, as the comments of a review, each as high as it asks; the other side of a split view leaves the room empty, so that the lines stay aligned. ```go app.diff.HunkActions = true app.diff.OnGutterButton = func(r editor.DiffLineRange) { app.comments = append(app.comments, comment{side: r.Side, line: r.End}) } app.diff.Annotations = app.diff.Annotations[:0] for i, cm := range app.comments { app.diff.Annotations = append(app.diff.Annotations, editor.DiffAnnotation{Side: cm.side, Line: cm.line, Height: 72, Key: i}) } app.diff.RenderAnnotation = func(c *ui.Context, a editor.DiffAnnotation) { app.commentView(c, a.Key.(int)) } ``` `ActiveSide` is the side that has the keyboard, or had it last: the new side until the old one of a split view has it. `Cursor` and `CursorPos` return the offset and the position of its newest caret, as the code editor's do, and `CurrentHunk` the change the caret is in, with `inside` true, or else the last before it, -1 before the first, as "2 of 5" counts them; `GoToHunk` moves that caret, so Next Change can step from it, and leaves the keyboard where it was: `Focus` gives it to the diff, to its active side, as the frame is next built, so that its caret shows and its keys work after a button or a menu item moved the caret. A button that `KeepFocus`es leaves the keyboard in the diff by itself, when it was there. `Run` runs a command in its editor as its key would, and `Find` opens its find bar on a query, as an app's menu items do where the menu takes the keys first: ```go if ui.Button(c, "Find").Clicked() { app.diff.Run(editor.Find) } i, inside := app.diff.CurrentHunk() n := len(app.diff.Hunks()) label := fmt.Sprintf("%d changes", n) // before the first if i >= 0 { label = fmt.Sprintf("%d of %d", i+1, n) } ui.Text(c, label) if ui.Button(c, "Next change").Clicked() { app.diff.GoToHunk(i + 1) } if inside && ui.Button(c, "Revert this change").Clicked() { app.diff.Revert(i) } ``` `ScrollY` is how far the diff is scrolled, in DIPs, and `ViewportHeight` how high the part of it in view is, as the last frame laid them out, whether the wheel, the keys, the scroll bar or `GoToHunk` scrolled it; `SetScrollY` scrolls it. `LineTop(side, line)` is where a line of either side shows, below the diff's top, collapsed lines taking no room and, in a unified view, deleted lines above their change; `LineTop` of a side's count of lines is the height of the whole diff. With them an app draws a minimap beside the diff: its changes, and a box where the view is, which a click or a drag scrolls to: ```go d := app.diff var scale float64 // DIPs of the minimap per DIP of the diff, as last drawn ui.Row(c).Fill().Children(func() { editor.DiffView(c, d).Grow(1).FillHeight() mini := ui.Box(c).Width(18).FillHeight() mini.Draw(func(p *ui.Painter, r ui.Rect) { scale = float64(r.H) / max(d.LineTop(editor.DiffNew, d.New.LineCount()), 1) at := func(y float64) float32 { return r.Y + float32(y*scale) } for _, h := range d.Hunks() { top := at(d.LineTop(editor.DiffNew, h.NewStart)) bottom := at(d.LineTop(editor.DiffNew, max(h.NewEnd, h.NewStart+1))) p.Fill(ui.Rect{X: r.X, Y: top, W: r.W, H: max(bottom-top, 2)}, app.changeColor, 0) } view := ui.Rect{X: r.X, Y: at(d.ScrollY()), W: r.W, H: float32(d.ViewportHeight() * scale)} p.Stroke(view, c.Theme().Border, 0, 1) }) mini.HandleInput(func(ev ui.InputEvent) bool { if ev.Kind == ui.InputPointerDown || ev.Kind == ui.InputPointerMove && ev.Button == 0 { // The view centered where the minimap is pressed, or dragged. d.SetScrollY(float64(ev.Y)/max(scale, 1e-9) - d.ViewportHeight()/2) return true } return ev.Kind == ui.InputPointerUp }) }) ``` ## Styling `Theme` colors the diff as it does the [code editor](https://mygo.egoist.dev/docs/ui/code-editor.md#themes), changed lines included. The parts around the lines are the app's to build, as Pierre's diffs render them: `RenderSeparator`, `RenderHunkActions` and `RenderGutterButton` are given the element the viewer places and what the part shows and does, and the viewer's own looks are `DefaultSeparator`, `DefaultHunkActions` and `DefaultGutterButton`, which they can call. `RenderFindBar` and `RenderGoToLine` build the bars of the sides' editors, as the code editor's do. ```go app.diff.RenderSeparator = func(c *ui.Context, sep ui.Element, s *editor.DiffSeparator) { sep.Padding(4).Children(func() { if s.Lines == 0 { // a patch's hunk ui.Text(c, s.Header).Font("monospace") return } if ui.Button(c, fmt.Sprintf("Show %d hidden lines", s.Lines)).Clicked() { s.ExpandAll() } }) } app.diff.RenderHunkActions = func(c *ui.Context, bar ui.Element, a *editor.DiffHunkActions) { bar.Gap(4).Children(func() { if ui.Button(c, "Reject").Clicked() { a.Revert() } if ui.PrimaryButton(c, "Accept").Clicked() { a.Keep() } }) } ``` * A `DiffSeparator` spans the viewer, both sides of a split one, less the room of the scroll bar's track while the viewer scrolls (none with `FitContent`), 32 DIPs high. It collapses `Lines` unchanged lines, which `ExpandUp`, `ExpandDown` and `ExpandAll` show, `Step` lines at a time; `First` and `Last` mark those before the first change and after the last, which expand one way. A patch's hunk has a separator of no lines, with its `Header`. * `DiffHunkActions` sit at the top right of the change under the pointer, or the caret's: `Index` and `Hunk` say which, and `Revert` and `Keep` act. * The gutter button is a button on the gutter of the line under the pointer, which calls `OnGutterButton` when clicked; its render function gives it a look and a label. ## Patches `editor.ParsePatch` reads the files a unified diff changes, as `git diff` and `diff -u` print them, with renames, modes and new and deleted files; `FilePatch.Apply` applies one to the old file's text. `SetPatch` shows a file's patch without the files, as a pull request's diff arrives: its hunks' lines, numbered as in the files, each hunk under its header. Each hunk is highlighted on its own, from the start of its first line, as `git diff` colors it, so a comment or a string that the hunk before ends in doesn't go on into it. A language's own `Highlighter` ([Highlighters](https://mygo.egoist.dev/docs/ui/code-editor.md#highlighters)) sees the hunks' lines as one text. ```go files, err := editor.ParsePatch(output) // of git diff if err != nil { return err } for _, f := range files { d := &editor.DiffState{} d.SetPatch(f) app.files = append(app.files, d) } ``` When the app has the files too, as a git client reads them from the repository, `SetPatchFiles(f, old, new)` shows the whole files with the patch's changes: its runs of `-` and `+` lines, as `git diff` aligned them with its options (`--patience`, `--histogram`), not what comparing the texts would find. The unchanged lines between them collapse into separators that expand, as in any diff. It returns an error, and changes nothing, when the patch is binary or doesn't make `new` from `old`: ```go old := app.fileAt("HEAD", f.OldName) // the app's own git read new := app.fileAt("", f.NewName) // the working tree's if err := d.SetPatchFiles(f, old, new); err != nil { d.SetPatch(f) // the files moved on since the patch: show its hunks } ``` ## Accessibility Assistive technology sees each side as a text field, "Old text" and "New text", the old one read only, with its text and selection, and the line between the sides of a split view as a splitter named "Divider", whose value is the old side's width, which the arrows move. Inside each side, every line in view is an element of its own, in the order they show, named by its text and described by its number ("Line 12"): a line added is an insertion, one deleted a deletion (the old side's changed lines, and the deleted lines a unified view shows between the new text's, whose numbers are the old text's, "Old line 12"), and an unchanged one a text, so that screen readers read each line as what it is. A separator is a group named by how many lines it collapses and described by which ("Lines 30 to 41", or the old and the new numbers where they differ), with buttons expanding them up, down or all; Revert and Keep are buttons, "Revert change" and "Keep change". These names, and what the viewer writes ("4 unmodified lines"), are in the window's language ([MyGo's own strings](https://mygo.egoist.dev/docs/i18n.md#mygos-own-strings)). ```go for _, a := range tt.AccessAll() { if a.Role == ui.RoleInsertion { fmt.Println("added:", a.Description, a.Name) // added: Line 12 return nil } } ``` --- Source: https://mygo.egoist.dev/docs/ui/drag-and-drop.md # Drag and drop `Drag(value)` makes an element the source of a value dragged within the window: once the pointer pressing it moves a few DIPs, a translucent copy of the element follows the pointer, and the press is no click. `ui.Drop[T](e)` makes `e` take values of type `T`, returning the one dropped on it, and `ui.DragOver[T](e)` the one over it, for showing it would take it: ```go for _, task := range app.todo { ui.Row(c).Key(task.ID).Drag(task).Children(func() { ui.Text(c, task.Name) }) } done := ui.Column(c).Grow(1).Padding(12).Radius(8).Border(1, t.Border) if _, over := ui.DragOver[*Task](done); over { done.Border(2, t.Accent) } if task, ok := ui.Drop[*Task](done); ok { task.Done = true } ``` * **Targets.** The innermost element under the pointer that takes the value's type gets it, so a target inside another that takes other types does not block it. * **Controls inside.** A press on a control that only takes clicks, as a button, inside an element that drags drags that element once the pointer moves, and is no click: a list's rows made of buttons reorder. A press that does not move clicks the control. Controls that take the pointer's moves, as text inputs and sliders, keep them. * **Canceling.** Escape gives up a drag. * **Scrolling.** Scroll containers scroll as a drag nears their top or bottom, faster nearer to the edge. * **Dragging several.** The copy shows how many values a drag holds, beside the pointer, as when the rows chosen in a list are dragged together. `Dragging` reports that an element is dragging its value, to dim it where it was. `DragMissed` reports, in the frame after, that the value was let go over no element taking it, and where, in the window's coordinates: outside the window when it was let go past its edge, as to tear a tab out into a window of its own. A drag given up with Escape is not missed. ```go tab := ui.Row(c).Drag(t.id) w, h := c.Size() if at, ok := tab.DragMissed(); ok && (at.X < 0 || at.Y < 0 || at.X > w || at.Y > h) { app.tearOut(t, at) } ``` ## Reordering Lists, tables and grid views reorder their rows by dragging with `ListState.Reorder` and `GridState.Reorder`: the rows chosen move together when the row dragged is one of them, the list shows where they would go with a line, and the rows go where the pointer let them go. ```go app.list.Reorder = func(rows []int, to int) { app.items = move(app.items, rows, to) // before row to, len for the end } ``` See [List](https://mygo.egoist.dev/docs/ui/list.md#reordering) and [Grid view](https://mygo.egoist.dev/docs/ui/grid-view.md). A list's rows can also leave it, as files dragged into a folder: with `ListState.DragRows` they drag a value of the app's, for `ui.Drop` to take anywhere. See [List](https://mygo.egoist.dev/docs/ui/list.md#dragging-rows-out). Files dragged from other apps are [dropped files](https://mygo.egoist.dev/docs/ui/input.md#dropped-files). ## Between windows and applications `DragData` starts a system drag with explicit representations from package `transfer`. Files, text, URLs, HTML, PNG and custom serialized formats can leave the app or come from another app. `DropData` and `DataDragOver` declare the formats and operations an element accepts: ```go data := transfer.TextData("Hello from MyGo") ui.Text(c, "Drag me").Padding(12).DragData(data) zone := ui.Box(c).Size(260, 140).Border(1, c.Theme().Border) options := transfer.DropOptions{Formats: []transfer.Format{transfer.Text}} if _, over := ui.DataDragOver(zone, options); over { zone.Border(2, c.Theme().Accent) } if drop, ok := ui.DropData(zone, options); ok { text, err := drop.Data.Read(transfer.Text) if err == nil { app.message = string(text) } } ``` The innermost matching enabled target receives the drop once, in the next frame. At least one advertised format must match, and the source and target must share an operation. Hover advertises formats without reading bytes. Accepted representations are copied on drop; the resulting data is safe to keep and read from a goroutine after the native session ends. ### Representations and lazy providers An item can offer alternatives to the same content. Custom formats use MIME names and explicit encodings, such as JSON: ```go const taskFormat transfer.Format = "application/vnd.example.task+json" frozen := *task // snapshot the value that all representations describe data := transfer.New(transfer.NewItem( transfer.Bytes(transfer.Text, []byte(frozen.Title)), transfer.Lazy(taskFormat, func() ([]byte, error) { return json.Marshal(frozen) }), )) row.Drag(task).DragData(data) ``` `Bytes` copies its input. `Lazy` advertises a format and caches its result or error once per drag session, when requested by a receiver. Providers run on the main thread and must return promptly. Prepare expensive data on a goroutine before offering it; a provider must never wait for work needing the main thread. External applications can request data before release. Use `DragDataFrom(func() transfer.Data { ... })` to snapshot a changing selection when the gesture starts. Use `transfer.URLData(url)` and `transfer.FileData(absolutePaths...)` for URLs and file lists. File paths are escaped as file URLs; the receiver's `Data.Files()` returns local paths, while `Data.URLs()` returns URI-list entries. `FileData` transfers existing paths; it does not create promised files or stream file contents. `Drag(value)` alone stays within its window. Combining it with `DragData` also offers its Go value to existing `Drop[T]` and `DragOver[T]` targets in other windows of the same process. Those typed targets accept copy. A temporary random session token identifies the value; native representations contain no Go pointer and the token stops resolving when the source ends. Other processes use the serialized representations and decode them explicitly. ### Copy, move, completion and cancellation Sources and destinations default to copy. To allow moves, give both `Operations: transfer.Copy | transfer.Move`. The modifier-key suggestion wins when both ends allow it; otherwise copy is preferred, then move. An incompatible offer is rejected. Option requests copy on macOS and Ctrl elsewhere; Cmd requests move on macOS and Shift elsewhere. ```go row.DragData(data, transfer.DragOptions{ Operations: transfer.Copy | transfer.Move, Done: func(result transfer.Result) { if result.Err != nil { app.report(result.Err) } else if result.Operation == transfer.Move { app.removeOriginal(task.ID) } }, }) ``` `Done` runs exactly once on the main thread, including cancellation, native startup failure, source removal and window destruction. Escape cancels through the system drag tracker. `Window.CancelDataDrag()` cancels a source owned by that window, from any goroutine. `Window.StartDataDrag` starts a transfer directly from a current native pointer gesture; UI elements normally use `DragData` so the movement threshold is applied. `Result.Operation` is the destination's final effect. `Canceled` means no drop occurred; `Escaped` tells a drag the user gave up (Escape, `CancelDataDrag` or the window closing) from one let go over no target, and `Point` is where the drag ended, in the screen coordinates of `Screen.CursorScreenPoint`. A tab let go outside every window, for example, is `Canceled && !Escaped` at `Point`. `Err` reports a native/provider failure. MyGo never deletes files. Remove application records only after a successful move, and account for file managers that move a file themselves. Existing `DroppedFiles` and `OnFileDrop` listeners keep accepting files with copy semantics. The default preview is a snapshot of the source's visible element, bounded to 512 DIPs. Set `DragOptions.Preview` to an `image.Image` and `Hotspot` to its pointer offset for a custom preview (up to 4096 pixels per dimension). The image is copied at drag start; one image pixel represents one DIP. ### Native format mapping | Platform | Native transfer | Representations | | -------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | macOS | AppKit dragging sessions and pasteboard item providers | Text/HTML/PNG/file URLs use system UTIs. MIME names map through `UTType`, with a reversible identifier fallback. Item boundaries are preserved. | | Linux | GTK 3 drag contexts and asynchronous selections | MIME targets, UTF8_STRING for text, text/uri-list for URLs and files. Accepted formats are requested after drop. | | Windows | OLE IDataObject / IDropSource / IDropTarget | Unicode text, CF_HDROP, URL, CF_HTML, PNG and registered custom names; delayed rendering and Shell drag images. Streams preserve exact binary lengths; HGLOBAL sources may include padding. | | Browsers | Files dropped on the canvas, read as they drop (see [browsers](https://mygo.egoist.dev/docs/ui/browsers.md)) | Files only, at paths of the backend's that `os` reads. Other drags, and drags out of the window, have no transfer. | GTK and OLE have a single selection/data object: multiple text items are joined by newlines, URI/file lists by CRLF, and other formats use the first item offering them. Transfers between windows in the same MyGo process preserve all items through the core's local registry. Incoming GTK/OLE representations are limited to 64 MiB each; native providers must supply memory or stream representations (virtual-file promises are not supported). See [`examples/drag-drop`](https://github.com/egoist/mygo/tree/main/examples/drag-drop) for two windows exchanging notes, files, text and URLs, including a lazy JSON representation and move completion. The transfer model is reusable without native UI; existing clipboard convenience methods keep their signatures. `Clipboard.Write` and `Clipboard.Read` exchange this same `transfer.Data`; each clipboard write and drag gets an independent provider cache. See [Clipboard and drag data](https://mygo.egoist.dev/docs/data-transfer.md) for clipboard negotiation, persistence, and provider lifetimes. --- Source: https://mygo.egoist.dev/docs/ui/drawing.md # Drawing and animation `Draw` paints on an element after its background, and `DrawOver` after its children, with a `*ui.Painter` in DIPs of the window: rectangles with `Fill`, `FillGradient`, `FillConicGradient` and `FillRadialGradient`, `Stroke` and `StrokeDashed`, `Shadow`, `Line` (horizontal or vertical), `Image`, `Clip` and `ClipPath`, paths of lines and curves with `FillPath` and `StrokePath`, or in a gradient with `FillPathGradient` and `StrokePathGradient`, and text with `Text`, or `RichText` in spans of any style, which `MeasureText` measures first, to center or align it: ```go ui.Box(c).Height(120).Draw(func(p *ui.Painter, r ui.Rect) { var wave ui.Path for i := 0; i <= 100; i++ { x := r.X + r.W*float32(i)/100 y := r.Y + r.H/2 + 40*float32(math.Sin(float64(i)/8)) if i == 0 { wave.MoveTo(x, y) } else { wave.LineTo(x, y) } } p.StrokePath(&wave, 2, c.Theme().Accent) }) ``` ```go ui.Box(c).Size(200, 40).Draw(func(p *ui.Painter, r ui.Rect) { label := ui.Span{Text: "42%", Weight: 600, Color: c.Theme().TextMuted} w, h := p.MeasureText(0, label) p.RichText(r.X+(r.W-w)/2, r.Y+(r.H-h)/2, 0, label) }) ``` Paragraphs a view lays out itself, as the pages of a book reader, are shaped once with `ui.ShapeRichTextWith`, justified and indented if need be, and drawn with `Painter.TextLayout`; their `Lines` tell where each line is, to break pages between them (see [retained text geometry](https://mygo.egoist.dev/docs/ui/text-input-client.md#retained-text-geometry)). Draw functions only paint: MyGo may call them more than once a frame. `Painter.Icon` and `Painter.Image` draw SVGs and bitmaps, `Painter.ImageRegion` parts of bitmaps (see [Parts of bitmaps](#parts-of-bitmaps)), and `Painter.FocusRing` the ring of the keyboard focus, as the theme draws it (see [the focus ring](https://mygo.egoist.dev/docs/ui/styling.md#the-focus-ring)), for widgets that draw their own. `Path.Trim(from, to)` keeps the part of a path's length from `from` to `to`, as fractions of it, which draws a path in as `to` animates from 0 to 1, as SwiftUI's `trim` and Motion's `pathLength`: ```go drawn := float32(0) if app.done { drawn = 1 } drawn = box.AnimateTo("check", drawn, ui.Smooth) box.Draw(func(p *ui.Painter, r ui.Rect) { check := (&ui.Path{}).MoveTo(r.X+4, r.Y+12).LineTo(r.X+10, r.Y+18).LineTo(r.X+20, r.Y+6) p.StrokePath(check.Trim(0, drawn), 2, c.Theme().Accent) }) ``` A stroke has round ends and corners unless its path sets them, as SVG's `stroke-linecap`, `stroke-linejoin` and `stroke-miterlimit` do: `Path.Cap` ends it flat (`ui.ButtCap`) or square (`ui.SquareCap`), and `Path.Join` turns its corners in points (`ui.MiterJoin`, bevelled past `Path.MiterLimit`) or cuts them (`ui.BevelJoin`). `Path.Dash` strokes it in dashes, as `stroke-dasharray` and `stroke-dashoffset` do, and they stay where they are as `Trim` draws the path in: ```go box.Draw(func(p *ui.Painter, r ui.Rect) { edge := (&ui.Path{}).MoveTo(r.X, r.Y+r.H/2).LineTo(r.X+r.W, r.Y+r.H/2) p.StrokePath(edge.Cap(ui.ButtCap).Dash(0, 6, 4), 1.5, c.Theme().TextMuted) }) ``` ## Fill rules and hits A path fills, and clips, the points its subpaths wind around (SVG's `nonzero`), so a subpath inside another one leaves a hole only when it goes the other way round. `Path.FillRule(ui.EvenOdd)` fills the points its subpaths go around an odd number of times instead, as SVG's `fill-rule` and `clip-rule: evenodd` do, which makes a ring or a donut of two circles, and a shape with a cut-out, whichever way their path data draws them: ```go box.Draw(func(p *ui.Painter, r ui.Rect) { cx, cy := r.X+r.W/2, r.Y+r.H/2 donut := (&ui.Path{}).Circle(cx, cy, r.W/2).Circle(cx, cy, r.W/4).FillRule(ui.EvenOdd) p.FillPath(donut, c.Theme().Accent) }) ``` `Path.Contains(x, y)` reports whether a point is inside a path as it fills, by its rule, as the web's `isPointInPath`: a view's handler can tell which segment of a pie a press is in. `HitTest` makes an element take the pointer only where a function says, given the pointer in the coordinates `Draw` paints in, so a pie's segments, a map's regions or a ring take presses, hover and the cursor only where they paint, as SVG's `pointer-events: visiblePainted`, and the pointer reaches what is under them elsewhere: ```go seg := func(r ui.Rect) *ui.Path { return slice(r, from, to) } // a segment's outline ui.Box(c).Absolute().Fill(). Draw(func(p *ui.Painter, r ui.Rect) { p.FillPath(seg(r), color) }). HitTest(func(x, y float32, r ui.Rect) bool { return seg(r).Contains(x, y) }). OnClick(func() { app.pick(i) }) ``` ## Paths from SVG data `ui.ParsePath(d)` reads the path data of an SVG `` (all of its commands, absolute and relative, arcs too) into a `*ui.Path`, so an icon's outline copied from an SVG can be filled, stroked, trimmed or clipped to like any path. It returns an error that gives the offset of the first thing it can't read; `ui.MustParsePath` panics instead, for data written into the program: ```go var heart = ui.MustParsePath("M12 21 L10.6 19.7 C5.4 15 2 11.9 2 8.1 C2 5 4.4 2.6 7.5 2.6 " + "C9.2 2.6 10.9 3.4 12 4.7 C13.1 3.4 14.8 2.6 16.5 2.6 C19.6 2.6 22 5 22 8.1 " + "C22 11.9 18.6 15 13.4 19.7 Z") box.Draw(func(p *ui.Painter, r ui.Rect) { p.Transform(ui.Scaling(r.W/24, r.H/24).Then(ui.Translation(r.X, r.Y)), 0, 0, func() { p.StrokePath(heart.Trim(0, drawn), 1.5, c.Theme().Accent) }) }) ``` The path is in the data's own units; a transform scales it to the box. ## Clipping to a path `Painter.Clip(r, radius, fn)` clips what `fn` draws to a rounded rectangle. `Painter.ClipPath(path, fn)` clips it to the inside of any path (by its `FillRule`), with smooth edges, as SVG's and CSS's `clip-path`: a chart drawn into a polygon, or a picture cut to a star. ```go star := ui.MustParsePath("M50 0 L61 35 L98 35 L68 57 L79 91 L50 70 L21 91 L32 57 L2 35 L39 35 Z") ui.Box(c).Size(100, 100).Draw(func(p *ui.Painter, r ui.Rect) { p.Transform(ui.Translation(r.X, r.Y), 0, 0, func() { p.ClipPath(star, func() { p.FillGradient(ui.Rect{W: 100, H: 100}, ui.LinearGradient{From: gold, To: orange, Angle: 135}, 0) }) }) }) ``` Path clips nest with each other and with `Clip`, and turn with a transform. The clip is a mask of the path's coverage that every renderer samples, made once for each shape and size it is drawn at and kept while frames draw it, so a still path costs nothing to clip to again. A moving or changing one makes a new mask every frame, sized to the path in device pixels (at most 8192 each way). To clip an element and its children rather than a drawing, see `ClipInset` and the gradient masks in [styling](https://mygo.egoist.dev/docs/ui/styling.md). ## Parts of bitmaps A bitmap can hold many pictures: the icons of a sheet, the frames of an animation, the cells of a contact sheet. `Painter.ImageRegion` draws one part of it, `src` in the bitmap's pixels, into a rectangle; nothing of the bitmap around the part shows, smooth or pixelated. Its `ImageOptions` mirror the part (`FlipX`, `FlipY`) and tint it (`Tint` multiplies its colors and alpha): ```go icons, _ := ui.DecodeBitmap(iconsPNG) // 16×16 icons in a row icon := func(i int) ui.Rect { return ui.Rect{X: float32(i * 16), W: 16, H: 16} } box.Draw(func(p *ui.Painter, r ui.Rect) { p.ImageRegion(icons, icon(3), ui.Rect{X: r.X, Y: r.Y, W: 24, H: 24}, ui.ImageOptions{Tint: c.Theme().TextMuted}) }) ``` A part outside what the painter shows draws nothing, so a view of many can draw them all without culling them itself, as games draw their sprites and tiles. ## Canvases A `ui.Canvas` is a bitmap a painter draws, on the GPU where the window draws there: render to texture, as Skia's `SkSurface` and LÖVE's `Canvas`. `Draw` draws it anew during a frame, with a painter in its pixels, and it keeps what it holds, showing anywhere a bitmap does through `Bitmap`: ```go grid := ui.NewCanvas(800, 400) drawn := false box.Draw(func(p *ui.Painter, r ui.Rect) { if !drawn { // once, then every frame for the price of an image drawn = true grid.Draw(p, func(cp *ui.Painter) { drawGrid(cp, 800, 400) }) } p.Image(grid.Bitmap(), r, ui.FillBox) drawSeries(p, r) }) ``` A canvas drawn with a tint or an opacity fades or colors a whole layer at once. Canvases show other canvases, and text. A canvas's pixels are its units: draw it at the window's scale (`Painter.Scale`) for one as sharp as the window, or smaller and make its bitmap `Pixelated` to scale pixel art up crisp (the [game plugin](https://mygo.egoist.dev/docs/plugins/game.md#pixel-perfect-scaling) shows one at whole multiples). A [shader](https://mygo.egoist.dev/docs/ui/shaders.md) reads canvases as images, and draws into them. ## Transforms `Painter.Transform(t, ox, oy, fn)` transforms what `fn` draws by `t`, a `ui.Transform` such as `Translation`, `Scaling` or `Rotation`, around the point `(ox, oy)`, which stays where it is. Transforms nest, after the painter's own, so a view that pans and zooms, as a map or a diagram, draws its content through one, and turns a part of it inside: ```go ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) { view := ui.Translation(-doc.panX, -doc.panY).Then(ui.Scaling(doc.zoom, doc.zoom)) p.Transform(view, r.X, r.Y, func() { for _, n := range doc.nodes { p.Fill(n.box, n.color, 6) // culled where the view does not look } cx, cy := doc.dial.X, doc.dial.Y p.Transform(ui.Rotation(doc.dial.angle), cx, cy, func() { p.Line(cx, cy, cx, cy-40, 2, c.Theme().Accent) }) }) }) ``` Clips made inside turn with what they clip. Input is not transformed: the pointer comes in the element's coordinates, which the app maps to its content with the inverse of its view. Under a transform, images and their parts are placed where they are rather than on whole pixels, so that one moving through a zoomed view glides. ## Shaping text Text that a widget lays out itself, as in the cells of a grid, is shaped once with `ui.Shape`, which returns glyphs placed along a line by the system's text engine, with ligatures, kerning and fallback fonts, and the runes each comes from. The glyphs come in visual order on every platform, from the left: through Hebrew or Arabic their `Cluster` descends, and `RTL` marks them, so find a range of runes' glyphs by `Cluster` and `Runes`. Move their `X` and draw them with `Painter.Glyphs`; `Font.Metrics` returns the font's ascent, descent and line gap, and `Painter.Scale` the device pixels of a DIP, to line things up with the display's pixels. `Shape` caches nothing, unlike the text of elements: keep the glyphs of text drawn in many frames. `Font.Features` turns OpenType features on and off, and `Font.Thicken` draws text with a thicker stroke on macOS, as Ghostty's `font-thicken`, and `Font.Antialiased` a thinner one, without font smoothing, as browsers draw text styled `-webkit-font-smoothing: antialiased`. ```go font := ui.Font{Family: "monospace", Size: 13} glyphs := ui.Shape("grid", font) for i := range glyphs { glyphs[i].X = float32(glyphs[i].Cluster) * cellWidth // one per cell } ui.Box(c).Height(20).Draw(func(p *ui.Painter, r ui.Rect) { p.Glyphs(glyphs, r.X, r.Y+font.Metrics().Ascent, c.Theme().Text) }) ``` ## Animation For motion, `Element.Animate` returns a value that eases to a target and draws frames until it gets there: ```go panel := ui.Column(c).Clip() width := float32(0) if app.sidebar { width = 280 } panel.Width(panel.Animate("width", width, 200*time.Millisecond)) ``` `AnimateWith` takes the easing: `ui.Linear`, `ui.EaseIn`, `ui.EaseOut` (as `Animate`), `ui.EaseInOut`, `ui.CubicBezier(x1, y1, x2, y2)`, any `func(t float32) float32`, or `ui.Bounce(e)`, which goes along `e` and comes back. `AnimateTo` takes springs as well (see [Motion](https://mygo.egoist.dev/docs/ui/motion.md)). `Loop` returns the progress of an animation that starts over every period, for spinners and pulses; `Rotate` turns an element, as an icon: ```go spin := ui.Icon(c, loader) spin.Rotate(spin.Loop("spin", time.Second, ui.Linear) * 360) skeleton := ui.Box(c).Height(14).Radius(7).Background(t.Border) skeleton.Opacity(0.4 + 0.6*skeleton.Loop("pulse", 1600*time.Millisecond, ui.Bounce(ui.EaseInOut))) ``` To animate in other ways, compute from `c.Now()` and call `c.AnimationFrame()` in every frame that moves: MyGo draws the next frame when the display can show it, and draws nothing while nothing changes. A drawing that moves while the layout stays, as a spinner or a chart scrolling by, animates from its `Draw` instead: compute it from `p.Now()` and call `p.AnimationFrame()` while it moves, or `p.After(d)` when it changes in steps. Unless something else changed, those frames paint the elements of the last frame again without running the view, so they cost only the painting; and an element out of view is not painted, so it asks for none. While the window is out of sight (hidden, minimized, or covered by other windows), MyGo draws no frames at all, from `Draw` or the view, until some of it shows again: compute what moves from the time, as here, and it shows where the time puts it (see [Motion](https://mygo.egoist.dev/docs/ui/motion.md#out-of-sight)): ```go ui.Box(c).Height(4).Draw(func(p *ui.Painter, r ui.Rect) { p.AnimationFrame() x := r.X + (r.W-20)*float32(p.Now().UnixMilli()%1000)/1000 p.Fill(ui.Rect{X: x, Y: r.Y, W: 20, H: r.H}, c.Theme().Accent, 2) }) ``` A drawing that looks as smooth at fewer frames, as a record turning, a slow wave or a level meter, can ask for them with `p.AnimationFrameRate(fps)` in place of `p.AnimationFrame()`: the window paints it again that often, rather than at each of the display's refreshes (120 a second on ProMotion displays), and on macOS has the display refresh as often, which saves power. The rate rounds up to one the display shows evenly, a whole number of refreshes a frame: 60, 40 or 30 frames a second on a 120 Hz display, 60 or 30 on a 60 Hz one. The window draws at the fastest rate anything in it asks for, so a drawing asking for `AnimationFrame` or a view that animates still draws at the display's. Pacing with `p.After(time.Second / 60)` instead draws unevenly: a frame asked for later than a refresh waits for the next. Such a `Draw` sees the state as the view last ran: what it reads that changes otherwise is the view's to build anew, after `Window.Update`. When the desktop asks for less motion (`c.Preferences().ReduceMotion`), `Animate` and `AnimateWith` go to their target at once. `Loop` goes on, as the system's spinners do: it shows that something is going on. Motion you compute yourself should read the preference too. [Motion](https://mygo.egoist.dev/docs/ui/motion.md) has springs that keep their velocity, delays, values following the pointer, keyframes, and how to tell when an animation is done; [Transforms](https://mygo.egoist.dev/docs/ui/transforms.md) move, scale and rotate any element. --- Source: https://mygo.egoist.dev/docs/ui/editable-text.md # Editable text `ui.EditableText` shows a `*string` as a text that the user edits in place, as a file's name in Finder: a double click on it, or Enter while it has the focus, shows a text input of it, with the text before its extension selected. Enter keeps what was typed, as moving the focus away does, and Escape goes back; `Changed` reports a new value. ```go if ui.EditableText(c, &app.title).Changed() { app.save() } ``` ## In lists and tables In a [list](https://mygo.egoist.dev/docs/ui/list.md)'s or a [table](https://mygo.egoist.dev/docs/ui/table.md)'s rows, the list keeps the focus and the text takes none: Return on macOS, and F2 elsewhere, edit the text of the row chosen, while a double click on the row is `Submitted`; a click on the text of a row already chosen edits it, once a second click would no longer make a double click. ```go ui.Table(c, &app.files, cols, len(files), func(row, col int) { if col == 0 && ui.EditableText(c, &files[row].Name).Changed() { app.rename(files[row]) } }) ``` ## Accessibility Assistive technology reads the text, and the text field while it is edited. --- Source: https://mygo.egoist.dev/docs/ui/find-bar.md # Find bar `ui.FindBar` creates a bar for finding text while a `*bool` is true, as Safari's and Xcode's: a field of the query, which takes the focus as the bar opens with the last query selected, how many matches there are, previous and next buttons choosing the current match, and Done. ```go if c.Shortcut(ui.Cmd, ui.KeyF) { app.finding = true } matches := app.find(app.query) // the app counts them ui.FindBar(c, &app.finding, &app.query, len(matches), &app.match) if app.finding && len(matches) > 0 { app.show(matches[app.match]) } ``` The app finds: it counts the matches of the query and shows the current one, which `Changed` reports moving. ## Keyboard Enter in the field goes to the next match, Shift+Enter to the previous, as do Cmd+G and Shift+Cmd+G on macOS, F3 and Shift+F3 elsewhere, round the ends; Escape and Done close the bar. While closed, it returns an element that shows nothing. ## Accessibility Assistive technology sees a toolbar named "Find", holding a search field, and hears the count of matches as it changes. Its names, its count ("3 of 12", "No matches") and Done are in the window's language ([MyGo's own strings](https://mygo.egoist.dev/docs/i18n.md#mygos-own-strings)). --- Source: https://mygo.egoist.dev/docs/ui/form.md # Form A `ui.Field` labels the control its function builds: the label names the control for assistive technology, and a click on it focuses the control, or clicks a check box, a switch or a radio button. `Description` and `Error` add texts below the control, which assistive technology reads with it; an error also marks the control's value invalid, and a text input draws its border in the theme's `Danger` color. An empty error leaves the control valid: ```go var invalid string if app.email != "" && !strings.Contains(app.email, "@") { invalid = "Enter an email address." } ui.Field(c, "Email", func() { ui.TextInput(c, &app.email) }).Description("For receipts.").Error(invalid) ``` The control is the first element the function builds that takes the focus, or a group of them, such as a [radio group](https://mygo.egoist.dev/docs/ui/radio.md). ## Forms A field's label sits above its control, as on the web. In a `ui.Form`, the labels of its fields sit in a column of their own beside the controls, as in macOS's forms: aligned to the right, as wide as the widest, and level with the first line of text of their control, or centered on a control without text, such as a switch. ```go ui.Form(c, func() { ui.Field(c, "Name", func() { ui.TextInput(c, &app.name) }) ui.Field(c, "Plan", func() { ui.Select(c, &app.plan, plans) }) ui.Field(c, "Sound", func() { ui.Switch(c, &app.sound) }) }) ``` ## Fieldsets A `ui.Fieldset` groups fields under a legend, which names the group; their labels line up with the form's others, and `Disabled` disables them all: ```go ui.Form(c, func() { ui.Field(c, "Name", func() { ui.TextInput(c, &app.name) }) ui.Fieldset(c, "Notifications", func() { ui.Field(c, "Email", func() { ui.Checkbox(c, &app.mail, "Weekly summary") }) ui.Field(c, "Sound", func() { ui.Switch(c, &app.sound) }) }).Disabled(!app.signedIn) }) ``` A control with a name of its own, as a check box with its text, keeps it, and the field's label names the group around them. ## Labels of your own A view that draws a control's caption itself, as a text above an input in a component's own layout, ties the two with `LabelledBy`, as a `