This commit is contained in:
Lea Anthony
2023-12-09 17:29:56 +11:00
parent 07fc8e3707
commit 6a8322cdb5
526 changed files with 42791 additions and 249 deletions
@@ -0,0 +1,4 @@
{
"label": "Reference",
"position": 40
}
@@ -0,0 +1,245 @@
---
sidebar_position: 2
---
# CLI
The Wails CLI has a number of commands that are used for managing your projects. All commands are run in the following way:
`wails <command> <flags>`
## init
`wails init` is used for generating projects.
| Flag | Description | Default |
| :----------------- | :---------------------------------------------------------------------------------------------------------------------- | :-----------------: |
| -n "project name" | Name of the project. **Mandatory**. | |
| -d "project dir" | Project directory to create | Name of the project |
| -g | Initialise git repository | |
| -l | List available project templates | |
| -q | Suppress output to console | |
| -t "template name" | The project template to use. This can be the name of a default template or a URL to a remote template hosted on github. | vanilla |
| -ide | Generate IDE project files | |
| -f | Force build application | false |
Example:
`wails init -n test -d mytestproject -g -ide vscode -q`
This will generate a a project called "test" in the "mytestproject" directory, initialise git,
generate vscode project files and do so silently.
More information on using IDEs with Wails can be found [here](../guides/ides.mdx).
### Remote Templates
Remote templates (hosted on GitHub) are supported and can be installed by using the template's project URL.
Example:
`wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]`
A list of community maintained templates can be found [here](../community/templates.mdx)
:::warning Attention
**The Wails project does not maintain, is not responsible nor liable for 3rd party templates!**
If you are unsure about a template, inspect `package.json` and `wails.json` for what scripts are run and what packages are installed.
:::
## build
`wails build` is used for compiling your project to a production-ready binary.
| Flag | Description | Default |
|:---------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------|
| -clean | Cleans the `build/bin` directory | |
| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go |
| -debug | Retains debug information in the application and shows the debug console. Allows the use of the devtools in the application window | |
| -devtools | Allows the use of the devtools in the application window in production (when -debug is not used). Ctrl/Cmd+Shift+F12 may be used to open the devtools window. *NOTE*: This option will make your application FAIL Mac appstore guidelines. Use for debugging only. | |
| -dryrun | Prints the build command without executing it | |
| -f | Force build application | |
| -garbleargs | Arguments to pass to garble | `-literals -tiny -seed=random` |
| -ldflags "flags" | Additional ldflags to pass to the compiler | |
| -m | Skip mod tidy before compile | |
| -nopackage | Do not package application | |
| -nocolour | Disable colour in output | |
| -nosyncgomod | Do not sync go.mod with the Wails version | |
| -nsis | Generate NSIS installer for Windows | |
| -o filename | Output filename | |
| -obfuscated | Obfuscate the application using [garble](https://github.com/burrowers/garble) | |
| -platform | Build for the given (comma delimited) [platforms](../reference/cli.mdx#platforms) eg. `windows/arm64`. Note, if you do not give the architecture, `runtime.GOARCH` is used. | platform = `GOOS` environment variable if given else `runtime.GOOS`.<br/>arch = `GOARCH` envrionment variable if given else `runtime.GOARCH`. |
| -race | Build with Go's race detector | |
| -s | Skip building the frontend | |
| -skipbindings | Skip bindings generation | |
| -tags "extra tags" | Build tags to pass to Go compiler. Must be quoted. Space or comma (but not both) separated | |
| -trimpath | Remove all file system paths from the resulting executable. | |
| -u | Updates your project's `go.mod` to use the same version of Wails as the CLI | |
| -upx | Compress final binary using "upx" | |
| -upxflags | Flags to pass to upx | |
| -v int | Verbosity level (0 - silent, 1 - default, 2 - verbose) | 1 |
| -webview2 | WebView2 installer strategy: download,embed,browser,error | download |
| -windowsconsole | Keep the console window for Windows builds | |
For a detailed description of the `webview2` flag, please refer to the [Windows](../guides/windows.mdx) Guide.
If you prefer to build using standard Go tooling, please consult the [Manual Builds](../guides/manual-builds.mdx)
guide.
Example:
`wails build -clean -o myproject.exe`
:::info
On Mac, the application will be bundled with `Info.plist`, not `Info.dev.plist`.
:::
:::info UPX on Apple Silicon
There are [issues](https://github.com/upx/upx/issues/446) with using UPX with Apple Silicon.
:::
:::info UPX on Windows
Some Antivirus vendors false positively mark `upx` compressed binaries as virus, see [issue](https://github.com/upx/upx/issues/437).
:::
### Platforms
Supported platforms are:
| Platform | Description |
| :--------------- | :-------------------------------------------- |
| darwin | MacOS + architecture of build machine |
| darwin/amd64 | MacOS 10.13+ AMD64 |
| darwin/arm64 | MacOS 11.0+ ARM64 |
| darwin/universal | MacOS AMD64+ARM64 universal application |
| windows | Windows 10/11 + architecture of build machine |
| windows/amd64 | Windows 10/11 AMD64 |
| windows/arm64 | Windows 10/11 ARM64 |
| linux | Linux + architecture of build machine |
| linux/amd64 | Linux AMD64 |
| linux/arm64 | Linux ARM64 |
## doctor
`wails doctor` will run diagnostics to ensure that your system is ready for development.
Example:
```
Wails CLI v2.0.0-beta
Scanning system - Please wait (this may take a long time)...Done.
System
------
OS: Windows 10 Pro
Version: 2009 (Build: 19043)
ID: 21H1
Go Version: go1.18
Platform: windows
Architecture: amd64
Dependency Package Name Status Version
---------- ------------ ------ -------
WebView2 N/A Installed 93.0.961.52
npm N/A Installed 6.14.15
*upx N/A Installed upx 3.96
* - Optional Dependency
Diagnosis
---------
Your system is ready for Wails development!
```
## dev
`wails dev` is used to run your application in a "live development" mode. This means:
- The application's `go.mod` will be updated to use the same version of Wails as the CLI
- The application is compiled and run automatically
- A watcher is started and will trigger a rebuild of your dev app if it detects changes to your go files
- A webserver is started on `http://localhost:34115` which serves your application (not just frontend) over http. This allows you to use your favourite browser development extensions
- All application assets are loaded from disk. If they are changed, the application will automatically reload (not rebuild). All connected browsers will also reload
- A JS module is generated that provides the following:
- JavaScript wrappers of your Go methods with autogenerated JSDoc, providing code hinting
- TypeScript versions of your Go structs, that can be constructed and passed to your go methods
- A second JS module is generated that provides a wrapper + TS declaration for the runtime
- On macOS, it will bundle the application into a `.app` file and run it. It will use a `build/darwin/Info.dev.plist` for development.
| Flag | Description | Default |
|:-----------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------|
| -appargs "args" | Arguments passed to the application in shell style | |
| -assetdir "./path/to/assets" | Serve assets from the given directory instead of using the provided asset FS | Value in `wails.json` |
| -browser | Opens a browser to `http://localhost:34115` on startup | |
| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go |
| -debounce | The time to wait for reload after an asset change is detected | 100 (milliseconds) |
| -devserver "host:port" | The address to bind the wails dev server to | "localhost:34115" |
| -extensions | Extensions to trigger rebuilds (comma separated) | go |
| -forcebuild | Force build of application | |
| -frontenddevserverurl "url" | Use 3rd party dev server url to serve assets, EG Vite | "" |
| -ldflags "flags" | Additional ldflags to pass to the compiler | |
| -loglevel "loglevel" | Loglevel to use - Trace, Debug, Info, Warning, Error | Debug |
| -nocolour | Turn off colour cli output | false |
| -noreload | Disable automatic reload when assets change | |
| -nosyncgomod | Do not sync go.mod with the Wails version | false |
| -race | Build with Go's race detector | false |
| -reloaddirs | Additional directories to trigger reloads (comma separated) | Value in `wails.json` |
| -s | Skip building the frontend | false |
| -save | Saves the given `assetdir`, `reloaddirs`, `wailsjsdir`, `debounce`, `devserver` and `frontenddevserverurl` flags in `wails.json` to become the defaults for subsequent invocations. | |
| -skipbindings | Skip bindings generation | |
| -tags "extra tags" | Build tags to pass to compiler (quoted and space separated) | |
| -v | Verbosity level (0 - silent, 1 - standard, 2 - verbose) | 1 |
| -wailsjsdir | The directory to generate the generated Wails JS modules | Value in `wails.json` |
Example:
`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser`
This command will do the following:
- Build the application and run it (more details [here](../guides/manual-builds.mdx)
- Generate the Wails JS modules in `./frontend/src`
- Watch for updates to files in `./frontend/dist` and reload on any change
- Open a browser and connect to the application
There is more information on using this feature with existing framework scripts [here](../guides/application-development.mdx#live-reloading).
## generate
### template
Wails uses templates for project generation. The `wails generate template` command helps scaffold a template so that
it may be used for generating projects.
| Flag | Description |
|:-----------------|:--------------------------------------------|
| -name | The template name (Mandatory) |
| -frontend "path" | Path to frontend project to use in template |
For more details on creating templates, consult the [Templates guide](../guides/templates.mdx).
### module
The `wails generate module` command allows you to manually generate the `wailsjs` directory for your application.
## update
`wails update` will update the version of the Wails CLI.
| Flag | Description |
|:-------------------|:--------------------------------------|
| -pre | Update to latest pre-release version |
| -version "version" | Install a specific version of the CLI |
## version
`wails version` will simply output the current CLI version.
@@ -0,0 +1,240 @@
---
sidebar_position: 4
---
# Menus
It is possible to add an application menu to Wails projects. This is achieved by defining a [Menu](#menu) struct and
setting it in the [`Menu`](../reference/options.mdx#menu) application config, or by calling the runtime method
[MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu).
An example of how to create a menu:
```go
app := NewApp()
AppMenu := menu.NewMenu()
FileMenu := AppMenu.AddSubmenu("File")
FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile)
FileMenu.AddSeparator()
FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
runtime.Quit(app.ctx)
})
if runtime.GOOS == "darwin" {
AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut
}
err := wails.Run(&options.App{
Title: "Menus Demo",
Width: 800,
Height: 600,
Menu: AppMenu, // reference the menu above
Bind: []interface{}{
app,
},
)
// ...
```
It is also possible to dynamically update the menu, by updating the menu struct and calling
[MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu).
The example above uses helper methods, however it's possible to build the menu structs manually.
## Menu
A Menu is a collection of MenuItems:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
type Menu struct {
Items []*MenuItem
}
```
For the Application menu, each MenuItem represents a single menu such as "Edit".
A simple helper method is provided for building menus:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu
```
This makes the layout of the code more like that of a menu without the need to add the menu items manually after creating them.
Alternatively, you can just create the menu items and add them to the menu manually.
## MenuItem
A MenuItem represents an item within a Menu.
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
// MenuItem represents a menu item contained in a menu
type MenuItem struct {
Label string
Role Role
Accelerator *keys.Accelerator
Type Type
Disabled bool
Hidden bool
Checked bool
SubMenu *Menu
Click Callback
}
```
| Field | Type | Notes |
| ----------- | ---------------------------------- | ------------------------------------------------------------- |
| Label | string | The menu text |
| Accelerator | [\*keys.Accelerator](#accelerator) | Key binding for this menu item |
| Type | [Type](#type) | Type of MenuItem |
| Disabled | bool | Disables the menu item |
| Hidden | bool | Hides this menu item |
| Checked | bool | Adds check to item (Checkbox & Radio types) |
| SubMenu | [\*Menu](#menu) | Sets the submenu |
| Click | [Callback](#callback) | Callback function when menu clicked |
| Role | string | Defines a [role](#role) for this menu item. Mac only for now. |
### Accelerator
Accelerators (sometimes called keyboard shortcuts) define a binding between a keystroke and a menu item. Wails defines
an Accelerator as a combination or key + [Modifier](#modifier). They are available in the `"github.com/wailsapp/wails/v2/pkg/menu/keys"` package.
Example:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut := keys.CmdOrCtrl("o")
```
Keys are any single character on a keyboard with the exception of `+`, which is defined as `plus`.
Some keys cannot be represented as characters so there are a set of named characters that may be used:
| | | | |
| :---------: | :---: | :---: | :-------: |
| `backspace` | `f1` | `f16` | `f31` |
| `tab` | `f2` | `f17` | `f32` |
| `return` | `f3` | `f18` | `f33` |
| `enter` | `f4` | `f19` | `f34` |
| `escape` | `f5` | `f20` | `f35` |
| `left` | `f6` | `f21` | `numlock` |
| `right` | `f7` | `f22` | |
| `up` | `f8` | `f23` | |
| `down` | `f9` | `f24` | |
| `space` | `f10` | `f25` | |
| `delete` | `f11` | `f36` | |
| `home` | `f12` | `f37` | |
| `end` | `f13` | `f38` | |
| `page up` | `f14` | `f39` | |
| `page down` | `f15` | `f30` | |
Wails also supports parsing accelerators using the same syntax as Electron. This is useful for storing accelerators in
config files.
Example:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut, err := keys.Parse("Ctrl+Option+A")
```
#### Modifier
The following modifiers are keys that may be used in combination with the accelerator key:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
const (
// CmdOrCtrlKey represents Command on Mac and Control on other platforms
CmdOrCtrlKey Modifier = "cmdorctrl"
// OptionOrAltKey represents Option on Mac and Alt on other platforms
OptionOrAltKey Modifier = "optionoralt"
// ShiftKey represents the shift key on all systems
ShiftKey Modifier = "shift"
// ControlKey represents the control key on all systems
ControlKey Modifier = "ctrl"
)
```
A number of helper methods are available to create Accelerators using modifiers:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
func CmdOrCtrl(key string) *Accelerator
func OptionOrAlt(key string) *Accelerator
func Shift(key string) *Accelerator
func Control(key string) *Accelerator
```
Modifiers can be combined using `keys.Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)`:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines "Ctrl+Option+A" on Mac and "Ctrl+Alt+A" on Window/Linux
myShortcut := keys.Combo("a", ControlKey, OptionOrAltKey)
```
### Type
Each menu item must have a type and there are 5 types available:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
const (
TextType Type = "Text"
SeparatorType Type = "Separator"
SubmenuType Type = "Submenu"
CheckboxType Type = "Checkbox"
RadioType Type = "Radio"
)
```
For convenience, helper methods are provided to quickly create a menu item:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func Text(label string, accelerator *keys.Accelerator, click Callback) *MenuItem
func Separator() *MenuItem
func Radio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func Checkbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func SubMenu(label string, menu *Menu) *Menu
```
You can also create menu items directly on a menu by using the "Add" helpers:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func (m *Menu) AddText(label string, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddSeparator() *MenuItem
func (m *Menu) AddRadio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddCheckbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddSubMenu(label string, menu *Menu) *MenuI
```
A note on radio groups: A radio group is defined as a number of radio menu items that are next to each other in the menu.
This means that you do not need to group items together as it is automatic. However, that also means you cannot have 2
radio groups next to each other - there must be a non-radio item between them.
### Callback
Each menu item may have a callback that is executed when the item is clicked:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
type Callback func(*CallbackData)
type CallbackData struct {
MenuItem *MenuItem
}
```
The function is given a `CallbackData` struct which indicates which menu item triggered the callback. This is useful when
using radio groups that may share a callback.
### Role
:::info Roles
Roles are currently supported on Mac only.
:::
A menu item may have a role, which is essentially a pre-defined menu item. We currently support the following roles:
| Role | Description |
| ------------ | ------------------------------------------------------------------------ |
| AppMenuRole | The standard Mac application menu. Can be created using `menu.AppMenu()` |
| EditMenuRole | The standard Mac edit menu. Can be created using `menu.EditMenu()` |
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,130 @@
---
sidebar_position: 5
---
# Project Config
The project config resides in the `wails.json` file in the project directory. The structure of the config is:
```json5
{
// Project config version
"version": "",
// The project name
"name": "",
// Relative path to the directory containing the compiled assets, this is normally inferred and could be left empty
"assetdir": "",
// Additional directories to trigger reloads (comma separated), this is only used for some advanced asset configurations
"reloaddirs": "",
// The directory where the build files reside. Defaults to 'build'
"build:dir": "",
// Relative path to the frontend directory. Defaults to 'frontend'
"frontend:dir": "",
// The command to install node dependencies, run in the frontend directory - often `npm install`
"frontend:install": "",
// The command to build the assets, run in the frontend directory - often `npm run build`
"frontend:build": "",
// This command has been replaced by frontend:dev:build. If frontend:dev:build is not specified will falls back to this command. \nIf this command is also not specified will falls back to frontend:build
"frontend:dev": "",
// This command is the dev equivalent of frontend:build. If not specified falls back to frontend:dev
"frontend:dev:build": "",
// This command is the dev equivalent of frontend:install. If not specified falls back to frontend:install
"frontend:dev:install": "",
// This command is run in a separate process on `wails dev`. Useful for 3rd party watchers or starting 3d party dev servers
"frontend:dev:watcher": "",
// URL to a 3rd party dev server to be used to serve assets, EG Vite. \nIf this is set to 'auto' then the devServerUrl will be inferred from the Vite output
"frontend:dev:serverUrl": "",
// Relative path to the directory that the auto-generated JS modules will be created
"wailsjsdir": "",
// The name of the binary
"outputfilename": "",
// The default time the dev server waits to reload when it detects a change in assets
"debounceMS": 100,
// Address to bind the wails dev sever to. Default: localhost:34115
"devServer": "",
// Arguments passed to the application in shell style when in dev mode
"appargs": "",
// Defines if build hooks should be run though they are defined for an OS other than the host OS.
"runNonNativeBuildHooks": false,
"preBuildHooks": {
// The command that will be executed before a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook.
"GOOS/GOARCH": "",
// The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook.
"GOOS/*": "",
// The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH".
"*/*": ""
},
"postBuildHooks": {
// The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook.
"GOOS/GOARCH": "",
// The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook.
"GOOS/*": "",
// The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary.
"*/*": ""
},
// Data used to populate manifests and version info.
"info": {
// The company name. Default: [The project name]
"companyName": "",
// The product name. Default: [The project name]
"productName": "",
// The version of the product. Default: '1.0.0'
"productVersion": "",
// The copyright of the product. Default: 'Copyright.........'
"copyright": "",
// A short comment of the app. Default: 'Built using Wails (https://wails.app)'
"comments": "",
// File associations for the app
"fileAssociations": [
{
// The extension (minus the leading period). e.g. png
"ext": "wails",
// The name. e.g. PNG File
"name": "Wails",
// Windows-only. The description. It is displayed on the `Type` column on Windows Explorer.
"description": "Wails file",
// The icon name without extension. Icons should be located in build folder. Proper icons will be generated from .png file for both macOS and Windows)
"iconName": "fileIcon",
// macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole.
"role": "Editor"
},
],
// Custom URI protocols that should be opened by the application
"protocols": [
{
// protocol scheme. e.g. myapp
"scheme": "myapp",
// Windows-only. The description. It is displayed on the `Type` column on Windows Explorer.
"description": "Myapp protocol",
// macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole.
"role": "Editor"
}
]
},
// 'multiple': One installer per architecture. 'single': Single universal installer for all architectures being built. Default: 'multiple'
"nsisType": "",
// Whether the app should be obfuscated. Default: false
"obfuscated": "",
// The arguments to pass to the garble command when using the obfuscated flag
"garbleargs": "",
// Bindings configurations
"bindings": {
// model.ts file generation config
"ts_generation": {
// All generated JavaScript entities will be prefixed with this value
"prefix": "",
// All generated JavaScript entities will be suffixed with this value
"suffix": "",
// Type of output to generate (classes|interfaces)
"outputType": "classes",
}
}
}
```
This file is read by the Wails CLI when running `wails build` or `wails dev`.
The `assetdir`, `reloaddirs`, `wailsjsdir`, `debounceMS`, `devserver` and `frontenddevserverurl` flags in `wails build/dev` will update the project config
and thus become defaults for subsequent runs.
The JSON Schema for this file is located [here](https://wails.io/schemas/config.v2.json).
@@ -0,0 +1,4 @@
{
"label": "Runtime",
"position": 1
}
@@ -0,0 +1,14 @@
---
sidebar_position: 7
---
# Browser
These methods are related to the system browser.
### BrowserOpenURL
Opens the given URL in the system browser.
Go: `BrowserOpenURL(ctx context.Context, url string)`<br/>
JS: `BrowserOpenURL(url string)`
@@ -0,0 +1,28 @@
---
sidebar_position: 8
---
# Clipboard
This part of the runtime provides access to the operating system's clipboard.<br/>
The current implementation only handles text.
### ClipboardGetText
This method reads the currently stored text from the clipboard.
Go: `ClipboardGetText(ctx context.Context) (string, error)`<br/>
Returns: a string (if the clipboard is empty an empty string will be returned) or an error.
JS: `ClipboardGetText(): Promise<string>`<br/>
Returns: a promise with a string result (if the clipboard is empty an empty string will be returned).
### ClipboardSetText
This method writes a text to the clipboard.
Go: `ClipboardSetText(ctx context.Context, text string) error`<br/>
Returns: an error if there is any.
JS: `ClipboardSetText(text: string): Promise<boolean>`<br/>
Returns: a promise with true result if the text was successfully set on the clipboard, false otherwise.
@@ -0,0 +1,309 @@
---
sidebar_position: 5
---
# Dialog
This part of the runtime provides access to native dialogs, such as File Selectors and Message boxes.
:::info JavaScript
Dialog is currently unsupported in the JS runtime.
:::
### OpenDirectoryDialog
Opens a dialog that prompts the user to select a directory. Can be customised using [OpenDialogOptions](#opendialogoptions).
Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)`
Returns: Selected directory (blank if the user cancelled) or an error
### OpenFileDialog
Opens a dialog that prompts the user to select a file. Can be customised using [OpenDialogOptions](#opendialogoptions).
Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)`
Returns: Selected file (blank if the user cancelled) or an error
### OpenMultipleFilesDialog
Opens a dialog that prompts the user to select multiple files. Can be customised using [OpenDialogOptions](#opendialogoptions).
Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)`
Returns: Selected files (nil if the user cancelled) or an error
### SaveFileDialog
Opens a dialog that prompts the user to select a filename for the purposes of saving. Can be customised using [SaveDialogOptions](#savedialogoptions).
Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)`
Returns: The selected file (blank if the user cancelled) or an error
### MessageDialog
Displays a message using a message dialog. Can be customised using [MessageDialogOptions](#messagedialogoptions).
Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)`
Returns: The text of the selected button or an error
## Options
### OpenDialogOptions
```go
type OpenDialogOptions struct {
DefaultDirectory string
DefaultFilename string
Title string
Filters []FileFilter
ShowHiddenFiles bool
CanCreateDirectories bool
ResolvesAliases bool
TreatPackagesAsDirectories bool
}
```
| Field | Description | Win | Mac | Lin |
| -------------------------- | ---------------------------------------------- | --- | --- | --- |
| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ |
| DefaultFilename | The default filename | ✅ | ✅ | ✅ |
| Title | Title for the dialog | ✅ | ✅ | ✅ |
| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ |
| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ |
| CanCreateDirectories | Allow user to create directories | | ✅ | |
| ResolvesAliases | If true, returns the file not the alias | | ✅ | |
| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | |
### SaveDialogOptions
```go
type SaveDialogOptions struct {
DefaultDirectory string
DefaultFilename string
Title string
Filters []FileFilter
ShowHiddenFiles bool
CanCreateDirectories bool
TreatPackagesAsDirectories bool
}
```
| Field | Description | Win | Mac | Lin |
| -------------------------- | ---------------------------------------------- | --- | --- | --- |
| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ |
| DefaultFilename | The default filename | ✅ | ✅ | ✅ |
| Title | Title for the dialog | ✅ | ✅ | ✅ |
| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ |
| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ |
| CanCreateDirectories | Allow user to create directories | | ✅ | |
| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | |
### MessageDialogOptions
```go
type MessageDialogOptions struct {
Type DialogType
Title string
Message string
Buttons []string
DefaultButton string
CancelButton string
}
```
| Field | Description | Win | Mac | Lin |
|---------------|----------------------------------------------------------------------------|----------------|-----|-----|
| Type | The type of message dialog, eg question, info... | ✅ | ✅ | ✅ |
| Title | Title for the dialog | ✅ | ✅ | ✅ |
| Message | The message to show the user | ✅ | ✅ | ✅ |
| Buttons | A list of button titles | | ✅ | |
| DefaultButton | The button with this text should be treated as default. Bound to `return`. | ✅[*](#windows) | ✅ | |
| CancelButton | The button with this text should be treated as cancel. Bound to `escape` | | ✅ | |
#### Windows
Windows has standard dialog types in which the buttons are not customisable.
The value returned will be one of: "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" or "Continue".
For Question dialogs, the default button is "Yes" and the cancel button is "No".
This can be changed by setting the `DefaultButton` value to `"No"`.
Example:
```go
result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "Question",
Message: "Do you want to continue?",
DefaultButton: "No",
})
```
#### Linux
Linux has standard dialog types in which the buttons are not customisable.
The value returned will be one of: "Ok", "Cancel", "Yes", "No"
#### Mac
A message dialog on Mac may specify up to 4 buttons. If no `DefaultButton` or `CancelButton` is given, the first button
is considered default and is bound to the `return` key.
For the following code:
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
})
```
the first button is shown as default:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_no_defaults.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
```
And if we specify `DefaultButton` to be "two":
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
DefaultButton: "two",
})
```
the second button is shown as default. When `return` is pressed, the value "two" is returned.
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_default_button.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
```
If we now specify `CancelButton` to be "three":
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
DefaultButton: "two",
CancelButton: "three",
})
```
the button with "three" is shown at the bottom of the dialog. When `escape` is pressed, the value "three" is returned:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_default_cancel.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### DialogType
```go
const (
InfoDialog DialogType = "info"
WarningDialog DialogType = "warning"
ErrorDialog DialogType = "error"
QuestionDialog DialogType = "question"
)
```
### FileFilter
```go
type FileFilter struct {
DisplayName string // Filter information EG: "Image Files (*.jpg, *.png)"
Pattern string // semi-colon separated list of extensions, EG: "*.jpg;*.png"
}
```
#### Windows
Windows allows you to use multiple file filters in dialog boxes. Each FileFilter will show up as a separate entry in the
dialog:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_win_filters.png").default}
width="50%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### Linux
Linux allows you to use multiple file filters in dialog boxes. Each FileFilter will show up as a separate entry in the
dialog:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_lin_filters.png").default}
width="50%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### Mac
Mac dialogs only have the concept of a single set of patterns to filter files. If multiple FileFilters are provided,
Wails will use all the Patterns defined.
Example:
```go
selection, err := runtime.OpenFileDialog(b.ctx, runtime.OpenDialogOptions{
Title: "Select File",
Filters: []runtime.FileFilter{
{
DisplayName: "Images (*.png;*.jpg)",
Pattern: "*.png;*.jpg",
}, {
DisplayName: "Videos (*.mov;*.mp4)",
Pattern: "*.mov;*.mp4",
},
},
})
```
This will result in the Open File dialog using `*.png,*.jpg,*.mov,*.mp4` as a filter.
@@ -0,0 +1,47 @@
---
sidebar_position: 2
---
# Events
The Wails runtime provides a unified events system, where events can be emitted or received by either Go or JavaScript.
Optionally, data may be passed with the events. Listeners will receive the data in the local data types.
### EventsOn
This method sets up a listener for the given event name. When an event of type `eventName` is [emitted](#EventsEmit),
the callback is triggered. Any additional data sent with the emitted event will be passed to the callback. It returns
a function to cancel the listener.
Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`<br/>
JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void`
### EventsOff
This method unregisters the listener for the given event name, optionally multiple listeneres can be unregistered via `additionalEventNames`.
Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`<br/>
JS: `EventsOff(eventName string, ...additionalEventNames)`
### EventsOnce
This method sets up a listener for the given event name, but will only trigger once. It returns a function to cancel
the listener.
Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`<br/>
JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void`
### EventsOnMultiple
This method sets up a listener for the given event name, but will only trigger a maximum of `counter` times. It returns
a function to cancel the listener.
Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`<br/>
JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void`
### EventsEmit
This method emits the given event. Optional data may be passed with the event. This will trigger any event listeners.
Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`<br/>
JS: `EventsEmit(eventName: string, ...optionalData: any)`
@@ -0,0 +1,100 @@
---
sidebar_position: 1
---
# Introduction
The runtime is a library that provides utility methods for your application. There is both a Go and JavaScript runtime
and the aim is to try and keep them at parity where possible.
It has utility methods for:
- [Window](window.mdx)
- [Menu](menu.mdx)
- [Dialog](dialog.mdx)
- [Events](events.mdx)
- [Browser](browser.mdx)
- [Log](log.mdx)
- [Clipboard](clipboard.mdx)
The Go Runtime is available through importing `github.com/wailsapp/wails/v2/pkg/runtime`. All methods in this package
take a context as the first parameter. This context should be obtained from the [OnStartup](../options.mdx#onstartup)
or [OnDomReady](../options.mdx#ondomready) hooks.
:::info Note
Whilst the context will be provided to the
[OnStartup](../options.mdx#onstartup) method, there's no guarantee the runtime will work in this method as
the window is initialising in a different thread. If
you wish to call runtime methods at startup, use [OnDomReady](../options.mdx#ondomready).
:::
The JavaScript library is available to the frontend via the `window.runtime` map. There is a runtime package generated when using `dev`
mode that provides TypeScript declarations for the runtime. This should be located in the `wailsjs` directory in your
frontend directory.
### Hide
Go: `Hide(ctx context.Context)`<br/>
JS: `Hide()`
Hides the application.
:::info Note
On Mac, this will hide the application in the same way as the `Hide` menu item in standard Mac applications.
This is different to hiding the window, but the application still being in the foreground.
For Windows and Linux, this is currently the same as `WindowHide`.
:::
### Show
Shows the application.
:::info Note
On Mac, this will bring the application back into the foreground.
For Windows and Linux, this is currently the same as `WindowShow`.
:::
Go: `Show(ctx context.Context)`<br/>
JS: `Show()`
### Quit
Quits the application.
Go: `Quit(ctx context.Context)`<br/>
JS: `Quit()`
### Environment
Returns details of the current environment.
Go: `Environment(ctx context.Context) EnvironmentInfo`<br/>
JS: `Environment(): Promise<EnvironmentInfo>`
#### EnvironmentInfo
Go:
```go
type EnvironmentInfo struct {
BuildType string
Platform string
Arch string
}
```
JS:
```ts
interface EnvironmentInfo {
buildType: string;
platform: string;
arch: string;
}
```
@@ -0,0 +1,142 @@
---
sidebar_position: 3
---
# Log
The Wails runtime provides a logging mechanism that may be called from Go or JavaScript. Like most
loggers, there are a number of log levels:
- Trace
- Debug
- Info
- Warning
- Error
- Fatal
The logger will output any log message at the current, or higher, log level. Example: The `Debug` log
level will output all messages except `Trace` messages.
### LogPrint
Logs the given message as a raw message.
Go: `LogPrint(ctx context.Context, message string)`<br/>
JS: `LogPrint(message: string)`
### LogPrintf
Logs the given message as a raw message.
Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`<br/>
### LogTrace
Logs the given message at the `Trace` log level.
Go: `LogTrace(ctx context.Context, message string)`<br/>
JS: `LogTrace(message: string)`
### LogTracef
Logs the given message at the `Trace` log level.
Go: `LogTracef(ctx context.Context, format string, args ...interface{})`<br/>
### LogDebug
Logs the given message at the `Debug` log level.
Go: `LogDebug(ctx context.Context, message string)`<br/>
JS: `LogDebug(message: string)`
### LogDebugf
Logs the given message at the `Debug` log level.
Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`<br/>
### LogInfo
Logs the given message at the `Info` log level.
Go: `LogInfo(ctx context.Context, message string)`<br/>
JS: `LogInfo(message: string)`
### LogInfof
Logs the given message at the `Info` log level.
Go: `LogInfof(ctx context.Context, format string, args ...interface{})`<br/>
### LogWarning
Logs the given message at the `Warning` log level.
Go: `LogWarning(ctx context.Context, message string)`<br/>
JS: `LogWarning(message: string)`
### LogWarningf
Logs the given message at the `Warning` log level.
Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`<br/>
### LogError
Logs the given message at the `Error` log level.
Go: `LogError(ctx context.Context, message string)`<br/>
JS: `LogError(message: string)`
### LogErrorf
Logs the given message at the `Error` log level.
Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`<br/>
### LogFatal
Logs the given message at the `Fatal` log level.
Go: `LogFatal(ctx context.Context, message string)`<br/>
JS: `LogFatal(message: string)`
### LogFatalf
Logs the given message at the `Fatal` log level.
Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`<br/>
### LogSetLogLevel
Sets the log level. In JavaScript, the number relates to the following log levels:
| Value | Log Level |
| ----- | --------- |
| 1 | Trace |
| 2 | Debug |
| 3 | Info |
| 4 | Warning |
| 5 | Error |
Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`<br/>
JS: `LogSetLogLevel(level: number)`
## Using a Custom Logger
A custom logger may be used by providing it using the [Logger](../options.mdx#logger)
application option. The only requirement is that the logger implements the `logger.Logger` interface
defined in `github.com/wailsapp/wails/v2/pkg/logger`:
```go title="logger.go"
type Logger interface {
Print(message string)
Trace(message string)
Debug(message string)
Info(message string)
Warning(message string)
Error(message string)
Fatal(message string)
}
```
@@ -0,0 +1,25 @@
---
sidebar_position: 6
---
# Menu
These methods are related to the application menu.
:::info JavaScript
Menu is currently unsupported in the JS runtime.
:::
### MenuSetApplicationMenu
Sets the application menu to the given [menu](../menus.mdx).
Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)`
### MenuUpdateApplicationMenu
Updates the application menu, picking up any changes to the menu passed to `MenuSetApplicationMenu`.
Go: `MenuUpdateApplicationMenu(ctx context.Context)`
@@ -0,0 +1,37 @@
---
sidebar_position: 9
---
# Screen
These methods provide information about the currently connected screens.
### ScreenGetAll
Returns a list of currently connected screens.
Go: `ScreenGetAll(ctx context.Context) []screen`<br/>
JS: `ScreenGetAll()`
#### Screen
Go struct:
```go
type Screen struct {
IsCurrent bool
IsPrimary bool
Width int
Height int
}
```
Typescript interface:
```ts
interface Screen {
isCurrent: boolean;
isPrimary: boolean;
width : number
height : number
}
```
@@ -0,0 +1,261 @@
---
sidebar_position: 4
---
# Window
These methods give control of the application window.
### WindowSetTitle
Sets the text in the window title bar.
Go: `WindowSetTitle(ctx context.Context, title string)`<br/>
JS: `WindowSetTitle(title: string)`
### WindowFullscreen
Makes the window full screen.
Go: `WindowFullscreen(ctx context.Context)`<br/>
JS: `WindowFullscreen()`
### WindowUnfullscreen
Restores the previous window dimensions and position prior to full screen.
Go: `WindowUnfullscreen(ctx context.Context)`<br/>
JS: `WindowUnfullscreen()`
### WindowIsFullscreen
Returns true if the window is full screen.
Go: `WindowIsFullscreen(ctx context.Context) bool`<br/>
JS: `WindowIsFullscreen() bool`
### WindowCenter
Centers the window on the monitor the window is currently on.
Go: `WindowCenter(ctx context.Context)`<br/>
JS: `WindowCenter()`
### WindowExecJS
Executes arbitrary JS code in the window.
This method runs the code in the browser asynchronously and returns immediately.
If the script causes any errors, they will only be available in the browser console.
Go: `WindowExecJS(ctx context.Context, js string)`
### WindowReload
Performs a "reload" (Reloads current page).
Go: `WindowReload(ctx context.Context)`<br/>
JS: `WindowReload()`
### WindowReloadApp
Reloads the application frontend.
Go: `WindowReloadApp(ctx context.Context)`<br/>
JS: `WindowReloadApp()`
### WindowSetSystemDefaultTheme
Windows only.
Go: `WindowSetSystemDefaultTheme(ctx context.Context)`<br/>
JS: `WindowSetSystemDefaultTheme()`
Sets window theme to system default (dark/light).
### WindowSetLightTheme
Windows only.
Go: `WindowSetLightTheme(ctx context.Context)`<br/>
JS: `WindowSetLightTheme()`
Sets window theme to light.
### WindowSetDarkTheme
Windows only.
Go: `WindowSetDarkTheme(ctx context.Context)`<br/>
JS: `WindowSetDarkTheme()`
Sets window theme to dark.
### WindowShow
Shows the window, if it is currently hidden.
Go: `WindowShow(ctx context.Context)`<br/>
JS: `WindowShow()`
### WindowHide
Hides the window, if it is currently visible.
Go: `WindowHide(ctx context.Context)`<br/>
JS: `WindowHide()`
### WindowIsNormal
Returns true if the window not minimised, maximised or fullscreen.
Go: `WindowIsNormal(ctx context.Context) bool`<br/>
JS: `WindowIsNormal() bool`
### WindowSetSize
Sets the width and height of the window.
Go: `WindowSetSize(ctx context.Context, width int, height int)`<br/>
JS: `WindowSetSize(width: number, height: number)`
### WindowGetSize
Gets the width and height of the window.
Go: `WindowGetSize(ctx context.Context) (width int, height int)`<br/>
JS: `WindowGetSize() : Size`
### WindowSetMinSize
Sets the minimum window size.
Will resize the window if the window is currently smaller than the given dimensions.
Setting a size of `0,0` will disable this constraint.
Go: `WindowSetMinSize(ctx context.Context, width int, height int)`<br/>
JS: `WindowSetMinSize(width: number, height: number)`
### WindowSetMaxSize
Sets the maximum window size.
Will resize the window if the window is currently larger than the given dimensions.
Setting a size of `0,0` will disable this constraint.
Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`<br/>
JS: `WindowSetMaxSize(width: number, height: number)`
### WindowSetAlwaysOnTop
Sets the window AlwaysOnTop or not on top.
Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`<br/>
JS: `WindowSetAlwaysOnTop(b: Boolen)`
### WindowSetPosition
Sets the window position relative to the monitor the window is currently on.
Go: `WindowSetPosition(ctx context.Context, x int, y int)`<br/>
JS: `WindowSetPosition(x: number, y: number)`
### WindowGetPosition
Gets the window position relative to the monitor the window is currently on.
Go: `WindowGetPosition(ctx context.Context) (x int, y int)`<br/>
JS: `WindowGetPosition() : Position`
### WindowMaximise
Maximises the window to fill the screen.
Go: `WindowMaximise(ctx context.Context)`<br/>
JS: `WindowMaximise()`
### WindowUnmaximise
Restores the window to the dimensions and position prior to maximising.
Go: `WindowUnmaximise(ctx context.Context)`<br/>
JS: `WindowUnmaximise()`
### WindowIsMaximised
Returns true if the window is maximised.
Go: `WindowIsMaximised(ctx context.Context) bool`<br/>
JS: `WindowIsMaximised() bool`
### WindowToggleMaximise
Toggles between Maximised and UnMaximised.
Go: `WindowToggleMaximise(ctx context.Context)`<br/>
JS: `WindowToggleMaximise()`
### WindowMinimise
Minimises the window.
Go: `WindowMinimise(ctx context.Context)`<br/>
JS: `WindowMinimise()`
### WindowUnminimise
Restores the window to the dimensions and position prior to minimising.
Go: `WindowUnminimise(ctx context.Context)`<br/>
JS: `WindowUnminimise()`
### WindowIsMinimised
Returns true if the window is minimised.
Go: `WindowIsMinimised(ctx context.Context) bool`<br/>
JS: `WindowIsMinimised() bool`
### WindowSetBackgroundColour
Sets the background colour of the window to the given RGBA colour definition.
This colour will show through for all transparent pixels.
Valid values for R, G, B and A are 0-255.
:::info Windows
On Windows, only alpha values of 0 or 255 are supported.
Any value that is not 0 will be considered 255.
:::
Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`<br/>
JS: `WindowSetBackgroundColour(R, G, B, A)`
### WindowPrint
Opens tha native print dialog.
Go: `WindowPrint(ctx context.Context)`<br/>
JS: `WindowPrint()`
## TypeScript Object Definitions
### Position
```ts
interface Position {
x: number;
y: number;
}
```
### Size
```ts
interface Size {
w: number;
h: number;
}
```