### Wails Project Info Configuration Source: https://wails.io/docs/guides/windows-installer Example of the `Info` section in `wails.json` used to configure installer details. ```json // ... "Info": { "companyName": "My Company Name", "productName": "Wails Vite", "productVersion": "1.0.0", "copyright": "Copyright.........", "comments": "Built using Wails (https://wails.io)" }, ``` -------------------------------- ### Bash Script for SvelteKit Wails Setup Source: https://wails.io/docs/guides/sveltekit A bash script to automate the Wails + SvelteKit installation steps, with optional Wails branding. ```bash manager=$1 project=$2 brand=$3 wails init -n $project -t svelte cd $project sed -i "s|npm|$manager|g" wails.json sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json sed -i "s|all:frontend/dist|all:frontend/build|" main.go if [[ -n $brand ]]; then mv frontend/src/App.svelte +page.svelte sed -i "s|'./assets|'\$lib/assets|" +page.svelte sed -i "s|'../wails|'\$lib/wails|" +page.svelte mv frontend/src/assets . fi rm -r frontend $manager create svelte@latest frontend if [[ -n $brand ]]; then mv +page.svelte frontend/src/routes/+page.svelte mkdir frontend/src/lib mv assets frontend/src/lib/ fi cd frontend $manager i $manager uninstall @sveltejs/adapter-auto $manager i -D @sveltejs/adapter-static echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts sed -i "s|-auto';|-static';|" svelte.config.js cd .. wails dev ``` -------------------------------- ### Example Info.plist Source: https://wails.io/docs/guides/signing An example Info.plist file that should have its bundle ID updated to match the one specified in gon-sign.json. ```xml ``` -------------------------------- ### Full CI/CD Workflow Example with Signing Source: https://wails.io/docs/guides/signing This is a comprehensive GitHub Actions workflow that builds a Wails application for both Windows and macOS, and includes a step to sign the Windows binaries using PowerShell commands. It demonstrates the complete setup from checking out code to uploading artifacts. ```yaml name: "example" on: workflow_dispatch: # This Action only starts when you go to Actions and manually run the workflow. jobs: package: strategy: matrix: platform: [windows-latest, macos-latest] go-version: [1.18] runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - name: Install Go uses: actions/setup-go@v2 with: go-version: ${{ matrix.go-version }} - name: setup node uses: actions/setup-node@v2 with: node-version: 14 # You may need to manually build you frontend here, unless you have configured frontend build and install commands in wails.json. - name: Get Wails run: go install github.com/wailsapp/wails/v2/cmd/wails@latest - name: Build Wails app run: | wails build - name: Sign Windows binaries if: matrix.platform == 'windows-latest' run: | echo "Creating certificate file" New-Item -ItemType directory -Path certificate Set-Content -Path certificate\certificate.txt -Value '${{ secrets.WIN_SIGNING_CERT }}' certutil -decode certificate\certificate.txt certificate\certificate.pfx echo "Signing our binaries" & 'C:/Program Files (x86)/Windows Kits/10/bin/10.0.17763.0/x86/signtool.exe' sign /fd sha256 /tr http://ts.ssl.com /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' .\build\bin\app.exe - name: upload artifacts macOS if: matrix.platform == 'macos-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-macos path: build/bin/* - name: upload artifacts windows if: matrix.platform == 'windows-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-windows path: build/bin/* ``` -------------------------------- ### Check Go Installation Source: https://wails.io/docs/gettingstarted/installation Verify that Go is installed correctly by running this command in your terminal. ```bash go version ``` -------------------------------- ### Install SvelteKit Dependencies Source: https://wails.io/docs/guides/sveltekit Install necessary dependencies and replace the auto adapter with the static adapter for SvelteKit. ```bash npm i ``` ```bash npm uninstall @sveltejs/adapter-auto ``` ```bash npm i -D @sveltejs/adapter-static ``` -------------------------------- ### Project Configuration Example Source: https://wails.io/docs/reference/project-config Example of a Wails project configuration file, demonstrating settings for application icons, custom URI protocols, and frontend binding generation. ```json { "iconName": "fileIcon", "role": "Editor" }, ], "protocols": [ { "scheme": "myapp", "description": "Myapp protocol", "role": "Editor" } ], "nsisType": "", "obfuscated": "", "garbleargs": "", "bindings": { "ts_generation": { "prefix": "", "suffix": "", "outputType": "classes" } } } ``` -------------------------------- ### Install Frontend Dependencies Manually Source: https://wails.io/docs/guides/manual-builds Use 'npm install' to manually install frontend dependencies. This is an alternative to the Wails CLI's automated step. ```bash npm install ``` -------------------------------- ### Install Wails CLI Source: https://wails.io/docs/gettingstarted/installation Install the Wails command-line interface using the Go install command. Ensure you have Go 1.18+. ```bash go install github.com/wailsapp/wails/v2/cmd/wails@latest ``` -------------------------------- ### Local Wails go.mod Example ('nix) Source: https://wails.io/docs/guides/local-development Example of updating the go.mod file on Linux/macOS to point to a local Wails clone. ```go replace github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2 ``` -------------------------------- ### Local Wails go.mod Example (Windows) Source: https://wails.io/docs/guides/local-development Example of updating the go.mod file on Windows to point to a local Wails clone. ```go replace github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2 ``` -------------------------------- ### Install gon via Homebrew Source: https://wails.io/docs/guides/signing Add this step to your GitHub Actions workflow to install the 'gon' tool for macOS code signing and notarization. ```bash - name: MacOS download gon for code signing and app notarization if: matrix.platform == 'macos-latest' run: | brew install Bearer/tap/gon ``` -------------------------------- ### Configure Go Proxy for Installation Source: https://wails.io/docs/guides/troubleshooting If experiencing proxy errors during Wails installation, manually set the Go proxy environment variables. ```bash go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn,direct ``` -------------------------------- ### Verify NPM Installation Source: https://wails.io/docs/gettingstarted/installation Check if NPM is installed and its version by running this command. ```bash npm --version ``` -------------------------------- ### Get Environment Info (Go) Source: https://wails.io/docs/reference/runtime/intro Returns details about the current environment, including build type, platform, and architecture. ```go runtime.Environment(ctx context.Context) EnvironmentInfo ``` -------------------------------- ### Install Local Wails CLI Source: https://wails.io/docs/guides/local-development Build and install the Wails CLI from your cloned local repository. This ensures your project uses the bleeding-edge version. ```bash cd wails/v2/cmd/wails go install ``` -------------------------------- ### Go Backend Method Definition Source: https://wails.io/docs/guides/troubleshooting Example of a Go backend method with a string and variadic interface parameters. ```go func (a *App) TestFunc(msg string, args ...interface{}) error { // Code } ``` -------------------------------- ### Checkout and Install Specific Branch Source: https://wails.io/docs/guides/local-development Clone Wails, checkout a specific branch, and install the CLI from that branch to test new features or fixes. ```bash git clone https://github.com/wailsapp/wails cd wails git checkout -b branch-to-test --track origin/branch-to-test cd v2/cmd/wails go install ``` -------------------------------- ### Get Environment Info (JavaScript) Source: https://wails.io/docs/reference/runtime/intro Returns details about the current environment, including build type, platform, and architecture. ```javascript runtime.Environment(): Promise ``` -------------------------------- ### Check Linux Notification Support (Go) Source: https://wails.io/docs/reference/runtime/notification On Linux, check if notifications are supported by the desktop environment before attempting to send them. This example also notes that text input may not be supported. ```go // Check system support if !runtime.IsNotificationAvailable(ctx) { return fmt.Errorf("notifications not supported on this Linux desktop") } // Linux notifications may not support text input // Only use actions that don't require user text ``` -------------------------------- ### Basic GitHub Actions Workflow for Wails Build Source: https://wails.io/docs/guides/signing This workflow template sets up a CI environment to build Wails applications for both Windows and macOS. It includes steps for checking out code, setting up Go and Node.js, installing Wails, building the app, and uploading artifacts. ```yaml name: "example" on: workflow_dispatch: # This Action only starts when you go to Actions and manually run the workflow. jobs: package: strategy: matrix: platform: [windows-latest, macos-latest] go-version: [1.18] runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - name: Install Go uses: actions/setup-go@v2 with: go-version: ${{ matrix.go-version }} - name: setup node uses: actions/setup-node@v2 with: node-version: 14 # You may need to manually build you frontend manually here, unless you have configured frontend build and install commands in wails.json. - name: Get Wails run: go install github.com/wailsapp/wails/v2/cmd/wails@latest - name: Build Wails app run: | wails build - name: upload artifacts macOS if: matrix.platform == 'macos-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-macos path: build/bin/* - name: upload artifacts windows if: matrix.platform == 'windows-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-windows path: build/bin/* ``` -------------------------------- ### Message Dialog Example Source: https://wails.io/docs/reference/runtime/dialog Displays a message dialog with customizable options. For Windows and Linux, buttons are standard and not customizable. For macOS, buttons can be customized. ```Go result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ Type: runtime.QuestionDialog, Title: "Question", Message: "Do you want to continue?", DefaultButton: "No", }) ``` -------------------------------- ### WindowGetSize Source: https://wails.io/docs/reference/runtime/window Gets the width and height of the window. ```APIDOC ## WindowGetSize ### Description Gets the width and height of the window. ### Method Signature (Go) `WindowGetSize(ctx context.Context) (width int, height int)` ### Method Signature (JavaScript) `WindowGetSize(): Promise` ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://wails.io/docs/gettingstarted/installation On macOS, Wails requires the Xcode command line tools. Install them using this command. ```bash xcode-select --install ``` -------------------------------- ### Custom AssetsHandler Example in Go Source: https://wails.io/docs/guides/dynamic-assets Implement a custom http.Handler to serve assets dynamically. This handler is invoked for non-GET requests or when bundled assets are not found. It reads files directly from the filesystem. ```go package main import ( "embed" "fmt" "github.com/wailsapp/wails/v2" "github.com/wailsapp/wails/v2/pkg/options" "github.com/wailsapp/wails/v2/pkg/options/assetserver" "net/http" "os" "strings" ) //go:embed all:frontend/dist var assets embed.FS type FileLoader struct { http.Handler } func NewFileLoader() *FileLoader { return &FileLoader{} } func (h *FileLoader) ServeHTTP(res http.ResponseWriter, req *http.Request) { var err error requestedFilename := strings.TrimPrefix(req.URL.Path, "/") println("Requesting file:", requestedFilename) fileData, err := os.ReadFile(requestedFilename) if err != nil { res.WriteHeader(http.StatusBadRequest) res.Write([]byte(fmt.Sprintf("Could not load file %s", requestedFilename))) } res.Write(fileData) } func main() { // Create an instance of the app structure app := NewApp() // Create application with options err := wails.Run(&options.App{ Title: "helloworld", Width: 1024, Height: 768, AssetServer: &assetserver.Options{ Assets: assets, Handler: NewFileLoader(), }, BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 255}, OnStartup: app.startup, Bind: []interface{}{ app, }, }) if err != nil { println("Error:", err) } } ``` -------------------------------- ### Start Wails Live Development Server Source: https://wails.io/docs/reference/cli Use `wails dev` to run your application in live development mode. This command compiles and runs the application, starts a watcher for file changes, and launches a development server. ```bash wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser ``` -------------------------------- ### Get Environment Info Source: https://wails.io/docs/reference/runtime/intro Returns information about the current runtime environment, including build type, platform, and architecture. ```APIDOC ## Environment ### Description Returns details of the current environment. ### Method Go: `Environment(ctx context.Context) EnvironmentInfo` JS: `Environment(): Promise` ### EnvironmentInfo Go: ``` type EnvironmentInfo struct { BuildType string Platform string Arch string } ``` JS: ``` interface EnvironmentInfo { buildType: string; platform: string; arch: string; } ``` ``` -------------------------------- ### Parse Accelerator String in Go Source: https://wails.io/docs/reference/menus Parses an accelerator string, similar to Electron's syntax, which is useful for loading shortcuts from configuration files. This example parses 'Ctrl+Option+A'. ```go // Defines cmd+o on Mac and ctrl-o on Window/Linux myShortcut, err := keys.Parse("Ctrl+Option+A") ``` -------------------------------- ### Fetch and Checkout a Pull Request Source: https://wails.io/docs/guides/local-development Fetch a specific pull request from GitHub, checkout its branch, and install the Wails CLI from it for testing. ```bash git clone https://github.com/wailsapp/wails cd wails git fetch -u origin pull/[IDofThePR]/head:test/pr-[IDofThePR] git checkout test/pr-[IDofThePR] git reset --hard HEAD cd v2/cmd/wails go install ``` -------------------------------- ### Linux Post-Install Script for MIME and Desktop Databases Source: https://wails.io/docs/guides/file-association Use post-install scripts in your Linux package to reload MIME types and desktop databases, ensuring file associations are registered correctly after installation. ```bash # reload mime types to register file associations update-mime-database /usr/share/mime # reload desktop database to load app in list of available update-desktop-database /usr/share/applications ``` -------------------------------- ### Define Accelerator Key Binding in Go Source: https://wails.io/docs/reference/menus Creates a keyboard shortcut (accelerator) for a menu item. This example shows how to define Cmd+O on macOS and Ctrl+O on Windows/Linux. ```go // Defines cmd+o on Mac and ctrl-o on Window/Linux myShortcut := keys.CmdOrCtrl("o") ``` -------------------------------- ### Example Entitlements File for Mac App Store Source: https://wails.io/docs/guides/mac-appstore This XML file configures app sandbox permissions required for Mac App Store submissions. Ensure 'TEAM_ID' and 'APP_NAME' are replaced with your specific values. ```xml com.apple.security.app-sandbox com.apple.security.network.client com.apple.security.network.server com.apple.security.files.user-selected.read-write com.apple.security.files.downloads.read-write com.apple.application-identifier TEAM_ID.APP_NAME com.apple.developer.team-identifier TEAM_ID ``` -------------------------------- ### Implement OnBeforeClose Callback in Go Source: https://wails.io/docs/reference/options Use the OnBeforeClose callback to intercept application shutdown requests. This example shows how to display a confirmation dialog to the user before closing the application. ```go func (b *App) beforeClose(ctx context.Context) (prevent bool) { dialog, err := runtime.MessageDialog(ctx, runtime.MessageDialogOptions{ Type: runtime.QuestionDialog, Title: "Quit?", Message: "Are you sure you want to quit?", }) if err != nil { return false } return dialog != "Yes" } ``` -------------------------------- ### Combined GitHub Actions Workflow for macOS and Windows Source: https://wails.io/docs/guides/signing This workflow automates the build and signing process for Wails applications. It uses a matrix strategy to build on both 'windows-latest' and 'macos-latest' platforms, setting up Go and Node.js environments, installing Wails, and then performing platform-specific signing steps before uploading artifacts. ```yaml name: "example combined" on: workflow_dispatch: # This Action only starts when you go to Actions and manually run the workflow. jobs: package: strategy: matrix: platform: [windows-latest, macos-latest] go-version: [1.18] runs-on: ${{ matrix.platform }} steps: - uses: actions/checkout@v3 - name: Install Go uses: actions/setup-go@v2 with: go-version: ${{ matrix.go-version }} - name: setup node uses: actions/setup-node@v2 with: node-version: 14 # You may need to manually build you frontend here, unless you have configured frontend build and install commands in wails.json. - name: Get Wails run: go install github.com/wailsapp/wails/v2/cmd/wails@latest - name: Build Wails app run: | wails build - name: MacOS download gon for code signing and app notarization if: matrix.platform == 'macos-latest' run: | brew install Bearer/tap/gon - name: Import Code-Signing Certificates for macOS if: matrix.platform == 'macos-latest' uses: Apple-Actions/import-codesign-certs@v1 with: # The certificates in a PKCS12 file encoded as a base64 string p12-file-base64: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_P12_BASE64 }} # The password used to import the PKCS12 file. p12-password: ${{ secrets.APPLE_DEVELOPER_CERTIFICATE_PASSWORD }} - name: Sign our macOS binary if: matrix.platform == 'macos-latest' run: | echo "Signing Package" gon -log-level=info ./build/darwin/gon-sign.json - name: Sign Windows binaries if: matrix.platform == 'windows-latest' run: | echo "Creating certificate file" New-Item -ItemType directory -Path certificate Set-Content -Path certificate\certificate.txt -Value '${{ secrets.WIN_SIGNING_CERT }}' certutil -decode certificate\certificate.txt certificate\certificate.pfx echo "Signing our binaries" & 'C:/Program Files (x86)/Windows Kits/10/bin/10.0.17763.0/x86/signtool.exe' sign /fd sha256 /tr http://ts.ssl.com /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' .\build\bin\Monitor.exe - name: upload artifacts macOS if: matrix.platform == 'macos-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-macos path: build/bin/* - name: upload artifacts windows if: matrix.platform == 'windows-latest' uses: actions/upload-artifact@v2 with: name: wails-binaries-windows path: build/bin/* ``` -------------------------------- ### Build and Run a Project from a Template Source: https://wails.io/docs/guides/templates After initializing a project from a template, navigate to the project directory and build it. Then, run the compiled executable. ```bash cd my-vue3-project wails build .\build\bin\my-vue3-project.exe ``` -------------------------------- ### Configure Create React App Dev Server in wails.json Source: https://wails.io/docs/guides/application-development Add these configurations to your wails.json to enable live frontend reloading for Create React App projects. The watcher starts the CRA dev server, and serverUrl tells Wails where to serve assets from. ```json "frontend:dev:watcher": "yarn start", "frontend:dev:serverUrl": "http://localhost:3000", ``` -------------------------------- ### Implement Dog API Fetching Functions in App.go Source: https://wails.io/docs/tutorials/dogsapi These Go functions handle fetching data from the Dog API. 'GetRandomImageUrl' retrieves a random dog image URL, 'GetBreedList' fetches a list of all dog breeds, and 'GetImageUrlsByBreed' gets images for a specific breed. Error handling and JSON unmarshalling are included. ```go func (a *App) GetRandomImageUrl() string { response, err := http.Get("https://dog.ceo/api/breeds/image/random") if err != nil { log.Fatal(err) } responseData, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } var data RandomImage json.Unmarshal(responseData, &data) return data.Message } func (a *App) GetBreedList() []string { var breeds []string response, err := http.Get("https://dog.ceo/api/breeds/list/all") if err != nil { log.Fatal(err) } responseData, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } var data AllBreeds json.Unmarshal(responseData, &data) for k := range data.Message { breeds = append(breeds, k) } sort.Strings(breeds) return breeds } func (a *App) GetImageUrlsByBreed(breed string) []string { url := fmt.Sprintf("%s%s%s%s", "https://dog.ceo/api/", "breed/", breed, "/images") response, err := http.Get(url) if err != nil { log.Fatal(err) } responseData, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } var data ImagesByBreed json.Unmarshal(responseData, &data) return data.Message } ``` -------------------------------- ### Handle Second Instance Launch Callback Source: https://wails.io/docs/guides/single-instance-lock Implement the `OnSecondInstanceLaunch` callback to process data from a newly launched instance. This callback receives `SecondInstanceData` containing command-line arguments and the working directory. It's essential to unminimise and show the window, and emit an event with the launch arguments. Remember to treat received arguments as untrusted. ```go 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) } ``` -------------------------------- ### Show Application (Go) Source: https://wails.io/docs/reference/runtime/intro Shows the application. On Mac, this brings the application to the foreground. On Windows and Linux, it functions like `WindowShow`. ```go runtime.Show(ctx context.Context) ``` -------------------------------- ### Install NSIS with Chocolatey Source: https://wails.io/docs/guides/windows-installer Installs the NSIS package using the Chocolatey package manager. ```powershell choco install nsis ``` -------------------------------- ### Install NSIS with Winget Source: https://wails.io/docs/guides/windows-installer Installs the NSIS package silently using the Winget package manager on Windows 10+. ```bash winget install NSIS.NSIS --silent ``` -------------------------------- ### Install NSIS with Scoop Source: https://wails.io/docs/guides/windows-installer Installs the NSIS package and adds it to your system's PATH using the Scoop package manager. ```bash scoop bucket add extras scoop install nsis ``` -------------------------------- ### Initialize Notifications (Go) Source: https://wails.io/docs/reference/runtime/notification Initializes the notification system. It should be called during app startup. Returns an error if initialization fails. ```go err := runtime.InitializeNotifications(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create Application: Wails v1 vs v2 Source: https://wails.io/docs/guides/migrating Compares the application creation methods in Wails v1 (`wails.CreateApp`) and v2 (`wails.Run`). ```go app := wails.CreateApp(&wails.AppConfig{ Title: "MyApp", Width: 1024, Height: 768, JS: js, CSS: css, Colour: "#131313", }) app.Bind(basic) app.Run() ``` ```go err := wails.Run(&options.App{ Title: "MyApp", Width: 800, Height: 600, AssetServer: &assetserver.Options{ Assets: assets, }, Bind: []interface{}{ basic, }, }) ``` -------------------------------- ### Build Wails Application with NSIS Installer Source: https://wails.io/docs/guides/windows-installer Generates the NSIS installer for your Wails application using the `-nsis` flag during the build process. ```bash wails build -nsis ``` -------------------------------- ### Create SvelteKit Frontend Source: https://wails.io/docs/guides/sveltekit Use the Svelte CLI to create a SvelteKit project as the new frontend after deleting the default Svelte frontend. ```bash npx sv create frontend ``` -------------------------------- ### Import and Call a Bound Go Method Source: https://wails.io/docs/howdoesitwork Import the `Greet` method from the generated Go bindings and call it with a name. The result is handled via a Promise. ```javascript // ... import { Greet } from "../wailsjs/go/main/App"; function doGreeting(name) { Greet(name).then((result) => { // Do something with result }); } ``` -------------------------------- ### Generate Windows Icon and Manifest Source: https://wails.io/docs/guides/manual-builds Manually create a Windows icon (.ico) using 'winicon' and a manifest file. Then, use 'winres' to generate a .syso file for linking. ```bash winicon --output build/windows/icon.ico --size 256,128,64,48,32,16 appicon.png winres --output ".syso" --icon build/windows/icon.ico --manifest build/windows/.manifest ``` -------------------------------- ### Update PATH after Go Installation Source: https://wails.io/docs/gettingstarted/installation After installing Wails via Go, update your PATH environment variable to include the Go binary directory. ```bash export PATH=$PATH:$(go env GOPATH)/bin ``` -------------------------------- ### Runtime Logging: Wails v2 Source: https://wails.io/docs/guides/migrating Shows how to use the Wails v2 runtime package for logging within lifecycle hooks, passing the context received during startup. ```go package main import "github.com/wailsapp/wails/v2/pkg/runtime" type Basic struct { ctx context.Context } // startup is called at application startup func (a *App) startup(ctx context.Context) { a.ctx = ctx runtime.LogInfo(ctx, "Application Startup called!") } ``` -------------------------------- ### macOS Destructive Action Example (Go) Source: https://wails.io/docs/reference/runtime/notification Example of creating notification actions in Go, demonstrating the use of the `Destructive` flag for macOS. This flag causes the action button to appear in red on macOS. ```go actions := []runtime.NotificationAction{ {ID: "SAVE", Title: "Save"}, {ID: "DELETE", Title: "Delete", Destructive: true}, // Shows as red button on macOS } ``` -------------------------------- ### Build a Wails Project for Production Source: https://wails.io/docs/reference/cli Compile your Wails project into a production-ready binary using 'wails build'. Options include cleaning the build directory, specifying the output filename, and enabling features like debugging or obfuscation. ```bash wails build -clean -o myproject.exe ``` -------------------------------- ### Initialize a Project from a Local Template Source: https://wails.io/docs/guides/templates Create a new Wails project using a locally defined template. Ensure the template path is correct. ```bash wails init -n my-vue3-project -t .\wails-vue3-template\ ``` -------------------------------- ### Install GStreamer Plugins for Audio/Video Elements Source: https://wails.io/docs/guides/linux Install the 'gst-plugins-good' package to resolve GStreamer errors when using Audio or Video elements in Wails applications on Linux. This is often required due to an upstream WebkitGTK issue. ```bash pacman -S gst-plugins-good ``` ```bash apt-get install gstreamer1.0-plugins-good ``` ```bash dnf install gstreamer1-plugins-good ``` -------------------------------- ### tasks.json with npm install and build steps for VS Code Source: https://wails.io/docs/guides/ides This `tasks.json` file is an enhanced version for Wails projects with frontend build steps. It includes tasks for `npm install` and `npm run build`, and configures the main build task to depend on them. ```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 Desktop Entry for Custom Protocol Source: https://wails.io/docs/guides/custom-protocol-schemes Create a .desktop file for your Linux application to associate custom protocols. Ensure the Exec line includes '%u' to pass the URL, and specify the MimeType for your custom scheme. ```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; ``` -------------------------------- ### WindowGetPosition Source: https://wails.io/docs/reference/runtime/window Gets the window position relative to the monitor the window is currently on. ```APIDOC ## WindowGetPosition ### Description Gets the window position relative to the monitor the window is currently on. ### Method Signature (Go) `WindowGetPosition(ctx context.Context) (x int, y int)` ### Method Signature (JavaScript) `WindowGetPosition(): Promise` ``` -------------------------------- ### Initialize a New Wails Application Source: https://wails.io/docs/tutorials/helloworld Use this command to create a new Wails project with the default vanilla JS template. Specify the project name with the -n flag. ```bash wails init -n helloworld ``` -------------------------------- ### Show Application (JavaScript) Source: https://wails.io/docs/reference/runtime/intro Shows the application. On Mac, this brings the application to the foreground. On Windows and Linux, it functions like `WindowShow`. ```javascript runtime.Show() ``` -------------------------------- ### Open Inspector on Startup Source: https://wails.io/docs/reference/options Enables opening the WebInspector automatically when the application starts. This is useful for debugging purposes during development. ```go Debug: &options.Debug{ OpenInspectorOnStartup: true, } ``` -------------------------------- ### Define App Struct and Lifecycle Hooks in Go Source: https://wails.io/docs/guides/application-development Defines the main application struct and its startup/shutdown methods. The startup method is used for resource initialization and can save the context for runtime calls. If startup returns an error, the application will terminate. ```go import ( "context" ) type App struct { ctx context.Context } func NewApp() *App { return &App{} } func (a *App) startup(ctx context.Context) { a.ctx = ctx } func (a *App) shutdown(ctx context.Context) { } ``` -------------------------------- ### Linux .desktop File Configuration Source: https://wails.io/docs/guides/file-association Create a .desktop file for your application on Linux to define file associations. Specify the Exec, Icon, Name, Type, and MimeType for your 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=application/x-wails;application/x-test ``` -------------------------------- ### Test Wails Development Server Source: https://wails.io/docs/guides/sveltekit Run the Wails development server to test the SvelteKit integration. ```bash wails dev ``` -------------------------------- ### React Router HashRouter Setup Source: https://wails.io/docs/guides/routing Implement routing in React using HashRouter from react-router-dom. This is the recommended approach for React applications. ```javascript import { HashRouter, Routes, Route } from "react-router-dom"; ReactDOM.render( {/* The rest of your app goes here */} } exact /> } /> } /> {/* more... */} , root ); ``` -------------------------------- ### Configure Application Options Source: https://wails.io/docs/reference/options Set application-wide options, including platform-specific configurations for macOS and Linux, and debugging settings. Ensure correct types and values are used for each option. ```go err := wails.Run(&options.App{ Title: "my-app", Width: 1024, Height: 768, Mac: &mac.Options{ Titlebar: &mac.Titlebar{ Style: mac.TitlebarStyle:Unified, Show: true, }, WebviewIsTransparent: true, WindowIsTranslucent: false, ContentProtection: false, About: &mac.AboutInfo{ Title: "My Application", Message: "© 2021 Me", Icon: icon, }, }, Linux: &linux.Options{ Icon: icon, WindowIsTranslucent: false, WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, ProgramName: "wails" }, Debug: options.Debug{ OpenInspectorOnStartup: false, }, BindingsAllowedOrigins: "https://my.topapp,https://*.wails.isgreat", }) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Sign macOS Binary with Gon Source: https://wails.io/docs/guides/signing This step executes the gon-sign tool to sign your macOS binary. It requires a configuration file located at ./build/darwin/gon-sign.json. Signing can be a time-consuming process. ```bash - name: Sign our macOS binary if: matrix.platform == 'macos-latest' run: | echo "Signing Package" gon -log-level=info ./build/darwin/gon-sign.json ``` -------------------------------- ### entitlements.plist Configuration Source: https://wails.io/docs/guides/signing An example entitlements.plist file used to configure necessary permissions for your macOS application, such as network access or file access. ```xml com.apple.security.app-sandbox com.apple.security.network.client com.apple.security.network.server com.apple.security.files.user-selected.read-write com.apple.security.files.downloads.read-write ``` -------------------------------- ### Basic Wails Application Structure Source: https://wails.io/docs/howdoesitwork This is a minimal Wails application. It sets up the application configuration, including window dimensions, title, asset server, and lifecycle callbacks. The `Bind` option exposes application structs to 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) } ``` -------------------------------- ### Get All Screens (JavaScript) Source: https://wails.io/docs/reference/runtime/screen Retrieves a list of all connected screens. Each screen object contains properties like isCurrent, isPrimary, width, and height. ```javascript const screens = await Wails.Screen.GetAll() console.log(screens) ``` -------------------------------- ### OnStartup Source: https://wails.io/docs/reference/options A callback function executed after the frontend is created but before index.html is loaded. ```APIDOC ## OnStartup ### Description This callback is called after the frontend has been created, but before `index.html` has been loaded. It is given the application context. ### Type `func(ctx context.Context)` ``` -------------------------------- ### Get All Screens (Go) Source: https://wails.io/docs/reference/runtime/screen Retrieves a list of all connected screens. Each screen object contains properties like isCurrent, isPrimary, width, and height. ```go import "context" // ... func (a *App) GetAllScreens(ctx context.Context) []screen { return screen.GetAll(ctx) } ``` -------------------------------- ### Application Lifecycle Hooks: Wails v2 Source: https://wails.io/docs/guides/migrating Demonstrates the use of Wails v2 lifecycle hooks (OnStartup, OnShutdown, OnDomReady) within application options, replacing v1's `WailsInit` and `WailsShutdown`. ```go basic := NewBasicApp() err := wails.Run(&options.App{ /* Other Options */ OnStartup: basic.startup, OnShutdown: basic.shutdown, OnDomReady: basic.domready, }) ... type Basic struct { ctx context.Context } func (b *Basic) startup(ctx context.Context) { b.ctx = ctx } ... ``` -------------------------------- ### Vue Router Hash Mode Setup Source: https://wails.io/docs/guides/routing Configure Vue Router to use hash mode for routing. This is the recommended approach for Vue applications. ```javascript import { createRouter, createWebHashHistory } from "vue-router"; const router = createRouter({ history: createWebHashHistory(), routes: [ //... ], }); ``` -------------------------------- ### Manual Script Injection Example Source: https://wails.io/docs/guides/frontend This HTML demonstrates manual injection of Wails scripts (`/wails/ipc.js` and `/wails/runtime.js`) after disabling autoinjection via the meta tag. ```html injection example
Please enter your name below 👇
``` -------------------------------- ### Wails Project Initialization Output Source: https://wails.io/docs/tutorials/helloworld This output indicates the successful initialization of a new Wails project, showing the project name, directory, and template used. ```bash Wails CLI v2.0.0 Initialising Project 'helloworld' --------------------------------- Project Name: helloworld Project Directory: C:\Users\leaan\tutorial\helloworld Project Template: vanilla Template Support: https://wails.io Initialised project 'helloworld' in 232ms. ``` -------------------------------- ### Generate Vanilla Project with JavaScript Source: https://wails.io/docs/gettingstarted/firstproject Use this command to create a new Wails project with a Vanilla JavaScript frontend. ```bash wails init -n myproject -t vanilla ``` -------------------------------- ### Configure Angular Dev Mode in Wails Source: https://wails.io/docs/guides/angular Add these settings to your `wails.json` file to enable Angular's development mode. This configures the build, install, and dev server commands. ```json "frontend:build": "npx ng build", "frontend:install": "npm install", "frontend:dev:watcher": "npx ng serve", "frontend:dev:serverUrl": "http://localhost:4200", ``` -------------------------------- ### Check Linux Notification Support (JavaScript) Source: https://wails.io/docs/reference/runtime/notification On Linux, check if notifications are supported by the desktop environment before attempting to send them. This example also notes that text input may not be supported. ```javascript // Check system support const available = await runtime.IsNotificationAvailable(); if (!available) { throw new Error("Notifications not supported on this Linux desktop"); } // Linux notifications may not support text input // Only use actions that don't require user text ``` -------------------------------- ### Check Go Bin in PATH Source: https://wails.io/docs/gettingstarted/installation Ensure that the Go binary directory is included in your system's PATH environment variable. ```bash echo $PATH | grep go/bin ``` -------------------------------- ### Initialize Notifications Source: https://wails.io/docs/guides/notifications Initialize the notification system during app startup. On macOS, this may fail if the bundle identifier is not set. ```go err := runtime.InitializeNotifications(a.ctx) if err != nil { // Handle initialization error // On macOS, this may fail if bundle identifier is not set } ``` -------------------------------- ### Pre-defined Menu Roles (Mac Only) Source: https://wails.io/docs/reference/menus Describes the concept of 'roles' for menu items, which are pre-defined system menus available on macOS. Examples include the application menu and edit menu. ```go // AppMenuRole The standard Mac application menu. Can be created using `menu.AppMenu()` // EditMenuRole The standard Mac edit menu. Can be created using `menu.EditMenu()` ``` -------------------------------- ### Build the Wails Application Source: https://wails.io/docs/tutorials/helloworld Navigate to your project directory and run this command to compile your Wails application. This command builds the application for the target platform. ```bash wails build ``` -------------------------------- ### Spawn Hidden Program Window Source: https://wails.io/docs/guides/windows Execute an external program or script while ensuring its window remains hidden from the user. This is achieved by setting `HideWindow` and `CreationFlags` in `syscall.SysProcAttr` before starting the command. ```go cmd := exec.Command("your_script.exe") cmd.SysProcAttr = &syscall.SysProcAttr{ HideWindow: true, CreationFlags: 0x08000000, } cmd.Start() ``` -------------------------------- ### Generate React Project with JavaScript Source: https://wails.io/docs/gettingstarted/firstproject Use this command to create a new Wails project with the React frontend framework using JavaScript. ```bash wails init -n myproject -t react ``` -------------------------------- ### Initialize a New Wails Project Source: https://wails.io/docs/reference/cli Use 'wails init' to generate a new Wails project. Specify the project name and directory, and optionally enable git initialization, generate IDE files, or use a specific template. ```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] ``` -------------------------------- ### Initialize Notifications (JavaScript) Source: https://wails.io/docs/reference/runtime/notification Initializes the notification system. It should be called during app startup. ```javascript await runtime.InitializeNotifications(); ``` -------------------------------- ### Linux Desktop Database Update Script Source: https://wails.io/docs/guides/custom-protocol-schemes Use a postInstall script to update the desktop database after installing your Linux application, ensuring the system recognizes the new file associations and custom protocols. ```bash # reload desktop database to load app in list of available update-desktop-database /usr/share/applications ``` -------------------------------- ### Create Menu from Items in Go Source: https://wails.io/docs/reference/menus A helper method for constructing a Menu from a list of MenuItems, simplifying menu creation. ```go func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu ```