运行时是一个为应用程序提供实用方法的库。 有 Go 和 JavaScript 运行时,目的是在可能的情况下尝试使它们保持一致。
Go 运行时可通过导入 github.com/wailsapp/wails/v2/pkg/runtime
获取。 此包中的所有方法都将 context 作为第一个参数。此 context 应该从应用启动回调或前端 Dom 加载完成回调方法中获取。
JavaScript 库可通过 window.runtime
提供给前端。 使用 开发
模式时会生成一个运行时包,该包为运行时提供 TypeScript 声明。 这应该位于您的前端目录的wailsjs
目录中。
隐藏应用程序。
Hide(ctx context.Context)
Hide()
Hide
在 Mac 上,这将以与标准 Mac 应用程序中的菜单项相同的方式隐藏应用程序。 这与隐藏窗口不同,但应用程序仍处于前台。 对于 Windows 和 Linux,这与 WindowHide
相同。
显示应用程序。
Show(ctx context.Context)
Show()
在 Mac 上,这会将应用程序带回前台。 对于 Windows 和 Linux,这目前与 WindowShow
相同。
退出应用程序。
Quit(ctx context.Context)
Quit()
返回当前环境的详细信息。
Environment(ctx context.Context) EnvironmentInfo
Environment(): Promise<EnvironmentInfo>
type EnvironmentInfo struct {
BuildType string
Platform string
Arch string
}
interface EnvironmentInfo {
buildType: string;
platform: string;
arch: string;
}
使用系统默认浏览器打开给定的 URL。
BrowserOpenURL(ctx context.Context, url string)
BrowserOpenURL(url string)
Wails 运行时提供了一个统一的事件系统,其中事件可以由 Go 或 JavaScript 发出或接收。
可选地,数据可以与事件一起传递。 侦听器将接收本地数据类型中的数据。
此方法为给定的事件名称设置一个侦听器。
当触发指定事件名为 eventName
类型的事件时,将触发回调。 与触发事件一起发送的任何其他数据都将传递给回调。 它返回一个函数来取消侦听器。
EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()
EventsOn(eventName string, callback function(optionalData?: any)): () => void
此方法取消注册给定事件名称的侦听器,可选地,可以通过 additionalEventNames
取消注册多个侦听器。
EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)
EventsOff(eventName string, ...additionalEventNames)
此方法为给定的事件名称设置一个侦听器,但只会触发一次。 它返回 一个函数来取消侦听器。
EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()
EventsOnce(eventName string, callback function(optionalData?: any)): () => void
此方法为给定的事件名称设置一个侦听器,但最多只能触发 counter
次。 它返回 一个函数来取消侦听器。
EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()
EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void
此方法触发指定的事件。 可选数据可以与事件一起传递。 这将触发任意事件侦听器。
EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})
EventsEmit(eventName: string, ...optionalData: any)
Wails 运行时提供了一种可以从 Go 或 JavaScript 调用日志记录的机制。 像大多数记录器一样,有许多日志级别:
记录器将输出当前或更高日志级别的任何日志消息。
示例:Debug
日志级别将输出除Trace
消息之外的所有消息。
将给定的消息记录为原始消息。
LogPrint(ctx context.Context, message string)
LogPrint(message: string)
将给定的消息记录为原始消息。
Go: LogPrintf(ctx context.Context, format string, args ...interface{})
在 Trace
日志级别记录给定的消息。
LogTrace(ctx context.Context, message string)
LogTrace(message: string)
在 Trace
日志级别记录给定的消息。
Go: LogTracef(ctx context.Context, format string, args ...interface{})
在 Debug
日志级别记录给定的消息。
LogDebug(ctx context.Context, message string)
LogDebug(message: string)
在 Debug
日志级别记录给定的消息。
Go: LogDebugf(ctx context.Context, format string, args ...interface{})
在Info
日志级别记录给定的消息。
LogInfo(ctx context.Context, message string)
LogInfo(message: string)
在Info
日志级别记录给定的消息。
Go: LogInfof(ctx context.Context, format string, args ...interface{})
在 Warning
日志级别记录给定的消息。
LogWarning(ctx context.Context, message string)
LogWarning(message: string)
在 Warning
日志级别记录给定的消息。
Go: LogWarningf(ctx context.Context, format string, args ...interface{})
在 Error
日志级别记录给定的消息。
LogError(ctx context.Context, message string)
LogError(message: string)
在 Error
日志级别记录给定的消息。
Go: LogErrorf(ctx context.Context, format string, args ...interface{})
在 Fatal
日志级别记录给定的消息。
LogFatal(ctx context.Context, message string)
LogFatal(message: string)
在 Fatal
日志级别记录给定的消息。
Go: LogFatalf(ctx context.Context, format string, args ...interface{})
设置日志级别。 在 JavaScript 中,该数字与以下日志级别有关:
值 | 日志等级 |
---|---|
1 | Trace(追踪) |
2 | Debug(调试) |
3 | Info(信息) |
4 | Warning(警告) |
5 | Error(错误) |
LogSetLogLevel(ctx context.Context, level logger.LogLevel)
LogSetLogLevel(level: number)
可以通过使用应用程序参数选项日志提供自定义记录器来使用它。
唯一的要求是记录器实现在 github.com/wailsapp/wails/v2/pkg/logger
里 logger.Logger
定义的接口:
type Logger interface {
Print(message string)
Trace(message string)
Debug(message string)
Info(message string)
Warning(message string)
Error(message string)
Fatal(message string)
}
interface Position {
x: number;
y: number;
}
interface Size {
w: number;
h: number;
}
设置窗口标题栏中的文本。
WindowSetTitle(ctx context.Context, title string)
WindowSetTitle(title: string)
使窗口全屏。
WindowFullscreen(ctx context.Context)
WindowFullscreen()
恢复全屏之前的先前窗口尺寸和位置。
WindowUnfullscreen(ctx context.Context)
WindowUnfullscreen()
如果窗口是全屏的,则返回 true。
WindowIsFullscreen(ctx context.Context) bool
WindowIsFullscreen() Promise<boolean>
使窗口在当前窗口所在的监视器上居中。
WindowCenter(ctx context.Context)
WindowCenter()
在窗口中执行任意 JS 代码。
此方法在浏览器中异步运行代码并立即返回。 如果脚本导致任何错误,它们将只在浏览器控制台中可用。
Go: WindowExecJS(ctx context.Context, js string)
执行“重新加载”(重新加载当前页面)。
WindowReload(ctx context.Context)
WindowReload()
重新加载应用程序前端。
WindowReloadApp(ctx context.Context)
WindowReloadApp()
仅限 Windows。
WindowSetSystemDefaultTheme(ctx context.Context)
WindowSetSystemDefaultTheme()
将窗口主题设置为系统默认值(暗/亮)。
仅限 Windows。
WindowSetLightTheme(ctx context.Context)
WindowSetLightTheme()
将窗口主题设置为浅色。
仅限 Windows。
WindowSetDarkTheme(ctx context.Context)
WindowSetDarkTheme()
将窗口主题设置为深色。
显示窗口,如果它当前是隐藏的。
WindowShow(ctx context.Context)
WindowShow()
如果当前可见,则隐藏窗口。
WindowHide(ctx context.Context)
WindowHide()
如果窗口未最小化、最大化或全屏,则返回 true。
WindowIsNormal(ctx context.Context) bool
WindowIsNormal() Promise<boolean>
设置窗口的宽度和高度。
WindowSetSize(ctx context.Context, width int, height int)
WindowSetSize(width: number, height: number)
获取窗口的宽度和高度。
WindowGetSize(ctx context.Context) (width int, height int)
WindowGetSize(): Promise<Size>
设置窗口最小尺寸。 如果窗口当前小于给定尺寸,将调整窗口大小。
设置大小 0,0
将禁用此约束。
WindowSetMinSize(ctx context.Context, width int, height int)
WindowSetMinSize(width: number, height: number)
设置窗口最大尺寸。 如果窗口当前大于给定尺寸,将调整窗口大小。
设置大小 0,0
将禁用此约束。
WindowSetMaxSize(ctx context.Context, width int, height int)
WindowSetMaxSize(width: number, height: number)
设置窗口置顶或取消置顶。
WindowSetAlwaysOnTop(ctx context.Context, b bool)
WindowSetAlwaysOnTop(b: boolean)
设置相对于窗口当前所在监视器的窗口位置。
WindowSetPosition(ctx context.Context, x int, y int)
WindowSetPosition(x: number, y: number)
获取相对于窗口当前所在监视器的窗口位置。
WindowGetPosition(ctx context.Context) (x int, y int)
WindowGetPosition(): Promise<Position>
最大化窗口以填满屏幕。
WindowMaximise(ctx context.Context)
WindowMaximise()
将窗口恢复到最大化之前的尺寸和位置。
WindowUnmaximise(ctx context.Context)
WindowUnmaximise()
如果窗口最大化,则返回 true。
WindowIsMaximised(ctx context.Context) bool
WindowIsMaximised() Promise<boolean>
在最大化和未最大化之间切换。
WindowToggleMaximise(ctx context.Context)
WindowToggleMaximise()
最小化窗口。
WindowMinimise(ctx context.Context)
WindowMinimise()
将窗口恢复到最小化之前的尺寸和位置。
WindowUnminimise(ctx context.Context)
WindowUnminimise()
如果窗口最小化,则返回 true。
WindowIsMinimised(ctx context.Context) bool
WindowIsMinimised() Promise<boolean>
将窗口的背景颜色设置为给定的 RGBA 颜色定义。 这种颜色将显示所有透明像素。
R、G、B 和 A 的有效值为 0-255
。
**注意:**在 Windows 上,仅支持 0 或 255 的 alpha 值。 任何非 0 的值都将被视为 255。
WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)
WindowSetBackgroundColour(R, G, B, A)
打开本地打印对话框。
WindowPrint(ctx context.Context)
WindowPrint()
运行时的这一部分提供对原生对话框的调用,例如文件选择器和消息框。
**注意:**JS 运行时当前不支持对话框。
type OpenDialogOptions struct {
DefaultDirectory string
DefaultFilename string
Title string
Filters []FileFilter
ShowHiddenFiles bool
CanCreateDirectories bool
ResolvesAliases bool
TreatPackagesAsDirectories bool
}
字段 | 描述 | Win | Mac | Linux |
---|---|---|---|---|
DefaultDirectory | 对话框打开时显示的目录 | ✅ | ✅ | ✅ |
DefaultFilename | 默认文件名 | ✅ | ✅ | ✅ |
Title | 对话框的标题 | ✅ | ✅ | ✅ |
Filters | 文件过滤器列表 | ✅ | ✅ | ✅ |
ShowHiddenFiles | 显示系统隐藏的文件 | ✅ | ✅ | |
CanCreateDirectories | 允许用户创建目录 | ✅ | ||
ResolvesAliases | 如果为 true,则返回文件而不是别名 | ✅ | ||
TreatPackagesAsDirectories | 允许导航到包 | ✅ |
type MessageDialogOptions struct {
Type DialogType
Title string
Message string
Buttons []string
DefaultButton string
CancelButton string
}
字段 | 描述 | Win | Mac | Lin |
---|---|---|---|---|
Type | 消息对话框的类型,例如问题、信息... | ✅ | ✅ | ✅ |
Title | 对话框的标题 | ✅ | ✅ | ✅ |
Message | 向用户显示的消息 | ✅ | ✅ | ✅ |
Buttons | 按钮标题列表 | ✅ | ||
DefaultButton | 带有此文本的按钮应被视为默认按钮。 必定 return 。 |
✅ | ✅ | |
CancelButton | 带有此文本的按钮应被视为取消。 必定 escape |
✅ |
Windows 具有标准对话框类型,其中的按钮不可自定义。 返回的值将是以下之一:"Ok"、"Cancel"、"Abort"、"Retry"、"Ignore"、"Yes"、"No"、"Try Again"或"Continue"。
对于问题对话框,默认按钮是 “是”,取消按钮是 “否”。 可以通过将 默认按钮
值设置为 "否"
来改变这一点。
result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "Question",
Message: "Do you want to continue?",
DefaultButton: "No",
})
Linux 有标准的对话框类型,其中的按钮是不可定制的。 返回的值将是以下之一:“Ok”、“Cancel”、“Yes”、“No”。
Mac 上的消息对话框最多可以指定 4 个按钮。 如果没有 DefaultButton
或 CancelButton
给出,第一个按钮被认为是默认的并绑定到 return
键。
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”,则第二个按钮显示为默认值。 当 return
被按下时,则返回数值“two”。
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",
})
const (
InfoDialog DialogType = "info"
WarningDialog DialogType = "warning"
ErrorDialog DialogType = "error"
QuestionDialog DialogType = "question"
)
type FileFilter struct {
DisplayName string // Filter information EG: "Image Files (*.jpg, *.png)"
Pattern string // semi-colon separated list of extensions, EG: "*.jpg;*.png"
}
Windows 允许您在对话框中使用多个文件过滤器。 每个 FileFilter 将在对话框中显示为一个单独的条目:
Linux 允许您在对话框中使用多个文件过滤器。 每个 FileFilter 将在对话框中显示为一个单独的条目:
Mac 对话框只有一组模式来过滤文件的概念。 如果提供了多个 FileFilters,Wails 将使用所有定义的模式。
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",
},
},
})
这将导致使用 *.png,*.jpg,*.mov,*.mp4
作为过滤器打开文件对话框。
打开一个对话框,提示用户选择目录。
Go: OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)
返回值: 所选目录(如果用户取消则为空白)或错误
打开一个对话框,提示用户选择文件。
Go: OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)
返回值: 所选文件(如果用户取消则为空白)或错误
打开一个对话框,提示用户选择多个文件。
Go: OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)
返回值: 选定的文件(如果用户取消则为 nil)或错误
打开一个对话框,提示用户选择文件名以进行保存。
Go: SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)
返回值: 所选文件(如果用户取消则为空白)或错误
使用消息对话框显示消息。
Go: MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)
返回值: 所选按钮的文本或错误
这些方法与应用程序菜单相关。
**注意:**JS 运行时当前不支持菜单。
type Menu struct {
Items []*MenuItem
}
提供了一个简单的辅助方法来构建菜单:
func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *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
}
字段 | 类型 | 注解 |
---|---|---|
Label |
string |
菜单文字 |
Accelerator |
*keys.Accelerator |
此菜单项的键绑定 |
Type |
Type |
菜单项的类型 |
Disabled |
bool |
禁用菜单项 |
Hidden |
bool |
隐藏此菜单项 |
Checked |
bool |
添加检查项目 (复选框和单选类型) |
SubMenu |
*Menu |
设置子菜单 |
Click |
Callback |
单击菜单时的回调函数 |
Role |
string |
定义此菜单项的角色。 暂时只支持 Mac |
键盘快捷键定义了按键和菜单项之间的绑定。 Wails 将加速器定义为一个组合或键 + 修饰符。 它们在 "github.com/wailsapp/wails/v2/pkg/menu/keys"
包中提供。
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut := keys.CmdOrCtrl("o")
Wails 还支持使用与 Electron 相同的语法来解析快捷键。 这对于将快捷键存储在配置文件中很有用。
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut, err := keys.Parse("Ctrl+Option+A")
以下修饰符是可以与快捷键结合使用的键:
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"
)
许多辅助方法可用于使用修饰符创建快捷键:
func CmdOrCtrl(key string) *Accelerator
func OptionOrAlt(key string) *Accelerator
func Shift(key string) *Accelerator
func Control(key string) *Accelerator
可以使用 keys.Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)
用以下方式组合修饰符 :
// Defines "Ctrl+Option+A" on Mac and "Ctrl+Alt+A" on Window/Linux
myShortcut := keys.Combo("a", ControlKey, OptionOrAltKey)
每个菜单项必须有一个类型,有 5 种类型可用:
const (
TextType Type = "Text"
SeparatorType Type = "Separator"
SubmenuType Type = "Submenu"
CheckboxType Type = "Checkbox"
RadioType Type = "Radio"
)
为方便起见,提供了帮助方法来快速创建菜单项:
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
您还可以使用addXXX
方法直接在菜单上创建指定类型的菜单项:
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
type Callback func(*CallbackData)
type CallbackData struct {
MenuItem *MenuItem
}
该函数被赋予一个 CallbackData
结构,该结构指示哪个菜单项触发了回调。 这在使用可能共享回调的单选组时很有用。
**注意:**目前仅 Mac 支持角色。
一个菜单项可能有一个角色,它本质上是一个预定义的菜单项。 我们目前支持以下角色:
角色 | 描述 |
---|---|
AppMenuRole |
标准的 Mac 应用程序菜单。 可以使用 menu.AppMenu() 创建 |
EditMenuRole |
标准的 Mac 编辑菜单。 可以使用 menu.EditMenu() 创建 |
将应用程序菜单设置为给定的菜单。
Go: MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)
获取传递给 MenuSetApplicationMenu
的菜单的任意更改更新应用程序菜单。
Go: MenuUpdateApplicationMenu(ctx context.Context)
app := NewApp()
// 创建菜单
AppMenu := menu.NewMenu()
// 创建子菜单
FileMenu := AppMenu.AddSubmenu("File")
// 创建类型为 Text 的菜单项
FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile)
// 创建分隔线
FileMenu.AddSeparator()
// 创建类型为 Text 的菜单项
FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) {
runtime.Quit(app.ctx)
})
// 判断如果是 Mac,则创建默认的角色菜单
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,
},
)
运行时的这一部分提供了对操作系统剪贴板的访问。
当前实现仅处理文本。
从剪切板读取当前存储的文本。
ClipboardGetText(ctx context.Context) (string, error)
ClipboardGetText(): Promise<string>
将文本写入剪切板。
Go: ClipboardSetText(ctx context.Context, text string) error
JS: ClipboardSetText(text: string): Promise<boolean>
这些方法提供有关当前连接屏幕的信息。
type Screen struct {
IsCurrent bool
IsPrimary bool
Width int
Height int
}
interface Screen {
isCurrent: boolean;
isPrimary: boolean;
width : number
height : number
}
返回当前连接屏幕的列表。
ScreenGetAll(ctx context.Context) []screen
ScreenGetAll()
运行时的这一部分处理将文件或文件夹拖放到窗口中的操作。
要启用此功能,必须在 options.App
中将 EnableFileDrop
设置为 true
。
这个方法是注册文件或文件夹拖放到窗口时回调函数
Go: OnFileDrop(ctx context.Context, callback func(x, y int, paths []string))
JS: OnFileDrop(callback: (x: number, y: number, paths: string[]) => void, useDropTarget: boolean) :void
调用回调函数,其中包含释放拖动时窗口内的坐标和绝对文件路径。
此方法会移除所有已注册的拖放事件侦听器和处理程序。
OnFileDropOff(ctx context.Context)
OnFileDropOff(): void