### Wails project info for NSIS installer Source: https://wails.io/ru/docs/guides/windows-installer Example JSON structure within `installer/info.json` that Wails reads to configure the NSIS installer. It includes company name, product name, version, copyright, and comments. ```json // ... "Info": { "companyName": "My Company Name", "productName": "Wails Vite", "productVersion": "1.0.0", "copyright": "Copyright.........", "comments": "Built using Wails (https://wails.io)" }, // ... ``` -------------------------------- ### Basic Wails Application Structure (Go) Source: https://wails.io/ru/docs/v2.9.0/howdoesitwork A fundamental Wails application setup using Go. It demonstrates the use of `wails.Run()` with essential configuration options, including embedding frontend assets, setting window properties, and defining startup/shutdown callbacks. This code also shows how to bind Go methods for use in the frontend. ```go package main import ( "embed" "log" "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" ) //go:embed all:frontend/dist var assets embed.FS func main() { app := &App{} err := wails.Run(&options.App{ Title: "Basic Demo", Width: 1024, Height: 768, AssetServer: &assetserver.Options{ Assets: assets, }, OnStartup: app.startup, OnShutdown: app.shutdown, Bind: []interface{}{ app, }, }) if err != nil { log.Fatal(err) } } type App struct { ctx context.Context } func (b *App) startup(ctx context.Context) { b.ctx = ctx } func (b *App) shutdown(ctx context.Context) {} func (b *App) Greet(name string) string { return fmt.Sprintf("Hello %s!", name) } ``` -------------------------------- ### Install NSIS with Scoop Source: https://wails.io/ru/docs/guides/windows-installer Installs the NSIS installer using the Scoop package manager. This command adds the 'extras' bucket and then installs NSIS. ```bash scoop bucket add extras scoop install nsis ``` -------------------------------- ### Example: Initialize Wails Project with Vue Template Source: https://wails.io/ru/docs/v2.9.0/community/templates This is an example of initializing a Wails project using a Vue template from a GitHub repository. The command specifies the project name and the URL of the template. ```bash wails init -n "Project Name" -t https://github.com/misitebao/wails-template-vue ``` -------------------------------- ### Install NSIS with Chocolatey Source: https://wails.io/ru/docs/guides/windows-installer Installs the NSIS installer using the Chocolatey package manager. Requires running a script. ```bash choco install nsis ``` -------------------------------- ### Initialize Project from Wails Template Source: https://wails.io/ru/docs/guides/templates Command to initialize a new Wails project using a specified template. This allows users to start new projects based on custom or community templates. ```shell wails init -n my-vue3-project -t .\wails-vue3-template\ ``` -------------------------------- ### Generate NSIS Installer with Wails Source: https://wails.io/ru/docs/guides/windows-installer Command to generate the NSIS installer for a Wails project. The installer will be placed in the `build/bin` directory. ```bash wails build -nsis ``` -------------------------------- ### Install NSIS with Winget Source: https://wails.io/ru/docs/guides/windows-installer Installs the NSIS installer silently using the Winget package manager on Windows 10+. ```bash winget install NSIS.NSIS --silent ``` -------------------------------- ### Go: Setting Proxy Configuration Source: https://wails.io/ru/docs/guides/troubleshooting Configures Go environment variables to use a specific proxy server, which can resolve installation issues caused by network restrictions or blocked official Go proxies. ```bash go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct ``` -------------------------------- ### Configure nfpm for Linux Package with Custom Protocol Source: https://wails.io/ru/docs/v2.9.0/guides/custom-protocol-schemes An example nfpm configuration file for creating a Linux package. It specifies the application binary, the .desktop file for protocol association, and an application icon. ```yaml name: "wails-open-file" arch: "arm64" platform: "linux" version: "1.0.0" section: "default" priority: "extra" maintainer: "FooBarCorp " description: "Sample Package" vendor: "FooBarCorp" homepage: "http://example.com" license: "MIT" contents: - src: ../bin/wails-open-file dst: /usr/bin/wails-open-file - src: ./main.desktop dst: /usr/share/applications/wails-open-file.desktop - src: ../appicon.svg dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg ``` -------------------------------- ### VS Code tasks.json for projects with frontend build steps Source: https://wails.io/ru/docs/guides/ides This Visual Studio Code tasks.json file configures tasks for projects that include frontend build processes. It defines separate tasks for 'npm install' and 'npm run build', and a main 'build' task that depends on these frontend steps before executing the Go build command. ```json { "version": "2.0.0", "tasks": [ { "label": "npm install", "type": "npm", "script": "install", "options": { "cwd": "${workspaceFolder}/frontend" }, "presentation": { "clear": true, "panel": "shared", "showReuseMessage": false }, "problemMatcher": [] }, { "label": "npm run build", "type": "npm", "script": "build", "options": { "cwd": "${workspaceFolder}/frontend" }, "presentation": { "clear": true, "panel": "shared", "showReuseMessage": false }, "problemMatcher": [] }, { "label": "build", "type": "shell", "options": { "cwd": "${workspaceFolder}" }, "command": "go", "args": [ "build", "-tags", "dev", "-gcflags", "all=-N -l", "-o", "build/bin/vscode.exe" ], "dependsOn": ["npm install", "npm run build"] } ] } ``` -------------------------------- ### Linux Build with Webkit Flag Source: https://wails.io/ru/docs/gettingstarted/building For Linux distributions that do not have webkit2gtk-4.0 installed (e.g., Ubuntu 24.04), use this flag during the build process. This ensures proper compilation on such systems. ```bash wails build -tags webkit2_41 ``` -------------------------------- ### Handle Custom URL Arguments on Windows (New Instance) Source: https://wails.io/ru/docs/v2.9.0/guides/custom-protocol-schemes Parses command-line arguments in a Wails application for Windows when a custom protocol URL is opened. Each custom URL launch starts a new instance of the app. ```go argsWithoutProg := os.Args[1:] if len(argsWithoutProg) != 0 { println("launchArgs", argsWithoutProg) } ``` -------------------------------- ### Create Wails Template from Existing Vue 3 Project Source: https://wails.io/ru/docs/guides/templates Steps to create a Wails template from an existing Vue 3 project using the Wails CLI. This involves installing Vue CLI, creating a base Vue 3 project, and then using 'wails generate template' with the frontend project path. ```shell npm install -g @vue/cli vue create vue3-base wails generate template -name wails-vue3-template -frontend .\vue3-base\ ``` -------------------------------- ### Configure Wails for Angular Dev Mode Source: https://wails.io/ru/docs/next/guides/angular These settings in the wails.json file enable Wails' developer mode for Angular projects. They specify the commands for frontend installation, building, and running the development server, along with the server URL. ```json { "frontend:build": "npx ng build", "frontend:install": "npm install", "frontend:dev:watcher": "npx ng serve", "frontend:dev:serverUrl": "http://localhost:4200" } ``` -------------------------------- ### Initialize a new Wails project Source: https://wails.io/ru/docs/tutorials/helloworld Creates a new Wails project using the vanilla JavaScript template. This command sets up the basic file structure for a Wails application. ```bash wails init -n helloworld ``` -------------------------------- ### Build a Wails application Source: https://wails.io/ru/docs/tutorials/helloworld Compiles the Wails application for the target platform. This command handles both the frontend and backend compilation. Ensure you are in the project directory before running. ```bash wails build ``` -------------------------------- ### Initialize a new Wails application (JS) Source: https://wails.io/ru/docs/next/tutorials/helloworld This command initializes a new Wails project with the standard JavaScript template. It creates a project directory and populates it with necessary files for frontend and backend development. ```bash wails init -n helloworld ``` -------------------------------- ### Просмотр опций инициализации Wails CLI Source: https://wails.io/ru/docs/gettingstarted/firstproject Отображает доступные опции и шаблоны для команды `wails init`, позволяя пользователям узнать о различных возможностях и фреймворках, включая шаблоны сообщества. ```bash wails init -help ``` -------------------------------- ### Wails Project Structure Overview Source: https://wails.io/ru/docs/v2.9.0/gettingstarted/firstproject Illustrates the typical directory structure of a Wails project. It highlights key directories and files such as the main Go application file, frontend assets, build configurations, and project metadata. ```text . ├── build/ │ ├── appicon.png │ ├── darwin/ │ └── windows/ ├── frontend/ ├── go.mod ├── go.sum ├── main.go └── wails.json ``` -------------------------------- ### Running the Wails Application Source: https://wails.io/ru/docs/v2.9.0/tutorials/helloworld Details on how to launch the compiled Wails application on different operating systems. For Windows, it's an .exe file; for macOS, a .app bundle; and for Linux, an executable file. ```text On Mac, Wails generates a 'helloworld.app' file which can be launched by double-clicking. On Linux you can launch the application using the './helloworld' file from the 'build/bin' directory. ``` -------------------------------- ### Пример ошибки при неверной версии Go Source: https://wails.io/ru/docs/v2.9.0/gettingstarted/installation Этот фрагмент кода демонстрирует пример ошибки, которая может возникнуть, если установлена версия Go ниже 1.18, необходимая для корректной работы Wails. ```go ....\Go\pkg\mod\github.com\wailsapp\wails\v2@v2.1.0\pkg\templates\templates.go:28:12: pattern all:ides/*: no matching files found ``` -------------------------------- ### Running a Wails application on different platforms Source: https://wails.io/ru/docs/next/tutorials/helloworld Instructions on how to execute the compiled Wails application on Windows, macOS, and Linux. This involves locating the executable in the build output directory. ```text On Mac, Wails generates a `helloworld.app` file which can be launched by double clicking. On Linux you can run the application using the `./helloworld` file from the `build/bin` directory. ``` -------------------------------- ### Project Structure Explanation Source: https://wails.io/ru/docs/next/tutorials/helloworld An overview of the generated project files and their purpose within a Wails application. This includes build artifacts, frontend assets, application logic, and configuration files. ```text build/ - Contains the build files + compiled application frontend/ - Contains the frontend files app.go - Contains the application code main.go - The main program with the application configuration wails.json - The project configuration file go.mod - The go module file go.sum - The go module checksum file ``` -------------------------------- ### Проверка переменной PATH для Go Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда проверяет, включен ли каталог bin Go в переменную окружения PATH. ```shell echo $PATH | grep go/bin ``` -------------------------------- ### Проверка установки Go Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда используется для проверки правильности установки Go и версии. ```shell go version ``` -------------------------------- ### Установка Wails CLI Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда устанавливает последнюю версию Wails CLI с использованием Go. ```shell go install github.com/wailsapp/wails/v2/cmd/wails@latest ``` -------------------------------- ### Инициализация проекта Vanilla (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с использованием Vanilla JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t vanilla ``` -------------------------------- ### Инициализация проекта Vanilla (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с использованием Vanilla TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t vanilla-ts ``` -------------------------------- ### Wails Project File Descriptions Source: https://wails.io/ru/docs/v2.9.0/gettingstarted/firstproject Provides a brief explanation of the purpose of each file and directory within a standard Wails project. This includes details on the main application file, frontend directory, build artifacts, and configuration files. ```text * /main.go - основное приложение * /frontend/ - фронтенд файлы проекта * /build/ - директория сборки проекта * /build/appicon.png - значок приложения * /build/darwin/ - файлы проекта для Mac * /build/windows/ - файлы проектов, специфичных для Windows * /wails.json - Конфигурация проекта * /go.mod - Go module файл * /go.sum - Go module проверочная сумма ``` -------------------------------- ### Initialize Wails Project with a Template Source: https://wails.io/ru/docs/v2.9.0/community/templates This command initializes a new Wails project with a specified template. You can use a URL to a template repository, optionally including a version tag. If no version suffix is provided, the main branch's template is used. ```bash wails init -n "Your Project Name" -t [template_url[@version]] ``` -------------------------------- ### Определение пакетов для Apt Manager в Wails Source: https://wails.io/ru/docs/next/guides/linux-distro-support Этот код показывает, как определить список пакетов для менеджера пакетов Apt в Wails. Он включает имена пакетов, необходимые для зависимостей, таких как GTK, WebKit, GCC, pkg-config, npm и Docker. ```go func (a *Apt) Packages() packagemap { return packagemap{ "libgtk-3": []*Package{ {Name: "libgtk-3-dev", SystemPackage: true, Library: true}, }, "libwebkit": []*Package{ {Name: "libwebkit2gtk-4.0-dev", SystemPackage: true, Library: true}, }, "gcc": []*Package{ {Name: "build-essential", SystemPackage: true}, }, "pkg-config": []*Package{ {Name: "pkg-config", SystemPackage: true}, }, "npm": []*Package{ {Name: "npm", SystemPackage: true}, }, "docker": []*Package{ {Name: "docker.io", SystemPackage: true, Optional: true}, }, } } ``` -------------------------------- ### Инициализация проекта Svelte (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Svelte, используя JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t svelte ``` -------------------------------- ### Build Wails Project Source: https://wails.io/ru/docs/gettingstarted/building This command compiles the Wails project and outputs a release-ready binary to the `build/bin` directory. Ensure you are in the project's root directory when executing. ```bash wails build ``` -------------------------------- ### Build and Run Wails Project Source: https://wails.io/ru/docs/guides/templates Commands to build a Wails project and then run the compiled executable. This is typically done after initializing a project from a template or creating a new project. ```shell cd my-vue3-project wails build .\build\bin\my-vue3-project.exe ``` -------------------------------- ### Добавление имен пакетов для Apt в Go Source: https://wails.io/ru/docs/guides/linux-distro-support Пример определения пакетов для менеджера пакетов Apt в Wails. Метод `Packages()` возвращает `packagemap`, где ключи - это абстрактные имена зависимостей, а значения - срезы `Package`, содержащие реальные имена системных пакетов. Этот код демонстрирует, как добавить альтернативное имя пакета ('lib-gtk3-dev') для зависимости 'libgtk-3'. ```Go func (a *Apt) Packages() packagemap { return packagemap{ "libgtk-3": []*Package{ {Name: "libgtk-3-dev", SystemPackage: true, Library: true}, {Name: "lib-gtk3-dev", SystemPackage: true, Library: true}, }, "libwebkit": []*Package{ {Name: "libwebkit2gtk-4.0-dev", SystemPackage: true, Library: true}, }, "gcc": []*Package{ {Name: "build-essential", SystemPackage: true}, }, "pkg-config": []*Package{ {Name: "pkg-config", SystemPackage: true}, }, "npm": []*Package{ {Name: "npm", SystemPackage: true}, }, "docker": []*Package{ {Name: "docker.io", SystemPackage: true, Optional: true}, }, } } ``` -------------------------------- ### Инициализация проекта Preact (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Preact, используя JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t preact ``` -------------------------------- ### Инициализация проекта Preact (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Preact, используя TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t preact-ts ``` -------------------------------- ### Инициализация проекта Svelte (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Svelte, используя TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t svelte-ts ``` -------------------------------- ### Wails Apt Packages Go Source: https://wails.io/ru/docs/v2.9.0/guides/linux-distro-support Определяет карту пакетов для пакетного менеджера apt, используемого Wails. Эта карта связывает общие имена зависимостей с их соответствующими именами пакетов в системе. ```go func (a *Apt) Packages() packagemap { return packagemap{ "libgtk-3": []*Package{ {Name: "libgtk-3-dev", SystemPackage: true, Library: true}, }, "libwebkit": []*Package{ {Name: "libwebkit2gtk-4.0-dev", SystemPackage: true, Library: true}, }, "gcc": []*Package{ {Name: "build-essential", SystemPackage: true}, }, "pkg-config": []*Package{ {Name: "pkg-config", SystemPackage: true}, }, "npm": []*Package{ {Name: "npm", SystemPackage: true}, }, "docker": []*Package{ {Name: "docker.io", SystemPackage: true, Optional: true}, }, } } ``` -------------------------------- ### Go: Backend Method with Variadic Arguments Source: https://wails.io/ru/docs/guides/troubleshooting Demonstrates how to define a backend method in Go that accepts a variable number of arguments. This is often used for flexible logging or event handling. ```go func (a *App) TestFunc(msg string, args ...interface{}) error { // Code } ``` -------------------------------- ### Create Keyboard Accelerator in Go Source: https://wails.io/ru/docs/reference/menus Shows how to define a keyboard shortcut (accelerator) for a menu item using the Wails `keys` package. It demonstrates creating a shortcut that works across different operating systems (e.g., Cmd+O on macOS, Ctrl+O on Windows/Linux). ```go package github.com/wailsapp/wails/v2/pkg/menu/keys // Defines cmd+o on Mac and ctrl-o on Window/Linux myShortcut := keys.CmdOrCtrl("o") ``` -------------------------------- ### Обзор структуры проекта Wails Source: https://wails.io/ru/docs/gettingstarted/firstproject Демонстрирует стандартную структуру каталогов и файлов для нового проекта Wails, включая директории для фронтенда, сборки, конфигурации и основного кода Go. ```tree . ├── build/ │ ├── appicon.png │ ├── darwin/ │ └── windows/ ├── frontend/ ├── go.mod ├── go.sum ├── main.go └── wails.json ``` -------------------------------- ### Инициализация проекта Lit (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Lit, используя TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t lit-ts ``` -------------------------------- ### Инициализация проекта React (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком React, используя JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t react ``` -------------------------------- ### Create and Configure Application Menu in Go Source: https://wails.io/ru/docs/reference/menus Demonstrates creating a Wails application menu with submenus, text items, separators, and platform-specific additions like the Edit menu for macOS. It shows how to bind a Go struct to the Wails runtime and run the application with the defined menu. ```go package main import ( "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/menu" "github.com/wailsapp/wails/v2/pkg/menu/keys" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/runtime" ) func main() { 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, }, }) // ... } // Placeholder for the openFile function func openFile(_ *menu.CallbackData) { // Implementation to open a file } // Placeholder for the App struct and NewApp function type App struct { ctx runtime.Context } func NewApp() *App { return &App{} } ``` -------------------------------- ### Инициализация проекта Lit (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Lit, используя JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t lit ``` -------------------------------- ### Инициализация проекта React (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком React, используя TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t react-ts ``` -------------------------------- ### Установка инструментов командной строки Xcode Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда устанавливает инструменты командной строки Xcode, необходимые для macOS. ```shell xcode-select --install ``` -------------------------------- ### Инициализация проекта Vue (JavaScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Vue, используя JavaScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t vue ``` -------------------------------- ### Accelerator Definition Source: https://wails.io/ru/docs/reference/menus Explains how to define keyboard shortcuts (accelerators) for menu items using the `keys` package. ```APIDOC ## Accelerator Definition ### Description Accelerators, or keyboard shortcuts, link a key combination to a menu item. Wails provides the `keys` package for defining these shortcuts in a platform-aware manner. ### Package `github.com/wailsapp/wails/v2/pkg/menu/keys` ### Defining Accelerators Use helper functions like `CmdOrCtrl()` for common shortcuts or `Parse()` for custom combinations. ### Example 1: Using `CmdOrCtrl` ```go // Defines cmd+o on Mac and ctrl-o on Window/Linux myShortcut := keys.CmdOrCtrl("o") ``` ### Example 2: Using `Parse` ```go // Defines a custom shortcut, e.g., Ctrl+Shift+A myShortcut, err := keys.Parse("Ctrl+Shift+A") ``` ### Supported Keys Special keys like `backspace`, `tab`, `enter`, `escape`, arrow keys (`left`, `right`, `up`, `down`), `space`, `delete`, `home`, `end`, `page up`, `page down`, and function keys (`f1` through `f39`) are supported. The `+` key is represented as `plus`. ``` -------------------------------- ### Initialize a new Wails project Source: https://wails.io/ru/docs/reference/cli The 'wails init' command is used to generate new Wails projects. It supports various flags for customizing project name, directory, Git initialization, template selection (including remote GitHub templates), and IDE project file generation. ```bash wails init -n "project name" -d "project dir" -g -l -q -t "template name" -ide vscode -f ``` ```bash wails init -n test -d mytestproject -g -ide vscode -q ``` ```bash wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0] ``` -------------------------------- ### HTML: Отображение изображения с использованием относительного пути Source: https://wails.io/ru/docs/next/guides/dynamic-assets Этот пример показывает, как обновить HTML-шаблон для отображения изображения, используя относительный путь. Заменяет стандартный элемент img на новый, указывающий на 'build/appicon.png' и устанавливая стиль ширины. ```HTML ``` ```HTML ``` -------------------------------- ### JavaScript: Calling Backend Variadic Methods Source: https://wails.io/ru/docs/guides/troubleshooting Illustrates how to call Go backend methods with variadic arguments from JavaScript. It shows the correct way to pass an array of arguments to avoid errors. ```javascript var msg = "Hello "; var args = ["Go", "JS"]; window.go.main.App.TestFunc(msg, args) .then((result) => { //without the 3 dots //do things here }) .catch((error) => { //handle error }); ``` -------------------------------- ### Проверка версии NPM Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда используется для проверки правильности установки NPM и его версии. ```shell npm --version ``` -------------------------------- ### Инициализация проекта Vue (TypeScript) Source: https://wails.io/ru/docs/gettingstarted/firstproject Создает новый Wails проект с фреймворком Vue, используя TypeScript. Не требует внешних зависимостей, кроме установленного Wails CLI. ```bash wails init -n myproject -t vue-ts ``` -------------------------------- ### Build a Wails project for production Source: https://wails.io/ru/docs/reference/cli The 'wails build' command compiles your Wails project into a production-ready binary. It offers extensive flags for cleaning build directories, specifying compilers, enabling debugging and devtools, obfuscation, platform targeting, and more. ```bash wails build -clean -compiler "compiler" -debug -devtools -dryrun -f -garbleargs "-literals -tiny -seed=random" -ldflags "flags" -m -nopackage -nocolour -nosyncgomod -nsis -o filename -obfuscated -platform "windows/arm64" -race -s -skipbindings -tags "extra tags" -trimpath -u -upx -upxflags "flags" -v 2 -webview2 download -windowsconsole ``` ```bash wails build -clean -o myproject.exe ``` -------------------------------- ### Application Menu Configuration Source: https://wails.io/ru/docs/reference/menus This snippet demonstrates how to create and configure an application menu by defining a Menu struct and setting it in the application options. ```APIDOC ## Application Menu Configuration ### Description This section details how to integrate a custom application menu into your Wails project. It involves defining a `Menu` struct and associating it with the application's configuration. ### Method Configuration within `wails.Run` ### Endpoint N/A (Configuration) ### Parameters #### Request Body (Implicit in `wails.Run` options) - **Title** (string) - Required - The title of the application window. - **Width** (int) - Required - The width of the application window. - **Height** (int) - Required - The height of the application application window. - **Menu** (*menu.Menu) - Optional - A pointer to the application's menu structure. - **Bind** ([]interface{}) - Optional - A slice of interfaces to be bound to the frontend. ### Request Example ```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, }, }) // ... ``` ### Response #### Success Response (N/A) Configuration does not return a direct response, but successful execution leads to an application window with the defined menu. #### Response Example N/A ``` -------------------------------- ### Parse Keyboard Accelerator String in Go Source: https://wails.io/ru/docs/reference/menus Demonstrates parsing a keyboard accelerator string into a Wails `Accelerator` object, similar to Electron's syntax. This is useful for defining shortcuts in configuration files. ```go 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") ``` -------------------------------- ### Инициализация проекта Wails с использованием шаблона Source: https://wails.io/ru/docs/community/templates Эта команда используется для инициализации нового проекта Wails с использованием указанного шаблона. Параметр `-n` задает имя проекта, а `-t` указывает URL репозитория шаблона. При отсутствии суффикса версии используется основной шаблон ветки. ```bash wails init -n "Название вашего проекта" -t [ссылка ниже[@version]] ``` ```bash wails init -n "Project Name" -t https://github.com/misitebao/wails-template-vue ``` -------------------------------- ### VS Code launch.json for debugging Wails projects Source: https://wails.io/ru/docs/guides/ides This Visual Studio Code launch configuration enables debugging of Wails applications. It specifies the executable to run, the build task to execute beforehand, and sets the working directory. ```json { "version": "0.2.0", "configurations": [ { "name": "Wails: Debug myproject", "type": "go", "request": "launch", "mode": "exec", "program": "${workspaceFolder}/build/bin/myproject.exe", "preLaunchTask": "build", "cwd": "${workspaceFolder}", "env": {} } ] } ``` -------------------------------- ### Интерфейс менеджера пакетов в Go Source: https://wails.io/ru/docs/guides/linux-distro-support Определение интерфейса `PackageManager` в Wails, который описывает контракт для всех менеджеров пакетов. Каждый менеджер пакетов должен реализовать эти методы для взаимодействия с системой. Методы включают получение имени менеджера, списка пакетов, проверку установки и доступности пакета, а также команду установки. ```Go type PackageManager interface { Name() string Packages() packagemap PackageInstalled(*Package) (bool, error) PackageAvailable(*Package) (bool, error) InstallCommand(*Package) string } ``` -------------------------------- ### Create Linux .desktop File for Custom Protocol Source: https://wails.io/ru/docs/v2.9.0/guides/custom-protocol-schemes Defines a .desktop file for a Linux application to associate it with a custom protocol scheme ('myapp'). The `Exec` line includes `%u` to pass the URL to the application. ```ini [Desktop Entry] Categories=Office Exec=/usr/bin/wails-open-file %u Icon=wails-open-file.png Name=wails-open-file Terminal=false Type=Application MimeType=x-scheme-handler/myapp; ``` -------------------------------- ### Запуск Wails приложения в режиме разработки Source: https://wails.io/ru/docs/gettingstarted/development Команда для запуска приложения Wails в режиме разработки. Автоматически собирает приложение, привязывает Go-код к фронтенду, наблюдает за изменениями в Go-файлах и запускает веб-сервер. ```bash wails dev ``` -------------------------------- ### Wails Apt Packages with Custom Name Go Source: https://wails.io/ru/docs/v2.9.0/guides/linux-distro-support Демонстрирует добавление альтернативного имени пакета для зависимости 'libgtk-3' в пакетном менеджере apt. Это полезно, когда пакеты имеют разные имена в разных дистрибутивах. ```go func (a *Apt) Packages() packagemap { return packagemap{ "libgtk-3": []*Package{ {Name: "libgtk-3-dev", SystemPackage: true, Library: true}, {Name: "lib-gtk3-dev", SystemPackage: true, Library: true}, }, "libwebkit": []*Package{ {Name: "libwebkit2gtk-4.0-dev", SystemPackage: true, Library: true}, }, "gcc": []*Package{ {Name: "build-essential", SystemPackage: true}, }, "pkg-config": []*Package{ {Name: "pkg-config", SystemPackage: true}, }, "npm": []*Package{ {Name: "npm", SystemPackage: true}, }, "docker": []*Package{ {Name: "docker.io", SystemPackage: true, Optional: true}, }, } } ``` -------------------------------- ### GitHub Actions Workflow for Cross-Platform Wails Builds Source: https://wails.io/ru/docs/v2.9.0/guides/crossplatform-build This workflow automates the building of a Wails application for Linux, Windows, and macOS whenever a new Git tag is pushed. It uses the 'dAppServer/wails-build-action' to handle the build process, specifying build names, platforms, and Go versions. ```yaml name: Wails build on: push: tags: # Match any new tag - '*' env: # Necessary for most environments as build failure can occur due to OOM issues NODE_OPTIONS: "--max-old-space-size=4096" jobs: build: strategy: # Failure in one platform build won't impact the others fail-fast: false matrix: build: - name: 'App' platform: 'linux/amd64' os: 'ubuntu-latest' - name: 'App' platform: 'windows/amd64' os: 'windows-latest' - name: 'App' platform: 'darwin/universal' os: 'macos-latest' runs-on: ${{ matrix.build.os }} steps: - name: Checkout uses: actions/checkout@v2 with: submodules: recursive - name: Build wails uses: dAppServer/wails-build-action@v2.2 id: build with: build-name: ${{ matrix.build.name }} build-platform: ${{ matrix.build.platform }} package: false go-version: '1.20' ``` -------------------------------- ### Set Application Menu in Go Source: https://wails.io/ru/docs/next/reference/runtime/menu Sets the application menu for the Wails application. This function takes a context and a menu object as input. ```Go MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu) ``` -------------------------------- ### Generate Wails Template from Existing Project Source: https://wails.io/ru/docs/next/guides/templates Command to create a Wails template from an existing frontend project. It extracts files, migrates project files, and renames package manager files. ```bash wails generate template -name wails-vue3-template -frontend .\vue3-base\ ``` -------------------------------- ### React Routing with HashRouter Source: https://wails.io/ru/docs/v2.9.0/guides/routing Illustrates how to set up React Router using `HashRouter` for hash-based navigation within a Wails application, including basic route definitions. ```javascript import { HashRouter } from "react-router-dom"; import { Routes, Route } from "react-router-dom"; ReactDOM.render( {/* The rest of your app goes here */} } exact /> } /> } /> {/* more... */} , root ); ``` -------------------------------- ### Create Menu from Items in Go Source: https://wails.io/ru/docs/reference/menus Provides a helper function signature in Go for creating a Wails menu directly from a list of menu items. This simplifies menu construction by allowing items to be passed during menu creation. ```go package github.com/wailsapp/wails/v2/pkg/menu func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu ``` -------------------------------- ### Enable Single Instance Lock in Go Source: https://wails.io/ru/docs/v2.9.0/guides/single-instance-lock This Go code snippet demonstrates how to enable and configure the single instance lock for a Wails application. It includes setting a unique identifier and defining a callback function (`onSecondInstanceLaunch`) that is executed when a second instance of the application is launched, handling the arguments passed to it and bringing the application window to the front. ```go package main import ( "strings" "context" "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" "github.com/wailsapp/wails/v2/pkg/runtime" ) var wailsContext *context.Context var secondInstanceArgs []string // App struct type App struct {} // NewApp creates a new App application struct func NewApp() *App { return &App{} } // startup is called when the app starts. The context is saved // so we can call the runtime methods func (a *App) startup(ctx context.Context) { wailsContext = &ctx } func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { secondInstanceArgs = secondInstanceData.Args println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) println("user opened second from", secondInstanceData.WorkingDirectory) runtime.WindowUnminimise(*wailsContext) runtime.Show(*wailsContext) go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) } func main() { // Create an instance of the app structure app := NewApp() // Create application with options err := wails.Run(&options.App{ Title: "wails-open-file", Width: 1024, Height: 768, AssetServer: &assetserver.Options{ Assets: assets, }, BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, OnStartup: app.startup, SingleInstanceLock: &options.SingleInstanceLock{ UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", // Replace with your app's UUID OnSecondInstanceLaunch: app.onSecondInstanceLaunch, }, Bind: []interface{}{ app, }, }) if err != nil { println("Error:", err.Error()) } } ``` -------------------------------- ### Проверка зависимостей Wails Source: https://wails.io/ru/docs/gettingstarted/installation Эта команда запускает утилиту 'doctor' Wails для проверки установленных зависимостей и выявления недостающих. ```shell wails doctor ```