Documentation
¶
Overview ¶
Package mygo is a desktop application framework written in pure Go, without cgo. Each window shows a web page, in the system webview (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows), or native UI that MyGo draws itself, written in Go with package github.com/egoist/mygo/ui; one app can have windows of both kinds.
A window with a web page shows the app's frontend, which calls the Go services the app binds through a TypeScript client that `mygo generate` writes. The app opens its windows once it is ready:
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)
}
}
The frontend then calls `await Greeter.greet("Ada")`. Go reaches pages with typed events declared with NewEvent.
A window of native UI takes a view, a function of the app's state that builds its interface each frame, in place of a URL, and needs no bindings:
mygo.NewWindow(mygo.WindowOptions{Title: "Counter", Content: ui.View(app.view)})
The rest of the package covers the desktop, for windows of both kinds: App (the lifecycle, deep links, file associations, the Dock), Window and its Page, NewMenu and NewTray, Dialog, NewNotification, Clipboard, Shell, Screen, Theme, Power, GlobalShortcut, Protocol (custom URL schemes served by an http.Handler) and Updater. The guides in the repository's docs directory show how they fit together.
Threading ¶
The system's UI toolkits (AppKit, GTK, Win32) must be driven from the process' main thread. MyGo locks the main goroutine to the main thread during package initialization, so App.Run must be called from main(). Every other function and method in this package is safe to call from any goroutine: calls made off the main thread are forwarded to it and wait for the result.
Before App.Run, main sets the app up: it binds services, adds listeners and makes settings, such as Theme.SetSource, which apply once the app starts. Calls that need the running app, such as the clipboard, displays or dialogs, panic when main makes them before Run; other goroutines wait for the app to start.
Event listeners (OnClose, OnFocus, ...) run on the main thread; keep them short and move slow work to a goroutine. Methods of bound services run on goroutines of their own, one per call, so they may block.
Index ¶
- Constants
- Variables
- func Bind(services ...any)
- func BindAs(name string, service any)
- func ClearNotifications()
- func EvalAs[T any](p *Page, code string) (T, error)
- func FileServer(fsys fs.FS) http.Handler
- func GenerateTypeScript() ([]byte, error)
- func IsDev() bool
- func NotificationsSupported() bool
- func RunOnMain(fn func())
- func SetFrontend(fsys fs.FS)
- func StatIdentity(info fs.FileInfo) fs.FileInfo
- func Use(ps ...Plugin)
- func WebViewAvailable() bool
- func WriteTypeScript(path string) error
- type AboutPanelOptions
- type ActivationPolicy
- type Application
- func (a *Application) AddRecentDocument(path string) error
- func (a *Application) ClearBrowsingData() error
- func (a *Application) ClearRecentDocuments() error
- func (a *Application) Exit(code int)
- func (a *Application) Focus()
- func (a *Application) Hide()
- func (a *Application) IsHidden() bool
- func (a *Application) IsPackaged() bool
- func (a *Application) IsReady() bool
- func (a *Application) IsURLSchemeRegistered(scheme string) bool
- func (a *Application) Languages() []string
- func (a *Application) Locale() string
- func (a *Application) Menu() *Menu
- func (a *Application) Name() string
- func (a *Application) OnActivate(fn func(hasVisibleWindows bool)) (off func())
- func (a *Application) OnBeforeQuit(fn func(e *QuitEvent)) (off func())
- func (a *Application) OnDidBecomeActive(fn func()) (off func())
- func (a *Application) OnDidResignActive(fn func()) (off func())
- func (a *Application) OnLocaleChanged(fn func(locale string)) (off func())
- func (a *Application) OnNotificationClick(fn func(id string)) (off func())
- func (a *Application) OnOpenFile(fn func(path string)) (off func())
- func (a *Application) OnOpenURL(fn func(url string)) (off func())
- func (a *Application) OnQuit(fn func()) (off func())
- func (a *Application) OnReady(fn func()) (off func())
- func (a *Application) OnRegionChanged(fn func(Region)) (off func())
- func (a *Application) OnSecondInstance(fn func(args []string, workingDir string)) (off func())
- func (a *Application) OnWillQuit(fn func(e *QuitEvent)) (off func())
- func (a *Application) OnWindowAllClosed(fn func()) (off func())
- func (a *Application) OnWindowCreated(fn func(w *Window)) (off func())
- func (a *Application) OpenAtLogin() bool
- func (a *Application) Path(name PathName) (string, error)
- func (a *Application) PreferredLanguages() []string
- func (a *Application) Quit()
- func (a *Application) RecentDocuments() []string
- func (a *Application) Region() Region
- func (a *Application) RegisterURLScheme(scheme string) error
- func (a *Application) Relaunch()
- func (a *Application) RequestSingleInstanceLock() bool
- func (a *Application) Run() error
- func (a *Application) SetActivationPolicy(p ActivationPolicy)
- func (a *Application) SetBadgeCount(n int)
- func (a *Application) SetLanguages(tags ...string)
- func (a *Application) SetLocale(tag string)
- func (a *Application) SetMenu(m *Menu)
- func (a *Application) SetName(name string)
- func (a *Application) SetOpenAtLogin(open bool) error
- func (a *Application) SetPath(name PathName, path string)
- func (a *Application) SetVersion(v string)
- func (a *Application) SetWindowStateStore(s WindowStateStore)
- func (a *Application) Show()
- func (a *Application) ShowAboutPanel(opts AboutPanelOptions)
- func (a *Application) UnregisterURLScheme(scheme string) error
- func (a *Application) Version() string
- func (a *Application) WasOpenedAtLogin() bool
- func (a *Application) WhenReady(fn func())
- type Autosave
- type Channel
- type ClipboardModule
- func (ClipboardModule) AvailableFormats() []string
- func (ClipboardModule) Clear()
- func (ClipboardModule) Flush() error
- func (ClipboardModule) Formats() []transfer.Format
- func (ClipboardModule) Read(formats ...transfer.Format) (transfer.Data, error)
- func (c ClipboardModule) ReadFiles() ([]string, error)
- func (c ClipboardModule) ReadFormat(format transfer.Format) ([]byte, error)
- func (ClipboardModule) ReadHTML() string
- func (ClipboardModule) ReadImage() []byte
- func (ClipboardModule) ReadText() string
- func (ClipboardModule) Write(data transfer.Data, options ...ClipboardOptions) error
- func (c ClipboardModule) WriteFiles(paths ...string) error
- func (c ClipboardModule) WriteHTML(markup string)
- func (c ClipboardModule) WriteImage(data []byte) error
- func (c ClipboardModule) WriteText(text string)
- type ClipboardOptions
- type CloseEvent
- type Content
- type Cookie
- type CookieFilter
- type CookieSameSite
- type CookiesModule
- type DevTools
- type DialogModule
- type Display
- type Dock
- type Document
- func (d *Document[T]) Changed()
- func (b *Document) Close()
- func (d *Document[T]) Content() T
- func (d *Document[T]) Duplicate() *Document[T]
- func (b *Document) HasConflict() bool
- func (b *Document) IsEdited() bool
- func (b *Document) IsReadOnly() bool
- func (b *Document) MoveTo(dir string) error
- func (b *Document) Name() string
- func (b *Document) OnReload(fn func()) (off func())
- func (b *Document) OnStateChange(fn func(DocumentState)) (off func())
- func (b *Document) Path() string
- func (b *Document) Rename(name string) error
- func (b *Document) Revert() error
- func (b *Document) Save() error
- func (b *Document) SaveAnyway() error
- func (b *Document) SaveAs(path string) error
- func (d *Document[T]) Set(content T)
- func (d *Document[T]) SetEdited(edited bool)
- func (b *Document) State() DocumentState
- func (d *Document[T]) Window() *Window
- type DocumentService
- func (s *DocumentService[T]) Content(ctx context.Context) (T, error)
- func (s *DocumentService[T]) Duplicate(ctx context.Context) error
- func (s *DocumentService[T]) MoveTo(ctx context.Context) error
- func (s *DocumentService[T]) Rename(ctx context.Context) error
- func (s *DocumentService[T]) Revert(ctx context.Context) error
- func (s *DocumentService[T]) Save(ctx context.Context) error
- func (s *DocumentService[T]) SaveAs(ctx context.Context) error
- func (s *DocumentService[T]) SetContent(ctx context.Context, content T) error
- func (s *DocumentService[T]) State(ctx context.Context) (DocumentState, error)
- type DocumentState
- type DocumentType
- type Documents
- func (ds *Documents[T]) Documents() []*Document[T]
- func (ds *Documents[T]) ForWindow(w *Window) *Document[T]
- func (ds *Documents[T]) New() *Document[T]
- func (ds *Documents[T]) Open(path string) (*Document[T], error)
- func (ds *Documents[T]) OpenDialog() ([]*Document[T], error)
- func (ds *Documents[T]) Service() *DocumentService[T]
- type DocumentsOptions
- type Download
- type DownloadEvent
- type DragOptions
- type DragResult
- type EvalError
- type Event
- type FileDropEvent
- type FileEvent
- type FileFilter
- type FileOp
- type FileWatchOptions
- type FileWatcher
- type FindOptions
- type FindResult
- type FlyoutOptions
- type GlobalShortcutModule
- type InstalledApp
- type JumpList
- type JumpListTask
- type LoadError
- type Margins
- type Menu
- type MenuItem
- func (it *MenuItem) IsChecked() bool
- func (it *MenuItem) IsEnabled() bool
- func (it *MenuItem) IsVisible() bool
- func (it *MenuItem) SetAccelerator(acc string)
- func (it *MenuItem) SetChecked(v bool)
- func (it *MenuItem) SetEnabled(v bool)
- func (it *MenuItem) SetLabel(label string)
- func (it *MenuItem) SetVisible(v bool)
- type MenuItemType
- type MenuRole
- type MessageOptions
- type MessageResult
- type MessageType
- type NavigateEvent
- type NetworkModule
- type NetworkStatus
- type Notification
- type NotificationOptions
- type OpenDialogOptions
- type PDFOptions
- type Page
- func (p *Page) CanGoBack() bool
- func (p *Page) CanGoForward() bool
- func (p *Page) CloseDevTools()
- func (p *Page) Eval(code string) (any, error)
- func (p *Page) EvalContext(ctx context.Context, code string) (any, error)
- func (p *Page) FindInPage(text string, opts FindOptions) (FindResult, error)
- func (p *Page) GoBack()
- func (p *Page) GoForward()
- func (p *Page) IsDevToolsOpened() bool
- func (p *Page) IsLoading() bool
- func (p *Page) LoadFile(path string) error
- func (p *Page) LoadHTML(html, baseURL string)
- func (p *Page) LoadURL(rawURL string) error
- func (p *Page) OnDOMReady(fn func()) (off func())
- func (p *Page) OnDidFailLoad(fn func(err *LoadError)) (off func())
- func (p *Page) OnDidFinishLoad(fn func()) (off func())
- func (p *Page) OnDidNavigate(fn func(url string)) (off func())
- func (p *Page) OnDownloadDone(fn func(d *Download)) (off func())
- func (p *Page) OnPageTitleUpdated(fn func(e *TitleEvent)) (off func())
- func (p *Page) OnRenderProcessGone(fn func(reason string)) (off func())
- func (p *Page) OnWillDownload(fn func(e *DownloadEvent)) (off func())
- func (p *Page) OnWillNavigate(fn func(e *NavigateEvent)) (off func())
- func (p *Page) OpenDevTools()
- func (p *Page) Print()
- func (p *Page) PrintToPDF(opts PDFOptions) ([]byte, error)
- func (p *Page) Reload()
- func (p *Page) ReloadIgnoringCache()
- func (p *Page) SetPermissionHandler(fn func(req PermissionRequest) bool)
- func (p *Page) SetUserAgent(ua string)
- func (p *Page) SetWindowOpenHandler(fn func(req WindowOpenRequest) *WindowOptions)
- func (p *Page) SetZoomFactor(f float64)
- func (p *Page) Stop()
- func (p *Page) StopFindInPage()
- func (p *Page) ToggleDevTools()
- func (p *Page) URL() string
- func (p *Page) UserAgent() string
- func (p *Page) WebView() *WebView
- func (p *Page) Window() *Window
- func (p *Page) ZoomFactor() float64
- type PageOptions
- type PageSize
- type PathName
- type Permission
- type PermissionRequest
- type Placement
- type Plugin
- type Point
- type PowerModule
- func (p *PowerModule) IdleTime() time.Duration
- func (p *PowerModule) IsOnBattery() bool
- func (p *PowerModule) KeepAwake(reason string, display bool) (release func())
- func (p *PowerModule) OnLockScreen(fn func()) (off func())
- func (p *PowerModule) OnResume(fn func()) (off func())
- func (p *PowerModule) OnSuspend(fn func()) (off func())
- func (p *PowerModule) OnUnlockScreen(fn func()) (off func())
- type Preventable
- type ProgressBar
- type ProgressState
- type ProtocolModule
- type QuitEvent
- type Rectangle
- type Region
- type SaveDialogOptions
- type ScreenModule
- func (s *ScreenModule) CursorScreenPoint() Point
- func (s *ScreenModule) DisplayMatching(r Rectangle) Display
- func (s *ScreenModule) DisplayNearestPoint(p Point) Display
- func (s *ScreenModule) Displays() []Display
- func (s *ScreenModule) OnDisplaysChanged(fn func()) (off func())
- func (s *ScreenModule) PrimaryDisplay() Display
- type SecretsModule
- type ShellModule
- func (ShellModule) Beep()
- func (ShellModule) FileIcon(path string, size int) ([]byte, error)
- func (ShellModule) InstalledApps() ([]InstalledApp, error)
- func (ShellModule) LaunchApp(app InstalledApp) error
- func (ShellModule) OpenExternal(url string) error
- func (ShellModule) OpenPath(path string) error
- func (ShellModule) ShowItemInFolder(path string)
- func (ShellModule) TrashItem(path string) error
- type Size
- type ThemeModule
- type ThemePreferences
- type ThemeSource
- type TitleBarStyle
- type TitleEvent
- type Tray
- func (t *Tray) Bounds() Rectangle
- func (t *Tray) Destroy()
- func (t *Tray) OnClick(fn func()) (off func())
- func (t *Tray) OnRightClick(fn func()) (off func())
- func (t *Tray) PopUpMenu()
- func (t *Tray) SetIcon(png []byte, template bool) error
- func (t *Tray) SetMenu(m *Menu)
- func (t *Tray) SetTitle(title string)
- func (t *Tray) SetToolTip(tip string)
- type TrayOptions
- type Update
- type UpdaterModule
- type Vibrancy
- type WebView
- func (v *WebView) CapturePage() ([]byte, error)
- func (v *WebView) Destroy()
- func (v *WebView) Focus()
- func (v *WebView) IsDestroyed() bool
- func (v *WebView) Page() *Page
- func (v *WebView) SetBackgroundColor(color string) error
- func (v *WebView) SurfaceWebView(conn *surface.Conn) platform.WebView
- func (v *WebView) Window() *Window
- type WebViewOptions
- type Window
- func (w *Window) Blur()
- func (w *Window) Bounds() Rectangle
- func (w *Window) CancelDataDrag()
- func (w *Window) CapturePage() ([]byte, error)
- func (w *Window) Center()
- func (w *Window) Close()
- func (w *Window) ContentBounds() Rectangle
- func (w *Window) ContentSize() (width, height int)
- func (w *Window) Destroy()
- func (w *Window) FlashFrame(flash bool)
- func (w *Window) Focus()
- func (w *Window) HasShadow() bool
- func (w *Window) Hide()
- func (w *Window) ID() int
- func (w *Window) Invalidate()
- func (w *Window) IsAlwaysOnTop() bool
- func (w *Window) IsClosable() bool
- func (w *Window) IsDestroyed() bool
- func (w *Window) IsDocumentEdited() bool
- func (w *Window) IsFlyout() bool
- func (w *Window) IsFocused() bool
- func (w *Window) IsFullScreen() bool
- func (w *Window) IsMaximizable() bool
- func (w *Window) IsMaximized() bool
- func (w *Window) IsMinimizable() bool
- func (w *Window) IsMinimized() bool
- func (w *Window) IsMovable() bool
- func (w *Window) IsPanel() bool
- func (w *Window) IsResizable() bool
- func (w *Window) IsVisible() bool
- func (w *Window) Maximize()
- func (w *Window) Minimize()
- func (w *Window) NativeHandle() uintptr
- func (w *Window) NewWebView(opts WebViewOptions) (*WebView, error)
- func (w *Window) OnBlur(fn func()) (off func())
- func (w *Window) OnClose(fn func(e *CloseEvent)) (off func())
- func (w *Window) OnClosed(fn func()) (off func())
- func (w *Window) OnEnterFullScreen(fn func()) (off func())
- func (w *Window) OnFileDrop(fn func(e *FileDropEvent)) (off func())
- func (w *Window) OnFocus(fn func()) (off func())
- func (w *Window) OnHide(fn func()) (off func())
- func (w *Window) OnLeaveFullScreen(fn func()) (off func())
- func (w *Window) OnMaximize(fn func()) (off func())
- func (w *Window) OnMinimize(fn func()) (off func())
- func (w *Window) OnMove(fn func()) (off func())
- func (w *Window) OnReadyToShow(fn func()) (off func())
- func (w *Window) OnResize(fn func()) (off func())
- func (w *Window) OnRestore(fn func()) (off func())
- func (w *Window) OnShow(fn func()) (off func())
- func (w *Window) OnUnmaximize(fn func()) (off func())
- func (w *Window) Opacity() float64
- func (w *Window) Page() *Page
- func (w *Window) Parent() *Window
- func (w *Window) Position() (x, y int)
- func (w *Window) RepresentedFile() string
- func (w *Window) Restore()
- func (w *Window) SetAlwaysOnTop(v bool)
- func (w *Window) SetAnchor(anchor Rectangle)
- func (w *Window) SetAutoHideMenuBar(v bool)
- func (w *Window) SetBackgroundColor(color string) error
- func (w *Window) SetBounds(r Rectangle)
- func (w *Window) SetClosable(v bool)
- func (w *Window) SetContentBounds(r Rectangle)
- func (w *Window) SetContentProtection(v bool)
- func (w *Window) SetContentSize(width, height int)
- func (w *Window) SetDocumentEdited(edited bool)
- func (w *Window) SetFullScreen(v bool)
- func (w *Window) SetHasShadow(v bool)
- func (w *Window) SetIcon(png []byte) error
- func (w *Window) SetIgnoreMouseEvents(v bool)
- func (w *Window) SetMaximizable(v bool)
- func (w *Window) SetMaximumSize(width, height int)
- func (w *Window) SetMenu(m *Menu)
- func (w *Window) SetMinimizable(v bool)
- func (w *Window) SetMinimumSize(width, height int)
- func (w *Window) SetMovable(v bool)
- func (w *Window) SetOpacity(v float64)
- func (w *Window) SetPosition(x, y int)
- func (w *Window) SetProgressBar(p ProgressBar)
- func (w *Window) SetRepresentedFile(path string)
- func (w *Window) SetResizable(v bool)
- func (w *Window) SetSize(width, height int)
- func (w *Window) SetSkipTaskbar(v bool)
- func (w *Window) SetTitle(title string)
- func (w *Window) SetVibrancy(v Vibrancy)
- func (w *Window) SetVisibleOnAllWorkspaces(v bool)
- func (w *Window) Show()
- func (w *Window) ShowInactive()
- func (w *Window) Size() (width, height int)
- func (w *Window) StartDataDrag(data transfer.Data, options DragOptions) error
- func (w *Window) Title() string
- func (w *Window) ToggleFullScreen()
- func (w *Window) ToggleMaximize()
- func (w *Window) Unmaximize()
- func (w *Window) Update(fn func())
- type WindowOpenRequest
- type WindowOptions
- type WindowState
- type WindowStateStore
Constants ¶
const MaxSecretSize = 2560
MaxSecretSize is the largest secret Secrets.Set stores, in bytes: the most the Windows Credential Manager keeps, so that an app behaves the same everywhere. To keep more, encrypt it into a file of PathUserData with a key kept in Secrets.
const Version = "0.5.5"
Version is the MyGo version.
Variables ¶
var ( PageLetter = PageSize{8.5, 11} PageLegal = PageSize{8.5, 14} PageTabloid = PageSize{11, 17} PageA3 = PageSize{11.69, 16.54} PageA4 = PageSize{8.27, 11.69} PageA5 = PageSize{5.83, 8.27} )
Paper sizes.
var App = &Application{readyCh: make(chan struct{}), Dock: &Dock{}, JumpList: &JumpList{}}
App is the application singleton.
var ErrCanceled = errors.New("mygo: canceled")
ErrCanceled is what a document's command returns when the user cancels it, in a dialog it showed.
var ErrChannelClosed = errors.New("mygo: channel closed")
ErrChannelClosed is returned by Channel.Send once the channel is closed.
var ErrClipboardChanged = platform.ErrClipboardChanged
ErrClipboardChanged means ownership changed while a read was in progress.
var ErrClipboardPersistence = platform.ErrClipboardPersistence
ErrClipboardPersistence means the desktop cannot store clipboard data after the owning application exits. Providers have still been materialized.
var ErrClipboardReentrant = errors.New("mygo: clipboard access from a clipboard provider")
ErrClipboardReentrant means a provider tried to access the clipboard. Providers may return prepared bytes, but must not read or replace the clipboard while the system is requesting their representation.
var ErrDocumentChanged = errors.New("mygo: the file was changed by another application")
ErrDocumentChanged is what Document.Save returns when another app changed the document's file since it was read or saved; SaveAnyway writes it all the same.
var ErrNotificationsDenied = platform.ErrNotificationsDenied
ErrNotificationsDenied is returned by Notification.Show when the user has not allowed the app to show notifications (macOS).
var ErrSecretNotFound = platform.ErrSecretNotFound
ErrSecretNotFound is what Secrets.Get fails with when no secret is stored for the key.
var ErrUpdatesDisabled = errors.New("mygo: updates are not enabled for this build")
ErrUpdatesDisabled is returned by Check for builds without updates: development builds, and builds of apps without updates in mygo.config.ts.
var ErrWatchLimit = errors.New("mygo: file watch entry limit exceeded")
ErrWatchLimit is what a watch stops with when its directory has more than FileWatchOptions.MaxEntries files and directories.
var GlobalShortcut = &GlobalShortcutModule{}
GlobalShortcut registers keyboard shortcuts that work while the app is in the background.
var Network = &NetworkModule{}
Network reports whether the computer is online.
var Power = &PowerModule{}
Power reports power and session changes and keeps the computer awake.
var Protocol = &ProtocolModule{handlers: map[string]http.Handler{}}
Protocol serves custom URL schemes such as app:// from Go.
var Screen = &ScreenModule{}
Screen describes the connected displays.
var Theme = &ThemeModule{}
Theme is the system appearance. Pages follow it through the prefers-color-scheme media query, and the accent color and accessibility settings through the --mygo-accent and --mygo-text-scale CSS variables and preferences and onPreferences of mygo-runtime.
var Updater = &UpdaterModule{}
Updater installs new versions of the app.
Functions ¶
func Bind ¶
func Bind(services ...any)
Bind exposes the exported methods of each service to the frontend. The generated TypeScript client (see `mygo generate`) turns
type Greeter struct{}
// Greet returns a greeting.
func (Greeter) Greet(name string) (string, error)
into a typed `Greeter.greet(name: string): Promise<string>` function.
Arguments and results are encoded as JSON. A method may take a context.Context as its first parameter: it is canceled when the calling page navigates away or its window closes, and CallerWindow returns the calling window from it. A method may return nothing, a value, an error, or a value and an error; a non-nil error rejects the promise on the JavaScript side. Calls run on their own goroutine.
The service is named after its type; Bind panics if the name is taken or a method uses a type that cannot be encoded as JSON (channels, functions).
func ClearNotifications ¶ added in v0.2.15
func ClearNotifications()
ClearNotifications removes the app's notifications, on macOS those of earlier runs left in Notification Center too. An app calls it as it comes to the front, so that what the user has seen in the app does not wait there:
mygo.App.OnDidBecomeActive(func() { mygo.ClearNotifications() })
func EvalAs ¶
EvalAs evaluates JavaScript in a page like Page.Eval and decodes the result into a value of type T:
title, err := mygo.EvalAs[string](win.Page(), "document.title")
A nil page, as a window showing native UI has, returns an error.
func FileServer ¶
FileServer serves files from fsys and falls back to index.html for unknown paths without an extension, so client side routers work. Files are served with their content type and support range requests.
func GenerateTypeScript ¶
GenerateTypeScript renders the typed TypeScript client for all services bound with Bind and events declared with NewEvent.
You rarely call this directly: `mygo generate` runs your app with the MYGO_GENERATE environment variable set, which makes App.Run write the client and return before opening any window.
func IsDev ¶
func IsDev() bool
IsDev reports whether the app runs in development: true unless it was built for production with `mygo build`, or MYGO_ENV=production is set. Development builds enable the web inspector by default.
func NotificationsSupported ¶
func NotificationsSupported() bool
NotificationsSupported reports whether desktop notifications can be shown. On macOS they require a packaged app, which `mygo dev` and `mygo build` produce.
func RunOnMain ¶
func RunOnMain(fn func())
RunOnMain runs fn on the main (UI) thread and waits for it to return. Use it to call native APIs directly, e.g. through Window.NativeHandle. It runs fn right away when called on the main thread, and drops it after the application has quit.
func SetFrontend ¶
SetFrontend serves fsys as the app's frontend at mygo://localhost/. Paths without a file extension that match no file serve index.html, for client-side routing.
`mygo build` calls it with the frontendDist files it embeds into the app, so apps rarely need to. Call it to ship a frontend without the mygo CLI, e.g. from an embed.FS.
func StatIdentity ¶ added in v0.5.0
StatIdentity returns info with its identity fixed as it is now, for comparing with os.SameFile later.
A FileInfo from Stat, Lstat or a directory entry carries the file's identity, which os.SameFile compares. On Windows, Stat and Lstat defer reading it to the first comparison, which opens the path again: after a rename and replace, the stat of the directory before compares equal to the one after, and a file replaced as editors save is taken for the one before. Where identities of stats taken apart are compared, as the file watches do, pass them here first.
func Use ¶ added in v0.1.8
func Use(ps ...Plugin)
Use adds plugins to the app. Call it before App.Run, like Bind. Use panics when a plugin is invalid, already used, or its Setup fails.
func WebViewAvailable ¶ added in v0.5.0
func WebViewAvailable() bool
WebViewAvailable reports whether the system webview is there, and so whether a window showing a web page can work: WKWebView on macOS, WebKitGTK on Linux, the WebView2 Runtime on Windows. A window showing native UI (WindowOptions.Content) needs none, so an app whose windows all do runs without one, and this reports false in browsers, which show native UI only.
Ask before creating the first window showing a page, as NewWindow panics when the platform has no webview. It may be called from any goroutine, also in main before App.Run:
mygo.App.WhenReady(func() {
if mygo.WebViewAvailable() {
mygo.NewWindow(mygo.WindowOptions{URL: "/"})
} else {
mygo.NewWindow(mygo.WindowOptions{Content: ui.View(offlineView)})
}
})
It looks for the runtime without starting it: on Windows for the WebView2 Runtime or a WebView2Loader.dll next to the executable, on Linux by loading WebKitGTK. A runtime that is there but broken still reports true; the window then reports calls that need its page as failed. Once a window showing a page started the runtime, it reports whether that worked.
func WriteTypeScript ¶
WriteTypeScript writes the TypeScript client to path, creating parent directories. The file is left untouched when its content did not change, so frontend dev servers do not reload needlessly. An app that binds no services and declares no events, as one of native UI, has nothing for a frontend to call: it gets no client, and path is not written.
Types ¶
type AboutPanelOptions ¶
type AboutPanelOptions struct {
ApplicationName string
ApplicationVersion string
// Version is the build version shown next to ApplicationVersion.
Version string
Copyright string
Credits string
}
AboutPanelOptions customizes the standard about panel.
type ActivationPolicy ¶
type ActivationPolicy string
ActivationPolicy controls how a macOS application appears in the Dock and app switcher.
const ( // ActivationPolicyRegular is an ordinary app with a Dock icon and menu bar. ActivationPolicyRegular ActivationPolicy = "regular" // ActivationPolicyAccessory hides the Dock icon; windows can still be // shown. Typical for menu bar (tray) apps. ActivationPolicyAccessory ActivationPolicy = "accessory" // ActivationPolicyProhibited hides the app entirely. ActivationPolicyProhibited ActivationPolicy = "prohibited" )
Activation policies.
type Application ¶
type Application struct {
// Dock controls the Dock icon on macOS.
Dock *Dock
// JumpList controls the jump list of the taskbar button on Windows.
JumpList *JumpList
// contains filtered or unexported fields
}
Application controls the event loop and the lifecycle of the process. Use the App singleton.
func (*Application) AddRecentDocument ¶ added in v0.5.0
func (a *Application) AddRecentDocument(path string) error
AddRecentDocument records path as a document the user opened: it goes first in RecentDocuments and the Open Recent menu (RoleOpenRecent), and the system offers it again, in the app's Dock menu on macOS, in the recently used files of the user (the file chooser's and file manager's Recent) on Linux, and in the Recent category of the app's jump list on Windows. Documents (NewDocuments) record the files they open and save; other apps call it whenever they open a document or folder, including one the user chose with a file dialog:
if err := mygo.App.AddRecentDocument(path); err != nil { … }
A relative path is resolved against the working directory. Choosing an entry of the Dock menu, the jump list or the Open Recent menu opens the file with the app, which gets it through OnOpenFile, or opens it as a document.
func (*Application) ClearBrowsingData ¶
func (a *Application) ClearBrowsingData() error
ClearBrowsingData deletes what the app's pages stored: cookies, local and session storage, IndexedDB, service workers and caches, e.g. when the user signs out. Open pages keep what they hold in memory until they are reloaded.
func (*Application) ClearRecentDocuments ¶ added in v0.5.0
func (a *Application) ClearRecentDocuments() error
ClearRecentDocuments empties RecentDocuments and the Open Recent menu, and removes the documents the app recorded with the system: the app's recent documents on macOS, the files the app recorded on Linux (the user's other recent files stay), and the Recent category of the app's jump list on Windows. The Open Recent menu's Clear Menu calls it.
func (*Application) Exit ¶
func (a *Application) Exit(code int)
Exit terminates the process immediately with the given exit code, without emitting quit events or asking windows.
func (*Application) Focus ¶
func (a *Application) Focus()
Focus brings the application to the foreground.
func (*Application) Hide ¶
func (a *Application) Hide()
Hide hides all windows of the application (macOS).
func (*Application) IsHidden ¶
func (a *Application) IsHidden() bool
IsHidden reports whether the application is hidden (macOS).
func (*Application) IsPackaged ¶
func (a *Application) IsPackaged() bool
IsPackaged reports whether the application runs from an app bundle (created by `mygo dev` and `mygo build`) rather than a plain executable.
func (*Application) IsReady ¶
func (a *Application) IsReady() bool
IsReady reports whether the application has finished launching.
func (*Application) IsURLSchemeRegistered ¶
func (a *Application) IsURLSchemeRegistered(scheme string) bool
IsURLSchemeRegistered reports whether the system opens URLs of scheme with this app.
func (*Application) Languages ¶ added in v0.5.0
func (a *Application) Languages() []string
Languages returns the languages the app is written in, its own first (SetLanguages).
func (*Application) Locale ¶
func (a *Application) Locale() string
Locale returns the language the app shows, as a tag of the languages it is written in (SetLanguages), e.g. "zh-Hans": the one the user reads best of them, or the one SetLocale chose, else the app's own language. The app's own texts, MyGo's controls and menus, the text engine and the pages (mygo.locale) all show it.
Before MyGo 0.5 it was the user's preferred language whatever the app is written in; PreferredLanguages reports those now.
func (*Application) Name ¶
func (a *Application) Name() string
Name returns the application name. It defaults to the bundle name of a packaged app, else to the executable name.
func (*Application) OnActivate ¶
func (a *Application) OnActivate(fn func(hasVisibleWindows bool)) (off func())
OnActivate is called when the application is re-activated, for example by clicking its Dock icon (macOS). Apps usually open a window when hasVisibleWindows is false.
func (*Application) OnBeforeQuit ¶
func (a *Application) OnBeforeQuit(fn func(e *QuitEvent)) (off func())
OnBeforeQuit is called when a quit starts, before windows are closed.
func (*Application) OnDidBecomeActive ¶
func (a *Application) OnDidBecomeActive(fn func()) (off func())
OnDidBecomeActive is called when the application becomes the active one.
func (*Application) OnDidResignActive ¶
func (a *Application) OnDidResignActive(fn func()) (off func())
OnDidResignActive is called when the application stops being active.
func (*Application) OnLocaleChanged ¶ added in v0.5.0
func (a *Application) OnLocaleChanged(fn func(locale string)) (off func())
OnLocaleChanged calls fn on the main thread with the language the app shows when it changes: SetLocale chose another, the languages the app is written in changed, or the user's languages changed while the app follows them. It returns a function that stops the listener.
func (*Application) OnNotificationClick ¶ added in v0.2.15
func (a *Application) OnNotificationClick(fn func(id string)) (off func())
OnNotificationClick is called with the ID of every notification of the app that the user clicks, after its OnClick listeners: also one of an earlier run, which no Notification of this run holds, such as the one whose click launched the app (macOS). Register it before Run to receive that one. Give notifications IDs of the app's own, such as the conversation they are about, to know what to open.
func (*Application) OnOpenFile ¶
func (a *Application) OnOpenFile(fn func(path string)) (off func())
OnOpenFile is called when a file is opened with the application: one of the types of fileAssociations in mygo.config.ts opened from the file manager, a file dropped on the Dock icon (macOS), or one passed on the command line. Register it before Run to receive the files the app was launched with; on Windows and Linux, RequestSingleInstanceLock makes the first instance get those of later ones.
func (*Application) OnOpenURL ¶
func (a *Application) OnOpenURL(fn func(url string)) (off func())
OnOpenURL is called when the application is asked to open a URL of a scheme it handles: one listed in urlSchemes in mygo.config.ts or registered with RegisterURLScheme. Register it before Run to receive the URL the app was launched with. On Windows and Linux, where a URL starts a new instance of the app, use RequestSingleInstanceLock so that the first instance gets the URLs of later ones.
func (*Application) OnQuit ¶
func (a *Application) OnQuit(fn func()) (off func())
OnQuit is called after the event loop has stopped.
func (*Application) OnReady ¶
func (a *Application) OnReady(fn func()) (off func())
OnReady is called once the application has finished launching.
func (*Application) OnRegionChanged ¶ added in v0.5.0
func (a *Application) OnRegionChanged(fn func(Region)) (off func())
OnRegionChanged calls fn on the main thread with the user's regional formats when they change. It returns a function that stops the listener.
func (*Application) OnSecondInstance ¶
func (a *Application) OnSecondInstance(fn func(args []string, workingDir string)) (off func())
OnSecondInstance is called in the first instance when another instance was started and called RequestSingleInstanceLock. Apps usually focus their main window here.
func (*Application) OnWillQuit ¶
func (a *Application) OnWillQuit(fn func(e *QuitEvent)) (off func())
OnWillQuit is called after all windows have been closed, right before the event loop stops.
func (*Application) OnWindowAllClosed ¶
func (a *Application) OnWindowAllClosed(fn func()) (off func())
OnWindowAllClosed is called when the last window has been closed, unless the application is quitting. Without listeners the application quits; registering one keeps it running (the common choice on macOS).
func (*Application) OnWindowCreated ¶
func (a *Application) OnWindowCreated(fn func(w *Window)) (off func())
OnWindowCreated is called for every new window.
func (*Application) OpenAtLogin ¶
func (a *Application) OpenAtLogin() bool
OpenAtLogin reports whether the app starts when the user logs in.
func (*Application) Path ¶
func (a *Application) Path(name PathName) (string, error)
Path returns a well known directory, for example where to store user data:
dir, err := mygo.App.Path(mygo.PathUserData)
func (*Application) PreferredLanguages ¶ added in v0.5.0
func (a *Application) PreferredLanguages() []string
PreferredLanguages returns the languages the user reads, most preferred first, as normalized BCP 47 tags, e.g. ["zh-Hans-CN", "en-GB"]: on macOS the languages of System Settings, on Windows the display languages, on Linux LANGUAGE, then the locale of messages (LC_ALL, LC_MESSAGES, LANG), in a browser navigator.languages. The language the app chose (SetLocale) never changes them.
func (*Application) Quit ¶
func (a *Application) Quit()
Quit closes all windows and then quits. OnBeforeQuit and OnWillQuit listeners, as well as the OnClose listeners of every window, can cancel it.
func (*Application) RecentDocuments ¶ added in v0.5.0
func (a *Application) RecentDocuments() []string
RecentDocuments returns the documents the app opened lately, newest first, which the Open Recent menu (RoleOpenRecent) lists: those of AddRecentDocument, also of earlier runs, up to ten. As in AppKit, files that no longer exist are left out, and come back if they do again.
func (*Application) Region ¶ added in v0.5.0
func (a *Application) Region() Region
Region returns the user's regional formats, as the system's settings have them, with the changes the user made: the locale of the formats, which may be another language's than the app's (an English app reading German dates for a reader in Germany), the first day of the week and the hour cycle. macOS, Windows and browsers report changes while the app runs (OnRegionChanged); Linux reads the environment (LC_TIME, LC_ALL, LANG) once.
func (*Application) RegisterURLScheme ¶
func (a *Application) RegisterURLScheme(scheme string) error
RegisterURLScheme makes the app the handler of the URLs of scheme for the current user, e.g. myapp://open?item=1 for "myapp": they reach OnOpenURL, including the one the app is started with. Call it before Run, typically every time the app starts: registering again is cheap.
On Windows it registers the executable under HKEY_CURRENT_USER, on Linux a hidden desktop entry that becomes the default handler (as xdg-mime does). On macOS the scheme must be listed in urlSchemes in mygo.config.ts, which registers it with the system; this makes the app its default handler when others claim it too. Unregister it when the app is uninstalled, for example with UnregisterURLScheme.
func (*Application) Relaunch ¶
func (a *Application) Relaunch()
Relaunch quits the app like Quit, then starts it again with the same arguments, e.g. after changing a setting that needs a restart. Nothing happens when OnBeforeQuit, OnWillQuit or a window cancels the quit. Under `mygo dev` the build exits once it has quit and mygo dev starts it again.
func (*Application) RequestSingleInstanceLock ¶
func (a *Application) RequestSingleInstanceLock() bool
RequestSingleInstanceLock makes sure a single instance of the app runs. It returns true in the first instance. In any later instance it returns false after forwarding its command line arguments and working directory to the first one (see OnSecondInstance); that instance should then exit:
if !mygo.App.RequestSingleInstanceLock() {
return
}
The lock is identified by the application name and, in a packaged app, its identifier, and released on quit.
func (*Application) Run ¶
func (a *Application) Run() error
Run starts the native event loop and blocks until the application quits. It must be called from the main goroutine, usually as the last statement of main.
SIGINT and SIGTERM quit the application like Quit; a second signal exits immediately.
When the MYGO_GENERATE environment variable is set (see `mygo generate`), Run writes the TypeScript client for the bound services to that path, or nothing when the app binds none, and returns without starting the event loop.
func (*Application) SetActivationPolicy ¶
func (a *Application) SetActivationPolicy(p ActivationPolicy)
SetActivationPolicy changes how the app appears in the Dock (macOS).
func (*Application) SetBadgeCount ¶
func (a *Application) SetBadgeCount(n int)
SetBadgeCount shows a counter on the application icon. Zero clears it.
func (*Application) SetLanguages ¶ added in v0.5.0
func (a *Application) SetLanguages(tags ...string)
SetLanguages sets the languages the app is written in, its own language first, which the app falls back to: those the app's texts are translated to, e.g. "en", "de", "zh-Hans". Locale picks among them. By default they are the languages of the catalogs of the app (package i18n), and English alone without any. It panics on a tag that names no language.
func (*Application) SetLocale ¶ added in v0.5.0
func (a *Application) SetLocale(tag string)
SetLocale makes the app show the language of tag, a BCP 47 tag such as "de" or "zh-Hant-TW", of those it is written in, or "" to follow the user's languages again, which is the default. The app shows it at once: windows of native UI draw anew, menus say their items in it, pages hear the mygo:locale event and those loaded later start with it, and OnLocaleChanged listeners are called. It is kept for the next launches: on macOS as the app's language in its defaults, which System Settings shows and AppKit and WebKit say their own texts in from the next launch, in browsers in localStorage, elsewhere in a file in PathUserData. The MYGO_LOCALE environment variable (`mygo dev -lang`) chooses the language for one run and keeps nothing.
The pseudo locales en-XA and ar-XB are always shown, to test what translations would do. SetLocale panics on a tag that names no language. It is safe from any goroutine; calls made before the main thread gets to them show the last tag only. While MYGO_LOCALE is set, calls made before the app is ready change nothing.
func (*Application) SetMenu ¶
func (a *Application) SetMenu(m *Menu)
SetMenu sets the application menu: the menu bar on macOS and the menu bar of windows without their own menu on Linux and Windows. nil removes it. Without a call to SetMenu a default menu with the usual App, Edit, View and Window items is installed.
func (*Application) SetName ¶
func (a *Application) SetName(name string)
SetName overrides the application name. Call it before Run.
func (*Application) SetOpenAtLogin ¶
func (a *Application) SetOpenAtLogin(open bool) error
SetOpenAtLogin makes the app start when the user logs in, or stops it from doing so. Apps usually offer it as a setting:
if err := mygo.App.SetOpenAtLogin(enabled); err != nil { … }
On macOS 13 and later the app becomes a login item of the user (System Settings > General > Login Items), which needs an app bundle; on macOS 12 a launch agent starts it. On Linux it gets an XDG autostart entry, on Windows a Run entry of the user, which Task Manager can disable.
func (*Application) SetPath ¶
func (a *Application) SetPath(name PathName, path string)
SetPath overrides a directory returned by Path.
func (*Application) SetVersion ¶
func (a *Application) SetVersion(v string)
SetVersion overrides the application version.
func (*Application) SetWindowStateStore ¶ added in v0.4.6
func (a *Application) SetWindowStateStore(s WindowStateStore)
SetWindowStateStore keeps the states of windows (WindowOptions.StateKey) in s, such as the app's own database, instead of window-state.json in PathUserData. nil restores the file. Call it before the first window with a StateKey is created, usually before Run. Browsers keep no window state, and never call s.
func (*Application) Show ¶
func (a *Application) Show()
Show shows the application after Hide (macOS).
func (*Application) ShowAboutPanel ¶
func (a *Application) ShowAboutPanel(opts AboutPanelOptions)
ShowAboutPanel shows the standard about panel (macOS).
func (*Application) UnregisterURLScheme ¶
func (a *Application) UnregisterURLScheme(scheme string) error
UnregisterURLScheme undoes RegisterURLScheme (Linux, Windows); URLs of the scheme no longer reach the app unless mygo.config.ts declares it.
func (*Application) Version ¶
func (a *Application) Version() string
Version returns the application version, which defaults to the version of the packaged app.
func (*Application) WasOpenedAtLogin ¶
func (a *Application) WasOpenedAtLogin() bool
WasOpenedAtLogin reports whether the system started the app because the user logged in, e.g. to start it in the background:
mygo.NewWindow(mygo.WindowOptions{URL: "/", Hidden: mygo.App.WasOpenedAtLogin()})
func (*Application) WhenReady ¶
func (a *Application) WhenReady(fn func())
WhenReady calls fn on the main thread once the application has finished launching. Windows can only be created after that point. If the application is already ready, fn is scheduled right away.
type Autosave ¶ added in v0.5.0
type Autosave int
Autosave is how documents save their changes.
const ( // AutosaveInPlace writes a document's changes to its file a moment // after the user stops editing, when its window loses the focus, // and when it closes, as macOS apps do: saved documents never ask to // be saved. Untitled documents ask when they close (Delete, Cancel or // Save), and so do documents that can't be written (read-only, // changed on disk). AutosaveInPlace Autosave = iota // AutosaveOff writes documents when the user saves them, and asks to // save their changes when they close, as Windows and Linux apps // traditionally do. AutosaveOff )
type Channel ¶ added in v0.1.3
type Channel[T any] struct { // contains filtered or unexported fields }
Channel streams values of type T from a bound method to the page that called it, like a response that arrives in parts: the lines a command prints, the tokens of a model's answer, the progress of a download. The method takes it as a parameter:
// Tail sends the lines of a command's output as it prints them.
func (Shell) Tail(ctx context.Context, command string, lines *mygo.Channel[string]) error {
cmd := exec.CommandContext(ctx, "sh", "-c", command)
out, err := cmd.StdoutPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
scanner := bufio.NewScanner(out)
for scanner.Scan() {
if err := lines.Send(scanner.Text()); err != nil {
return err
}
}
return cmd.Wait()
}
and the page passes a Channel of mygo-runtime in its place, whose values it iterates or handles with onmessage:
const lines = new Channel<string>();
const done = Shell.tail("ping -c 3 example.com", lines);
for await (const line of lines) output.append(line + "\n");
await done;
Values arrive in order, and before the call's result. The channel closes when the method returns, or earlier with Close, which ends the page's iteration. The page may close it too, for example by breaking out of the loop: Send then fails and the context of the call is canceled, which stops the work the method passed it to. Navigating away and closing the window do the same.
Send waits while the page has more than a MiB of values yet to take, so a fast producer does not pile them up in memory, except on the main thread, which must not wait.
Channels are parameters of bound methods only, never parts of other values.
type ClipboardModule ¶
type ClipboardModule struct{}
ClipboardModule reads and writes the system clipboard.
var Clipboard ClipboardModule
Clipboard is the system clipboard.
func (ClipboardModule) AvailableFormats ¶
func (ClipboardModule) AvailableFormats() []string
AvailableFormats lists the formats (MIME types or platform types) on the clipboard.
func (ClipboardModule) Flush ¶ added in v0.2.17
func (ClipboardModule) Flush() error
Flush requests all representations of MyGo's current clipboard and hands them to native storage, releasing lazy-provider resources on success. Provider errors leave ownership intact. It does nothing to another app's clipboard. App quitting calls it automatically, on a best-effort basis. Linux persistence requires a clipboard manager; without one Flush returns ErrClipboardPersistence after materializing providers. Window closure needs no flush.
func (ClipboardModule) Formats ¶ added in v0.2.17
func (ClipboardModule) Formats() []transfer.Format
Formats discovers portable format names without requesting provider data. Use transfer.PreferredFormat to negotiate in receiver preference order. The older AvailableFormats method keeps its platform-specific naming convention.
func (ClipboardModule) Read ¶ added in v0.2.17
Read copies the requested representations from the current clipboard. With no formats it reads all advertised representations; an empty clipboard returns empty data. Explicit formats select alternatives without invoking other providers; no matching representation is transfer.ErrFormat. The returned data has no native providers and is safe to keep, read from any goroutine, or offer in a later drag. Ownership changes during a native read return an error, rather than mixing contents from different owners.
func (ClipboardModule) ReadFiles ¶ added in v0.2.17
func (c ClipboardModule) ReadFiles() ([]string, error)
ReadFiles returns local paths from the clipboard's file/URI list. Remote URLs are ignored. No file is opened, created, moved or deleted.
func (ClipboardModule) ReadFormat ¶ added in v0.2.17
func (c ClipboardModule) ReadFormat(format transfer.Format) ([]byte, error)
ReadFormat copies one representation, coalescing text/file items as Data.Read does. It returns transfer.ErrFormat when it is unavailable.
func (ClipboardModule) ReadHTML ¶
func (ClipboardModule) ReadHTML() string
ReadHTML returns the HTML on the clipboard.
func (ClipboardModule) ReadImage ¶
func (ClipboardModule) ReadImage() []byte
ReadImage returns the image on the clipboard as PNG, or nil.
func (ClipboardModule) ReadText ¶
func (ClipboardModule) ReadText() string
ReadText returns the plain text on the clipboard.
func (ClipboardModule) Write ¶ added in v0.2.17
func (ClipboardModule) Write(data transfer.Data, options ...ClipboardOptions) error
Write replaces the clipboard with items offering alternative serialized representations. It takes a fresh provider snapshot without invoking any providers. Providers run on the main thread at most once per write; errors and panics are cached. Native receivers can request them until ownership ends, even after the source window closes. Keep captured resources alive until OnRelease; prepare expensive data beforehand on a goroutine.
Empty data clears the clipboard. At most one options value is allowed. It is safe from any goroutine. Go values from Drag(value) are never copied to the clipboard; offer an explicit encoding with transfer.Bytes or Lazy.
func (ClipboardModule) WriteFiles ¶ added in v0.2.17
func (c ClipboardModule) WriteFiles(paths ...string) error
WriteFiles copies absolute paths to the clipboard as native file URLs/lists.
func (ClipboardModule) WriteHTML ¶
func (c ClipboardModule) WriteHTML(markup string)
WriteHTML puts HTML on the clipboard.
func (ClipboardModule) WriteImage ¶
func (c ClipboardModule) WriteImage(data []byte) error
WriteImage puts a PNG image on the clipboard.
func (ClipboardModule) WriteText ¶
func (c ClipboardModule) WriteText(text string)
WriteText puts plain text on the clipboard.
type ClipboardOptions ¶ added in v0.2.17
type ClipboardOptions struct {
// OnRelease runs once on the main thread after native providers are no
// longer needed: replacement, Clear, Flush, or application shutdown.
// The system may also finish providers after fetching all their data.
// It is scheduled after the native callback returns and may safely write
// a new clipboard. It does not run when Write fails. Closing a window
// does not release the application-owned clipboard.
OnRelease func()
}
ClipboardOptions configures the lifetime of a clipboard write.
type CloseEvent ¶
type CloseEvent struct {
Preventable
Window *Window
}
CloseEvent is passed to Window.OnClose listeners. Preventing it keeps the window open.
type Content ¶ added in v0.2.0
type Content interface {
// AttachContent connects the content to its window. NewWindow calls it
// on the main thread; only MyGo's own packages implement it.
AttachContent(conn *surface.Conn)
}
Content is what a window shows in place of a web page: a user interface MyGo draws itself, on the GPU where it can. Package ui provides it:
mygo.NewWindow(mygo.WindowOptions{Title: "Counter", Content: ui.View(counter.View)})
type Cookie ¶ added in v0.5.0
type Cookie struct {
Name string
Value string
// Domain is the host the cookie is sent to, such as "example.com", or
// with a leading dot, ".example.com", the domain whose subdomains get
// it too. It is in lowercase ASCII (punycode), without a port.
Domain string
// Path is the path the cookie is sent for; empty means "/".
Path string
// Expires is when the cookie expires, in whole seconds; zero for a
// cookie that lasts until the app quits.
Expires time.Time
Secure bool
HTTPOnly bool
SameSite CookieSameSite
}
Cookie is a cookie of the app's pages. Its name, domain and path identify it.
type CookieFilter ¶ added in v0.5.0
type CookieFilter struct {
// URL keeps the cookies a request to this http or https URL sends:
// those of its host's domain and the path, Secure ones only to https.
URL string
// Name keeps the cookies of this name.
Name string
// Domain keeps the cookies of this domain and of its subdomains, with
// or without a leading dot: "example.com" keeps those of
// "example.com", ".example.com" and "www.example.com".
Domain string
// Path keeps the cookies of exactly this path.
Path string
}
CookieFilter chooses cookies for Cookies.List. Its zero value chooses every cookie; each field set narrows the choice.
type CookieSameSite ¶ added in v0.5.0
type CookieSameSite string
CookieSameSite says whether a cookie goes along with requests from other sites. Cookies.Set takes an empty one as Lax; a cookie List returns has an empty one when the engine does not say.
const ( // CookieSameSiteLax sends the cookie along when the user navigates // from another site, but not with other requests from it. CookieSameSiteLax CookieSameSite = "lax" // CookieSameSiteStrict sends the cookie only with the site's own // requests. CookieSameSiteStrict CookieSameSite = "strict" // CookieSameSiteNone sends the cookie with every request; the cookie // must be Secure. CookieSameSiteNone CookieSameSite = "none" )
type CookiesModule ¶ added in v0.5.0
type CookiesModule struct{}
CookiesModule reads and changes the cookies of the app's pages. Use the Cookies singleton.
var Cookies CookiesModule
Cookies reads and changes the cookies of the app's pages, HTTPOnly ones included: the default cookie store, which every window shares, and which outlives the app as the system webview keeps it. Set one, e.g., to sign the pages in with a token the backend got, before the first page loads:
err := mygo.Cookies.Set(mygo.Cookie{Name: "session", Value: token,
Domain: "example.com", Secure: true, HTTPOnly: true})
The methods are safe from any goroutine once the app is running; on the main thread the app keeps handling events while they wait. Cookies may carry the user's credentials: bind a backend method that does what the page needs rather than giving the page the cookies.
func (CookiesModule) Clear ¶ added in v0.5.0
func (CookiesModule) Clear() error
Clear deletes every cookie, and nothing else the pages stored, unlike App.ClearBrowsingData. Pages may set new ones meanwhile.
func (CookiesModule) Delete ¶ added in v0.5.0
func (CookiesModule) Delete(c Cookie) error
Delete deletes the cookie of c's name, domain and path; its other fields do not matter, so that it deletes a cookie List returned. The domain is matched without regard to case and with its leading dot, if any: "example.com" and ".example.com" are different cookies. An empty path is "/". Deleting a cookie that does not exist is not an error.
func (CookiesModule) List ¶ added in v0.5.0
func (CookiesModule) List(f CookieFilter) ([]Cookie, error)
List returns the cookies f chooses, sorted by domain, path and name:
all, err := mygo.Cookies.List(mygo.CookieFilter{})
sent, err := mygo.Cookies.List(mygo.CookieFilter{URL: "https://example.com/account"})
sessions, err := mygo.Cookies.List(mygo.CookieFilter{Name: "session", Domain: "example.com"})
func (CookiesModule) Set ¶ added in v0.5.0
func (CookiesModule) Set(c Cookie) error
Set adds the cookie, or replaces the one of the same name, domain and path. An empty path is "/" and an empty SameSite Lax; SameSite None needs Secure, as do the __Secure- and __Host- name prefixes. The name and value take what browsers take: neither has control characters, a ";" or spaces at either end, and the name no "=". An Expires in the past deletes the cookie. The engine may still drop the cookie or expire it earlier, as it would one a server set.
type DialogModule ¶
type DialogModule struct{}
DialogModule shows native dialogs. Its methods block until the dialog is dismissed; they can be called from any goroutine.
var Dialog DialogModule
Dialog shows native file and message dialogs.
func (DialogModule) Error ¶
func (d DialogModule) Error(title, content string)
Error shows a modal error dialog.
func (DialogModule) Message ¶
func (DialogModule) Message(opts MessageOptions) (MessageResult, error)
Message shows a message dialog and reports which button was clicked.
func (DialogModule) Open ¶
func (DialogModule) Open(opts OpenDialogOptions) ([]string, error)
Open shows a dialog to pick files or directories and returns the chosen paths, or nil when canceled.
func (DialogModule) Save ¶
func (DialogModule) Save(opts SaveDialogOptions) (string, error)
Save shows a dialog to choose where to save a file and returns the path, or "" when canceled.
type Display ¶
type Display struct {
ID int64
Label string
// Bounds is the area of the display in screen coordinates.
Bounds Rectangle
// WorkArea excludes the menu bar, Dock and taskbars.
WorkArea Rectangle
ScaleFactor float64
Rotation int
Internal bool
Primary bool
}
Display describes a monitor.
type Dock ¶
type Dock struct {
// contains filtered or unexported fields
}
Dock controls the application's Dock icon (macOS). Its methods do nothing on other platforms.
func (*Dock) Bounce ¶
Bounce bounces the Dock icon to request attention and returns an id for CancelBounce. Critical bounces continue until the app is activated.
func (*Dock) CancelBounce ¶
CancelBounce stops a bounce started with Bounce.
type Document ¶ added in v0.5.0
type Document[T any] struct { // contains filtered or unexported fields }
Document is an open document: its content, the file it was read from and is saved to, and its window. Its methods are safe from any goroutine.
func (*Document[T]) Changed ¶ added in v0.5.0
func (d *Document[T]) Changed()
Changed tells that the content changed without being replaced, for a mutable content (see DocumentsOptions.Snapshot). It edits the document.
func (*Document) Close ¶ added in v0.5.0
func (b *Document) Close()
Close closes the document's window, which asks to save the document first when it must.
func (*Document[T]) Content ¶ added in v0.5.0
func (d *Document[T]) Content() T
Content returns the document's content.
func (*Document[T]) Duplicate ¶ added in v0.5.0
Duplicate opens an untitled copy of the document in a new window, as File > Duplicate does.
func (*Document) HasConflict ¶ added in v0.5.0
func (b *Document) HasConflict() bool
HasConflict reports whether another app changed the document's file while the document had unsaved changes.
func (*Document) IsEdited ¶ added in v0.5.0
func (b *Document) IsEdited() bool
IsEdited reports whether the document has unsaved changes.
func (*Document) IsReadOnly ¶ added in v0.5.0
func (b *Document) IsReadOnly() bool
IsReadOnly reports whether the document's file can't be written.
func (*Document) MoveTo ¶ added in v0.5.0
MoveTo moves the document's file into the folder dir, as File > Move To does; "" asks for the folder.
func (*Document) Name ¶ added in v0.5.0
func (b *Document) Name() string
Name returns the document's file name, or the name of an untitled document, such as "Untitled 2".
func (*Document) OnReload ¶ added in v0.5.0
func (b *Document) OnReload(fn func()) (off func())
OnReload is called on the main thread after the document's content was read from its file again: reverted, or changed by another app. Views that keep a copy of the content take it again.
func (*Document) OnStateChange ¶ added in v0.5.0
func (b *Document) OnStateChange(fn func(DocumentState)) (off func())
OnStateChange is called on the main thread when the document's state changes: it is edited or saved, moved, renamed, or its file changed.
func (*Document) Path ¶ added in v0.5.0
func (b *Document) Path() string
Path returns the document's file, "" while it is untitled.
func (*Document) Rename ¶ added in v0.5.0
Rename renames the document's file to name, in its folder, as File > Rename does; "" asks for the name. An untitled document is saved instead.
func (*Document) Revert ¶ added in v0.5.0
func (b *Document) Revert() error
Revert reads the document's file again, discarding the unsaved changes.
func (*Document) Save ¶ added in v0.5.0
func (b *Document) Save() error
Save writes the document to its file, as File > Save does: an untitled document asks where, a read-only one asks for another file, and one whose file another app changed asks whether to overwrite it. It returns ErrCanceled when the user cancels.
func (*Document) SaveAnyway ¶ added in v0.5.0
func (b *Document) SaveAnyway() error
SaveAnyway writes the document to its file even when another app changed the file since the document read it.
func (*Document) SaveAs ¶ added in v0.5.0
SaveAs asks where to save the document, then writes it there; the document then is that file. A path saves there without asking.
func (*Document[T]) Set ¶ added in v0.5.0
func (d *Document[T]) Set(content T)
Set replaces the document's content, which edits it, unless DocumentsOptions.Equal finds it equal to what its file has.
func (*Document[T]) SetEdited ¶ added in v0.5.0
SetEdited sets whether the document has unsaved changes, for an app that knows better, as one that keeps the undo history of its content: false makes the content the one its file has, without writing it.
func (*Document) State ¶ added in v0.5.0
func (b *Document) State() DocumentState
State describes the document.
type DocumentService ¶ added in v0.5.0
type DocumentService[T any] struct { // contains filtered or unexported fields }
DocumentService gives the pages of document windows their documents, through the generated TypeScript client: bind it with BindAs, under the name the client calls it by,
mygo.BindAs("Note", notes.Service())
and a page reads and replaces the content of the document its window shows, and saves it:
const text = await Note.content();
await Note.setContent(text + "!");
onDocumentState((state) => { title.textContent = state.name }); // mygo-runtime
Its methods fail for windows that show no document of its kind.
func (*DocumentService[T]) Content ¶ added in v0.5.0
func (s *DocumentService[T]) Content(ctx context.Context) (T, error)
Content returns the content of the window's document.
func (*DocumentService[T]) Duplicate ¶ added in v0.5.0
func (s *DocumentService[T]) Duplicate(ctx context.Context) error
Duplicate opens a copy of the window's document in a new window.
func (*DocumentService[T]) MoveTo ¶ added in v0.5.0
func (s *DocumentService[T]) MoveTo(ctx context.Context) error
MoveTo asks where to move the window's document's file.
func (*DocumentService[T]) Rename ¶ added in v0.5.0
func (s *DocumentService[T]) Rename(ctx context.Context) error
Rename asks for a new name of the window's document's file.
func (*DocumentService[T]) Revert ¶ added in v0.5.0
func (s *DocumentService[T]) Revert(ctx context.Context) error
Revert asks whether to discard the unsaved changes of the window's document, and reads its file again.
func (*DocumentService[T]) Save ¶ added in v0.5.0
func (s *DocumentService[T]) Save(ctx context.Context) error
Save saves the window's document, as File > Save does.
func (*DocumentService[T]) SaveAs ¶ added in v0.5.0
func (s *DocumentService[T]) SaveAs(ctx context.Context) error
SaveAs asks where to save the window's document, and saves it there.
func (*DocumentService[T]) SetContent ¶ added in v0.5.0
func (s *DocumentService[T]) SetContent(ctx context.Context, content T) error
SetContent replaces the content of the window's document, which edits it.
func (*DocumentService[T]) State ¶ added in v0.5.0
func (s *DocumentService[T]) State(ctx context.Context) (DocumentState, error)
State describes the window's document; onDocumentState of mygo-runtime tells its changes.
type DocumentState ¶ added in v0.5.0
type DocumentState struct {
// Name is the document's file name, or a name such as "Untitled 2"
// for an untitled document.
Name string `json:"name"`
// Path is the document's file, "" while it is untitled.
Path string `json:"path"`
// Edited reports whether the document has unsaved changes.
Edited bool `json:"edited"`
// ReadOnly reports that the document's file can't be written: saving
// asks for another file.
ReadOnly bool `json:"readOnly"`
// Conflict reports that another app changed the document's file while
// the document had unsaved changes: saving asks which to keep.
Conflict bool `json:"conflict"`
// Deleted reports that the document's file was deleted: saving
// writes it again.
Deleted bool `json:"deleted"`
}
DocumentState describes a document, as Document.State returns it and pages of its window get it.
type DocumentType ¶ added in v0.5.0
type DocumentType struct {
// Name describes the files, e.g. "Markdown Document". Open and save
// dialogs show it.
Name string
// Extensions are the file name extensions, without dots, e.g.
// []string{"md", "markdown"}. New documents are saved with the first.
Extensions []string
}
DocumentType is a kind of file that Documents reads and writes.
type Documents ¶ added in v0.5.0
type Documents[T any] struct { // contains filtered or unexported fields }
Documents opens, creates and keeps track of the documents of one kind, and their windows, as AppKit's NSDocumentController and SwiftUI's DocumentGroup do. Create it with NewDocuments, before App.Run. Its methods are safe from any goroutine.
Documents gives an app the File menu's commands (the RoleNew, RoleOpen, RoleSave… menu roles), autosave, a recovery copy of every unsaved change, documents opened from the file manager (OnOpenFile), the documents changed by other apps, and asks to save before closing and quitting where it must. See the documents guide.
func NewDocuments ¶ added in v0.5.0
func NewDocuments[T any](opts DocumentsOptions[T]) *Documents[T]
NewDocuments creates the controller of the documents of one kind. Call it before App.Run: when the app starts it opens the files it was started with, the documents a crash or a quit left unsaved, or else a new untitled document. An app may have several kinds of documents; the first is the one RoleNew creates.
func (*Documents[T]) Documents ¶ added in v0.5.0
Documents returns the open documents, in the order they opened.
func (*Documents[T]) New ¶ added in v0.5.0
New creates an untitled document with the content of DocumentsOptions.New and opens its window.
func (*Documents[T]) Open ¶ added in v0.5.0
Open opens the document at path in its window, or focuses the window of the document if it is open already.
func (*Documents[T]) OpenDialog ¶ added in v0.5.0
OpenDialog asks which documents to open, and opens them.
func (*Documents[T]) Service ¶ added in v0.5.0
func (ds *Documents[T]) Service() *DocumentService[T]
Service returns the service that gives pages their documents.
type DocumentsOptions ¶ added in v0.5.0
type DocumentsOptions[T any] struct { // Types are the kinds of files the documents are. Open dialogs show // them, and new documents are saved as the first. Types []DocumentType // New returns the content of a new, untitled document; nil gives the // zero value of T. New func() T // Read reads a document's content from its file. It runs on a // goroutine of its own. Read func(r io.Reader) (T, error) // Write writes a document's content to its file. It runs on a // goroutine of its own, with the content as it was when saving // started: edits made meanwhile stay unsaved. A content that is a // value the app replaces with Document.Set (a string, a struct of // values, a persistent snapshot such as ui.TextSnapshot) can be // written while the app goes on; a mutable one needs Snapshot. Write func(w io.Writer, content T) error // Snapshot, when set, copies a mutable content before it is written, // on the main thread, where the app changes it. It is called with the // content and returns a copy that nothing changes, which Write gets. Snapshot func(content T) T // Equal, when set, compares contents: a document whose content is // Equal to what its file has is not edited, so that undoing back to // it, or typing a character and deleting it, leaves the document // unedited. Without it, every Set and Changed edits the document // until it is saved. Equal func(a, b T) bool // Window creates the window that shows a document, on the main // thread. MyGo sets its title, represented file and edited state, // asks to save before it closes, and closes the document with it. Window func(doc *Document[T]) *Window // Autosave is how documents save their changes: AutosaveInPlace // (the default), or AutosaveOff. Autosave Autosave // AutosaveDelay is how long after the last edit a document is saved // in place: 5 seconds by default. A document being edited without a // pause is saved at least every 30 seconds. AutosaveDelay time.Duration // AskOnQuit asks to save the documents with unsaved changes when the // app quits, rather than keeping them and opening them again, still // edited, the next time the app starts, as VS Code and Zed do. AskOnQuit bool // NoUntitled opens no untitled document when the app starts without // documents to open, or (macOS) when its Dock icon is clicked while // it has no windows. NoUntitled bool }
DocumentsOptions configures NewDocuments. Read, Write, Window and at least one Type are required.
type Download ¶
type Download struct {
URL string
Path string
// Err is why the download failed, or nil.
Err error
}
Download is a finished download, passed to Page.OnDownloadDone.
type DownloadEvent ¶
type DownloadEvent struct {
Preventable
// URL of the download.
URL string
// SuggestedName is the file name the page or the server suggests.
SuggestedName string
// Path is where the file is saved: by default SuggestedName in the
// Downloads directory, numbered when a file has that name. A file
// already at a Path listeners set is replaced.
Path string
}
DownloadEvent is passed to Page.OnWillDownload listeners. Setting Path chooses where the file goes; preventing the event cancels the download.
type DragOptions ¶ added in v0.2.17
type DragOptions = transfer.DragOptions
DragOptions configures a native data source. See package transfer for representations, lazy providers and copy/move operations.
type DragResult ¶ added in v0.2.17
type EvalError ¶
type EvalError struct {
Message string
}
EvalError is returned by Eval when the script throws.
type Event ¶
type Event[T any] struct { // contains filtered or unexported fields }
Event is a typed event the Go side sends to pages. Declare events at package level so `mygo generate` includes them in the TypeScript client:
var Progress = mygo.NewEvent[ProgressInfo]("progress")
Progress.Emit(win, ProgressInfo{Done: 1, Total: 3})
and subscribe in the frontend with `events.progress.on(p => ...)`.
func NewEvent ¶
NewEvent declares an event with payload type T. Names must be unique; those starting with "mygo:" are reserved.
func (*Event[T]) Emit ¶
Emit sends the event to the page shown in w, or to the pages of the web views of a window showing native UI (WebView). Events sent before the page's DOM is ready are delivered once it is.
type FileDropEvent ¶
type FileDropEvent struct {
// Paths of the dropped files and directories.
Paths []string `json:"paths"`
// X and Y are where the files were dropped, in CSS pixels from the
// top-left corner of the page's viewport, like a DOM event's clientX
// and clientY.
X int `json:"x"`
Y int `json:"y"`
}
FileDropEvent is passed to Window.OnFileDrop listeners, and to the page's onFileDrop listeners.
type FileEvent ¶ added in v0.5.0
type FileEvent struct {
Op FileOp `json:"op"`
// Path is the path relative to the watched directory, separated by
// slashes; "." is the watched directory or file itself.
Path string `json:"path"`
// OldPath is where a FileRename moved from.
OldPath string `json:"oldPath,omitzero"`
// IsDir reports whether it is a directory, as it was before a
// FileRemove.
IsDir bool `json:"isDir"`
}
FileEvent is a change in a watched file or directory. A watch compares what it sees with what it saw before, so events say what is different, not every step that made it so: a file written twice in a row is one write, and one created and removed in between is nothing. Treat them as hints to read the files again.
type FileFilter ¶
FileFilter limits the files a file dialog shows, e.g. {Name: "Images", Extensions: []string{"png", "jpg"}}.
type FileOp ¶ added in v0.5.0
type FileOp string
FileOp is the kind of a FileEvent.
const ( // FileCreate is a file or directory that appeared. FileCreate FileOp = "create" // FileWrite is a file whose content may have changed: its size or // modification time changed, or the system said it was written. // Changes of permissions and other metadata are not reported, nor // are directories written, whose changes are their entries'. FileWrite FileOp = "write" // FileRemove is a file or directory that went away. FileRemove FileOp = "remove" // FileRename is a file or directory that moved within the watched // directory. FileRename FileOp = "rename" // FileHint says only that something in or under the directory at // Path changed: which file, and how, is unknown. A watch with // FileWatchOptions.HintsOnly reports nothing else, but a FileRemove // of "." when its directory goes away. FileHint FileOp = "hint" )
type FileWatchOptions ¶ added in v0.5.0
type FileWatchOptions struct {
// Recursive watches the directories in the directory too.
Recursive bool
// Ignore, when set, is asked about every file and directory the
// watch finds, by its path relative to the watched directory,
// separated by slashes, and whether it is a directory. What it
// ignores is not watched, reported or counted in MaxEntries, nor is
// anything in a directory it ignores, which is never opened: return
// true for node_modules and .git. It runs on a goroutine of the
// watch, and must be quick.
Ignore func(path string, isDir bool) bool
// Debounce is how long a watch waits for changes to stop before it
// reports them: 50 ms when zero, right away when negative.
Debounce time.Duration
// MaxDelay is the longest changes wait while more keep coming: 500 ms
// when zero, and never less than Debounce.
MaxDelay time.Duration
// MaxEntries is how many files and directories a watch keeps a
// snapshot of before it stops with ErrWatchLimit: 65536 on macOS,
// where a watch covers a whole tree with one stream, and 8192
// elsewhere, where a backend may take a handle per entry, when zero.
// With HintsOnly it counts the directories the watch enrolls.
MaxEntries int
// HintsOnly makes the watch cheap and coarse: it keeps no snapshot of
// the tree and stats no file, so it reports only FileHint events that
// name a directory in or under which the system said something
// changed, never which file, how, or that it was renamed. After the
// system lost changes it hints "." (look at everything). It suits a
// dev reloader, which rebuilds whatever changed; never use it where
// what changed matters, such as following a document's file.
//
// It still doesn't follow symlinks and doesn't leave the directory.
// Ignore is asked only about directories: what is in one it ignores
// is not watched or hinted, but a change to a file it would ignore
// still hints at that file's directory. On macOS and Windows a
// recursive watch enrolls only its directory, which the system
// watches as a tree; on Linux it enrolls every directory, without
// stat'ing what is in them.
HintsOnly bool
}
FileWatchOptions configures WatchFiles. The zero value watches a file, or a directory without the directories in it.
type FileWatcher ¶ added in v0.5.0
type FileWatcher struct {
// contains filtered or unexported fields
}
FileWatcher is a watch WatchFiles started. Its methods are safe from any goroutine.
func WatchFiles ¶ added in v0.5.0
func WatchFiles(ctx context.Context, path string, opts FileWatchOptions) (*FileWatcher, error)
WatchFiles watches the file or directory at path, and with opts.Recursive the directories in it, but not those that symlinks or Windows junctions point to. It returns once everything is watched; what is already there is not reported. Canceling ctx stops the watch, as Close does.
A file is watched through its directory, so that a file replaced, as editors save, is reported as written, one removed as removed, and one that appears again as created. When the directory itself (or the directory of the file) is removed, renamed or replaced, the watch reports a FileRemove of "." and ends: Next returns io.EOF.
It can be called from any goroutine, and on the main thread once the app runs. The app stops its watches when it quits.
func (*FileWatcher) Close ¶ added in v0.5.0
func (w *FileWatcher) Close() error
Close stops the watch and drops the changes not yet returned by Next, which then returns io.EOF. It doesn't wait for the watch to release what it holds; Done does. It returns nil.
func (*FileWatcher) Done ¶ added in v0.5.0
func (w *FileWatcher) Done() <-chan struct{}
Done is closed once the watch has stopped and released its handles.
func (*FileWatcher) Err ¶ added in v0.5.0
func (w *FileWatcher) Err() error
Err returns the error that stopped the watch: nil while it runs, and once it was closed, its context canceled, or its directory went away.
func (*FileWatcher) Next ¶ added in v0.5.0
func (w *FileWatcher) Next(ctx context.Context) ([]FileEvent, error)
Next waits for the next changes and returns them, a batch of the events that one look found once changes stopped for Debounce. The watch doesn't look again until Next has taken a batch, so nothing is lost when Next is called late: what changed meanwhile comes in the next batch.
It returns io.EOF once the watch is closed, or ended because its directory went away, and the error that stopped it otherwise. Canceling ctx cancels the wait, not the watch. On the main thread it keeps processing events while it waits.
func (*FileWatcher) Root ¶ added in v0.5.0
func (w *FileWatcher) Root() string
Root returns the path the watch watches, absolute and with its symlinks resolved (macOS's /tmp is /private/tmp), to which the paths of events are relative.
type FindOptions ¶
type FindOptions struct {
// MatchCase finds only text with the same capitalization.
MatchCase bool
// Backward goes to the previous match rather than the next one.
Backward bool
// FindNext moves on from the current match of the same text; without
// it the search starts over at the first match (the last, Backward).
FindNext bool
}
FindOptions configures Page.FindInPage.
type FindResult ¶
type FindResult struct {
// Matches is how many there are on the page, Active which of them is
// the current one, from 1; both are 0 without matches.
Matches int `json:"matches"`
Active int `json:"active"`
}
FindResult reports the matches of Page.FindInPage.
type FlyoutOptions ¶ added in v0.4.1
type FlyoutOptions struct {
// Parent owns the flyout, which stays above it, follows it as it moves
// and closes with it. A flyout has a Parent or a Tray.
Parent *Window
// Tray anchors the flyout to a tray icon instead, as the panel of a
// menu bar app: it goes next to the icon, on the side Placement
// names (PlacementBottom below an icon of the macOS menu bar, which
// flips above one of a taskbar at the bottom of the screen), and
// floats above the windows of other apps. Anchor does not apply.
// Linux's tray icons tell neither clicks nor where they are: a menu
// item of the icon opens it there, in the middle of the primary
// display's work area.
Tray *Tray
// Anchor is the rectangle the flyout is placed against, in DIPs
// relative to the parent's content area: the box of the element
// that opens it, as ui.Element.Bounds gives it, or a point (a
// rectangle of zero size), such as the pointer's.
Anchor Rectangle
// Placement is where the flyout goes from Anchor (default
// PlacementBottomStart). Where the display's work area has no room
// for it there, the flyout flips to the other side of the anchor, or
// to its other end, if that has room, then slides back into the work
// area, then shrinks to fit it.
Placement Placement
// Gap is the distance between Anchor and the flyout, in DIPs.
Gap int
// Width and Height of the flyout in DIPs (default 200x200).
Width, Height int
// Focusable makes the flyout take the keyboard as it shows, and close
// as a menu does when the user presses outside it, another window
// takes the keyboard or the app is deactivated: OnClose listeners
// hear it, and may keep it open, except on Wayland, whose compositor
// dismisses it. On Linux and Windows the press only closes it, as it
// closes their menus; on macOS it goes on to what is under the
// pointer, but on Anchor, as AppKit's popovers: so a click on the
// button that opened it closes it, and does not open it again.
// Menus, lists to choose from and popovers are focusable, and handle
// their own keys.
//
// Without it, the flyout never takes the keyboard, which stays in
// the parent, and stays until it is closed: tooltips, hover cards,
// or the suggestions of a text field in the parent, which closes
// them as it sees fit, as when it loses the keyboard.
//
// Either closes, as the user closing it, on an Escape its content
// does not handle: no element or shortcut of native UI takes it, no
// handler of the page calls preventDefault.
Focusable bool
// Hidden creates the flyout without showing it.
Hidden bool
// Shadow gives the flyout the system's window shadow (macOS,
// Windows). On macOS it follows the shape of what the content draws,
// and outlines it with a hairline: the content draws no border there.
// On Windows 11 the system rounds the flyout's corners as it rounds
// its menus, and outlines it: the content draws neither a border nor
// rounded corners there.
Shadow bool
// Popover gives the flyout the look of the system's popovers on macOS:
// it shows in an NSPopover, which draws its material, rounded corners,
// shadow and an arrow pointing at the middle of Anchor, and animates
// as it opens and closes. AppKit places it on the side Placement
// names, or the opposite one where the screen has no room: the rest
// of Placement, and Gap, do not apply. As AppKit's popovers do, it has
// the keyboard while it shows, Focusable or not, which makes it close
// as the user clicks elsewhere. Its content draws no background there
// (ui.Context.Vibrancy reports the material): elsewhere, where Popover
// changes nothing, it draws its own.
Popover bool
// URL is loaded right after the flyout is created, as
// WindowOptions.URL.
URL string
// Page configures the flyout's web page.
Page PageOptions
// Content makes the flyout show native UI instead of a web page, as
// WindowOptions.Content.
Content Content
}
FlyoutOptions configures NewFlyout.
type GlobalShortcutModule ¶
type GlobalShortcutModule struct {
// contains filtered or unexported fields
}
GlobalShortcutModule registers system wide keyboard shortcuts.
func (*GlobalShortcutModule) IsRegistered ¶
func (g *GlobalShortcutModule) IsRegistered(acc string) bool
IsRegistered reports whether accelerator is registered by this app.
func (*GlobalShortcutModule) Register ¶
func (g *GlobalShortcutModule) Register(acc string, fn func()) error
Register calls fn on the main thread whenever accelerator (e.g. "CmdOrCtrl+Shift+Space") is pressed, even when the app is not focused.
On Wayland the desktop binds the shortcut, through the XDG desktop portal, shortly after Register returns: it may ask the user to confirm it, lets them pick other keys, and needs the app installed with its desktop entry. The window fn shows or focuses first gets the activation token of the key press, which lets it take the focus.
Register claims the accelerator before the desktop binds it, so that calls arriving at once cannot bind it twice: IsRegistered reports it while the desktop binds it, and a second Register of the same accelerator fails.
func (*GlobalShortcutModule) Unregister ¶
func (g *GlobalShortcutModule) Unregister(acc string)
Unregister removes a shortcut.
func (*GlobalShortcutModule) UnregisterAll ¶
func (g *GlobalShortcutModule) UnregisterAll()
UnregisterAll removes all shortcuts registered by this app.
type InstalledApp ¶ added in v0.5.0
type InstalledApp struct {
// Name is the name the system shows for it, in the user's language.
Name string
// ID identifies it: its bundle identifier on macOS (or its path for a
// bundle without one), its AppUserModelID on Windows (for a desktop
// app without one, its path under a known folder), and its desktop
// file ID on Linux, such as org.gnome.Nautilus.desktop.
ID string
// Path is where it is: its .app bundle on macOS, its item of the
// Applications folder on Windows (shell:AppsFolder\<ID>), and its
// desktop entry on Linux. Shell.FileIcon draws its icon.
Path string
}
InstalledApp is an application installed on the computer, which Shell.InstalledApps lists.
type JumpList ¶ added in v0.5.0
type JumpList struct {
// contains filtered or unexported fields
}
JumpList controls the app's jump list on Windows, the menu of its taskbar button: the documents the user opened recently (see App.AddRecentDocument) and tasks. Use App.JumpList. Its methods do nothing on other platforms.
Windows replaces the whole list each time the app changes a part of it, so the JumpList keeps every part and commits them together.
func (*JumpList) SetTasks ¶ added in v0.5.0
func (j *JumpList) SetTasks(tasks []JumpListTask) error
SetTasks sets the Tasks category of the jump list, like Electron's app.setUserTasks; no tasks removes them. Windows keeps the list after the app quits, so apps usually set it once at startup. A task that runs the app is best a URL of the app's own scheme, which reaches App.OnOpenURL whether it starts the app or, with App.RequestSingleInstanceLock, the running instance gets it:
mygo.App.RegisterURLScheme("myapp") // or urlSchemes in mygo.config.ts
mygo.App.OnOpenURL(func(u string) {
if u == "myapp://new-note" { … }
})
if err := mygo.App.JumpList.SetTasks([]mygo.JumpListTask{
{Title: "New note", Args: []string{"myapp://new-note"}},
}); err != nil { … }
func (*JumpList) Tasks ¶ added in v0.5.0
func (j *JumpList) Tasks() []JumpListTask
Tasks returns the tasks set with SetTasks.
type JumpListTask ¶ added in v0.5.0
type JumpListTask struct {
// Title is the entry's label. It is required.
Title string
// Description is the entry's tooltip.
Description string
// Path is the program to run; empty is the app's own executable.
Path string
// Args are the program's arguments, each passed as it is: MyGo quotes
// them for the command line.
Args []string
// WorkingDir is the directory the program runs in; empty is the
// system's choice.
WorkingDir string
// IconPath and IconIndex choose the icon: the file holding it and the
// zero-based index of the icon in that file. An empty IconPath uses the
// program's own icon.
IconPath string
IconIndex int
}
JumpListTask is an entry of the Tasks category of the app's jump list on Windows. It runs a program, the app itself by default, whether the app is running or not.
type Margins ¶
type Margins struct{ Top, Right, Bottom, Left float64 }
Margins are page margins in inches.
type Menu ¶
type Menu struct {
// contains filtered or unexported fields
}
Menu is a list of menu items used as application menu, window menu, context menu or tray menu.
func NewMenu ¶
NewMenu builds a menu from a template:
menu := mygo.NewMenu([]*mygo.MenuItem{
{Role: mygo.RoleAppMenu},
{Label: "File", Submenu: []*mygo.MenuItem{
{Label: "New Window", Accelerator: "CmdOrCtrl+N", Click: newWindow},
mygo.Separator(),
{Role: mygo.RoleClose},
}},
{Role: mygo.RoleEditMenu},
})
type MenuItem ¶
type MenuItem struct {
// ID identifies the item for Menu.ItemByID.
ID string
Label string
Type MenuItemType
// Role gives the item a predefined behavior; Label and Accelerator
// default to the role's.
Role MenuRole
// Accelerator is a keyboard shortcut such as "CmdOrCtrl+Shift+N".
Accelerator string
Disabled bool
Hidden bool
// Checked is the state of checkbox and radio items. It is toggled
// before Click is called.
Checked bool
ToolTip string
// Click is called on the main thread when the item is chosen. On Linux
// and Windows, win is the window whose menu bar or context menu was
// chosen. Other menus use the focused window, which may be nil.
Click func(item *MenuItem, win *Window)
// contains filtered or unexported fields
}
MenuItem is an entry of a Menu. Fill in the exported fields to build a menu template; after the item has been added to a menu, change its state with the Set methods so native menus update.
func (*MenuItem) SetAccelerator ¶
SetAccelerator changes the keyboard shortcut of the item.
func (*MenuItem) SetChecked ¶
SetChecked checks or unchecks a checkbox or radio item.
func (*MenuItem) SetEnabled ¶
SetEnabled enables or disables the item.
func (*MenuItem) SetVisible ¶
SetVisible shows or hides the item.
type MenuItemType ¶
type MenuItemType string
MenuItemType is the kind of a menu item.
const ( MenuItemNormal MenuItemType = "normal" MenuItemSeparator MenuItemType = "separator" MenuItemCheckbox MenuItemType = "checkbox" MenuItemRadio MenuItemType = "radio" )
Menu item kinds. The type is inferred when empty: items with a Submenu are submenus, everything else is a normal item.
type MenuRole ¶
type MenuRole string
MenuRole gives a menu item a predefined behavior, label and accelerator.
const ( RoleUndo MenuRole = "undo" RoleRedo MenuRole = "redo" RoleCut MenuRole = "cut" RoleCopy MenuRole = "copy" RolePaste MenuRole = "paste" RolePasteAndMatchStyle MenuRole = "pasteAndMatchStyle" RoleDelete MenuRole = "delete" RoleSelectAll MenuRole = "selectAll" RoleReload MenuRole = "reload" RoleForceReload MenuRole = "forceReload" RoleToggleDevTools MenuRole = "toggleDevTools" RoleResetZoom MenuRole = "resetZoom" RoleZoomIn MenuRole = "zoomIn" RoleZoomOut MenuRole = "zoomOut" RoleToggleFullScreen MenuRole = "togglefullscreen" RoleMinimize MenuRole = "minimize" RoleZoom MenuRole = "zoom" RoleClose MenuRole = "close" // Documents (NewDocuments): they act on the focused window's // document, and New and Open on the app's first kind of documents. RoleNew MenuRole = "new" RoleOpen MenuRole = "open" RoleOpenRecent MenuRole = "openRecent" // submenu of the recent documents RoleSave MenuRole = "save" RoleSaveAs MenuRole = "saveAs" RoleDuplicate MenuRole = "duplicate" RoleRename MenuRole = "rename" RoleMoveTo MenuRole = "moveTo" RoleRevert MenuRole = "revert" RoleQuit MenuRole = "quit" RoleAbout MenuRole = "about" // (macOS) RoleHide MenuRole = "hide" // (macOS) RoleHideOthers MenuRole = "hideOthers" // (macOS) RoleUnhide MenuRole = "unhide" // (macOS) RoleFront MenuRole = "front" // (macOS) RoleServices MenuRole = "services" // (macOS) submenu RoleStartSpeaking MenuRole = "startSpeaking" // (macOS) RoleStopSpeaking MenuRole = "stopSpeaking" // (macOS) RoleWindow MenuRole = "window" // submenu listing open windows (macOS) RoleHelp MenuRole = "help" // submenu with the search field (macOS) RoleAppMenu MenuRole = "appMenu" // default application menu RoleFileMenu MenuRole = "fileMenu" // default File menu RoleEditMenu MenuRole = "editMenu" // default Edit menu RoleViewMenu MenuRole = "viewMenu" // default View menu RoleWindowMenu MenuRole = "windowMenu" // default Window menu // The Format menu's roles format the selection of a rich text editor // of native UI (ui/richtext), or of an editable web page. RoleBold MenuRole = "bold" RoleItalic MenuRole = "italic" RoleUnderline MenuRole = "underline" RoleStrikethrough MenuRole = "strikethrough" RoleAlignLeft MenuRole = "alignLeft" RoleAlignCenter MenuRole = "alignCenter" RoleAlignRight MenuRole = "alignRight" RoleFormatMenu MenuRole = "formatMenu" // default Format menu )
Menu roles. Roles marked (macOS) are ignored elsewhere.
type MessageOptions ¶
type MessageOptions struct {
Parent *Window
Type MessageType
Title string
Message string
// Detail is shown below Message in a smaller font.
Detail string
// Buttons defaults to a single "OK" button.
Buttons []string
// DefaultButton is the index of the button activated with Enter.
DefaultButton int
// CancelButton is the index of the button activated with Escape. When
// zero, the first button labeled "Cancel" or "No" is used.
CancelButton int
CheckboxLabel string
CheckboxChecked bool
}
MessageOptions configures Dialog.Message.
type MessageResult ¶
type MessageResult struct {
// Button is the index of the clicked button.
Button int
// CheckboxChecked is the final state of the checkbox.
CheckboxChecked bool
}
MessageResult is the outcome of Dialog.Message.
type MessageType ¶
type MessageType string
MessageType selects the icon of a message dialog.
const ( MessageNone MessageType = "none" MessageInfo MessageType = "info" MessageWarning MessageType = "warning" MessageError MessageType = "error" MessageQuestion MessageType = "question" )
Message dialog types.
type NavigateEvent ¶
type NavigateEvent struct {
// gesture such as clicking a link.
UserInitiated bool
}
NavigateEvent is passed to Page.OnWillNavigate listeners. Preventing it cancels the navigation.
type NetworkModule ¶ added in v0.5.0
type NetworkModule struct {
// contains filtered or unexported fields
}
NetworkModule reports whether the computer is online. Use the Network singleton.
func (*NetworkModule) OnChanged ¶ added in v0.5.0
func (n *NetworkModule) OnChanged(fn func(status NetworkStatus)) (off func())
OnChanged is called on the main thread when the computer's network state changes, with the new state.
func (*NetworkModule) Status ¶ added in v0.5.0
func (n *NetworkModule) Status() NetworkStatus
Status returns the computer's network state. It is safe from any goroutine; like the other calls that need the running app, it panics on the main goroutine before App.Run, and waits for Run elsewhere. On macOS the first call waits for the system's first answer, which comes within milliseconds.
type NetworkStatus ¶ added in v0.5.0
type NetworkStatus struct {
// Online reports whether the system has a connection to a network
// beyond the computer: a route out on macOS (Network.framework's
// satisfied path) and Linux (GNetworkMonitor's network-available, a
// default route), and on Windows a connectivity level of local
// access or more. A network behind a captive portal, or one whose
// way to the internet is down, counts, as it does for the browsers'
// navigator.onLine: it does not prove that a server answers.
Online bool `json:"online"`
// Metered reports whether the connection costs by the amount of data
// or is limited, so the app should send less and ask the user before
// it downloads something large: an expensive path (cellular, a
// phone's hotspot) or Low Data Mode on macOS, a metered connection on
// Linux, and on Windows a cost that is fixed or variable, or one
// that roams, is over its data limit or approaches it. It is false
// in browsers, which do not say.
Metered bool `json:"metered"`
}
NetworkStatus is the state of the computer's network connection. Pages get it as {"online": …, "metered": …}.
type Notification ¶
type Notification struct {
// contains filtered or unexported fields
}
Notification is a desktop notification.
func NewNotification ¶
func NewNotification(opts NotificationOptions) *Notification
NewNotification creates a notification; call Show to display it.
func (*Notification) ID ¶ added in v0.2.15
func (n *Notification) ID() string
ID returns the notification's ID: NotificationOptions.ID, or the one it was given.
func (*Notification) OnClick ¶
func (n *Notification) OnClick(fn func()) (off func())
OnClick is called when the user clicks the notification.
func (*Notification) Show ¶
func (n *Notification) Show() error
Show displays the notification, and returns once the system has it. On macOS the first notification asks the user whether to allow them, and Show waits for the answer; it returns ErrNotificationsDenied when they are not allowed.
type NotificationOptions ¶
type NotificationOptions struct {
// ID identifies the notification: App.OnNotificationClick receives
// it, also after the app has quit and been launched again, and showing
// a notification with the ID of one still shown replaces that one.
// Empty gives it an ID of its own.
ID string
Title string
Subtitle string
Body string
// Silent suppresses the notification sound.
Silent bool
// Group gathers the notifications that share it in one stack of
// Notification Center (macOS), such as the messages of a conversation.
// Empty leaves them in the app's.
Group string
}
NotificationOptions configures a desktop notification.
type OpenDialogOptions ¶
type OpenDialogOptions struct {
// Parent attaches the dialog to a window (a sheet on macOS).
Parent *Window
Title string
DefaultPath string
// ButtonLabel replaces the label of the confirm button.
ButtonLabel string
// Message is shown above the file list (macOS).
Message string
Filters []FileFilter
// Directory selects directories instead of files.
Directory bool
// Multiple allows selecting several entries.
Multiple bool
ShowHiddenFiles bool
// CreateDirectories shows a "New Folder" button (macOS).
CreateDirectories bool
// TreatPackagesAsDirectories lets the user browse into packages such as
// .app bundles (macOS).
TreatPackagesAsDirectories bool
}
OpenDialogOptions configures Dialog.Open.
type PDFOptions ¶
type PDFOptions struct {
// PageSize is the size of the paper; the zero value is PageLetter.
PageSize PageSize
Landscape bool
// Margins surround the content of every page; nil means 0.4 inch on
// every side, &Margins{} none.
Margins *Margins
// Background prints background colors and images, which printing
// leaves out by default.
Background bool
}
PDFOptions configures Page.PrintToPDF. The zero value prints Letter pages in portrait orientation with margins of 0.4 inch and without backgrounds, like a browser's print dialog.
type Page ¶ added in v0.2.0
type Page struct {
// contains filtered or unexported fields
}
Page is the web page a window shows: what it loads, the scripts it runs, its developer tools and its events. A window showing native UI (WindowOptions.Content) has none.
win := mygo.NewWindow(mygo.WindowOptions{Title: "Editor", URL: "/"})
win.Page().OnDOMReady(func() { log.Println("ready") })
Like the window's, its methods are safe from any goroutine.
func CallerPage ¶ added in v0.4.0
CallerPage returns the page that called a bound method, given the context.Context passed to that method: the page of the calling window, or of a web view in it (WebView), whose window CallerWindow returns. It returns nil for other contexts.
func (*Page) CanGoBack ¶ added in v0.2.0
CanGoBack reports whether there is a previous page in history.
func (*Page) CanGoForward ¶ added in v0.2.0
CanGoForward reports whether there is a next page in history.
func (*Page) CloseDevTools ¶ added in v0.2.0
func (p *Page) CloseDevTools()
CloseDevTools closes the web inspector.
func (*Page) Eval ¶ added in v0.2.0
Eval evaluates JavaScript in the page and returns its result, decoded from JSON. An expression's value is returned, with promises awaited:
title, err := win.Page().Eval("document.title")
data, err := win.Page().Eval("fetch('/data.json').then(r => r.json())")
Statements run as the body of an async function, so use return to produce a value:
n, err := win.Page().Eval("const items = document.querySelectorAll('li'); return items.length")
Eval is not subject to the page's Content Security Policy.
func (*Page) EvalContext ¶ added in v0.2.0
EvalContext is Eval with a context that can abort the wait.
func (*Page) FindInPage ¶ added in v0.2.0
func (p *Page) FindInPage(text string, opts FindOptions) (FindResult, error)
FindInPage highlights the occurrences of text in the page, scrolls to the active one and reports how many there are, like the find bar of a browser: call it as the user types, and with FindNext to go to the next match.
res, err := win.Page().FindInPage("mygo", mygo.FindOptions{FindNext: true})
Text split by markup, such as "my<b>go</b>", is not found.
func (*Page) GoForward ¶ added in v0.2.0
func (p *Page) GoForward()
GoForward navigates forward in history.
func (*Page) IsDevToolsOpened ¶ added in v0.2.0
IsDevToolsOpened reports whether the web inspector is open.
func (*Page) LoadFile ¶ added in v0.2.0
LoadFile loads a local HTML file. Relative paths are resolved against the working directory, then against the directory of the executable (and the Resources directory of a macOS app bundle).
func (*Page) LoadHTML ¶ added in v0.2.0
LoadHTML loads an HTML string. Relative URLs in it resolve against baseURL, which may be empty, and the page is at baseURL, or about:blank. Reloading the page, with Reload or from the page, loads html again.
func (*Page) LoadURL ¶ added in v0.2.0
LoadURL navigates the page to url. A URL without a scheme, such as "/" or "/settings?tab=1", is a page of the app's frontend: the dev server at devUrl during `mygo dev`, the frontend built into the app otherwise (see SetFrontend). Besides http(s) URLs, schemes registered with Protocol.Handle can be used.
func (*Page) OnDOMReady ¶ added in v0.2.0
func (p *Page) OnDOMReady(fn func()) (off func())
OnDOMReady is called when the page's DOM is ready (DOMContentLoaded).
func (*Page) OnDidFailLoad ¶ added in v0.2.0
OnDidFailLoad is called when the page failed to load.
func (*Page) OnDidFinishLoad ¶ added in v0.2.0
func (p *Page) OnDidFinishLoad(fn func()) (off func())
OnDidFinishLoad is called when the page finished loading.
func (*Page) OnDidNavigate ¶ added in v0.2.0
OnDidNavigate is called when a navigation committed and a new page started.
func (*Page) OnDownloadDone ¶ added in v0.2.0
OnDownloadDone is called when a download ended.
func (*Page) OnPageTitleUpdated ¶ added in v0.2.0
func (p *Page) OnPageTitleUpdated(fn func(e *TitleEvent)) (off func())
OnPageTitleUpdated is called when the page's <title> changes. Preventing the event keeps the native window title.
func (*Page) OnRenderProcessGone ¶ added in v0.2.0
OnRenderProcessGone is called when the web content process crashed or was killed. Call Reload to recover.
func (*Page) OnWillDownload ¶ added in v0.2.0
func (p *Page) OnWillDownload(fn func(e *DownloadEvent)) (off func())
OnWillDownload is called when a page starts a download: a link with the download attribute, or a response the page cannot show, such as a file sent as an attachment. Without listeners, downloads are saved to the Downloads directory.
func (*Page) OnWillNavigate ¶ added in v0.2.0
func (p *Page) OnWillNavigate(fn func(e *NavigateEvent)) (off func())
OnWillNavigate is called before the page navigates to another URL, for example after a link click. Preventing the event cancels the navigation. It is not called for LoadURL and friends.
func (*Page) OpenDevTools ¶ added in v0.2.0
func (p *Page) OpenDevTools()
OpenDevTools opens the web inspector (unless disabled with PageOptions.DevTools).
func (*Page) Print ¶ added in v0.2.0
func (p *Page) Print()
Print opens the print dialog for the page.
func (*Page) PrintToPDF ¶ added in v0.2.0
func (p *Page) PrintToPDF(opts PDFOptions) ([]byte, error)
PrintToPDF renders the page as a PDF document, laid out for printing (the page's print style sheets apply) on pages of the given size:
pdf, err := win.Page().PrintToPDF(mygo.PDFOptions{PageSize: mygo.PageA4, Background: true})
func (*Page) ReloadIgnoringCache ¶ added in v0.2.0
func (p *Page) ReloadIgnoringCache()
ReloadIgnoringCache reloads the page bypassing the cache.
func (*Page) SetPermissionHandler ¶ added in v0.2.0
func (p *Page) SetPermissionHandler(fn func(req PermissionRequest) bool)
SetPermissionHandler decides what the pages of the window may use, such as the camera: fn returns whether to grant a request, and runs on the main thread. nil restores the default: the app's own pages (see PageOptions.TrustedOrigins) get what they ask for, other pages do not.
The operating system may still ask the user, like macOS does once per app for the camera and the microphone. That needs usage descriptions in macos.infoPlist of mygo.config.ts (NSCameraUsageDescription, NSMicrophoneUsageDescription), without which macOS ends the app.
func (*Page) SetUserAgent ¶ added in v0.2.0
SetUserAgent overrides the user agent for subsequent requests.
func (*Page) SetWindowOpenHandler ¶ added in v0.2.0
func (p *Page) SetWindowOpenHandler(fn func(req WindowOpenRequest) *WindowOptions)
SetWindowOpenHandler decides what happens on window.open() and clicks on target="_blank" links. The handler returns the options of the window to open, or nil to deny the request. Without a handler, http(s) URLs open in the default browser and everything else is denied.
On macOS the new page keeps its relation to the opener (window.opener). On Linux it opens as an independent page, because WebKitGTK would share the opener's script message routing with a related page.
func (*Page) SetZoomFactor ¶ added in v0.2.0
SetZoomFactor zooms the page; 1 is 100%.
func (*Page) StopFindInPage ¶ added in v0.2.0
func (p *Page) StopFindInPage()
StopFindInPage removes the highlights of FindInPage.
func (*Page) ToggleDevTools ¶ added in v0.2.0
func (p *Page) ToggleDevTools()
ToggleDevTools opens or closes the web inspector.
func (*Page) WebView ¶ added in v0.4.0
WebView returns the web view whose page this is, nil for the page of a window.
func (*Page) Window ¶ added in v0.2.0
Window returns the window that shows the page: for the page of a web view, the window the web view is in.
func (*Page) ZoomFactor ¶ added in v0.2.0
ZoomFactor returns the page zoom; 1 is 100%.
type PageOptions ¶ added in v0.2.0
type PageOptions struct {
// PreloadScript is JavaScript injected into every page before the
// page's own scripts, after window.mygo is available.
PreloadScript string
// TrustedOrigins lists extra origins, such as "https://example.com",
// whose pages may call bound Go methods. By default only the app's own
// content can: custom schemes registered with Protocol, file: and
// about: pages, and loopback dev servers during development. "*"
// trusts every origin.
TrustedOrigins []string
// DevTools controls the web inspector, and for a window showing
// Content, the inspector of its native UI.
DevTools DevTools
// ZoomFactor of the page (default 1).
ZoomFactor float64
// UserAgent overrides the user agent string.
UserAgent string
}
PageOptions configure the web page of a window.
type PageSize ¶
type PageSize struct{ Width, Height float64 }
PageSize is the size of a sheet of paper in inches, in portrait orientation.
type PathName ¶
type PathName string
PathName names a well known directory for Application.Path.
const ( PathHome PathName = "home" // PathAppData is the per-user application data directory: // ~/Library/Application Support, $XDG_CONFIG_HOME or %AppData%. PathAppData PathName = "appData" // PathUserData is PathAppData joined with the application name. It is // created on first use. PathUserData PathName = "userData" // PathCache is the per-user cache directory of this application. It is // created on first use. PathCache PathName = "cache" // PathLogs is where the application should write logs. It is created on // first use. PathLogs PathName = "logs" // PathResources is the directory of the files the app ships with: the // contents of the project's resources directory, with those of its // directories for the app's platform (such as resources/darwin-arm64) // merged in, and the resources listed in mygo.config.ts, which // `mygo dev` and `mygo build` copy there. It is Contents/Resources in a // macOS app bundle and the executable's directory elsewhere. Under // `go run` and `go test`, whose executables are temporary, it is the // resources directory in the working directory, as it is. PathResources PathName = "resources" PathTemp PathName = "temp" PathExe PathName = "exe" PathDesktop PathName = "desktop" PathDocuments PathName = "documents" PathDownloads PathName = "downloads" PathMusic PathName = "music" PathPictures PathName = "pictures" PathVideos PathName = "videos" )
Well known directories.
type Permission ¶
type Permission string
Permission is something a page asks the user for.
const ( PermissionCamera Permission = "camera" PermissionMicrophone Permission = "microphone" PermissionGeolocation Permission = "geolocation" PermissionNotifications Permission = "notifications" )
Permissions.
type PermissionRequest ¶
type PermissionRequest struct {
// Permissions asked for together, such as the camera and the
// microphone of a video call.
Permissions []Permission
// Origin of the page asking, e.g. "https://example.com".
Origin string
}
PermissionRequest is passed to the permission handler of a window.
type Placement ¶ added in v0.4.1
type Placement string
Placement is where a flyout goes from its anchor: the side, and how it lines up with the anchor along that side, as in "bottom-start", below the anchor with their left edges lined up.
const ( PlacementBottomStart Placement = "bottom-start" PlacementBottom Placement = "bottom" PlacementBottomEnd Placement = "bottom-end" PlacementTopStart Placement = "top-start" PlacementTop Placement = "top" PlacementTopEnd Placement = "top-end" PlacementRightStart Placement = "right-start" PlacementRight Placement = "right" PlacementRightEnd Placement = "right-end" PlacementLeftStart Placement = "left-start" PlacementLeft Placement = "left" PlacementLeftEnd Placement = "left-end" )
Placements.
type Plugin ¶ added in v0.1.8
type Plugin struct {
// Name identifies the plugin: lowercase letters, digits and hyphens,
// starting with a letter, e.g. "fetch". "mygo" is reserved.
Name string
// Service is bound as "plugin:<Name>", when not nil.
Service any
// Setup runs once, when Use is called with the plugin, to add
// listeners, protocols and the like. An error makes Use panic.
Setup func() error
}
Plugin adds a feature to an app in two halves: Go services, and a JavaScript package whose pages call them. The official plugins live in the repository's plugins directory, such as fetch, whose npm package @mygo-plugins/fetch gives pages a fetch that runs in Go:
mygo.Use(fetch.Plugin, websocket.Plugin)
A plugin's services are bound like those of Bind, with the same rules for their methods, but under the name "plugin:<Name>" and outside the generated TypeScript client: its JavaScript package calls them with call of mygo-runtime, as in `call("plugin:fetch.Fetch", ...)`. Only trusted pages may call them, like every bound method.
type PowerModule ¶
type PowerModule struct {
// contains filtered or unexported fields
}
PowerModule reports power and session changes and keeps the computer awake. Use the Power singleton.
func (*PowerModule) IdleTime ¶
func (p *PowerModule) IdleTime() time.Duration
IdleTime returns how long the user has not used the keyboard or mouse, or 0 when the system does not tell (some Linux desktops).
func (*PowerModule) IsOnBattery ¶
func (p *PowerModule) IsOnBattery() bool
IsOnBattery reports whether the computer runs on battery power.
func (*PowerModule) KeepAwake ¶
func (p *PowerModule) KeepAwake(reason string, display bool) (release func())
KeepAwake keeps the computer from sleeping while idle, and with display the display from turning off, e.g. during a long task or while a video plays, until release is called:
release := mygo.Power.KeepAwake("Exporting the video", false)
defer release()
The reason shows where the system lists what keeps it awake.
func (*PowerModule) OnLockScreen ¶
func (p *PowerModule) OnLockScreen(fn func()) (off func())
OnLockScreen is called when the screen locks (on Linux, when the screen saver starts, which usually locks it).
func (*PowerModule) OnResume ¶
func (p *PowerModule) OnResume(fn func()) (off func())
OnResume is called when the system woke up.
func (*PowerModule) OnSuspend ¶
func (p *PowerModule) OnSuspend(fn func()) (off func())
OnSuspend is called when the system is about to sleep.
func (*PowerModule) OnUnlockScreen ¶
func (p *PowerModule) OnUnlockScreen(fn func()) (off func())
OnUnlockScreen is called when the screen unlocks.
type Preventable ¶
type Preventable struct {
// contains filtered or unexported fields
}
Preventable is embedded in events whose default action listeners can cancel.
func (*Preventable) DefaultPrevented ¶
func (p *Preventable) DefaultPrevented() bool
DefaultPrevented reports whether PreventDefault was called.
func (*Preventable) PreventDefault ¶
func (p *Preventable) PreventDefault()
PreventDefault cancels the default action of the event.
type ProgressBar ¶
type ProgressBar struct {
// State defaults to ProgressNormal when Value is above 0, else to
// ProgressNone.
State ProgressState
// Value is the fraction done, between 0 and 1.
Value float64
}
ProgressBar is the progress of a task, shown on the window's taskbar button (Windows), on the application's Dock icon (macOS) or on its launcher entry (Linux docks that implement the Unity launcher API, such as KDE Plasma's and Ubuntu's). The zero value shows no progress.
type ProgressState ¶
type ProgressState string
ProgressState is the state of a progress bar; see ProgressBar.
const ( ProgressNone ProgressState = "" ProgressNormal ProgressState = "normal" ProgressIndeterminate ProgressState = "indeterminate" // ProgressPaused and ProgressError color the bar yellow and red on // Windows, and show it like ProgressNormal elsewhere. ProgressPaused ProgressState = "paused" ProgressError ProgressState = "error" )
Progress states.
type ProtocolModule ¶
type ProtocolModule struct {
// contains filtered or unexported fields
}
ProtocolModule registers custom URL schemes served by Go.
func (*ProtocolModule) Handle ¶
func (p *ProtocolModule) Handle(scheme string, handler http.Handler) error
Handle serves requests for scheme with an http.Handler, for example files generated at run time:
mygo.Protocol.Handle("thumbs", mygo.FileServer(os.DirFS(cacheDir)))
win.Page().LoadURL("thumbs://localhost/")
Pages served this way are loaded like regular web pages: they can use fetch, ES modules and relative URLs. Schemes must be registered before the windows that use them are created. Handlers run on their own goroutines and responses are streamed to the page.
The mygo scheme serves the app's frontend (see SetFrontend) unless it is handled here.
func (*ProtocolModule) HandleFunc ¶
func (p *ProtocolModule) HandleFunc(scheme string, fn func(http.ResponseWriter, *http.Request)) error
HandleFunc is Handle for a handler function.
func (*ProtocolModule) IsHandled ¶
func (p *ProtocolModule) IsHandled(scheme string) bool
IsHandled reports whether scheme has a handler.
func (*ProtocolModule) Unhandle ¶
func (p *ProtocolModule) Unhandle(scheme string)
Unhandle removes the handler of scheme. Pages requesting it get an error.
type QuitEvent ¶
type QuitEvent struct {
Preventable
}
QuitEvent is passed to Application.OnBeforeQuit and OnWillQuit listeners. Preventing it cancels the quit.
type Rectangle ¶
type Rectangle struct{ X, Y, Width, Height int }
Rectangle is a position and size in screen coordinates (DIPs, origin at the top-left corner of the primary display).
type SaveDialogOptions ¶
type SaveDialogOptions struct {
Parent *Window
Title string
DefaultPath string
ButtonLabel string
Message string
// NameFieldLabel replaces the label in front of the file name field
// (macOS).
NameFieldLabel string
Filters []FileFilter
ShowHiddenFiles bool
CreateDirectories bool
TreatPackagesAsDirectories bool
}
SaveDialogOptions configures Dialog.Save.
type ScreenModule ¶
type ScreenModule struct {
// contains filtered or unexported fields
}
ScreenModule queries displays.
func (*ScreenModule) CursorScreenPoint ¶
func (s *ScreenModule) CursorScreenPoint() Point
CursorScreenPoint returns the mouse position in screen coordinates.
func (*ScreenModule) DisplayMatching ¶
func (s *ScreenModule) DisplayMatching(r Rectangle) Display
DisplayMatching returns the display that overlaps r the most.
func (*ScreenModule) DisplayNearestPoint ¶
func (s *ScreenModule) DisplayNearestPoint(p Point) Display
DisplayNearestPoint returns the display closest to p.
func (*ScreenModule) Displays ¶
func (s *ScreenModule) Displays() []Display
Displays returns all displays; the primary one comes first.
func (*ScreenModule) OnDisplaysChanged ¶
func (s *ScreenModule) OnDisplaysChanged(fn func()) (off func())
OnDisplaysChanged is called when displays are added, removed or change resolution.
func (*ScreenModule) PrimaryDisplay ¶
func (s *ScreenModule) PrimaryDisplay() Display
PrimaryDisplay returns the display with the menu bar or taskbar.
type SecretsModule ¶ added in v0.5.0
type SecretsModule struct {
// contains filtered or unexported fields
}
SecretsModule keeps small secrets, such as access tokens and API keys, in the system's credential store. Use the Secrets singleton, or Secrets.Service for the secrets of another service.
var Secrets SecretsModule
Secrets keeps small secrets in the system's credential store: the login Keychain on macOS, the Secret Service on Linux (GNOME Keyring, KWallet, KeePassXC…, through libsecret) and the Credential Manager on Windows. The system encrypts them for the user, unlike a file in PathUserData:
if err := mygo.Secrets.Set("github-token", []byte(token)); err != nil { … }
token, err := mygo.Secrets.Get("github-token")
if errors.Is(err, mygo.ErrSecretNotFound) { … ask the user to sign in }
A store keeps a secret under a service and an account, which Secrets takes the key for. The service is the app's identifier (identifier of mygo.config.ts); under `mygo dev`, whose app is "<identifier>.dev", the development app's, so it keeps secrets apart from the installed app; and without an identifier, as with `go run`, the app's name (App.Name). Service chooses another. Other apps of the user may still read them, on Linux without asking.
Where there is no credential store, the methods fail with an error for which errors.Is(err, errors.ErrUnsupported) holds: in browsers, and on Linux without libsecret, a session bus or a Secret Service on it, as on many servers and minimal desktops. An app can then keep the secret elsewhere, or ask for it each time.
The methods are safe from any goroutine and work before Run. They may block while the system asks the user, e.g. to unlock the keyring or, on macOS, to let a rebuilt app read what it stored; on the main thread the app keeps handling events meanwhile.
func (SecretsModule) Delete ¶ added in v0.5.0
func (s SecretsModule) Delete(key string) error
Delete removes the secret stored under key. Deleting a key without a secret is not an error.
func (SecretsModule) Get ¶ added in v0.5.0
func (s SecretsModule) Get(key string) ([]byte, error)
Get returns the secret stored under key, or ErrSecretNotFound.
func (SecretsModule) Service ¶ added in v0.5.0
func (SecretsModule) Service(service string) SecretsModule
Service returns Secrets for the secrets of service, in place of the app's identifier: to share them with another program of the app, such as a command line tool, or to read those an Electron app stored with keytar, which takes the same service and account and stores them as Secrets does, under the service the app passed to it. An empty service is the app's.
token, err := mygo.Secrets.Service("MyApp").Get("refresh-token") // keytar.getPassword("MyApp", "refresh-token")
type ShellModule ¶
type ShellModule struct{}
ShellModule integrates with the desktop environment.
var Shell ShellModule
Shell opens URLs and files with the default applications.
func (ShellModule) FileIcon ¶ added in v0.5.0
func (ShellModule) FileIcon(path string, size int) ([]byte, error)
FileIcon returns the icon the file manager shows for a file, a folder or an application, as a PNG image of size by size pixels: pass the size in DIPs times the display's scale factor for a sharp icon. On Windows path may also name a shell item, such as an app of the Start menu by its shell:AppsFolder\<AppUserModelID> path; on Linux, the icon of a desktop entry (.desktop) is its application's, from the icon theme. It fails in browsers.
func (ShellModule) InstalledApps ¶ added in v0.5.0
func (ShellModule) InstalledApps() ([]InstalledApp, error)
InstalledApps lists the applications installed on the computer, sorted by name, as a launcher shows them:
- macOS: the .app bundles in /Applications, /System/Applications, ~/Applications and CoreServices' Applications, and in their folders (Utilities), plus Finder.
- Windows: the Start menu's All apps, desktop and packaged apps alike (the shell's Applications folder).
- Linux: the applications of the desktop entries menus show.
It reads the disk: call it from a goroutine of its own, which it does not block the main thread from. Browsers return an error.
func (ShellModule) LaunchApp ¶ added in v0.5.0
func (ShellModule) LaunchApp(app InstalledApp) error
LaunchApp starts an application of InstalledApps, or brings it to the front if it runs.
func (ShellModule) OpenExternal ¶
func (ShellModule) OpenExternal(url string) error
OpenExternal opens a URL with the default application, e.g. a web page in the default browser.
func (ShellModule) OpenPath ¶
func (ShellModule) OpenPath(path string) error
OpenPath opens a file or directory with the default application.
func (ShellModule) ShowItemInFolder ¶
func (ShellModule) ShowItemInFolder(path string)
ShowItemInFolder reveals a file in the file manager.
func (ShellModule) TrashItem ¶
func (ShellModule) TrashItem(path string) error
TrashItem moves a file or directory to the trash.
type ThemeModule ¶
type ThemeModule struct {
// contains filtered or unexported fields
}
ThemeModule reads and overrides the light/dark appearance.
func (*ThemeModule) IsDark ¶
func (t *ThemeModule) IsDark() bool
IsDark reports whether the app currently uses a dark appearance.
func (*ThemeModule) OnUpdated ¶
func (t *ThemeModule) OnUpdated(fn func()) (off func())
OnUpdated is called when the effective appearance, or the desktop's preferences (Preferences), change.
func (*ThemeModule) Preferences ¶ added in v0.5.0
func (t *ThemeModule) Preferences() ThemePreferences
Preferences returns the accent color and the accessibility settings of the desktop, all read at once. It is safe from any goroutine; like the other calls that need the running app, it panics on the main goroutine before App.Run, and waits for Run elsewhere.
func (*ThemeModule) SetSource ¶
func (t *ThemeModule) SetSource(s ThemeSource)
SetSource forces a light or dark appearance, or follows the system. It may be called before App.Run, e.g. with a saved preference, to start the app in that appearance.
func (*ThemeModule) Source ¶
func (t *ThemeModule) Source() ThemeSource
Source returns the appearance override.
type ThemePreferences ¶ added in v0.5.0
type ThemePreferences struct {
// Accent is the color of the desktop's controls, 8-bit sRGB with
// straight alpha, or the zero color (A 0) where the desktop has none,
// as Linux desktops whose settings portal has no accent-color and
// browsers. Package ui's default theme already follows it; elsewhere
// ui.RGB(Accent.R, Accent.G, Accent.B) makes it a ui.Color.
Accent color.NRGBA
// ReduceMotion reports that the desktop asks for less motion: macOS's
// Reduce Motion, Windows's animation effects and GNOME's animations
// turned off.
ReduceMotion bool
// ReduceTransparency reports that the desktop asks for opaque
// surfaces in place of translucent ones, such as vibrancy: macOS's
// Reduce Transparency, Windows's transparency effects turned off, and
// prefers-reduced-transparency in browsers. Linux desktops have no
// such setting, so it is false there.
ReduceTransparency bool
// HighContrast reports that the desktop asks for more contrast:
// macOS's Increase Contrast, Windows's contrast themes, the settings
// portal's higher contrast or a HighContrast GTK theme on Linux.
HighContrast bool
// TextScale is how many times larger than usual text should be, as
// Windows's and GNOME's text size settings say; 1 is usual, and what
// macOS, which has no such setting, reports.
TextScale float64
}
ThemePreferences are the accent color and the accessibility settings of the desktop, which an app and its pages should follow. Pages get them as JSON, as mygo-runtime's ThemePreferences, which is also what they encode to: {"accent": "#rrggbb" or null, "reduceMotion": …, "reduceTransparency": …, "highContrast": …, "textScale": …}.
func (ThemePreferences) MarshalJSON ¶ added in v0.5.0
func (p ThemePreferences) MarshalJSON() ([]byte, error)
MarshalJSON encodes the preferences as pages get them, mygo-runtime's ThemePreferences, with the accent as "#rrggbb" ("#rrggbbaa" when it is not opaque), or null where the desktop has none.
func (*ThemePreferences) UnmarshalJSON ¶ added in v0.5.0
func (p *ThemePreferences) UnmarshalJSON(b []byte) error
UnmarshalJSON decodes what MarshalJSON encodes.
type ThemeSource ¶
type ThemeSource string
ThemeSource selects the appearance of the app.
const ( ThemeSystem ThemeSource = "system" ThemeLight ThemeSource = "light" ThemeDark ThemeSource = "dark" )
Theme sources.
type TitleBarStyle ¶
type TitleBarStyle string
TitleBarStyle selects how the title bar of a framed window looks.
const ( TitleBarDefault TitleBarStyle = "default" // TitleBarHidden gives the page the whole window while keeping the // window controls, which sit over it (see WindowOptions.TitleBarStyle). TitleBarHidden TitleBarStyle = "hidden" // TitleBarHiddenInset is TitleBarHidden with the window controls inset // further from the edges (macOS; TitleBarHidden elsewhere). TitleBarHiddenInset TitleBarStyle = "hiddenInset" )
Title bar styles.
type TitleEvent ¶
type TitleEvent struct {
Preventable
Title string
}
TitleEvent is passed to Page.OnPageTitleUpdated listeners. Preventing it keeps the native window title unchanged.
type Tray ¶
type Tray struct {
// contains filtered or unexported fields
}
Tray is an icon in the menu bar (macOS) or notification area.
func NewTray ¶
func NewTray(opts TrayOptions) (*Tray, error)
NewTray adds an icon to the menu bar or notification area. It must be called after the application is ready.
func (*Tray) OnClick ¶
func (t *Tray) OnClick(fn func()) (off func())
OnClick is called when the icon is clicked and it has no menu.
func (*Tray) OnRightClick ¶
func (t *Tray) OnRightClick(fn func()) (off func())
OnRightClick is called when the icon is right-clicked.
func (*Tray) SetMenu ¶
SetMenu sets the menu shown when the icon is clicked; nil removes it so clicks reach OnClick.
type TrayOptions ¶
type TrayOptions struct {
// Icon is a PNG image, ideally 16x16 points (32x32 pixels for Retina).
Icon []byte
// IconIsTemplate lets macOS tint a black-and-transparent icon to match
// the menu bar.
IconIsTemplate bool
// Title is shown next to the icon (macOS).
Title string
ToolTip string
// Menu is shown when the icon is clicked.
Menu *Menu
}
TrayOptions configures NewTray.
type Update ¶
type Update struct {
// Version of the update, and its release notes in Markdown.
Version string
Notes string
// Date is when the update was built.
Date time.Time
// contains filtered or unexported fields
}
Update is a newer version of the app, found by Updater.Check.
func (*Update) Install ¶
Install downloads the update, checks that it is signed with the app's key and replaces the app with it; progress, when not nil, is called with the bytes downloaded so far. When the update has a delta for the running version, only the delta is downloaded, unless it fails to make the new version: the whole update is downloaded then, and the progress starts over. The running app is not affected: the new version runs after App.Relaunch, or at the next launch.
The app must be able to write where it is installed: a bundle in /Applications of an administrator, or an app directory the user owns on Linux and Windows. Apps installed by a package manager are updated by it.
type UpdaterModule ¶
type UpdaterModule struct{}
UpdaterModule installs new versions of the app, which `mygo build` publishes when mygo.config.ts configures updates: signed archives and a manifest per platform. Use the Updater singleton:
update, err := mygo.Updater.Check(ctx)
if err == nil && update != nil {
if err := update.Install(ctx, nil); err == nil {
mygo.App.Relaunch()
}
}
func (*UpdaterModule) Check ¶
func (u *UpdaterModule) Check(ctx context.Context) (*Update, error)
Check asks the update feed for a version newer than the running one and returns it, or nil when the app is up to date.
func (*UpdaterModule) Enabled ¶
func (u *UpdaterModule) Enabled() bool
Enabled reports whether the app can update itself: it was built with updates and can write where it is installed. Apps installed by a package manager, such as a .deb in /opt, are updated by it instead.
type Vibrancy ¶
type Vibrancy string
Vibrancy is a translucent material that blurs what is behind a window, shown behind a transparent page (see WindowOptions.Vibrancy).
macOS has all of them (NSVisualEffectView materials). Windows 11 has the Mica, Acrylic and Tabbed system backdrops; the other materials use the closest one: Acrylic for transient UI (menus, popovers, HUDs, sheets, tooltips, selection, full-screen UI), Mica otherwise. On macOS, Mica and Tabbed use the under-window material and Acrylic the HUD one. Linux has none.
const ( VibrancyNone Vibrancy = "" VibrancyWindow Vibrancy = "window" VibrancyContent Vibrancy = "content" VibrancySidebar Vibrancy = "sidebar" VibrancyHeader Vibrancy = "header" VibrancyTitlebar Vibrancy = "titlebar" VibrancyUnderWindow Vibrancy = "under-window" VibrancyUnderPage Vibrancy = "under-page" )
Materials for window areas.
const ( VibrancyMenu Vibrancy = "menu" VibrancyPopover Vibrancy = "popover" VibrancyHUD Vibrancy = "hud" VibrancySheet Vibrancy = "sheet" VibrancyTooltip Vibrancy = "tooltip" VibrancySelection Vibrancy = "selection" VibrancyFullScreenUI Vibrancy = "fullscreen-ui" )
Materials for transient UI.
const ( // VibrancyMica tints the window with the desktop wallpaper. VibrancyMica Vibrancy = "mica" // VibrancyAcrylic blurs what is behind the window. VibrancyAcrylic Vibrancy = "acrylic" // VibrancyTabbed is Mica for windows with tabs in the title bar. VibrancyTabbed Vibrancy = "tabbed" )
Windows 11 system backdrops.
type WebView ¶ added in v0.4.0
type WebView struct {
// contains filtered or unexported fields
}
WebView is a web page inside a window's native UI, which the window's view places with ui.WebView: a document the web engine renders beside native controls, a page per tab, a preview of HTML the app makes.
docs, err := win.NewWebView(mygo.WebViewOptions{URL: "/docs"})
// In the view:
ui.Row(c).Fill().Children(func() {
sidebar(c)
ui.WebView(c, docs).Grow(1)
})
Its page works as a window's does: it loads the app's frontend, calls bound Go methods (CallerPage tells which page called, CallerWindow the window it is in), hears events (Event.EmitPage, Broadcast) and evaluates scripts. The web view shows where the view places it, under what the view paints after it, as popovers and menus, while the view builds it; it keeps its page while it does not show, until Destroy or until its window closes. Its methods are safe from any goroutine.
func (*WebView) CapturePage ¶ added in v0.4.0
CapturePage returns a PNG screenshot of the web view's page.
func (*WebView) Destroy ¶ added in v0.4.0
func (v *WebView) Destroy()
Destroy closes the web view and its page. Its window no longer shows it where the view still places it.
func (*WebView) Focus ¶ added in v0.4.0
func (v *WebView) Focus()
Focus gives the web view the keyboard, once it shows.
func (*WebView) IsDestroyed ¶ added in v0.4.0
IsDestroyed reports whether the web view was destroyed, or its window closed.
func (*WebView) SetBackgroundColor ¶ added in v0.4.6
SetBackgroundColor sets the color filling the web view until its page paints, in the syntax of WebViewOptions.BackgroundColor, as when the app's own theme changes; one given with light-dark follows the appearance by itself.
func (*WebView) SurfaceWebView ¶ added in v0.4.0
SurfaceWebView returns the native web view for package ui to place, nil once destroyed or for the content of another window, which is logged once. Main thread only.
type WebViewOptions ¶ added in v0.4.0
type WebViewOptions struct {
// URL is loaded right away. "/" and other URLs without a scheme are
// pages of the app's frontend (see Page.LoadURL).
URL string
// Page configures the web view's page.
Page PageOptions
// BackgroundColor fills the web view until its page paints, as
// WindowOptions.BackgroundColor does; by default the page's, or white.
BackgroundColor string
// Transparent shows what the window's view paints under the web view
// through the transparent parts of its page.
Transparent bool
}
WebViewOptions configure Window.NewWebView.
type Window ¶
type Window struct {
// contains filtered or unexported fields
}
Window is a native window hosting a web page, or the Content of package ui. Create windows with NewWindow once the application is ready.
func CallerWindow ¶
CallerWindow returns the window whose page called a bound method, given the context.Context passed to that method: for the page of a web view (WebView), the window it is in. It returns nil for other contexts.
func FocusedWindow ¶
func FocusedWindow() *Window
FocusedWindow returns the focused window of this application, or nil.
func NewFlyout ¶ added in v0.4.1
func NewFlyout(opts FlyoutOptions) *Window
NewFlyout creates a flyout: a window without a frame, a background, a shadow or a taskbar button, owned by its parent and placed next to a rectangle of it, which may extend beyond the parent but stays in the work area of a display. Its page or native UI draws all of it: give the page a background, or the native UI's root one. Like NewWindow, it must be called after the application is ready.
func NewWindow ¶
func NewWindow(opts WindowOptions) *Window
NewWindow creates a window. It must be called after the application is ready (see Application.WhenReady); when called from another goroutine it waits for that.
func WindowByID ¶
WindowByID returns the window with the given id, or nil.
func (*Window) CancelDataDrag ¶ added in v0.2.17
func (w *Window) CancelDataDrag()
CancelDataDrag cancels a native data drag sourced by this window. It is safe from any goroutine and does nothing when the window has no drag.
func (*Window) CapturePage ¶
CapturePage returns a PNG screenshot of the visible page. For a window showing Content it renders the content as it is.
func (*Window) Center ¶
func (w *Window) Center()
Center moves the window to the center of its screen.
func (*Window) Close ¶
func (w *Window) Close()
Close closes the window as if the user clicked its close button, so OnClose listeners can cancel it.
func (*Window) ContentBounds ¶
ContentBounds returns the bounds of the page area.
func (*Window) ContentSize ¶
ContentSize returns the size of the page area.
func (*Window) Destroy ¶
func (w *Window) Destroy()
Destroy closes the window without emitting OnClose.
func (*Window) FlashFrame ¶
FlashFrame draws the user's attention to the window, or stops doing so: its taskbar button flashes until it is focused (Windows), it is marked urgent (Linux), or the Dock icon bounces (macOS, while the app is not active).
func (*Window) ID ¶
ID returns the unique id of the window. The page sees it as window.mygo.windowId.
func (*Window) Invalidate ¶ added in v0.2.0
func (w *Window) Invalidate()
Invalidate redraws the window's Content, as after a change of the state its user interface shows. It is safe from any goroutine; calls made before the next frame make one frame. It does nothing for a web page.
func (*Window) IsAlwaysOnTop ¶
IsAlwaysOnTop reports whether the window stays above other windows.
func (*Window) IsClosable ¶
IsClosable reports whether the user can close the window.
func (*Window) IsDestroyed ¶
IsDestroyed reports whether the window has been closed.
func (*Window) IsDocumentEdited ¶ added in v0.5.0
IsDocumentEdited reports what SetDocumentEdited set.
func (*Window) IsFullScreen ¶
IsFullScreen reports whether the window is in full screen.
func (*Window) IsMaximizable ¶
IsMaximizable reports whether the window can be maximized.
func (*Window) IsMaximized ¶
IsMaximized reports whether the window is maximized.
func (*Window) IsMinimizable ¶
IsMinimizable reports whether the window can be minimized.
func (*Window) IsMinimized ¶
IsMinimized reports whether the window is minimized.
func (*Window) IsPanel ¶ added in v0.5.0
IsPanel reports whether the window was created with WindowOptions.Panel.
func (*Window) IsResizable ¶
IsResizable reports whether the user can resize the window.
func (*Window) NativeHandle ¶
NativeHandle returns the native window: NSWindow* on macOS, GtkWindow* on Linux and HWND on Windows.
func (*Window) NewWebView ¶ added in v0.4.0
func (w *Window) NewWebView(opts WebViewOptions) (*WebView, error)
NewWebView creates a web view for the window's native UI, which shows it where its view places it with ui.WebView. The window must show Content; the web view closes with it.
func (*Window) OnBlur ¶
func (w *Window) OnBlur(fn func()) (off func())
OnBlur is called when the window loses focus.
func (*Window) OnClose ¶
func (w *Window) OnClose(fn func(e *CloseEvent)) (off func())
OnClose is called when the window is about to close. Call e.PreventDefault to keep it open.
func (*Window) OnClosed ¶
func (w *Window) OnClosed(fn func()) (off func())
OnClosed is called after the window has been closed.
func (*Window) OnEnterFullScreen ¶
func (w *Window) OnEnterFullScreen(fn func()) (off func())
OnEnterFullScreen is called when the window entered full screen.
func (*Window) OnFileDrop ¶
func (w *Window) OnFileDrop(fn func(e *FileDropEvent)) (off func())
OnFileDrop is called when files, for example from Finder or Explorer, are dropped on the page, with their paths. The app's own pages also get them, through onFileDrop of mygo-runtime. In a window showing native UI, it gets the files no element takes (ui.Element.DroppedFiles), with X and Y in DIPs.
The page's own drag and drop keeps working: drop events still reach it with the File objects, and drags that start in the page are left alone. Only where the page does not handle dragged files are they accepted, so that dropping them there reaches OnFileDrop instead of replacing the page with the file.
func (*Window) OnFocus ¶
func (w *Window) OnFocus(fn func()) (off func())
OnFocus is called when the window gains focus.
func (*Window) OnHide ¶
func (w *Window) OnHide(fn func()) (off func())
OnHide is called when the window is hidden.
func (*Window) OnLeaveFullScreen ¶
func (w *Window) OnLeaveFullScreen(fn func()) (off func())
OnLeaveFullScreen is called when the window left full screen.
func (*Window) OnMaximize ¶
func (w *Window) OnMaximize(fn func()) (off func())
OnMaximize is called when the window is maximized.
func (*Window) OnMinimize ¶
func (w *Window) OnMinimize(fn func()) (off func())
OnMinimize is called when the window is minimized.
func (*Window) OnMove ¶
func (w *Window) OnMove(fn func()) (off func())
OnMove is called after the window was moved.
func (*Window) OnReadyToShow ¶
func (w *Window) OnReadyToShow(fn func()) (off func())
OnReadyToShow is called once, when the first page is ready to be displayed. Create the window with Hidden and call Show here to avoid a visual flash. A window showing Content is ready once it drew its first frame, which a hidden window may not draw until shown.
func (*Window) OnResize ¶
func (w *Window) OnResize(fn func()) (off func())
OnResize is called after the window was resized.
func (*Window) OnRestore ¶
func (w *Window) OnRestore(fn func()) (off func())
OnRestore is called when the window is restored from minimized.
func (*Window) OnShow ¶
func (w *Window) OnShow(fn func()) (off func())
OnShow is called when the window is shown.
func (*Window) OnUnmaximize ¶
func (w *Window) OnUnmaximize(fn func()) (off func())
OnUnmaximize is called when the window leaves the maximized state.
func (*Window) Page ¶ added in v0.2.0
Page returns the web page the window shows, or nil for a window that shows native UI.
func (*Window) RepresentedFile ¶ added in v0.5.0
RepresentedFile returns the path SetRepresentedFile set.
func (*Window) SetAlwaysOnTop ¶
SetAlwaysOnTop keeps the window above other windows.
func (*Window) SetAnchor ¶ added in v0.4.1
SetAnchor places a flyout against another rectangle of its parent, in DIPs relative to the parent's content area, as FlyoutOptions.Anchor. It does nothing for other windows.
func (*Window) SetAutoHideMenuBar ¶ added in v0.1.10
SetAutoHideMenuBar keeps the menu bar of this window out of sight until the user presses Alt or F10, or shows it for good again (Linux, Windows). See WindowOptions.AutoHideMenuBar.
func (*Window) SetBackgroundColor ¶
SetBackgroundColor sets the color shown behind the page, in the syntax of WindowOptions.BackgroundColor.
func (*Window) SetClosable ¶
SetClosable sets whether the user can close the window.
func (*Window) SetContentBounds ¶
SetContentBounds moves and resizes the window so the page area has the given bounds.
func (*Window) SetContentProtection ¶
SetContentProtection keeps the window content out of screenshots and screen recordings.
func (*Window) SetContentSize ¶
SetContentSize resizes the window so the page area has the given size.
func (*Window) SetDocumentEdited ¶ added in v0.5.0
SetDocumentEdited tells whether the window's document has unsaved changes: a dot in the close button on macOS, and a "*" before the title on Linux and Windows, as Notepad and gedit show it. Documents (NewDocuments) set it for their windows.
func (*Window) SetFullScreen ¶
SetFullScreen enters or leaves full screen.
func (*Window) SetHasShadow ¶
SetHasShadow sets whether the window has a shadow.
func (*Window) SetIcon ¶
SetIcon sets the icon of the window, shown in its title bar and taskbar button (Linux, Windows), from a PNG image; nil restores the application icon. macOS windows show no icon of their own.
func (*Window) SetIgnoreMouseEvents ¶
SetIgnoreMouseEvents makes the window transparent to mouse events.
func (*Window) SetMaximizable ¶
SetMaximizable sets whether the window can be maximized.
func (*Window) SetMaximumSize ¶
SetMaximumSize limits how large the window can be resized; 0 means no limit.
func (*Window) SetMenu ¶
SetMenu sets the menu bar of this window (Linux, Windows). On macOS the menu bar belongs to the application; see Application.SetMenu.
func (*Window) SetMinimizable ¶
SetMinimizable sets whether the window can be minimized.
func (*Window) SetMinimumSize ¶
SetMinimumSize limits how small the window can be resized; 0 means no limit.
func (*Window) SetMovable ¶
SetMovable sets whether the user can move the window.
func (*Window) SetOpacity ¶
SetOpacity sets the window opacity between 0 and 1.
func (*Window) SetPosition ¶
SetPosition moves the window's top-left corner.
func (*Window) SetProgressBar ¶
func (w *Window) SetProgressBar(p ProgressBar)
SetProgressBar shows the progress of a task:
win.SetProgressBar(mygo.ProgressBar{Value: done / total})
win.SetProgressBar(mygo.ProgressBar{}) // done: remove it
On macOS and Linux the progress belongs to the application: the window that set it last wins.
func (*Window) SetRepresentedFile ¶ added in v0.5.0
SetRepresentedFile tells which file the window shows, "" for none. On macOS the title bar shows its icon, which the user can drag, and Command-clicking the title lists the folders it is in. Other platforms show nothing. Documents (NewDocuments) set it for their windows.
func (*Window) SetResizable ¶
SetResizable sets whether the user can resize the window.
func (*Window) SetSkipTaskbar ¶
SetSkipTaskbar hides the window from the taskbar, or shows it there again (Linux, Windows). See WindowOptions.SkipTaskbar.
func (*Window) SetVibrancy ¶
SetVibrancy sets the material behind the page; VibrancyNone removes it. On Windows, it changes the material of a window created with one, and shows none in other windows. See WindowOptions.Vibrancy.
func (*Window) SetVisibleOnAllWorkspaces ¶
SetVisibleOnAllWorkspaces shows the window on every workspace (macOS Spaces, Linux virtual desktops), or on the current one only. On macOS it also shows over other apps in full screen, even with DisableFullScreen, if the app is an accessory (ActivationPolicyAccessory, Dock.Hide): macOS shows no windows of regular apps there.
func (*Window) ShowInactive ¶
func (w *Window) ShowInactive()
ShowInactive shows the window without focusing it.
func (*Window) StartDataDrag ¶ added in v0.2.17
func (w *Window) StartDataDrag(data transfer.Data, options DragOptions) error
StartDataDrag starts a native drag from this window's current pointer gesture. The window must show native UI. It returns after scheduling the drag; options.Done receives completion on the main thread. Use an element's DragData in package ui to start after the movement threshold. It is safe from any goroutine. An immediate validation error starts no session and does not call Done.
func (*Window) Title ¶
Title returns the window title, without the mark of an edited document (see SetDocumentEdited).
func (*Window) ToggleFullScreen ¶
func (w *Window) ToggleFullScreen()
ToggleFullScreen enters full screen or leaves it.
func (*Window) ToggleMaximize ¶
func (w *Window) ToggleMaximize()
ToggleMaximize maximizes the window or restores it if it is maximized.
func (*Window) Update ¶ added in v0.2.0
func (w *Window) Update(fn func())
Update runs fn on the main thread, where the window's Content builds its user interface, then redraws the Content. Goroutines change the state the interface shows through it:
go func() {
items := load()
win.Update(func() { app.items = items })
}()
It returns without waiting for fn.
type WindowOpenRequest ¶
type WindowOpenRequest struct {
URL string
FrameName string
// Width and Height requested through window.open() features; 0 when
// not specified.
Width, Height int
}
WindowOpenRequest describes a window.open() call or a click on a target="_blank" link.
type WindowOptions ¶
type WindowOptions struct {
// Title of the window. Defaults to the application name. The title
// follows the page's <title> unless an OnPageTitleUpdated listener
// prevents it.
Title string
// URL is loaded right after the window is created. "/" and other URLs
// without a scheme are pages of the app's frontend (see LoadURL).
URL string
// Width and Height of the window in DIPs (default 800x600).
Width, Height int
// UseContentSize makes Width and Height describe the page area instead
// of the whole window.
UseContentSize bool
// X and Y of the top-left corner. The window is centered when both are
// zero.
X, Y int
MinWidth, MinHeight int
MaxWidth, MaxHeight int
// Hidden creates the window without showing it. Call Show, typically
// from OnReadyToShow, to avoid a blank window while the page loads.
Hidden bool
// Frameless removes the title bar and window chrome. Mark draggable
// areas with the CSS `--app-region: drag`.
Frameless bool
// TitleBarStyle hides the title bar but keeps the window controls, so
// the page fills the window and draws its own title bar under them:
// the traffic lights on macOS, and minimize, maximize and close at the
// top corner on Linux and Windows. On Linux they are GTK's own title
// buttons, and the desktop's button layout decides which show and on
// which side, possibly none. Pages keep clear of them with the
// --mygo-titlebar-* CSS variables and drag the window by their title
// bar with --app-region: drag, as in a frameless window; native UI
// with ui.Context.TitleBar and ui.Element.DragWindow.
TitleBarStyle TitleBarStyle
// TrafficLightPosition moves the window controls of a window with a
// hidden title bar (macOS): the top-left corner of the close button
// goes this far from the top-left corner of the window.
TrafficLightPosition *Point
// TitleBarHeight is the height of the title bar that the page of a
// window with a hidden title bar draws (Linux, Windows): the window
// controls fill it on Windows and are centered in it on Linux. Zero is
// 32 on Windows, as Windows 11's own title bars, and the height of the
// desktop's header bars on Linux.
TitleBarHeight int
DisableResize bool
DisableMove bool
DisableMinimize bool
DisableMaximize bool
DisableClose bool
DisableFullScreen bool
DisableShadow bool
AlwaysOnTop bool
FullScreen bool
// Maximized creates the window maximized.
Maximized bool
// SkipTaskbar hides the window from the taskbar (Linux, Windows).
SkipTaskbar bool
// AutoHideMenuBar keeps the window's menu bar out of sight until the
// user presses Alt or F10, and hides it again once they leave it
// (Linux, Windows). Its keyboard shortcuts work all along.
AutoHideMenuBar bool
// Transparent makes the window background transparent, so a page with a
// transparent background shows the desktop through.
Transparent bool
// BackgroundColor fills the window until the page paints, which avoids
// a flash of another color while it loads. CSS syntax: "#1e1e1e",
// "#rgba", "rgb(30 30 30)", or "light-dark(#f5f5f7, #1e1e1e)" for a
// page that follows the light or dark appearance.
BackgroundColor string
// Vibrancy puts a translucent, blurred material behind a transparent
// page, or behind native UI where it draws no background (macOS and
// Windows 11 22H2), e.g. VibrancySidebar; ui.Context.Vibrancy tells
// native UI whether it shows. On Windows, only a window created with a
// material can show one, and it has no menu bar: Alt and F10 open its
// menus in a popup.
Vibrancy Vibrancy
// Opacity of the window between 0 and 1 (default 1).
Opacity float64
// Parent makes this window a child window that stays on top of it.
Parent *Window
// Modal makes a child window modal to its Parent.
Modal bool
// Panel makes the window a panel, as the windows of launchers and
// quick entry (Spotlight, Raycast) are: it floats above the windows of
// all apps, on whichever Space or virtual desktop the user is on, over
// full-screen apps too, and stays out of the taskbar, the Dock and the
// app switcher. It cannot be minimized, maximized or go full screen. On
// macOS, showing or focusing it gives it the keyboard without
// activating the app, so the app the user was in stays active and gets
// the keyboard back when the panel hides.
Panel bool
// Page configures the window's web page.
Page PageOptions
// StateKey remembers the window's position, size, and maximized and
// full screen state under this key, in window-state.json in
// PathUserData or the store of App.SetWindowStateStore, saved when
// the window closes and when the app quits. A window created with the
// same key, for example at the next launch, gets them back as long as
// it would show on a connected display: they override X, Y, Width,
// Height, UseContentSize, Maximized and FullScreen.
StateKey string
// Content makes the window show a user interface MyGo draws itself,
// on the GPU where it can, instead of a web page: create it with
// package ui. The window then has no page (Window.Page is nil): URL
// and Page are ignored.
Content Content
}
WindowOptions configures NewWindow. The zero value is a visible, resizable 800x600 window centered on screen.
type WindowState ¶ added in v0.4.6
type WindowState struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Maximized bool `json:"maximized,omitempty"`
FullScreen bool `json:"fullScreen,omitempty"`
}
WindowState is what WindowOptions.StateKey remembers of a window: its bounds in the normal state, which it gets back when it leaves the maximized or full screen state, and that state.
type WindowStateStore ¶ added in v0.4.6
type WindowStateStore interface {
// LoadWindowStates returns the saved states. It is called once, when
// the first window with a StateKey is created. Without states (nil, or
// an error) windows get their options.
LoadWindowStates() (map[string]WindowState, error)
// SaveWindowStates replaces the saved states with states, which the
// store may keep. It is called when a window with a StateKey closes
// and when the app quits, if a state changed. After an error the
// next call saves the states again.
SaveWindowStates(states map[string]WindowState) error
}
WindowStateStore keeps the states of the windows with a WindowOptions.StateKey, by key, for App.SetWindowStateStore. MyGo calls it on the main thread, so it should return quickly.
Source Files
¶
- app.go
- appfile.go
- backend_linux.go
- bridge.go
- channel.go
- clipboard.go
- color.go
- content.go
- cookies.go
- deeplink.go
- dev.go
- dialog.go
- document.go
- document_file.go
- document_flow.go
- document_menu.go
- document_recovery.go
- document_service.go
- document_unix.go
- document_watch.go
- downloads.go
- drag.go
- events.go
- find.go
- flyout.go
- frontend.go
- ipc.go
- jumplist.go
- locale.go
- locale_file.go
- login.go
- loop.go
- menu.go
- menu_text.go
- modules.go
- mygo.go
- network.go
- page.go
- paths.go
- pdf.go
- permissions.go
- plugin.go
- power.go
- protocol.go
- random.go
- recent_docs.go
- secrets.go
- signal_unix.go
- single_instance.go
- stat_identity.go
- stat_identity_other.go
- typescript.go
- updater.go
- vibrancy.go
- watch.go
- watch_entries_other.go
- watch_hints.go
- watch_hints_linux.go
- watch_identity_unix.go
- watch_path_unix.go
- watch_scan.go
- webview.go
- window.go
- window_state.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audio plays sound: effects decoded into memory, music streamed as it plays, and sound an app makes itself, mixed in Go and sent to the system's audio output:
|
Package audio plays sound: effects decoded into memory, music streamed as it plays, and sound an app makes itself, mixed in Go and sent to the system's audio output: |
|
mp3
Package mp3 decodes MP3 files for package audio, with github.com/hajimehoshi/go-mp3.
|
Package mp3 decodes MP3 files for package audio, with github.com/hajimehoshi/go-mp3. |
|
vorbis
Package vorbis decodes Ogg Vorbis files for package audio, with github.com/jfreymuth/oggvorbis.
|
Package vorbis decodes Ogg Vorbis files for package audio, with github.com/jfreymuth/oggvorbis. |
|
cmd
|
|
|
mygo
command
Command mygo is the MyGo development tool: it scaffolds projects, generates the typed TypeScript client for bound Go services, runs apps in development and builds packaged production apps.
|
Command mygo is the MyGo development tool: it scaffolds projects, generates the typed TypeScript client for bound Go services, runs apps in development and builds packaged production apps. |
|
examples
|
|
|
blackhole
command
Black hole is a black hole and its accretion disk, drawn by shaders written in Go (package ui/shader) on the GPU: every pixel's ray of light is traced back through the hole's gravity, so the disk's far side shows above and below the shadow, the side turning toward the camera blazes brighter and bluer, and the stars behind smear into arcs around an Einstein ring.
|
Black hole is a black hole and its accretion disk, drawn by shaders written in Go (package ui/shader) on the GPU: every pixel's ray of light is traced back through the hole's gravity, so the disk's far side shows above and below the shadow, the side turning toward the camera blazes brighter and bluer, and the stars behind smear into arcs around an Einstein ring. |
|
chart-streaming
command
Chart-streaming draws three rolling waveforms of 15,000 samples each, 1,000 new samples a second, reduced to a few points per pixel column.
|
Chart-streaming draws three rolling waveforms of 15,000 samples each, 1,000 new samples a second, reduced to a few points per pixel column. |
|
chat-glow
command
Chat-glow is an assistant's window, lit as Apple Intelligence lights its own: while the assistant works, the window's edges glow in flowing colors, the field to write in glows in its ring, and "Thinking…" shimmers; the assistant's orb, a glass sphere of drifting light, quickens as it thinks.
|
Chat-glow is an assistant's window, lit as Apple Intelligence lights its own: while the assistant works, the window's edges glow in flowing colors, the field to write in glows in its ring, and "Thinking…" shimmers; the assistant's orb, a glass sphere of drifting light, quickens as it thinks. |
|
clipboard
command
Clipboard demonstrates one data model for copying and dragging a note.
|
Clipboard demonstrates one data model for copying and dragging a note. |
|
code-editor
command
Code editor shows MyGo's code editor and diff viewer: files of several languages to edit, with completions of the words of the file, hovers, diagnostics of TODO comments and the changes against the file as it was in the gutter; and the diff of those changes, side by side or unified, which edits the same buffer.
|
Code editor shows MyGo's code editor and diff viewer: files of several languages to edit, with completions of the words of the file, hovers, diagnostics of TODO comments and the changes against the file as it was in the gutter; and the diff of those changes, side by side or unified, which edits the same buffer. |
|
confetti
command
Confetti throws confetti in native UI, as canvas-confetti does on a web page: bursts of squares, circles, stars, hearts and emoji that fly out, slow down, fall, tumble and fade.
|
Confetti throws confetti in native UI, as canvas-confetti does on a web page: bursts of squares, circles, stars, hearts and emoji that fly out, slow down, fall, tumble and fade. |
|
counter-native
command
Counter-native is a counter in native UI: a window MyGo draws itself from Go, with no web page.
|
Counter-native is a counter in native UI: a window MyGo draws itself from Go, with no web page. |
|
documents
command
Documents is a notes editor of Markdown and text files in native UI, built on mygo.NewDocuments: the File menu, a window per note, autosave, recovery after a crash, the proxy icon and the edited dot on macOS, and notes changed by other apps.
|
Documents is a notes editor of Markdown and text files in native UI, built on mygo.NewDocuments: the File menu, a window per note, autosave, recovery after a crash, the proxy icon and the edited dot on macOS, and notes changed by other apps. |
|
drag-drop
command
Drag-drop exchanges notes, text, URLs and files between two native UI windows and other applications.
|
Drag-drop exchanges notes, text, URLs and files between two native UI windows and other applications. |
|
effort-slider
command
Effort-slider redraws ozzy's "galaxy brain effort slider" demo (https://x.com/ozzyxs1a/status/2107523169649389677) in native UI: a card whose slider steps from Low to Max with a brain for a thumb, and past Max into Galaxy, where the brain bursts, the card shakes, the track fills with twinkling pixels and dotted rays stream out of the brain.
|
Effort-slider redraws ozzy's "galaxy brain effort slider" demo (https://x.com/ozzyxs1a/status/2107523169649389677) in native UI: a card whose slider steps from Low to Max with a brain for a thumb, and past Max into Galaxy, where the brain bursts, the card shakes, the track fills with twinkling pixels and dotted rays stream out of the brain. |
|
embed-webview
command
Embed-webview shows web pages in a window of native UI: a sidebar of tabs, each a web view, under a toolbar whose menu, select, tooltip and dialog show over the page, as the badge over its corner does.
|
Embed-webview shows web pages in a window of native UI: a sidebar of tabs, each a web view, under a toolbar whose menu, select, tooltip and dialog show over the page, as the badge over its corner does. |
|
farm
command
Farm is a little farming game in native UI: walk a farm with the keyboard, till the grass, plant seeds, water them and harvest what grows, through a camera that follows you, as days turn to night, with sound and music.
|
Farm is a little farming game in native UI: walk a farm with the keyboard, till the grass, plant seeds, water them and harvest what grows, through a camera that follows you, as days turn to night, with sound and music. |
|
flyout
command
Flyout opens flyouts from a small window of native UI: a list of colors, a note to edit and an About box with the look of the system's popovers on macOS.
|
Flyout opens flyouts from a small window of native UI: a list of colors, a note to edit and an About box with the look of the system's popovers on macOS. |
|
frameless
command
Frameless shows a window without native chrome: the page draws its own title bar, marks it draggable with `--app-region: drag` and drives the window through the built-in window.mygo.window controls.
|
Frameless shows a window without native chrome: the page draws its own title bar, marks it draggable with `--app-region: drag` and drives the window through the built-in window.mygo.window controls. |
|
gallery
command
Gallery tours MyGo's own user interface toolkit: a window drawn on the GPU from Go, without a web page.
|
Gallery tours MyGo's own user interface toolkit: a window drawn on the GPU from Go, without a web page. |
|
hello
command
Hello is the smallest MyGo app: one window and one Go method called from the page.
|
Hello is the smallest MyGo app: one window and one Go method called from the page. |
|
launcher
command
Launcher is an app launcher in the manner of Spotlight and Raycast, in native UI: Alt+Shift+Space shows a panel over every app, full-screen ones included, without taking the active app away; type to find an installed app, Up and Down to choose, Enter to open it, Escape to clear or close.
|
Launcher is an app launcher in the manner of Spotlight and Raycast, in native UI: Alt+Shift+Space shows a panel over every app, full-screen ones included, without taking the active app away; type to find an installed app, Up and Down to choose, Enter to open it, Escape to clear or close. |
|
markdown-chat
command
Markdown-chat is a chat with a pretend language model whose replies stream in token by token as Markdown: markdown.Stream shows a reply while it comes, markdown.View once it is done, and the list follows the end until the user scrolls up.
|
Markdown-chat is a chat with a pretend language model whose replies stream in token by token as Markdown: markdown.Stream shows a reply while it comes, markdown.View once it is done, and the list follows the end until the user scrolls up. |
|
mayoi
command
Mayoi is a little survivor game in native UI, a fan game after the anime BanG Dream! It's MyGO!!!!!, whose band MyGo is named after.
|
Mayoi is a little survivor game in native UI, a fan game after the anime BanG Dream! It's MyGO!!!!!, whose band MyGo is named after. |
|
menubar-flyout
command
Menubar-flyout is a menu bar app whose icon opens a flyout, the panel of the app: below the icon of the macOS menu bar, in a popover of the system's, and above an icon of the Windows taskbar.
|
Menubar-flyout is a menu bar app whose icon opens a flyout, the panel of the app: below the icon of the macOS menu bar, in a popover of the system's, and above an icon of the Windows taskbar. |
|
menubar-native
command
Menubar-native is a menu bar app whose icon opens a window of native UI.
|
Menubar-native is a menu bar app whose icon opens a window of native UI. |
|
native
command
Native tours the desktop integration: application and context menus, a tray icon, dialogs, notifications, a global shortcut, the clipboard and dark mode.
|
Native tours the desktop integration: application and context menus, a tray icon, dialogs, notifications, a global shortcut, the clipboard and dark mode. |
|
notes
command
Notes is a notes app in native UI: notes in a sidebar, each edited as rich text (package ui/richtext), with a toolbar of its formats, the Format menu, links, Markdown shortcuts and export, and the notes saved as JSON in the user's configuration directory.
|
Notes is a notes app in native UI: notes in a sidebar, each edited as rich text (package ui/richtext), with a toolbar of its formats, the Format menu, links, Markdown shortcuts and export, and the notes saved as JSON in the user's configuration directory. |
|
piano
command
Piano is a piano in native UI that plays with package audio: click or drag across its keys, play it from the keyboard, or have it play a tune.
|
Piano is a piano in native UI that plays with package audio: click or drag across its keys, play it from the keyboard, or have it play a tune. |
|
terminal
command
Terminal is a terminal app in native UI: the user's shell in a window, with the terminal plugin, which emulates it with Ghostty's libghostty-vt.
|
Terminal is a terminal app in native UI: the user's shell in a window, with the terminal plugin, which emulates it with Ghostty's libghostty-vt. |
|
text-buffer
command
A large editable document backed by indexed text chunks.
|
A large editable document backed by indexed text chunks. |
|
text-input
command
A custom text field built from MyGo's text-input and layout primitives.
|
A custom text field built from MyGo's text-input and layout primitives. |
|
timeline
command
Timeline shows what a ui.Timeline is for: several tweens on one playhead, arranged and controlled together.
|
Timeline shows what a ui.Timeline is for: several tweens on one playhead, arranged and controlled together. |
|
todo
command
Todo is a small but complete MyGo app: typed services and events shared with a TypeScript frontend, persistence, dialogs, menus and multiple windows kept in sync.
|
Todo is a small but complete MyGo app: typed services and events shared with a TypeScript frontend, persistence, dialogs, menus and multiple windows kept in sync. |
|
vibrancy
command
Vibrancy shows a window in the style of a native macOS app, in native UI: a sidebar over a translucent material, under a hidden title bar whose window controls sit over the view, the traffic lights inset over the sidebar on macOS.
|
Vibrancy shows a window in the style of a native macOS app, in native UI: a sidebar over a translucent material, under a hidden title bar whose window controls sit over the view, the traffic lights inset over the sidebar on macOS. |
|
wind
command
Wind is the texture behind the composer of the Claude desktop app's Code tab, redrawn in native UI: a field of monospaced characters that a wind lights in passing gusts, curling, streaked and thinning around the content, while each character steps through a set of its own.
|
Wind is the texture behind the composer of the Claude desktop app's Code tab, redrawn in native UI: a field of monospaced characters that a wind lights in passing gusts, curling, streaked and thinning around the content, while each character steps through a set of its own. |
|
Package i18n reads the languages people read and picks, of those an app is written in, the one that suits them best, and says an app's messages in it.
|
Package i18n reads the languages people read and picks, of those an app is written in, the one that suits them best, and says an app's messages in it. |
|
internal/gen
command
Command gen writes the data of the Unicode CLDR that package i18n uses, from a pinned release of cldr-json, as Go source: `go generate ./i18n` runs it.
|
Command gen writes the data of the Unicode CLDR that package i18n uses, from a pinned release of cldr-json, as Go source: `go generate ./i18n` runs it. |
|
internal
|
|
|
accelerator
Package accelerator parses Electron style keyboard accelerators such as "CmdOrCtrl+Shift+Z" into a platform neutral representation.
|
Package accelerator parses Electron style keyboard accelerators such as "CmdOrCtrl+Shift+Z" into a platform neutral representation. |
|
bridge
Package bridge embeds the renderer runtime that MyGo injects into pages.
|
Package bridge embeds the renderer runtime that MyGo injects into pages. |
|
darwin
Package darwin implements the macOS backend (AppKit + WKWebView) in pure Go: Objective-C is driven through the runtime with purego, no cgo.
|
Package darwin implements the macOS backend (AppKit + WKWebView) in pure Go: Objective-C is driven through the runtime with purego, no cgo. |
|
diff
Package diff compares sequences: the lines of two texts, or the words of two lines.
|
Package diff compares sequences: the lines of two texts, or the words of two lines. |
|
download
Package download fetches the files that MyGo keeps in the user's cache: the native libraries plugins name in their mygo-plugin.json, which the CLI and unpackaged programs download into <cache>/mygo/natives/<sha256>/, and the tools the CLI runs, as NSIS.
|
Package download fetches the files that MyGo keeps in the user's cache: the native libraries plugins name in their mygo-plugin.json, which the CLI and unpackaged programs download into <cache>/mygo/natives/<sha256>/, and the tools the CLI runs, as NSIS. |
|
fake
Package fake is an in-memory platform.Backend for testing the public API without a GUI.
|
Package fake is an in-memory platform.Backend for testing the public API without a GUI. |
|
gamut
Package gamut converts between sRGB, Display P3, Oklab and Oklch, and maps colors into a display's gamut as CSS Color 4 does.
|
Package gamut converts between sRGB, Display P3, Oklab and Oklch, and maps colors into a display's gamut as CSS Color 4 does. |
|
gpu
Package gpu turns scenes into what the GPU renderers draw: one instanced quad per operation, for a shader that computes rounded rectangles, borders, gradients, stripes, shadows and atlas coverage itself, in batches that share a scissor rectangle and an image.
|
Package gpu turns scenes into what the GPU renderers draw: one instanced quad per operation, for a shader that computes rounded rectangles, borders, gradients, stripes, shadows and atlas coverage itself, in batches that share a scissor rectangle and an image. |
|
gpu/d3d11
Package d3d11 draws scenes with Direct3D 11 into a window through a DXGI flip model swap chain, called through syscall like the rest of the Windows backend (no cgo).
|
Package d3d11 draws scenes with Direct3D 11 into a window through a DXGI flip model swap chain, called through syscall like the rest of the Windows backend (no cgo). |
|
gpu/d3d11/device
Package device creates Direct3D 11 devices: the device of package d3d11's renderer, and that of the Windows backend, which shows the controls of windows with a material through DirectComposition without the renderer.
|
Package device creates Direct3D 11 devices: the device of package d3d11's renderer, and that of the Windows backend, which shows the controls of windows with a material through DirectComposition without the renderer. |
|
gpu/gl
Package gl draws scenes with OpenGL 3.3, OpenGL ES 3.0 or WebGL 2 into the framebuffer bound when Render is called: the one GTK's GtkGLArea binds while it emits its render signal, or a canvas's (package web).
|
Package gl draws scenes with OpenGL 3.3, OpenGL ES 3.0 or WebGL 2 into the framebuffer bound when Render is called: the one GTK's GtkGLArea binds while it emits its render signal, or a canvas's (package web). |
|
gpu/gputest
Package gputest has what the tests of the GPU renderers share: a scene that draws every kind of operation, and a comparison of what a renderer drew with what the CPU renderer draws, which the renderers must match.
|
Package gputest has what the tests of the GPU renderers share: a scene that draws every kind of operation, and a comparison of what a renderer drew with what the CPU renderer draws, which the renderers must match. |
|
gpu/metal
Package metal draws scenes with Metal into a CAMetalLayer, called through the Objective-C runtime with purego like the rest of the macOS backend (no cgo).
|
Package metal draws scenes with Metal into a CAMetalLayer, called through the Objective-C runtime with purego like the rest of the macOS backend (no cgo). |
|
i18ngen
Package i18ngen reads the catalogs of an app's messages, checks them, and writes their typed accessors: Go functions in the catalogs' directory, which embed and register them, and a TypeScript module that formats the same messages in pages with mygo-runtime.
|
Package i18ngen reads the catalogs of an app's messages, checks them, and writes their typed accessors: Go functions in the catalogs' directory, which embed and register them, and a TypeScript module that formats the same messages in pages with mygo-runtime. |
|
i18nlink
Package i18nlink hands MyGo's own strings (internal/l10n) what package i18n does not export: a library's catalog that does not link the formatting of the dates of messages, which i18n.NewLibraryCatalog does for the catalogs of libraries and apps.
|
Package i18nlink hands MyGo's own strings (internal/l10n) what package i18n does not export: a library's catalog that does not link the formatting of the dates of messages, which i18n.NewLibraryCatalog does for the catalogs of libraries and apps. |
|
idlemem
command
Command idlemem launches apps and reports how much memory each takes once idle, alone and with the processes it runs, its webview's: scripts/bench.ts measures release builds of examples/hello and examples/counter-native with it on every push to main.
|
Command idlemem launches apps and reports how much memory each takes once idle, alone and with the processes it runs, its webview's: scripts/bench.ts measures release builds of examples/hello and examples/counter-native with it on every push to main. |
|
l10n
Package l10n holds MyGo's own strings, those of the controls of package ui, of the code editor and the diff viewer, and of the roles of menus, in the languages MyGo is translated to: a library's catalog (see i18n.NewLibraryCatalog) of the namespace mygo, whose functions say them in the language the app shows.
|
Package l10n holds MyGo's own strings, those of the controls of package ui, of the code editor and the diff viewer, and of the roles of menus, in the languages MyGo is translated to: a library's catalog (see i18n.NewLibraryCatalog) of the namespace mygo, whose functions say them in the language the app shows. |
|
linux
Package linux implements the Linux backend (GTK 3 + WebKitGTK) in pure Go: the libraries are loaded at run time with purego, no cgo.
|
Package linux implements the Linux backend (GTK 3 + WebKitGTK) in pure Go: the libraries are loaded at run time with purego, no cgo. |
|
nsis
Package nsis pins the NSIS that mygo build downloads on Windows to make the installer, and installs it into the user's cache directory, where makensis runs as it does from an installation.
|
Package nsis pins the NSIS that mygo build downloads on Windows to make the installer, and installs it into the user's cache directory, where makensis runs as it does from an installation. |
|
platform
Package platform defines the contract between the public mygo API and the native backends (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows).
|
Package platform defines the contract between the public mygo API and the native backends (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows). |
|
prefetch
command
Command prefetch downloads into the user's cache what this repository's tests otherwise download there while they run: the native libraries that the plugins name in their mygo-plugin.json, for this platform, and on Windows the NSIS that mygo build uses.
|
Command prefetch downloads into the user's cache what this repository's tests otherwise download there while they run: the native libraries that the plugins name in their mygo-plugin.json, for this platform, and on Windows the NSIS that mygo build uses. |
|
raster
Package raster draws scenes in memory: the software renderer behind headless rendering, window captures and windows without a GPU renderer.
|
Package raster draws scenes in memory: the software renderer behind headless rendering, window captures and windows without a GPU renderer. |
|
rope
Package rope stores text as a persistent tree of chunks of UTF-8: an AVL tree whose leaves own up to 4 KB of the text each, and whose nodes sum the bytes, runes, UTF-16 units and newlines below them, as Zed's rope sums its chunks.
|
Package rope stores text as a persistent tree of chunks of UTF-8: an AVL tree whose leaves own up to 4 KB of the text each, and whose nodes sum the bytes, runes, UTF-16 units and newlines below them, as Zed's rope sums its chunks. |
|
scene
Package scene is the display list the ui package paints a frame into and the renderers draw: rounded rectangles with borders and gradients, box shadows, glyphs from a shared atlas, images, effects and clips, in paint order.
|
Package scene is the display list the ui package paints a frame into and the renderers draw: rounded rectangles with borders and gradients, box shadows, glyphs from a shared atlas, images, effects and clips, in paint order. |
|
shader
Package shader compiles shaders written in Go's syntax into the intermediate representation of package shaderir, which its backends translate for each GPU renderer.
|
Package shader compiles shaders written in Go's syntax into the intermediate representation of package shaderir, which its backends translate for each GPU renderer. |
|
shaderir
Package shaderir offers intermediate representation for shader programs, forked from Ebitengine with package shader (see its documentation).
|
Package shaderir offers intermediate representation for shader programs, forked from Ebitengine with package shader (see its documentation). |
|
shaderir/interp
Package interp runs shaders on the CPU, for MyGo's CPU renderer: it compiles a program of package shaderir into Go closures, which compute what the GPU renderers' code computes, within the rounding of their floats.
|
Package interp runs shaders on the CPU, for MyGo's CPU renderer: it compiles a program of package shaderir into Go closures, which compute what the GPU renderers' code computes, within the rounding of their floats. |
|
surface
Package surface connects the content of a window that MyGo draws itself (package ui) to the window (package mygo), without either importing the other's internals.
|
Package surface connects the content of a window that MyGo draws itself (package ui) to the window (package mygo), without either importing the other's internals. |
|
svg
Package svg parses SVG documents and draws them into pixels, for the icons and pictures of package ui, in Go alone.
|
Package svg parses SVG documents and draws them into pixels, for the icons and pictures of package ui, in Go alone. |
|
text
Package text lays out text and rasterizes glyphs with the system's own text stack: DirectWrite on Windows, Core Text on macOS and Pango with cairo on Linux.
|
Package text lays out text and rasterizes glyphs with the system's own text stack: DirectWrite on Windows, Core Text on macOS and Pango with cairo on Linux. |
|
tsgen
Package tsgen generates a typed TypeScript client for Go services bound with mygo.Bind and events declared with mygo.NewEvent.
|
Package tsgen generates a typed TypeScript client for Go services bound with mygo.Bind and events declared with mygo.NewEvent. |
|
tsgen/internal/fixture
Package fixture declares types used to test the TypeScript generator.
|
Package fixture declares types used to test the TypeScript generator. |
|
uigen
command
Command uigen generates the checked public UI facade from the private renderer API.
|
Command uigen generates the checked public UI facade from the private renderer API. |
|
uimigrate
Package uimigrate migrates source syntax to the UI's checked value API.
|
Package uimigrate migrates source syntax to the UI's checked value API. |
|
uivet
Package uivet checks native UI build lifetimes using Go type information.
|
Package uivet checks native UI build lifetimes using Go type information. |
|
unsupported
Package unsupported is the backend for platforms without a native implementation.
|
Package unsupported is the backend for platforms without a native implementation. |
|
update
Package update holds what the updater of package mygo and `mygo build` share: the update manifest, signatures, versions, and the formats of archives and delta updates.
|
Package update holds what the updater of package mygo and `mygo build` share: the update manifest, signatures, versions, and the formats of archives and delta updates. |
|
vec
Package vec rasterizes vector paths (lines, quadratic and cubic Bézier curves) into anti-aliased coverage masks, with the signed area accumulation of font-rs: every edge adds the area it covers to the cells it crosses, and a running sum along each row gives the coverage.
|
Package vec rasterizes vector paths (lines, quadratic and cubic Bézier curves) into anti-aliased coverage masks, with the signed area accumulation of font-rs: every edge adds the area it covers to the cells it crosses, and a running sum along each row gives the coverage. |
|
wait
Package wait is how MyGo's tests wait for what happens elsewhere: on the main thread, in another goroutine or process, in the window system or the file system.
|
Package wait is how MyGo's tests wait for what happens elsewhere: on the main thread, in another goroutine or process, in the window system or the file system. |
|
watchdriver
Package watchdriver runs the native file watchers of the backends on one goroutine each: the goroutine owns the system's handles, adds and removes targets between waits, and reports what the system tells it.
|
Package watchdriver runs the native file watchers of the backends on one goroutine each: the goroutine owns the system's handles, adds and removes targets between waits, and reports what the system tells it. |
|
web
Package web is the backend for browsers (GOOS=js, GOARCH=wasm): windows showing content MyGo draws itself (package ui) on canvases of the page, drawn with WebGL 2 by the GL renderer (package gl), or in memory where the browser has no WebGL 2.
|
Package web is the backend for browsers (GOOS=js, GOARCH=wasm): windows showing content MyGo draws itself (package ui) on canvases of the page, drawn with WebGL 2 by the GL renderer (package gl), or in memory where the browser has no WebGL 2. |
|
webview2
Package webview2 finds the Microsoft Edge WebView2 Runtime as WebView2Loader.dll does.
|
Package webview2 finds the Microsoft Edge WebView2 Runtime as WebView2Loader.dll does. |
|
windows
Package windows implements the MyGo backend for Windows: Win32 windows hosting WebView2, called through the syscall package (no cgo).
|
Package windows implements the MyGo backend for Windows: Win32 windows hosting WebView2, called through the syscall package (no cgo). |
|
locales
|
|
|
zh-Hans
Package zhhans translates MyGo's own strings, those of its controls, dialogs and menus, to 简体中文 (zh-Hans), for apps that ship that language.
|
Package zhhans translates MyGo's own strings, those of its controls, dialogs and menus, to 简体中文 (zh-Hans), for apps that ship that language. |
|
zh-Hant
Package zhhant translates MyGo's own strings, those of its controls, dialogs and menus, to 繁體中文 (zh-Hant), for apps that ship that language.
|
Package zhhant translates MyGo's own strings, those of its controls, dialogs and menus, to 繁體中文 (zh-Hant), for apps that ship that language. |
|
plugins
|
|
|
fetch
Package fetch is the fetch plugin of MyGo: pages make HTTP requests from Go with the fetch of its JavaScript package, @mygo-plugins/fetch, which takes and returns the standard Request options and Response.
|
Package fetch is the fetch plugin of MyGo: pages make HTTP requests from Go with the fetch of its JavaScript package, @mygo-plugins/fetch, which takes and returns the standard Request options and Response. |
|
game
Package game has what games need beyond what apps do, opt-in, out of MyGo's core ui: a game loop that updates a world in fixed steps with the player's input and draws it every frame (View), and a camera that looks at a 2D world (Camera), shown pixel-perfect at any size through a ui.Canvas (IntegerFit).
|
Package game has what games need beyond what apps do, opt-in, out of MyGo's core ui: a game loop that updates a world in fixed steps with the player's input and draws it every frame (View), and a camera that looks at a 2D world (Camera), shown pixel-perfect at any size through a ui.Canvas (IntegerFit). |
|
game/gamepad
Package gamepad reads game controllers: their buttons, triggers and sticks in the standard layout of an Xbox controller, which the W3C's Gamepad API and SDL's game controller database name, whatever pad it is:
|
Package gamepad reads game controllers: their buttons, triggers and sticks in the standard layout of an Xbox controller, which the W3C's Gamepad API and SDL's game controller database name, whatever pad it is: |
|
glass
Package glass draws Liquid Glass in native UI, as macOS 26 and later draw it (AppKit's NSGlassEffectView), on every platform: what the elements under it painted shows through, blurred, bent near its edges as through the rim of a lens, and lit along its hairline rim.
|
Package glass draws Liquid Glass in native UI, as macOS 26 and later draw it (AppKit's NSGlassEffectView), on every platform: what the elements under it painted shows through, blurred, bent near its edges as through the rim of a lens, and lit along its hairline rim. |
|
glass/internal/gen
command
Command gen compiles the glass's and the blur's shaders ahead of time, so that renderers start without compiling them: the Metal libraries on macOS, with Xcode's metal tools, into shaders_darwin.go, and the Direct3D bytecode on Windows, with the system's d3dcompiler_47.dll, into shaders_windows.go.
|
Command gen compiles the glass's and the blur's shaders ahead of time, so that renderers start without compiling them: the Metal libraries on macOS, with Xcode's metal tools, into shaders_darwin.go, and the Direct3D bytecode on Windows, with the system's d3dcompiler_47.dll, into shaders_windows.go. |
|
sqlite
Package sqlite is MyGo's SQLite plugin.
|
Package sqlite is MyGo's SQLite plugin. |
|
sqlite/internal/libbuild
command
Builds SQLite's C amalgamation and the plugin's C shim with Zig 0.16:
|
Builds SQLite's C amalgamation and the plugin's C shim with Zig 0.16: |
|
terminal
Package terminal is a terminal for MyGo's native UI: a view that runs a shell, or any program, in a pseudo-terminal, with the terminal emulator of Ghostty, libghostty-vt, and draws it with package ui.
|
Package terminal is a terminal for MyGo's native UI: a view that runs a shell, or any program, in a pseudo-terminal, with the terminal emulator of Ghostty, libghostty-vt, and draws it with package ui. |
|
terminal/internal/libbuild
command
Libbuild builds libghostty-vt for every platform MyGo supports from Ghostty's sources at a commit, with Zig (the version Ghostty asks for), and writes mygo-plugin.json, which names the files and their SHA-256 for the CLI and the terminal package, and ghostty_themes.go, the themes that Ghostty ships:
|
Libbuild builds libghostty-vt for every platform MyGo supports from Ghostty's sources at a commit, with Zig (the version Ghostty asks for), and writes mygo-plugin.json, which names the files and their SHA-256 for the CLI and the terminal package, and ghostty_themes.go, the themes that Ghostty ships: |
|
terminal/internal/library
Package library finds libghostty-vt for the terminal plugin: next to the app, in the user's cache, or downloaded there, as mygo-plugin.json names it.
|
Package library finds libghostty-vt for the terminal plugin: next to the app, in the user's cache, or downloaded there, as mygo-plugin.json names it. |
|
terminal/internal/pty
Package pty runs processes in pseudo-terminals, in pure Go: /dev/ptmx on macOS and Linux, ConPTY on Windows.
|
Package pty runs processes in pseudo-terminals, in pure Go: /dev/ptmx on macOS and Linux, ConPTY on Windows. |
|
terminal/internal/vt
Package vt binds libghostty-vt, the terminal emulator of Ghostty, which it loads at run time through purego: no cgo.
|
Package vt binds libghostty-vt, the terminal emulator of Ghostty, which it loads at run time through purego: no cgo. |
|
updater
Package updater is the update window of MyGo apps, in the manner of Sparkle on macOS.
|
Package updater is the update window of MyGo apps, in the manner of Sparkle on macOS. |
|
updater/internal/frontend
Package frontend is what the updater shares with the windows that show its sessions: package updater shows them in a web page, package native in native UI.
|
Package frontend is what the updater shares with the windows that show its sessions: package updater shows them in a web page, package native in native UI. |
|
updater/internal/markdown
Package markdown parses the release notes of the update window.
|
Package markdown parses the release notes of the update window. |
|
updater/native
Package native is the update window of package updater drawn in native UI (package ui) instead of a web page, for apps whose windows all show native UI: it needs no webview, so neither WebKitGTK on Linux nor the WebView2 Runtime on Windows.
|
Package native is the update window of package updater drawn in native UI (package ui) instead of a web page, for apps whose windows all show native UI: it needs no webview, so neither WebKitGTK on Linux nor the WebView2 Runtime on Windows. |
|
watch
Package watch is the watch plugin of MyGo: it lets pages watch for changes to the files and directories the app names (see @mygo-plugins/watch).
|
Package watch is the watch plugin of MyGo: it lets pages watch for changes to the files and directories the app names (see @mygo-plugins/watch). |
|
websocket
Package websocket is the WebSocket plugin of MyGo: pages open WebSocket connections from Go with the WebSocket class of its JavaScript package, @mygo-plugins/websocket, which has the API of the browser's.
|
Package websocket is the WebSocket plugin of MyGo: pages open WebSocket connections from Go with the WebSocket class of its JavaScript package, @mygo-plugins/websocket, which has the API of the browser's. |
|
Package transfer describes data exchanged through the clipboard and native drag and drop.
|
Package transfer describes data exchanged through the clipboard and native drag and drop. |
|
Package ui builds user interfaces that MyGo draws itself, on the GPU where it can, for windows that show no web page:
|
Package ui builds user interfaces that MyGo draws itself, on the GPU where it can, for windows that show no web page: |
|
chart
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: 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.
|
Package chart builds charts in native UI without a look of their own, as headless libraries do on the web: 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. |
|
editor
Package editor is a code editor and a diff viewer for MyGo's native UI, on package ui.
|
Package editor is a code editor and a diff viewer for MyGo's native UI, on package ui. |
|
shader
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (Metal, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can.
|
Package shader draws with shaders an app writes: fragment shaders in Go's syntax, which run on the GPU, whichever renderer draws the window (Metal, Direct3D 11, OpenGL or WebGL 2), and on the CPU where none can. |
|
website
|
|
|
docs-demo
command
Docs-demo shows the previews of the pages of native UI's docs: the website builds it for browsers (website/docs-demo.ts) and shows a demo in a frame wherever a page of docs/ui has a comment
|
Docs-demo shows the previews of the pages of native UI's docs: the website builds it for browsers (website/docs-demo.ts) and shows a demo in a frame wherever a page of docs/ui has a comment |