Documentation
¶
Overview ¶
Package mygo is a desktop application framework built on the system webview (WKWebView on macOS, WebKitGTK on Linux, WebView2 on Windows), written in pure Go without cgo.
An app binds Go services, whose exported methods its web frontend calls through a TypeScript client that `mygo generate` writes, and opens 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.
The rest of the package covers the desktop: App (the lifecycle, deep links, file associations, the Dock), Window, 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 ¶
Native UI toolkits 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 EvalAs[T any](w *Window, 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 Use(ps ...Plugin)
- func WriteTypeScript(path string) error
- type AboutPanelOptions
- type ActivationPolicy
- type Application
- func (a *Application) ClearBrowsingData() 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) 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) 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) 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) Quit()
- 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) 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) 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 Channel
- type ClipboardModule
- func (ClipboardModule) AvailableFormats() []string
- func (ClipboardModule) Clear()
- func (ClipboardModule) ReadHTML() string
- func (ClipboardModule) ReadImage() []byte
- func (ClipboardModule) ReadText() string
- func (ClipboardModule) WriteHTML(markup string)
- func (ClipboardModule) WriteImage(png []byte) error
- func (ClipboardModule) WriteText(text string)
- type CloseEvent
- type DevTools
- type DialogModule
- type Display
- type Dock
- type Download
- type DownloadEvent
- type EvalError
- type Event
- type FileDropEvent
- type FileFilter
- type FindOptions
- type FindResult
- type GlobalShortcutModule
- 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 Notification
- type NotificationOptions
- type OpenDialogOptions
- type PDFOptions
- type PageSize
- type PathName
- type Permission
- type PermissionRequest
- 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 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 ShellModule
- type Size
- type ThemeModule
- 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 Window
- func (w *Window) Blur()
- func (w *Window) Bounds() Rectangle
- func (w *Window) CanGoBack() bool
- func (w *Window) CanGoForward() bool
- func (w *Window) CapturePage() ([]byte, error)
- func (w *Window) Center()
- func (w *Window) Close()
- func (w *Window) CloseDevTools()
- func (w *Window) ContentBounds() Rectangle
- func (w *Window) ContentSize() (width, height int)
- func (w *Window) Destroy()
- func (w *Window) Eval(code string) (any, error)
- func (w *Window) EvalContext(ctx context.Context, code string) (any, error)
- func (w *Window) FindInPage(text string, opts FindOptions) (FindResult, error)
- func (w *Window) FlashFrame(flash bool)
- func (w *Window) Focus()
- func (w *Window) GoBack()
- func (w *Window) GoForward()
- func (w *Window) HasShadow() bool
- func (w *Window) Hide()
- func (w *Window) ID() int
- func (w *Window) IsAlwaysOnTop() bool
- func (w *Window) IsClosable() bool
- func (w *Window) IsDestroyed() bool
- func (w *Window) IsDevToolsOpened() bool
- func (w *Window) IsFocused() bool
- func (w *Window) IsFullScreen() bool
- func (w *Window) IsLoading() 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) IsResizable() bool
- func (w *Window) IsVisible() bool
- func (w *Window) LoadFile(path string) error
- func (w *Window) LoadHTML(html, baseURL string)
- func (w *Window) LoadURL(rawURL string) error
- func (w *Window) Maximize()
- func (w *Window) Minimize()
- func (w *Window) NativeHandle() uintptr
- 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) OnDOMReady(fn func()) (off func())
- func (w *Window) OnDidFailLoad(fn func(err *LoadError)) (off func())
- func (w *Window) OnDidFinishLoad(fn func()) (off func())
- func (w *Window) OnDidNavigate(fn func(url string)) (off func())
- func (w *Window) OnDownloadDone(fn func(d *Download)) (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) OnPageTitleUpdated(fn func(e *TitleEvent)) (off func())
- func (w *Window) OnReadyToShow(fn func()) (off func())
- func (w *Window) OnRenderProcessGone(fn func(reason string)) (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) OnWillDownload(fn func(e *DownloadEvent)) (off func())
- func (w *Window) OnWillNavigate(fn func(e *NavigateEvent)) (off func())
- func (w *Window) Opacity() float64
- func (w *Window) OpenDevTools()
- func (w *Window) Parent() *Window
- func (w *Window) Position() (x, y int)
- func (w *Window) Print()
- func (w *Window) PrintToPDF(opts PDFOptions) ([]byte, error)
- func (w *Window) Reload()
- func (w *Window) ReloadIgnoringCache()
- func (w *Window) Restore()
- func (w *Window) SetAlwaysOnTop(v bool)
- 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) 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) SetPermissionHandler(fn func(req PermissionRequest) bool)
- func (w *Window) SetPosition(x, y int)
- func (w *Window) SetProgressBar(p ProgressBar)
- 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) SetUserAgent(ua string)
- func (w *Window) SetVibrancy(v Vibrancy)
- func (w *Window) SetVisibleOnAllWorkspaces(v bool)
- func (w *Window) SetWindowOpenHandler(fn func(req WindowOpenRequest) *WindowOptions)
- func (w *Window) SetZoomFactor(f float64)
- func (w *Window) Show()
- func (w *Window) ShowInactive()
- func (w *Window) Size() (width, height int)
- func (w *Window) Stop()
- func (w *Window) StopFindInPage()
- func (w *Window) Title() string
- func (w *Window) ToggleDevTools()
- func (w *Window) ToggleFullScreen()
- func (w *Window) ToggleMaximize()
- func (w *Window) URL() string
- func (w *Window) Unmaximize()
- func (w *Window) UserAgent() string
- func (w *Window) ZoomFactor() float64
- type WindowOpenRequest
- type WindowOptions
Constants ¶
const Version = "0.1.20"
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{}}
App is the application singleton.
var ErrChannelClosed = errors.New("mygo: channel closed")
ErrChannelClosed is returned by Channel.Send once the channel is closed.
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 GlobalShortcut = &GlobalShortcutModule{}
GlobalShortcut registers keyboard shortcuts that work while the app is in the background.
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.
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 EvalAs ¶
EvalAs evaluates JavaScript like Window.Eval and decodes the result into a value of type T.
title, err := mygo.EvalAs[string](win, "document.title")
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 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 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.
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
// contains filtered or unexported fields
}
Application controls the event loop and the lifecycle of the process. Use the App singleton.
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) 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) Locale ¶
func (a *Application) Locale() string
Locale returns the user's preferred locale, e.g. "en-US".
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) 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) 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) 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) 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 released on quit. Under `mygo dev`, a reload starts the new build while the previous one still runs, so the new build takes the lock over.
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 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) 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) 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 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) 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) WriteHTML ¶
func (ClipboardModule) WriteHTML(markup string)
WriteHTML puts HTML on the clipboard.
func (ClipboardModule) WriteImage ¶
func (ClipboardModule) WriteImage(png []byte) error
WriteImage puts a PNG image on the clipboard.
func (ClipboardModule) WriteText ¶
func (ClipboardModule) WriteText(text string)
WriteText puts plain text on the clipboard.
type CloseEvent ¶
type CloseEvent struct {
Preventable
Window *Window
}
CloseEvent is passed to Window.OnClose listeners. Preventing it keeps the window open.
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 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 Window.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 Window.OnWillDownload listeners. Setting Path chooses where the file goes; preventing the event cancels the download.
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.
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 FileFilter ¶
FileFilter limits the files a file dialog shows, e.g. {Name: "Images", Extensions: []string{"png", "jpg"}}.
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 Window.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 Window.FindInPage.
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.
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 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. win is
// the focused window, or 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" 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 )
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 Window.OnWillNavigate listeners. Preventing it cancels the navigation.
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) OnClick ¶
func (n *Notification) OnClick(fn func()) (off func())
OnClick is called when the user clicks the notification.
type NotificationOptions ¶
type NotificationOptions struct {
Title string
Subtitle string
Body string
// Silent suppresses the notification sound.
Silent bool
}
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 Window.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 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 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.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 ShellModule ¶
type ShellModule struct{}
ShellModule integrates with the desktop environment.
var Shell ShellModule
Shell opens URLs and files with the default applications.
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 changes.
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 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 Window.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 Window ¶
type Window struct {
// contains filtered or unexported fields
}
Window is a native window hosting a web page. 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. It returns nil for other contexts.
func FocusedWindow ¶
func FocusedWindow() *Window
FocusedWindow returns the focused window of this application, or nil.
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) CanGoForward ¶
CanGoForward reports whether there is a next page in history.
func (*Window) CapturePage ¶
CapturePage returns a PNG screenshot of the visible page.
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) CloseDevTools ¶
func (w *Window) CloseDevTools()
CloseDevTools closes the web inspector.
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) Eval ¶
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.Eval("document.title")
data, err := win.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.Eval("const items = document.querySelectorAll('li'); return items.length")
Eval is not subject to the page's Content Security Policy.
func (*Window) EvalContext ¶
EvalContext is Eval with a context that can abort the wait.
func (*Window) FindInPage ¶
func (w *Window) 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.FindInPage("mygo", mygo.FindOptions{FindNext: true})
Text split by markup, such as "my<b>go</b>", is not found.
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) 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) IsDevToolsOpened ¶
IsDevToolsOpened reports whether the web inspector is open.
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) IsResizable ¶
IsResizable reports whether the user can resize the window.
func (*Window) LoadFile ¶
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 (*Window) LoadHTML ¶
LoadHTML loads an HTML string. Relative URLs in it resolve against baseURL, which may be empty.
func (*Window) LoadURL ¶
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 (*Window) NativeHandle ¶
NativeHandle returns the native window: NSWindow* on macOS, GtkWindow* on Linux and HWND on Windows.
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) OnDOMReady ¶
func (w *Window) OnDOMReady(fn func()) (off func())
OnDOMReady is called when the page's DOM is ready (DOMContentLoaded).
func (*Window) OnDidFailLoad ¶
OnDidFailLoad is called when the page failed to load.
func (*Window) OnDidFinishLoad ¶
func (w *Window) OnDidFinishLoad(fn func()) (off func())
OnDidFinishLoad is called when the page finished loading.
func (*Window) OnDidNavigate ¶
OnDidNavigate is called when a navigation committed and a new page started.
func (*Window) OnDownloadDone ¶
OnDownloadDone is called when a download ended.
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.
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) OnPageTitleUpdated ¶
func (w *Window) 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 (*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.
func (*Window) OnRenderProcessGone ¶
OnRenderProcessGone is called when the web content process crashed or was killed. Call Reload to recover.
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) OnWillDownload ¶
func (w *Window) 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 (*Window) OnWillNavigate ¶
func (w *Window) 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 (*Window) OpenDevTools ¶
func (w *Window) OpenDevTools()
OpenDevTools opens the web inspector (unless disabled with WindowOptions.DevTools).
func (*Window) PrintToPDF ¶
func (w *Window) 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.PrintToPDF(mygo.PDFOptions{PageSize: mygo.PageA4, Background: true})
func (*Window) ReloadIgnoringCache ¶
func (w *Window) ReloadIgnoringCache()
ReloadIgnoringCache reloads the page bypassing the cache.
func (*Window) SetAlwaysOnTop ¶
SetAlwaysOnTop keeps the window above 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) 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) SetPermissionHandler ¶
func (w *Window) 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 WindowOptions.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 (*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) 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) SetUserAgent ¶
SetUserAgent overrides the user agent for subsequent requests.
func (*Window) SetVibrancy ¶
SetVibrancy sets the material behind the page; VibrancyNone removes it. See WindowOptions.Vibrancy.
func (*Window) SetVisibleOnAllWorkspaces ¶
SetVisibleOnAllWorkspaces shows the window on every workspace (macOS Spaces, Linux virtual desktops), or on the current one only.
func (*Window) SetWindowOpenHandler ¶
func (w *Window) 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 (*Window) SetZoomFactor ¶
SetZoomFactor zooms the page; 1 is 100%.
func (*Window) ShowInactive ¶
func (w *Window) ShowInactive()
ShowInactive shows the window without focusing it.
func (*Window) StopFindInPage ¶
func (w *Window) StopFindInPage()
StopFindInPage removes the highlights of FindInPage.
func (*Window) ToggleDevTools ¶
func (w *Window) ToggleDevTools()
ToggleDevTools opens or closes the web inspector.
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) ZoomFactor ¶
ZoomFactor returns the page zoom; 1 is 100%.
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.
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 (macOS and Windows 11), e.g. VibrancySidebar.
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
// 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.
DevTools DevTools
// ZoomFactor of the page (default 1).
ZoomFactor float64
// UserAgent overrides the user agent string.
UserAgent string
// StateKey remembers the window's position, size, and maximized and
// full screen state under this key, in window-state.json in
// PathUserData, which is written 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
}
WindowOptions configures NewWindow. The zero value is a visible, resizable 800x600 window centered on screen.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
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
|
|
|
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. |
|
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. |
|
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. |
|
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: a sidebar made of a translucent material, under a hidden title bar whose window controls sit over the page, the traffic lights inset over the sidebar on macOS.
|
Vibrancy shows a window in the style of a native macOS app: a sidebar made of a translucent material, under a hidden title bar whose window controls sit over the page, the traffic lights inset over the sidebar on macOS. |
|
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. |
|
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. |
|
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. |
|
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). |
|
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. |
|
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. |
|
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). |
|
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. |
|
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. |
|
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. |