Fix translations

This commit is contained in:
Lea Anthony 2024-06-16 13:10:56 +10:00
commit d96d3b0010
No known key found for this signature in database
GPG key ID: 33DAF7BB90A58405
557 changed files with 6271 additions and 39717 deletions

View file

@ -13,7 +13,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest, macos-11]
go-version: ['1.22']
go-version: ['1.21']
steps:
- name: Checkout code
@ -90,7 +90,7 @@ jobs:
vanilla-ts,
plain,
]
go-version: ['1.22']
go-version: ['1.21']
steps:
- name: Checkout
uses: actions/checkout@v4

View file

@ -2,8 +2,6 @@ module github.com/wailsapp/wails/v2
go 1.21
toolchain go1.22.0
require (
github.com/Masterminds/semver v1.5.0
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d

View file

@ -8,7 +8,7 @@ tasks:
aliases: [i]
cmds:
- corepack enable
- corepack prepare pnpm@8.2.0 --activate
- corepack prepare pnpm@8.3.1 --activate
- pnpm install
sources:
- package.json

View file

@ -7,36 +7,33 @@
</p>
```
[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) - Suivez les
matchs en direct de n'importe quel profil Street Fighter 6 ou V CFN. Consultez
[le site Web](https://cfn.williamsjokvist.se/) pour commencer.
[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) - Track any Street
Fighter 6 or V CFN profile's live matches. Check
[the website](https://cfn.williamsjokvist.se/) to get started.
## Caractéristiques
## Features
- Suivi des matchs en temps réel
- Stockage des journaux de match et des statistiques
- Prise en charge de l'affichage des statistiques en direct sur OBS via la
source du navigateur
- Prise en charge de SF6 et SFV
- Possibilité pour les utilisateurs de créer leurs propres thèmes de navigateur
OBS avec CSS
- Real-time match tracking
- Storing match logs and statistics
- Support for displaying live stats to OBS via Browser Source
- Support for both SF6 and SFV
- Ability for users to create their own OBS Browser themes with CSS
### Technologie majeure utilisée aux côtés de Wails
### Major tech used alongside Wails
- [Tâche](https://github.com/go-task/task) - encapsulation de la CLI Wails pour
rendre les commandes courantes faciles à utiliser
- [React](https://github.com/facebook/react) - choisi pour son riche écosystème
(radix, framer-motion)
- [Bun](https://github.com/oven-sh/bun) - utilisé pour sa résolution rapide des
dépendances et son temps de construction
- [Rod](https://github.com/go-rod/rod) - automatisation du navigateur sans tête
pour les modifications d'authentification et d'interrogation
- [SQLite](https://github.com/mattn/go-sqlite3) - utilisé pour stocker les
correspondances, les sessions et les profils
- [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) -
un flux http pour envoyer des mises à jour de suivi aux sources du navigateur
OBS
- [i18next](https://github.com/i18next/) - avec connecteur backend pour servir
les objets de localisation de la couche Go
- [xstate](https://github.com/statelyai/xstate) - machines à états pour le
processus d'authentification et le suivi
- [Task](https://github.com/go-task/task) - wrapping the Wails CLI to make
common commands easy to use
- [React](https://github.com/facebook/react) - chosen for its rich ecosystem
(radix, framer-motion)
- [Bun](https://github.com/oven-sh/bun) - used for its fast dependency
resolution and build-time
- [Rod](https://github.com/go-rod/rod) - headless browser automation for
authentication and polling changes
- [SQLite](https://github.com/mattn/go-sqlite3) - used for storing matches,
sessions and profiles
- [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) -
a http stream to send tracking updates to OBS browser sources
- [i18next](https://github.com/i18next/) - with backend connector to serve
localization objects from the Go layer
- [xstate](https://github.com/statelyai/xstate) - state machines for auth
process and tracking

View file

@ -9,5 +9,5 @@
</p>
```
[ESP Studio](https://github.com/torabian/esp-studio) - Logiciels multiplateformes, de bureau, cloud et embarqués
pour contrôler les appareils ESP/Arduino et créer des flux de travail et des systèmes de contrôle IOT complexes
[ESP Studio](https://github.com/torabian/esp-studio) - Cross platform, Desktop, Cloud, and Embedded software
for controlling ESP/Arduino devices, and building complex IOT workflows and control systems

View file

@ -0,0 +1,10 @@
# Mchat
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/mchat.gif").default} />
<br />
</p>
```
[Official page](https://marcio199226.github.io/mchat-site/public/) Fully anonymous end2end encrypted chat.

View file

@ -0,0 +1,27 @@
# Snippet Expander
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/snippetexpandergui-select-snippet.png").default} />
<br />
Screenshot of Snippet Expander's Select Snippet window
</p>
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/snippetexpandergui-add-snippet.png").default} />
<br />
Screenshot of Snippet Expander's Add Snippet screen
</p>
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/snippetexpandergui-search-and-paste.png").default} />
<br />
Screenshot of Snippet Expander's Search & Paste window
</p>
```
[Snippet Expander](https://snippetexpander.org) is "Your little expandable text snippets helper", for Linux.
Snippet Expander comprises of a GUI application built with Wails for managing snippets and settings, with a Search & Paste window mode for quickly selecting and pasting a snippet.
The Wails based GUI, go-lang CLI and vala-lang auto expander daemon all communicate with a go-lang daemon via D-Bus. The daemon does the majority of the work, managing the database of snippets and common settings, and providing services for expanding and pasting snippets etc.
Check out the [source code](https://git.sr.ht/~ianmjones/snippetexpander/tree/trunk/item/cmd/snippetexpandergui/app.go#L38) to see how the Wails app sends messages from the UI to the backend that are then sent to the daemon, and subscribes to a D-Bus event to monitor changes to snippets via another instance of the app or CLI and show them instantly in the UI via a Wails event.

View file

@ -8,4 +8,4 @@
</p>
```
The [Tiny RDM](https://redis.tinycraft.cc/) application is an open-source, modern lightweight Redis GUI. It has a beautful UI, intuitive Redis database management, and compatible with Windows, Mac, and Linux. It provides visual key-value data operations, supports various data decoding and viewing options, built-in console for executing commands, slow log queries and more.
L'application [Tiny RDM](https://redis.tinycraft.cc/) est une interface Redis moderne et open-source. Il possède une interface utilisateur magnifique, une gestion de base de données Redis intuitive et compatible avec Windows, Mac et Linux. Il fournit des opérations visuelles de données de clé-valeur, supporte diverses options de décodage et de visualisation des données, possède une console intégrée pour exécuter des commandes, des requêtes de log lentes et plus encore.

View file

@ -39,6 +39,7 @@ Si vous n'êtes pas sûr d'un modèle, inspectez `package.json` et `wails.json`
- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - Un modèle utilisant reactjs
- [wails-react-template](https://github.com/flin7/wails-react-template) - Un modèle minimal pour React qui supporte le développement en direct
- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - Un modèle utilisant Next.js et TypeScript
- [wails-template-nextjs-app-router](https://github.com/thisisvk-in/wails-template-nextjs-app-router) - A template using Next.js and TypeScript with App router
- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - Un modèle pour React + TypeScript + Vite + TailwindCSS
- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - Un modèle avec Vite, React, TypeScript, TailwindCSS, et shadcn/ui

View file

@ -133,6 +133,64 @@ func main() {
}
```
Also you might want to use Enums in your structs and have models for them on frontend. In that case you should create array that will contain all possible enum values, instrument enum type and bind it to the app:
```go {16-18} title="app.go"
type Weekday string
const (
Sunday Weekday = "Sunday"
Monday Weekday = "Monday"
Tuesday Weekday = "Tuesday"
Wednesday Weekday = "Wednesday"
Thursday Weekday = "Thursday"
Friday Weekday = "Friday"
Saturday Weekday = "Saturday"
)
var AllWeekdays = []struct {
Value Weekday
TSName string
}{
{Sunday, "SUNDAY"},
{Monday, "MONDAY"},
{Tuesday, "TUESDAY"},
{Wednesday, "WEDNESDAY"},
{Thursday, "THURSDAY"},
{Friday, "FRIDAY"},
{Saturday, "SATURDAY"},
}
```
In the main application configuration, the `EnumBind` key is where we can tell Wails what we want to bind enums as well:
```go {11-13} title="main.go"
func main() {
app := NewApp()
err := wails.Run(&options.App{
Title: "My App",
Width: 800,
Height: 600,
OnStartup: app.startup,
OnShutdown: app.shutdown,
Bind: []interface{}{
app,
},
EnumBind: []interface{}{
AllWeekdays,
},
})
if err != nil {
log.Fatal(err)
}
}
```
This will add missing enums to your `model.ts` file.
Plus d'informations à sur Binding peuvent être trouvées [ici](../howdoesitwork.mdx#method-binding).
## Menu de lapplication

View file

@ -1,14 +1,14 @@
# Crossplatform build with Github Actions
# Construction cross-plateforme avec Github Actions
To build a Wails project for all the available platforms, you need to create an application build for each operating system. One effective method to achieve this is by utilizing GitHub Actions.
Pour construire un projet Wails pour toutes les plateformes disponibles, vous devez créer un build de l'application pour chaque système d'exploitation. Une méthode efficace pour y parvenir est d'utiliser GitHub Actions.
An action that facilitates building a Wails app is available at:
Une action qui facilite la création d'une application Wails est disponible sur :
https://github.com/dAppServer/wails-build-action
In case the existing action doesn't fulfill your requirements, you can select only the necessary steps from the source:
Dans le cas où l'action existante ne répond pas à vos exigences, vous ne pouvez sélectionner que les étapes nécessaires à partir de la source :
https://github.com/dAppServer/wails-build-action/blob/main/action.yml
Below is a comprehensive example that demonstrates building an app upon the creation of a new Git tag and subsequently uploading it to the Actions artifacts:
Voici un exemple complet qui démontre la construction d'une application lors de la création d'une nouvelle balise Git et qui la téléversera ensuite sur les artefacts Actions :
```yaml
name: Wails build
@ -16,17 +16,17 @@ name: Wails build
on:
push:
tags:
# Match any new tag
# Matche n'importe quel nouveau tag
- '*'
env:
# Necessary for most environments as build failure can occur due to OOM issues
# Nécessaire pour la plupart des environnement, car des soucis de build peuvent arriver à cause de soucis de mémoire
NODE_OPTIONS: "--max-old-space-size=4096"
jobs:
build:
strategy:
# Failure in one platform build won't impact the others
# Afin d'éviter que l'échec du build d'une plateforme n'impacte les autres
fail-fast: false
matrix:
build:
@ -57,10 +57,10 @@ jobs:
go-version: '1.20'
```
This example offers opportunities for various enhancements, including:
Cet exemple offre des opportunités pour diverses améliorations, comprenant :
- Caching dependencies
- Code signing
- Uploading to platforms like S3, Supbase, etc.
- Injecting secrets as environment variables
- Utilizing environment variables as build variables (such as version variable extracted from the current Git tag)
- Mise en cache des dépendances
- Signature de code
- Envoi vers des plateformes comme S3, Supbase, etc.
- Injection de secrets en tant que variables d'environnement
- Utiliser des variables d'environnement comme variables de compilation (telles que la variable de version extraite de la balise Git actuelle)

View file

@ -25,15 +25,15 @@ For example:
}
```
| Property | Description |
| :---------- | :------------------------------------------------------------------------------------ |
| scheme | Custom Protocol scheme. e.g. myapp |
| description | Windows-only. The description. |
| role | macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole. |
| Propriété | Description |
| :----------- | :------------------------------------------------------------------------------------------ |
| scheme | Custom Protocol scheme. e.g. myapp |
| description | Windows seulement. La description. |
| role | macOS uniquement. The apps role with respect to the type. Corresponds to CFBundleTypeRole. |
## Platform Specifics:
## Spécificités par platefome :
### macOS
### MacOS
When you open custom protocol with your app, the system will launch your app and call the `OnUrlOpen` function in your Wails app. Example:

View file

@ -1,5 +1,11 @@
# Ressources dynamiques
:::info
This does not work with vite v5.0.0+ and wails v2 due to changes in vite. Changes are planned in v3 to support similar functionality under vite v5.0.0+. If you need this feature, stay with vite v4.0.0+. See [issue 3240](https://github.com/wailsapp/wails/issues/3240) for details
:::
Si vous voulez charger ou générer des ressources pour votre frontend de manière dynamique, vous pouvez y parvenir en utilisant l'option [AssetsHandler](../reference/options#assetshandler). Le AssetsHandler est un générique`http.Handler` qui sera appelé pour toute requête non GET sur le serveur d'assets et pour les requêtes GET qui ne peuvent pas être servies car l'asset n'est pas trouvé.
En installant un AssetsHandler personnalisé, vous pouvez servir vos propres ressources en utilisant un serveur de ressources personnalisé.

View file

@ -1,15 +1,15 @@
# File Association
# Associations de fichiers
File association feature allows you to associate specific file types with your app so that when users open those files,
your app is launched to handle them. This can be particularly useful for text editors, image viewers, or any application
that works with specific file formats. In this guide, we'll walk through the steps to implement file association in Wails app.
La fonction d'association de fichiers vous permet d'associer des types de fichiers spécifiques à votre application afin que lorsque les utilisateurs ouvrent ces fichiers,
votre application est lancée pour les gérer. Cela peut être particulièrement utile pour les éditeurs de texte, les visualisateurs d'images ou n'importe quelle application
qui fonctionne avec des formats de fichiers spécifiques. Dans ce guide, nous allons parcourir les étapes pour implémenter l'association de fichiers dans l'application Wails.
## Set Up File Association:
## Configurer l'association de fichiers :
To set up file association, you need to modify your application's wails.json file.
In "info" section add a "fileAssociations" section specifying the file types your app should be associated with.
Pour configurer l'association de fichiers, vous devez modifier le fichier wails.json de votre application.
Dans la section "info", ajoutez une section "fileAssociations" spécifiant les types de fichiers auxquels votre application doit être associée.
For example:
Par exemple :
```json
{
@ -34,23 +34,23 @@ For example:
}
```
| Property | Description |
| :---------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |
| ext | The extension (minus the leading period). e.g. png |
| name | The name. e.g. PNG File |
| iconName | The icon name without extension. Icons should be located in build folder. Proper icons will be generated from .png file for both macOS and Windows |
| description | Windows-only. The description. It is displayed on the `Type` column on Windows Explorer. |
| role | macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole. |
| Propriété | Description |
| :----------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ext | L'extension. ex: png |
| name | Le nom de l'extension. ex: PNG File |
| iconName | Le nom de l'icône sans extension. Les icônes doivent être situées dans le dossier de build. Des icônes appropriées seront générées à partir du fichier .png pour macOS et Windows |
| description | Windows seulement. La description. Il est affiché dans la colonne `Type` dans l'explorateur Windows. |
| role | macOS uniquement. Rôle de l'application par rapport au type. Correspond au rôle CFBundleTypeRole. |
## Platform Specifics:
## Spécificités par platefome :
### macOS
### MacOS
When you open file (or files) with your app, the system will launch your app and call the `OnFileOpen` function in your Wails app. Example:
Lorsque vous ouvrez un fichier (ou des fichiers) avec votre application, le système lancera votre application et appellera la fonction `OnFileOpen` dans votre application Wails. Exemple:
```go title="main.go"
func main() {
// Create application with options
// Création d'une application avec des options
err := wails.Run(&options.App{
Title: "wails-open-file",
Width: 1024,
@ -75,9 +75,9 @@ func main() {
### Windows
On Windows file association is supported only with NSIS installer. During installation, the installer will create a
registry entry for your file associations. When you open file with your app, new instance of app is launched and file path is passed
as argument to your app. To handle this you should parse command line arguments in your app. Example:
L'association de fichiers dans Windows n'est prise en charge qu'avec l'installateur NSS. Pendant l'installation, l'installateur créera une entrée de registre
pour vos associations de fichiers. Lorsque vous ouvrez un fichier avec votre application, une nouvelle instance d'application est lancée et le chemin d'accès est passé à
comme argument à votre application. Pour gérer cela, vous devez analyser les arguments de la ligne de commande dans votre application. Exemple:
```go title="main.go"
func main() {
@ -89,12 +89,12 @@ func main() {
}
```
You also can enable single instance lock for your app. In this case, when you open file with your app, new instance of app is not launched
and arguments are passed to already running instance. Check single instance lock guide for details. Example:
Vous pouvez également activer le verrouillage par instance unique pour votre application. Dans ce cas, lorsque vous ouvrez un fichier avec votre application, la nouvelle instance d'application n'est pas lancée
et les arguments sont passés à l'instance déjà en cours d'exécution. Consultez le guide de verrouillage de l'instance unique pour plus de détails. Exemple:
```go title="main.go"
func main() {
// Create application with options
// Création d'une application avec des options
err := wails.Run(&options.App{
Title: "wails-open-file",
Width: 1024,
@ -116,11 +116,11 @@ func main() {
### Linux
Currently, Wails doesn't support bundling for Linux. So, you need to create file associations manually.
For example if you distribute your app as a .deb package, you can create file associations by adding required files in you bundle.
You can use [nfpm](https://nfpm.goreleaser.com/) to create .deb package for your app.
Actuellement, Wails ne prend pas en charge l'association de fichiers pour Linux. Vous devez donc créer des associations de fichiers manuellement.
Par exemple, si vous distribuez votre application en tant que package .deb, vous pouvez créer des associations de fichiers en ajoutant les fichiers requis dans votre bundle.
Vous pouvez utiliser [nfpm](https://nfpm.goreleaser.com/) pour créer un package .deb pour votre application.
1. Create a .desktop file for your app and specify file associations there. Example:
1. Créez un fichier .desktop pour votre application et spécifiez des associations de fichiers là-bas. Exemple:
```ini
[Desktop Entry]
@ -133,7 +133,7 @@ Type=Application
MimeType=application/x-wails;application/x-test
```
2. Create mime types file. Example:
2. Créer un fichier de type MIME. Exemple:
```xml
<?xml version="1.0" encoding="UTF-8"?>
@ -145,19 +145,19 @@ MimeType=application/x-wails;application/x-test
</mime-info>
```
3. Create icons for your file types. SVG icons are recommended.
4. Prepare postInstall/postRemove scripts for your package. Example:
3. Créez des icônes pour vos types de fichiers. Les icônes SVG sont recommandées.
4. Préparez les scripts postInstall/postRemove pour votre paquet. Exemple:
```sh
# reload mime types to register file associations
# Recharge les types MIME pour enregistrer votre association de fichiers
update-mime-database /usr/share/mime
# reload desktop database to load app in list of available
# Recharge la base de données du bureau afin de rendre disponible votre application dans les choix possibles
update-desktop-database /usr/share/applications
# update icons
# Mise à jour des icônes
update-icon-caches /usr/share/icons/*
```
5. Configure nfpm to use your scripts and files. Example:
5. Configurez nfpm pour utiliser vos scripts et fichiers. Exemple:
```yaml
name: "wails-open-file"
@ -198,15 +198,14 @@ scripts:
postremove: ./postRemove.sh
```
6. Build your .deb package using nfpm:
6. Construisez votre paquet .deb en utilisant nfpm:
```sh
nfpm pkg --packager deb --target .
```
7. Now when your package is installed, your app will be associated with specified file types. When you open file with your app,
new instance of app is launched and file path is passed as argument to your app.
To handle this you should parse command line arguments in your app. Example:
7. Maintenant que votre paquet est installé, votre application sera associée aux types de fichiers qui ont été spécifiés. Lorsque vous ouvrez un fichier avec votre application, une nouvelle instance est lancée et le chemin du fichier est passé en argument à votre application.
Pour gérer cela, vous devez analyser les arguments de la ligne de commande dans votre application. Exemple:
```go title="main.go"
func main() {
@ -218,12 +217,12 @@ func main() {
}
```
You also can enable single instance lock for your app. In this case, when you open file with your app, new instance of app is not launched
and arguments are passed to already running instance. Check single instance lock guide for details. Example:
Vous pouvez également activer le verrouillage par instance unique pour votre application. Dans ce cas, lorsque vous ouvrez un fichier avec votre application, la nouvelle instance d'application n'est pas lancée
et les arguments sont passés à l'instance déjà en cours d'exécution. Consultez le guide de verrouillage de l'instance unique pour plus de détails. Exemple:
```go title="main.go"
func main() {
// Create application with options
// Création d'une application avec des options
err := wails.Run(&options.App{
Title: "wails-open-file",
Width: 1024,

View file

@ -2,7 +2,7 @@
Cette page a divers guides liés au développement d'applications Wails pour Linux.
## Le tag vidéo ne déclenche pas l'événement "terminé"
## Video tag doesn't fire "ended" event
Lorsque vous utilisez un tag vidéo, l'événement "terminé" n'est pas déclenché lorsque la vidéo est finie. Ceci est un bogue dans WebkitGTK, cependant vous pouvez utiliser le contournement suivant pour le corriger :
@ -16,3 +16,55 @@ videoTag.addEventListener("timeupdate", (event) => {
```
Source : [Lyimmi](https://github.com/Lyimmi) sur le [forum de discussion](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275)
## GStreamer error when using Audio or Video elements
If you are seeing the following error when including `<Audio>` or `<Video>` elements on Linux, you may need to install `gst-plugins-good`.
```
GStreamer element autoaudiosink not found. Please install it
```
### Installing
Run the following distro relevant install command:
```mdx-code-block
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
<Tabs
defaultValue="Arch"
values={[
{ label: "Arch", value: "Arch" },
{ label: "Debian/Ubuntu", value: "Debian" },
{ label: "Fedora", value: "Fedora" },
]}
>
<TabItem value="Arch">
pacman -S gst-plugins-good
</TabItem>
<TabItem value="Debian">
apt-get install gstreamer1.0-plugins-good
</TabItem>
<TabItem value="Fedora">
dnf install gstreamer1-plugins-good
</TabItem>
</Tabs>
```
If the added package does not resolve the issue, additional GStreamer dependencies may be required. [See the GStreamer installation page for more details.](https://gstreamer.freedesktop.org/documentation/installing/on-linux.html)
### Additional Notes
- This issue is caused by [an upstream issue with WebkitGTK](https://bugs.webkit.org/show_bug.cgi?id=146351).
- [Arch based systems](https://wiki.archlinux.org/title/Arch-based_distributions) seem to have this issue more often than other distributions.
- This issue impacts [Tauri apps](https://tauri.app/).
Source: [developomp](https://github.com/developomp) on the [Tauri discussion board](https://github.com/tauri-apps/tauri/issues/4642#issuecomment-1643229562).

View file

@ -21,12 +21,12 @@ Cette page donne un bref aperçu de la façon de soumettre votre application Wai
3. Remplissez votre application avec les bonnes captures d'écran, descriptions, etc. selon les besoins d'Apple
4. Créer une nouvelle version de votre application
#### Create Provisioning Profile
1. Go to the [Apple Developer Profiles](https://developer.apple.com/account/resources/profiles/list) page
2. Add a new provisioning profile for Mac App Store Distribution
3. Set the Profile Type as Mac and select the App ID for the application created above
4. Select the Mac App Distribution certificate
5. Name the Provisioning Profile embedded and download the created profile.
#### Créer un profil de provisioning
1. Allez sur la page [Profils de Développeur Apple](https://developer.apple.com/account/resources/profiles/list)
2. Ajouter un nouveau profil de provisioning pour la distribution Mac App Store
3. Définissez le type de profil comme Mac et sélectionnez l'ID d'application pour l'application créée ci-dessus
4. Sélectionnez le certificat de distribution Mac App
5. Nommez le profil de provisioning intégré et téléchargez le profil créé.
## Processus Mac App Store
@ -36,7 +36,7 @@ Les applications soumises au Mac App Store doivent tourner dans la [Sandbox](htt
**Example de fichier Entitlements**
Ceci est un exemple du fichier entitlements de l'application [RiftShare](https://github.com/achhabra2/riftshare). Pour référence, veuillez mettre dans les droits requis par votre application. Reportez-vous à [ce site](https://developer.apple.com/documentation/bundleresources/entitlements) pour plus d'informations. You will need to replace the Team ID and Application Name with the ones you registered above.
Ceci est un exemple du fichier entitlements de l'application [RiftShare](https://github.com/achhabra2/riftshare). Pour référence, veuillez mettre dans les droits requis par votre application. Reportez-vous à [ce site](https://developer.apple.com/documentation/bundleresources/entitlements) pour plus d'informations. Vous devrez remplacer l'ID de l'équipe et le nom de l'application par ceux que vous avez enregistrés ci-dessus.
```xml title="entitlements.plist"
<?xml version="1.0" encoding="UTF-8"?>
@ -61,7 +61,7 @@ Ceci est un exemple du fichier entitlements de l'application [RiftShare](https:/
</plist>
```
**Add the Embedded Provisioning Profile** The Provisioning Profile created above needs to be added to the root of the applicaton. It needs to be named embedded.provisionprofile.
**Ajouter le profil de provisionnement incorporé** Le profil de provisioning créé ci-dessus doit être ajouté à la racine de l'application. Il doit être nommé embedded.provisionprofile.
#### Construire et signer le package de l'application

View file

@ -53,43 +53,43 @@ Cette étape peut être réalisée à partir de la ligne de commande ou d'un scr
##### Windows
- If `build/windows/icon.ico` does not exist, it will create it from `build/appicon.png` using icon sizes of 256, 128, 64, 48, 32 and 16. This is done using [winicon](https://github.com/leaanthony/winicon).
- If the `build/windows/<projectname>.manifest` file does not exist, it creates it from a default version.
- Compiles the application as a production build (above)
- Uses [winres](https://github.com/tc-hib/winres) to bundle the icon and manifest into a `.syso` file ready for linking.
- Si `build/windows/icon.ico` n'existe pas, il le créera à partir de `build/appicon.png` en utilisant les tailles dicônes de 256, 128, 64, 48, 32 et 16. Ceci est fait en utilisant [winicon](https://github.com/leaanthony/winicon).
- Si le fichier `build/windows/<projectname>.manifest` n'existe pas, il le crée à partir d'une version par défaut.
- Compile l'application en tant que version de production
- Utilise [winres](https://github.com/tc-hib/winres) pour regrouper l'icône et manifest dans un fichier `.syso` prêt à être lié.
#### Étapes manuelles
- Create `icon.ico` using the [winicon](https://github.com/leaanthony/winicon) CLI tool (or any other tool).
- Create / Update a `.manifest` file for your application
- Use the [winres CLI](https://github.com/tc-hib/go-winres) to generate a `.syso` file.
- Créez le fichier `icon.ico` en utilisant l'outil CLI [winicon](https://github.com/leaanthony/winicon) (ou n'importe quel autre outil).
- Créez / Mettez à jour un fichier `.manifest` pour votre application
- Utilisez le CLI [winres](https://github.com/tc-hib/go-winres) pour générer un fichier `.syso`.
### Compiler l'application
#### CLI Wails
- If the `-clean` flag is provided, the `build` directory is deleted and recreated
- For `wails dev`, the following default Go flags are used: `-tags dev -gcflags "all=-N -l"`
- For `wails build`, the following default Go flags are used: `-tags desktop,production -ldflags "-w -s"`
- On Windows, `-ldflags "-w -h -H windowsgui"`
- Additional tags passed to the CLI using `-tags` are added to the defaults
- Additional ldflags passed to the CLI using `-ldflags` are added to the defaults
- The `-o` flag is passed through
- The Go compiler specified by `-compiler` will be used for compilation
- Si l'option `-clean` est fourni, le répertoire `build` est supprimé et recréé
- Pour `wails dev`, les options suivantes de Go sont utilisées : `-tags dev -gcflags "all=-N -l"`
- Pour `wails build`, les options suivantes de Go sont utilisées : `-tags desktop,production -ldflags "-w -s"`
- Sous Windows, `-ldflags "-w -h -H windowsgui"`
- Des tags additionnels peuvent être ajoutées à la liste par défaut en utilisant l'option `-tags` dans le CLI
- Des ldftags additionnels peuvent être ajoutés à la liste par défaut en utilisant l'option `-ldflags` dans le CLI
- L'option `-o` est transmise
- Le compilateur Go spécifié par `-compiler` sera utilisé pour la compilation
#### Manual steps
#### Étapes manuelles
- For dev build, the minimum command would be: `go build -tags dev -gcflags "all=-N -l"`
- For production build, the minimum command would be: `go build -tags desktop,production -ldflags "-w -s -H windowsgui"`
- Ensure that you compile in the same directory as the `.syso` file
- Pour la compilation du dev, la commande minimale serait : `go build -tags dev -gcflags "all=-N -l"`
- Pour la compilation en production, la commande minimale serait : `go build -tags desktop,production -ldflags "-w -s -H windowsgui"`
- Assurez-vous que vous compilez dans le même répertoire que le fichier `.syso`
### Compress application
### Compresser l'application
#### CLI Wails
- If the `-upx` flag has been given, the `upx` program will be run to compress the application with the default settings
- If `-upxflags` is also passed, these flags are used instead of the default ones
- Si l'option `-upx` est définie, le programme `upx` sera exécuté pour compresser l'application avec les paramètres par défaut
- Si l'option `-upxflags` est également passée, les options définies seront utilisées à la place des options par défaut
#### Manual steps
#### Étapes manuelles
- Run `upx [flags]` manually to compress the application.
- Exécutez manuellement `upx [flags]` pour compresser l'application.

View file

@ -1,14 +1,14 @@
# Migrating from v1
# Migration depuis la v1
## Overview
## Vue d'ensemble
Wails v2 is a significant change from v1. This document aims to highlight the changes and the steps in migrating an existing project.
Les changements dans Wails v2 comparés à la v1 sont significatifs. Ce document vise à mettre en évidence les changements et les étapes à suivre pour migrer un projet existant.
### Creating the Application
### Création de lApplication
In v1, the main application is created using `wails.CreateApp`, bindings are added with `app.Bind`, then the application is run using `app.Run()`.
Dans v1, l'application principale est créée à l'aide de `wails.CreateApp`, les liaisons sont ajoutées avec `app.Bind`, et l'application est alors exécutée en utilisant `app.Run()`.
Example:
Exemple:
```go title="v1"
app := wails.CreateApp(&wails.AppConfig{
@ -23,7 +23,7 @@ Example:
app.Run()
```
In v2, there is just a single method, `wails.Run()`, that accepts [application options](../reference/options.mdx#application-options).
Dans la v2, il n'y a qu'une seule méthode, `wails.Run()`, qui en paramètre les [options de l'application](../reference/options.mdx#application-options).
```go title="v2"
err := wails.Run(&options.App{
@ -39,9 +39,9 @@ In v2, there is just a single method, `wails.Run()`, that accepts [application o
})
```
### Binding
### Liaisons
In v1, it was possible to bind both arbitrary functions and structs. In v2, this has been simplified to only binding structs. The struct instances that were previously passed to the `Bind()` method in v1, are now specified in the `Bind` field of the [application options](../reference/options.mdx#application-options):
En v1, il était possible de lier à la fois des fonctions arbitraires et des structs. Dans la v2, cela a été simplifié pour seulement lier des structs. Les instances de struct qui étaient passées à la méthode `Bind()` dans v1, sont maintenant spécifiés dans le champ `Bind` des [options de l'application](../reference/options.mdx#application-options):
```go title="v1"
app := wails.CreateApp(/* options */)
@ -57,19 +57,19 @@ In v1, it was possible to bind both arbitrary functions and structs. In v2, this
})
```
In v1, bound methods were available to the frontend at `window.backend`. This has changed to `window.go`.``
Dans v1, les méthodes liées étaient disponibles sur dans le frontend via `window.backend`. Cela a changé pour `window.go`.``
### Application Lifecycle
### Cycle de vie de l'application
In v1, there were 2 special methods in a bound struct: `WailsInit()` and `WailsShutdown()`. These have been replaced with 3 lifecycle hooks as part of the [application options](../reference/options.mdx#application-options):
En v1, il y avait 2 méthodes spéciales dans un struct lié : `WailsInit()` et `WailsShutdown()`. Cela a été remplacé par trois hooks faisant partis des [options de l'application](../reference/options.mdx#application-options):
- [OnStartup](../reference/options.mdx#onstartup)
- [OnShutdown](../reference/options.mdx#onshutdown)
- [OnDomReady](../reference/options.mdx#ondomready)
Note: [OnDomReady](../reference/options.mdx#ondomready) replaces the `wails:ready` system event in v1.
Remarque : [OnDomReady](../reference/options.mdx#ondomready) remplace l'événement système `wails:ready` de la v1.
These methods can be standard functions, but a common practice is to have them part of a struct:
Ces méthodes peuvent être des fonctions simples, mais une bonne pratique est de les lier à un struct :
```go title="v2"
basic := NewBasicApp()
@ -91,9 +91,9 @@ func (b *Basic) startup(ctx context.Context) {
### Runtime
The runtime in v2 is much richer than v1 with support for menus, window manipulation and better dialogs. The signature of the methods has changed slightly - please refer the the [Runtime Reference](../reference/runtime/intro.mdx).
Le runtime de la v2 est beaucoup plus riche que dans la v1 avec le support des menus, la manipulation des fenêtres et de meilleures boites de dialogues. La signature des méthodes a légèrement changé - veuillez vous référer à la [référence du Runtime](../reference/runtime/intro.mdx).
In v1, the [runtime](../reference/runtime/intro.mdx) was available via a struct passed to `WailsInit()`. In v2, the runtime has been moved out to its own package. Each method in the runtime takes the `context.Context` that is passed to the [OnStartup](../reference/options.mdx#onstartup) method.
Dans la v1, le [runtime](../reference/runtime/intro.mdx) était disponible via un struct passé à `WailsInit()`. Dans v2, l'exécutable a été déplacé vers son propre paquet. Chaque méthode dans le runtime prend le contexte `Context` qui est passé à la méthode [OnStartup](../reference/options.mdx#onstartup).
```go title="Runtime Example"
package main
@ -112,24 +112,24 @@ func (a *App) startup(ctx context.Context) {
```
### Assets
### Ressources
The _biggest_ change in v2 is how assets are handled.
Le _plus grand_ changement dans la v2 est la façon dont les actifs sont gérés.
In v1, assets were passed via 2 application options:
En v1, les ressources sont passées via l'une des 2 options de l'application :
- `JS` - The application's JavaScript
- `CSS` - The application's CSS
- `JS` - Le JavaScript de l'application
- `CSS` - Le CSS de l'application
This meant that the responsibility of generating a single JS and CSS file was on the developer. This essentially required the use of complicated packers such as webpack.
Cela signifie que la responsabilité du développeur de générer un seul fichier JS et CSS. Cela nécessitait essentiellement l'utilisation de paquets compliqués tels que le webpack.
In v2, Wails makes no assumptions about your frontend assets, just like a webserver. All of your application assets are passed to the application options as an `embed.FS`.
En v2, Wails ne fait aucune hypothèse à propos de vos ressources en frontend, tout comme un serveur web. Toutes les ressources de votre application sont passées aux options de l'application en tant que `embed.FS`.
**This means there is no requirement to bundle your assets, encode images as Base64 or attempt the dark art of bundler configuration to use custom fonts**.
**Cela signifie qu'il n'y a pas de prérequis pour le regroupement de vos assets, l'encodage en base64 pour vos images ou tenter de configurer un regroupement de vos polices d'écriture personnalisées**.
At startup, Wails will scan the given `embed.FS` for `index.html` and use its location as the root path for all the other application assets - just like a webserver would.
Au démarrage, Wails va scanner `embed.FS` pour trouver `index.html` et utiliser son emplacement comme chemin racine pour toutes les autres ressources de l'application - comme le ferait un serveur web.
Example: An application has the following project layout. All final assets are placed in the `frontend/dist` directory:
Exemple : Une application est structurée de la manière suivante. Toutes les ressources finales sont placées dans le dossier `frontend/dist`:
```shell
.
@ -144,7 +144,7 @@ Example: An application has the following project layout. All final assets are p
└── wails.json
```
Those assets may be used by the application by simply creating an `embed.FS`:
Ces ressources peuvent être utilisées par l'application en créant simplement un `embed.FS`:
```go title="Assets Example"
//go:embed all:frontend/dist
@ -160,32 +160,32 @@ func main() {
}
```
Of course, bundlers can be used if you wish to. The only requirement is to pass the final application assets directory to Wails using an `embed.FS` in the `Assets` key of the [application options](../reference/options.mdx#application-options).
Bien sûr, les bundlers peuvent être utilisés si vous le souhaitez. La seule obligation est de donner à Wails le dossier contenant toutes les ressources en utilisant `embed.FS` dans le champ `Assets` des [options de l'application](../reference/options.mdx#application-options).
### Project Configuration
### Configuration du projet
In v1, the project configuration was stored in the `project.json` file in the project root. In v2, the project configuration is stored in the `wails.json` file in the project root.
Dans v1, la configuration du projet a été stockée dans le fichier `project.json` à la racine du projet. Dans la v2, la configuration du projet est stockée dans le fichier `wails.json` à la racine du projet.
The format of the file is slightly different. Here is a comparison:
Le format du fichier est légèrement différent. Voici une comparaison:
<p align="center">
| v1 | v2 | Notes |
| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | name | |
| description | | Removed |
| description | | Retiré |
| author / name | author / name | |
| author / email | author / email | |
| version | version | |
| binaryname | outputfilename | Changed |
| frontend / dir | | Removed |
| frontend / install | frontend:install | Changed |
| frontend / build | frontend:build | Changed |
| frontend / bridge | | Removed |
| frontend / serve | | Removed |
| tags | | Removed |
| | wailsjsdir | The directory to generate wailsjs modules |
| | assetdir | The directory of the compiled frontend assets for `dev` mode. This is normally inferred and could be left empty. |
| | reloaddirs | Comma separated list of additional directories to watch for changes and to trigger reloads in `dev` mode. This is only needed for some more advanced asset configurations. |
| binaryname | outputfilename | Changé |
| frontend / dir | | Retiré |
| frontend / install | frontend:install | Changé |
| frontend / build | frontend:build | Changé |
| frontend / bridge | | Retiré |
| frontend / serve | | Retiré |
| tags | | Retiré |
| | wailsjsdir | Le dossier où les modules wailsjs seront générés |
| | assetdir | Le dossier où les ressources compilées du frontend seront stockées en mode `dev`. Cela est normalement déduit et pourrait être laissé vide. |
| | reloaddirs | Liste de répertoires supplémentaires séparés par des virgules pour surveiller les changements et déclencher des recharges en mode `dev`. Ceci n'est nécessaire que pour certaines configurations plus avancées. |
</p>

View file

@ -1,6 +1,6 @@
# Mouse Buttons
# Boutons de Souris
The Wails runtime intercepts mouse clicks to determine whether a frameless window needs resizing or a window needs to be moved. It has been asked how to detect when a mouse click has occurred, because `window.onclick` doesn't report the mouse buttons correctly. The following code shows how to detect mouse clicks:
Le runtime Wails intercepte les clics de souris pour déterminer si une fenêtre sans cadre a besoin d'être redimensionnée ou si une fenêtre doit être déplacée. Il a été demandé comment détecter quand un clic de souris s'est produit, parce que `window.onclick` ne signale pas correctement les boutons de la souris. Le code suivant montre comment détecter les clics de souris :
```javascript
window.addEventListener("mousedown", handleMouseButtonDown);
@ -22,4 +22,4 @@ function handleMouseButtonDown(event) {
}
```
Reference: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
Référence : https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

View file

@ -0,0 +1,10 @@
# NixOS FontSize Bug
NixOS/Wayland can cause a bug where the `font-size` css property doesnt affect the rendered page. To fix this add the following to your devShell.
```shell
shellHook = with pkgs; ''
export XDG_DATA_DIRS=${gsettings-desktop-schemas}/share/gsettings-schemas/${gsettings-desktop-schemas.name}:${gtk3}/share/gsettings-schemas/${gtk3.name}:$XDG_DATA_DIRS;
export GIO_MODULE_DIR="${pkgs.glib-networking}/lib/gio/modules/";
'';
```

View file

@ -1,32 +1,32 @@
# Obfuscated Builds
# Constructions obfusquées
Wails includes support for obfuscating your application using [garble](https://github.com/burrowers/garble).
Wails inclut le support pour masquer votre application en utilisant [garble](https://github.com/burrowers/garble).
To produce an obfuscated build, you can use the `-obfuscate` flag with the `wails build` command:
Pour produire une version obfusquée, vous pouvez utiliser l'option `-obfuscate` avec la commande `wails build`:
```bash
wails build -obfuscated
```
To customise the obfuscation settings, you can use the `-garbleargs` flag:
Pour personnaliser les paramètres d'obfuscation, vous pouvez utiliser l'option `-garbleargs`:
```bash
wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed"
```
These settings may be persisted in your [project config](../reference/project-config).
Ces paramètres peuvent être maintenus dans la [configuration de votre projet](../reference/project-config).
## How it works
## Comment ça marche
In a standard build, all bound methods are available in the frontend under the `window.go` variable. When these methods are called, the corresponding backend method is called using the fully qualified function name. When using an obfuscated build, methods are bound using an ID instead of a name. The bindings generated in the `wailsjs` directory use these IDs to call the backend functions.
Dans une compilation standard, toutes les méthodes liées sont disponibles dans le frontend sous la variable `window.go` . Lorsque ces méthodes sont appelées, la méthode d'arrière-plan correspondante est appelée en utilisant le nom de la fonction. Lors de l'utilisation d'une compilation obfusquée, les méthodes sont liées en utilisant un ID au lieu d'un nom. Les liaisons générées dans le répertoire `wailsjs` utilisent ces IDs pour appeler les fonctions backend.
:::note
To ensure that your application will work in obfuscated mode, you must use the generated bindings under the `wailsjs` directory in your application.
Pour vous assurer que votre application fonctionnera en mode masqué, vous devez utiliser les liaisons générées dans le répertoire `wailsjs` de votre application.
:::
## Example
## Exemple
Importing the "Greet" method from the bindings like this:
@ -37,4 +37,4 @@ import { Greet } from "../../wailsjs/go/main/App";
Greet("World");
```
will ensure that the method will work correctly in obfuscated mode, as the bindings will be regenerated with IDs and the call mechanism updated.
Cela assurera que la méthode fonctionnera correctement en mode obfusqué, car les liaisons seront régénérées avec des identifiants et le mécanisme d'appel mis à jour.

View file

@ -1,6 +1,6 @@
# Overscroll
[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) is the "bounce effect" you sometimes get when you scroll beyond a page's content boundaries. This is common in mobile apps. This can be disabled using CSS:
[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) est l'effet de rebond que vous obtenez parfois lorsque vous faites défiler au-delà des limites de contenu d'une page. Ceci est courant dans les applications mobiles. Cette option peut être désactivée en utilisant le code CSS suivant :
```css
html {

View file

@ -1,10 +1,10 @@
# Routing
# Routage
Routing is a popular way to switch views in an application. This page offers some guidance around how to do that.
Le routage est un moyen populaire de changer de vue dans une application. Cette page offre quelques conseils sur la façon de le faire.
## Vue
The recommended approach for routing in Vue is [Hash Mode](https://next.router.vuejs.org/guide/essentials/history-mode.html#hash-mode):
L'approche recommandée pour le routage dans Vue est le [Mode Hash](https://next.router.vuejs.org/guide/essentials/history-mode.html#hash-mode):
```js
import { createRouter, createWebHashHistory } from "vue-router";
@ -19,7 +19,7 @@ const router = createRouter({
## Angular
The recommended approach for routing in Angular is [HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies#_hashlocationstrategy):
L'approche recommandée pour le routage dans Angular est [HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies#_hashlocationstrategy):
```ts
RouterModule.forRoot(routes, { useHash: true });
@ -27,7 +27,7 @@ RouterModule.forRoot(routes, { useHash: true });
## React
The recommended approach for routing in React is [HashRouter](https://reactrouter.com/en/main/router-components/hash-router):
L'approche recommandée pour le routage dans React est [HashRouter](https://reactrouter.com/en/main/router-components/hash-router):
```jsx
import { HashRouter } from "react-router-dom";

View file

@ -211,7 +211,7 @@ jobs:
path: build/bin/*
```
For code signing on macOS, [gon](https://github.com/mitchellh/gon) is a very handy tool for code signing and communicating with Apple servers, also written in Go, and will be used in this guide.
For code signing on macOS, [gon](https://github.com/Bearer/gon) is a very handy tool for code signing and communicating with Apple servers, also written in Go, and will be used in this guide.
After the `Build Wails app` step, add the following to the workflow:
@ -219,7 +219,7 @@ After the `Build Wails app` step, add the following to the workflow:
- name: MacOS download gon for code signing and app notarization
if: matrix.platform == 'macos-latest'
run: |
brew install mitchellh/gon/gon
brew install Bearer/tap/gon
```
Now we need to configure some gon config files in our `build/darwin` directory:
@ -232,18 +232,30 @@ Now we need to configure some gon config files in our `build/darwin` directory:
"bundle_id": "app.myapp",
"apple_id": {
"username": "my-appleid@email.com",
"password": "@env:APPLE_PASSWORD"
"password": "@env:APPLE_PASSWORD",
"provider": "ABCDE12345"
},
"sign": {
"application_identity": "Developer ID Application: My Name"
"application_identity": "Developer ID Application: Human User"
}
}
```
Where `source` is your Wails binary, `bundle_id` is your bundle ID, `apple_id` contains your Apple ID username and App-Specific password which you created earlier, and `sign.application_identity` is your identity which you can find by running the following command:
Here is a brief break down of the above fields:
- `source`: The location of your wails binary to be signed
- `apple_id`:
- `username`: Your Apple ID email address
- `password`: Your app-specific password, referenced using Gon's environment variable syntax
- `provider`: Your team ID for your App Store Connect account
- `sign`:
- `application_identity`: Your Apple developer identity
Your developer identity and team ID can both by found on macOS by running the following command:
```bash
security find-identity -v -p codesigning
$ security find-identity -v -p codesigning
1) 00000000000000000000000000000000000000000 "Developer ID Application: Human User (ABCDE12345)"
```
2. entitlements.plist:
@ -345,7 +357,7 @@ jobs:
- name: MacOS download gon for code signing and app notarization
if: matrix.platform == 'macos-latest'
run: |
brew install mitchellh/gon/gon
brew install Bearer/tap/gon
- name: Import Code-Signing Certificates for macOS
if: matrix.platform == 'macos-latest'
uses: Apple-Actions/import-codesign-certs@v1

View file

@ -1,66 +1,70 @@
# SvelteKit
This guide will go into:
Ce tutoriel va vous présenter :
1. Miminal Installation Steps - The steps needed to get a minimum Wails setup working for SvelteKit.
2. Install Script - Bash script for accomplishing the Minimal Installation Steps with optional Wails branding.
3. Important Notes - Issues that can be encountered when using SvelteKit + Wails and fixes.
1. L'installation minimale - Les étapes à suivre au minimum pour avoir Wails fonctionnant avec SvelteKit.
2. Script d'installation - Script Bash pour réaliser les étapes d'installation minimale avec la marque Wails (pouvant être changée dans les options).
3. Notes importantes - Problèmes qui peuvent être rencontrés avec SvelteKit + Wails et comment les corriger.
## 1. Minimal Installation Steps
## 1. Étapes d'installation minimales
##### Install Wails for Svelte.
##### Installer Wails pour Svelte.
- `wails init -n myapp -t svelte`
##### Delete the svelte frontend.
##### Supprimer le frontend svelte.
- Navigate into your newly created myapp folder.
- Delete the folder named "frontend"
- Naviguez dans votre dossier myapp nouvellement créé.
- Supprimer le dossier nommé "frontend"
##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts.
##### Lorsque vous êtes dans le dossier racine du projet Wails. Utilisez votre gestionnaire de paquets préféré et installez SvelteKit comme nouveau frontend. Suivez les instructions.
- `npm create svelte@latest frontend`
##### Modify wails.json.
##### Modifier wails.json.
- Add `"wailsjsdir": "./frontend/src/lib",` Do note that this is where your Go and runtime functions will appear.
- Change your package manager frontend here if not using npm.
- Ajoutez `"wailsjsdir": "./frontend/src/lib",` Notez que c'est là que vos fonctions Go et runtime apparaîtront.
- Changez le frontend de votre gestionnaire de paquets si vous n'utilisez pas npm.
##### Modify main.go.
##### Modifier main.go.
- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build`
- Le premier commentaire `//go:embed all:frontend/dist` doit être changé en `//go:embed all:frontend/build`
##### Install/remove dependencies using your favorite package manager.
##### Modify .gitignore
- Navigate into your "frontend" folder.
- The line `frontend/dist` needs to be replaced with `frontend/build`
##### Installez / supprimez des dépendances en utilisant votre gestionnaire de paquets favori.
- Naviguez dans votre dossier "frontend".
- `npm i`
- `npm uninstall @sveltejs/adapter-auto`
- `npm i -D @sveltejs/adapter-static`
##### Change adapter in svelte.config.js
##### Changer l'adaptateur dans svelte.config.js
- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';`
- La première ligne du fichier `import adapter from '@sveltejs/adapter-auto';` doit être changée en `import adapter from '@sveltejs/adapter-static';`
##### Put SvelteKit into SPA mode with prerendering.
##### Mettez SvelteKit en mode SPA avec la prévision.
- Create a file under myapp/frontend/src/routes/ named +layout.ts/+layout.js.
- Add two lines into the newly created file `export const prerender = true` and `export const ssr = false`
- Créez un fichier sous myapp/frontend/src/routes/ nommé +layout.ts/+layout.js.
- Ajoutez les deux lignes suivantes dans le fichier nouvellement créé : `export const prerender = true` et `export const ssr = false`
##### Test installation.
##### Tester l'installation.
- Navigate back into the Wails project root (one directory up).
- run `wails dev`
- If the application doesn't run please check through the previous steps.
- Naviguez à la racine du projet Wails
- Exécuter `wails dev`
- Si l'application ne fonctionne pas, veuillez vérifier les étapes précédentes.
## 2. Install Script
## 2. Script d'installation
##### This Bash Script does the steps listed above. Make sure to read over the script and understand what the script is doing on your computer.
##### Ce script Bash fait les étapes énumérées ci-dessus. Assurez-vous de lire le script et de comprendre ce que le script fait sur votre ordinateur.
- Create a file sveltekit-wails.sh
- Copy the below code into the new file then save it.
- Make it executable with `chmod +x sveltekit-wails.sh`
- Brand is an optional param below that adds back in the wails branding. Leave third param blank to not insert the Wails branding.
- Example usage: `./sveltekit-wails.sh pnpm newapp brand`
- Crée un fichier sveltekit-wails.sh
- Copie le code ci-dessous dans le nouveau fichier puis l'enregistre.
- Rende le script exécutable avec `chmod +x sveltekit-wails.sh`
- La marque est un paramètre optionnel qui ajoute à la marque Wails. Laissez vide le troisième paramètre pour ne pas insérer la marque Wails.
- Exemple d'utilisation : `./sveltekit-wails.sh pnpm newapp brand`
##### sveltekit-wails.sh:
@ -96,17 +100,17 @@ cd ..
wails dev
```
## 3. Important Notes
## 3. Notes importantes
##### Server files will cause build failures.
##### Les fichiers serveur provoqueront des échecs de compilation.
- \+layout.server.ts, +page.server.ts, +server.ts or any file with "server" in the name will fail to build as all routes are prerendered.
- \+layout.server.ts, +page.server.ts, +server.ts ou tout fichier avec "server" dans le nom échouera car toutes les routes sont prédéfinies.
##### The Wails runtime unloads with full page navigations!
##### Le runtime Wails se décharge avec des pages de navigation complètes !
- Anything that causes full page navigations: `window.location.href = '/<some>/<page>'` or Context menu reload when using wails dev. What this means is that you can end up losing the ability to call any runtime breaking the app. There are two ways to work around this.
- Use `import { goto } from '$app/navigation'` then call `goto('/<some>/<page>')` in your +page.svelte. This will prevent a full page navigation.
- If full page navigation can't be prevented the Wails runtime can be added to all pages by adding the below into the `<head>` of myapp/frontend/src/app.html
- Tout ce qui provoque la navigation de page complète : `window.location.href = '/<some>/<page>'` ou le menu contextuel se recharge lorsque vous utilisez wails dev. Cela signifie que vous pouvez finir par perdre la possibilité d'appeler n'importe quel runtime cassant l'application. Il y a deux façons de contourner ce problème.
- Utilisez `import { goto } de '$app/navigation'` puis appelez `goto('/<some>/<page>')` dans votre +page.svelte. Cela empêchera la navigation de la page complète.
- Si la navigation de la page complète ne peut pas être empêchée, le runtime Wails peut être ajouté à toutes les pages en ajoutant ce qui suit dans le `<head>` de myapp/frontend/src/app.html
```
<head>
@ -118,17 +122,17 @@ wails dev
</head>
```
See https://wails.io/docs/guides/frontend for more information.
Voir https://wails.io/docs/guides/frontend pour plus d'informations.
##### Inital data can be loaded and refreshed from +page.ts/+page.js to +page.svelte.
##### Les données initiales peuvent être chargées et actualisées de +page.ts/+page.js à +page.svelte.
- \+page.ts/+page.js works well with load() https://kit.svelte.dev/docs/load#page-data
- invalidateAll() in +page.svelte will call load() from +page.ts/+page.js https://kit.svelte.dev/docs/load#rerunning-load-functions-manual-invalidation.
- \+page.ts/+page.js fonctionne bien avec la fonction load() https://kit.svelte.dev/docs/load#page-data
- invalidateAll() dans +page.svelte appellera la fonction load() de +page.ts/+page.js https://kit.svelte.dev/docs/load#rerunning-load-functions-manual-invalidation.
##### Error Handling
##### Gestion des erreurs
- Expected errors using Throw error works in +page.ts/+page.js with a +error.svelte page. https://kit.svelte.dev/docs/errors#expected-errors
- Unexpected errors will cause the application to become unusable. Only recovery option (known so far) from unexpected errors is to reload the app. To do this create a file myapp/frontend/src/hooks.client.ts then add the below code to the file.
- Les erreurs attendues en utilisant Throw fonctionne dans +page.ts/+page.js avec une page +error.svelte. https://kit.svelte.dev/docs/errors#expected-errors
- Des erreurs inattendues rendront l'application inutilisable. Seule l'option de récupération (connue jusqu'ici) des erreurs inattendues est de recharger l'application. Pour ce faire, créez un fichier myapp/frontend/src/hooks.client.ts puis ajoutez le code ci-dessous au fichier.
```
import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime'
@ -137,10 +141,10 @@ export async function handleError() {
}
```
##### Using Forms and handling functions
##### Utilisation des formulaires et des fonctions de gestion
- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `<form method="POST" on:submit|preventDefault={handle}>`
- The more advanced way is to use:enhance (progressive enhancement) which will allow for convenient access to formData, formElement, submitter. The important note is to always cancel() the form which prevents server side behavior. https://kit.svelte.dev/docs/form-actions#progressive-enhancement Example:
- Le moyen le plus simple est d'appeler une fonction du formulaire est le standard bind:value vos variables et de prévenir la soumission avec `<form method="POST" on:submit|preventDefault={handle}>`
- La façon la plus avancée est d'utiliser l'action use:enhance (amélioration progressive) qui permettra un accès pratique aux formData, formElement et submitter. La note importante est de toujours utiliser cancel() pour prévenir certains comportements côté serveur. https://kit.svelte.dev/docs/form-actions#progressive-enhancement Exemple:
```
<form method="POST" use:enhance={({cancel, formData, formElement, submitter}) => {

View file

@ -1,17 +1,17 @@
# Templates
Wails generates projects from pre-created templates. In v1, this was a difficult to maintain set of projects that were subject to going out of date. In v2, to empower the community, a couple of new features have been added for templates:
Wails génère des projets à partir de modèles pré-créés. Dans la v1, c'était difficile de maintenir un ensemble de projets pour qu'ils restent toujours à jour. Dans v2, pour augmenter l'impact de la communauté sur le projet, quelques nouvelles fonctionnalités ont été ajoutées pour les modèles :
- Ability to generate projects from [Remote Templates](../reference/cli.mdx#remote-templates)
- Tooling to help create your own templates
- Possibilité de générer des projets à partir de [Modèles à distance](../reference/cli.mdx#remote-templates)
- Outils pour aider à créer vos propres modèles
## Creating Templates
## Création de modèles
To create a template, you can use the `wails generate template` command. To generate a default template, run:
Pour créer un modèle, vous pouvez utiliser la commande `wails generate template`. Pour générer un modèle par défaut, exécutez :
`wails generate template -name mytemplate`
This creates the directory "mytemplate" with default files:
Cela crée le répertoire "mytemplate" avec les fichiers par défaut :
```shell title=mytemplate/
.
@ -35,31 +35,31 @@ This creates the directory "mytemplate" with default files:
`-- wails.tmpl.json
```
### Template Overview
### Vue d'ensemble du modèle
The default template consists of the following files and directories:
Le modèle par défaut consiste en l'ensemble des fichiers et répertoires suivants :
| Filename / Dir | Description |
| --------------- | -------------------------------------------- |
| NEXTSTEPS.md | Instructions on how to complete the template |
| README.md | The README published with the template |
| app.tmpl.go | `app.go` template file |
| frontend/ | The directory containing frontend assets |
| go.mod.tmpl | `go.mod` template file |
| main.tmpl.go | `main.go` template file |
| template.json | The template metadata |
| wails.tmpl.json | `wails.json` template file |
| Nom du fichier / dossier | Description |
| ------------------------ | ------------------------------------------------ |
| NEXTSTEPS.md | Instructions sur la façon de compléter le modèle |
| README.md | Le README publié avec le modèle |
| app.tmpl.go | Fichier modèle `app.go` |
| frontend/ | Le répertoire contenant les assets du frontend |
| go.mod.tmpl | Fichier modèle `go.mod` |
| main.tmpl.go | Fichier modèle `main.go` |
| template.json | Template des metadonnées du projet |
| wails.tmpl.json | Fichier modèle `wails.json` |
At this point it is advisable to follow the steps in `NEXTSTEPS.md`.
À ce stade, il est conseillé de suivre les étapes dans `NEXTSTEPS.md`.
## Creating a Template from an Existing Project
## Créer un modèle à partir d'un projet existant
It's possible to create a template from an existing frontend project by passing the path to the project when generating the template. We will now walk through how to create a Vue 3 template:
Il est possible de créer un modèle à partir d'un projet frontend déjà existant, en passant le chemin du projet lors de la génération du template. Nous allons maintenant parcourir comment créer un modèle Vue 3 :
- Install the vue cli: `npm install -g @vue/cli`
- Create the default project: `vue create vue3-base`
- Select `Default (Vue 3) ([Vue 3] babel, eslint)`
- After the project has been generated, run:
- Installez le CLI Vue: `npm install -g @vue/cli`
- Créer le projet par défaut : `vue create vue3-base`
- Sélectionnez `Default (Vue 3) ([Vue 3] babel, eslint)`
- Une fois le projet généré, exécutez :
```shell
> wails generate template -name wails-vue3-template -frontend .\vue3-base\
@ -71,11 +71,11 @@ Updating package-lock.json data...
Renaming package-lock.json -> package-lock.tmpl.json...
```
- The template may now be customised as specified in the `NEXTSTEPS.md` file
- Once the files are ready, it can be tested by running: `wails init -n my-vue3-project -t .\wails-vue3-template\`
- To test the new project, run: `cd my-vue3-project` then `wails build`
- Once the project has compiled, run it: `.\build\bin\my-vue3-project.exe`
- You should have a fully functioning Vue3 application:
- Le modèle peut maintenant être personnalisé comme spécifié dans le fichier `NEXTSTEPS.md`
- Une fois les fichiers prêts, il peut être testé en exécutant : `wails init -n my-vue3-project -t .\wails-vue3-template\`
- Pour tester le nouveau projet, exécutez : `cd my-vue3-project` puis `wails build`
- Une fois que le projet est compilé, exécutez-le : `.\build\bin\my-vue3-project.exe`
- Vous devriez avoir une application Vue3 pleinement fonctionnelle :
```mdx-code-block
<div className="text--center">
@ -86,12 +86,12 @@ Renaming package-lock.json -> package-lock.tmpl.json...
</div>
```
## Publishing Templates
## Publication de modèles
Publishing a template is simply pushing the files to GitHub. The following best practice is encouraged:
Pour publier un modèle, il vous faut simplement pousser les fichiers dans GitHub. Les bonnes pratiques suivantes sont encouragées :
- Remove any unwanted files and directories (such as `.git`) from your frontend directory
- Ensure that `template.json` is complete, especially `helpurl`
- Push the files to GitHub
- Create a PR on the [Community Templates](../community/templates.mdx) page
- Announce the template on the [Template Announcement](https://github.com/wailsapp/wails/discussions/825) discussion board
- Supprimer tous les fichiers et répertoires indésirables (comme `.git`) de votre répertoire frontend
- Assurez-vous que le fichier `template.json` est complet, spécifiquement `helpurl`.
- Envoyer les fichiers vers GitHub
- Créez un PR sur la page [Community Templates](../community/templates.mdx)
- Annoncer le modèle sur le forum de discussion [Template Announcement](https://github.com/wailsapp/wails/discussions/825)

View file

@ -1,4 +1,4 @@
# Troubleshooting
# Résolution de problèmes
An assortment of troubleshooting tips.

View file

@ -1,15 +1,15 @@
# Visual Studio Code
This page is for miscellaneous tips and tricks when using Visual Studio Code with Wails.
Cette page est destinée à divers trucs et astuces lors de l'utilisation de Visual Studio Code avec Wails.
## Vetur Configuration
## Configuration Vetur
Many thanks to [@Lyimmi](https://github.com/Lyimmi) for this tip. Originally posted [here](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349).
Un grand merci à [@Lyimmi](https://github.com/Lyimmi) pour ce conseil. A initialement posté [ici](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349).
Vetur is a popular plugin for Visual Studio Code that provides syntax highlighting and code completion for Vue projects. When loading a Wails project in VSCode, Vetur will throw an error as it is expecting to find the frontend project in the root directory. To fix this, you can do the following:
Vetur est un plugin populaire pour Visual Studio Code qui fournit la coloration syntaxique et la complétion du code pour les projets Vue. Lors du chargement d'un projet Wails en VSCode, Vetur lancera une erreur car il attend de trouver le projet frontend dans le répertoire racine. Pour résoudre ce problème, vous pouvez faire ce qui suit :
Create a file named `vetur.config.js` in the project's root.
Créer un fichier nommé `vetur.config.js` à la racine du projet.
```javascript
// vetur.config.js
@ -56,7 +56,7 @@ module.exports = {
}
```
Next, configure `frontend/tsconfig.json`:
Ensuite, configurez `frontend/tsconfig.json`:
```javascript
{
@ -79,4 +79,4 @@ Next, configure `frontend/tsconfig.json`:
]
}
```
This should enable you to now use Vetur as expected.
Cela devrait vous permettre d'utiliser Vetur comme prévu.

View file

@ -18,13 +18,26 @@ Wails prend en charge la génération d'installateurs Windows en utilisant l'ins
L'installateur est disponible sur la page [de téléchargement NSIS](https://nsis.sourceforge.io/Download).
You can install with [Scoop](https://scoop.sh/) (which will automatically add it to your PATH):
```
scoop add bucket extras
scoop install nsis
```
Or, you can use Winget (on Windows 10+):
```
winget install NSIS.NSIS --silent
```
Si vous utilisez le gestionnaire de paquets chocolatey, exécutez le script suivant :
```
choco install nsis
```
Si vous installez NSIS manuellement, vous devez ajouter le dossier _Bin_ , qui contient `makensis.exe`, dans la variable d'environnement PATH. [Cette page](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) est un bon tutoriel sur comment ajouter un dossier dans votre variable d'environnement PATH sur Windows.
**NOTE:** If you install NSIS manually, you need to add the _Bin_ folder, which contains `makensis.exe`, in your NSIS installation to your path. [Cette page](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) est un bon tutoriel sur comment ajouter un dossier dans votre variable d'environnement PATH sur Windows.
### Linux

View file

@ -1,12 +1,12 @@
# Windows
This page has miscellaneous guides related to developing Wails applications for Windows.
Cette page a divers guides liés au développement d'applications Wails pour Windows.
## Handling the WebView2 Runtime Dependency
## Gestion de la dépendance d'exécution WebView2
Wails applications built for Windows have a runtime requirement on the Microsoft [WebView2 Runtime](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). Windows 11 will have this installed by default, but some machines won't. Wails offers an easy approach to dealing with this dependency.
Les applications Wails construites pour Windows ont une exigence d'exécution sur le runtime Microsoft [WebView2 Runtime](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). Par défaut, Windows 11 l'a d'installé mais certaines machines ne l'ont pas. Wails offre une approche facile pour gérer cette dépendance.
By using the `-webview2` flag when building, you can decide what your application will do when a suitable runtime is not detected (including if the installed runtime is too old). The four options are:
En utilisant l'option `-webview2` lors de la construction, vous pouvez décider ce que votre application fera quand un runtime approprié n'est pas détecté (y compris si le runtime installé est trop ancien). Les quatre options sont :
1. Download
2. Embed
@ -15,25 +15,25 @@ By using the `-webview2` flag when building, you can decide what your applicatio
### Download
This option will prompt the user that no suitable runtime has been found and then offer to download and run the official bootstrapper from Microsoft's WebView2 site. If the user proceeds, the official bootstrapper will be downloaded and run.
Cette option demandera à l'utilisateur qu'aucun runtime approprié n'a été trouvé et proposera ensuite de télécharger et d'exécuter le bootstrapper officiel depuis le site WebView2 de Microsoft. Si l'utilisateur continue, le bootstrapper officiel sera téléchargé et exécuté.
### Embed
This option embeds the official bootstrapper within the application. If no suitable runtime has been found, the application will offer to run the bootstrapper. This adds ~150k to the binary size.
Cette option intègre le bootstrapper officiel dans l'application. Si aucun runtime approprié n'a été trouvé, l'application proposera d'exécuter le bootstrapper. Cela ajoute ~150k à la taille du binaire.
### Navigateur
This option will prompt the user that no suitable runtime has been found and then offer to open a browser to the official WebView2 page where the bootstrapper can be downloaded and installed. The application will then exit, leaving the installation up to the user.
Cette option demandera à l'utilisateur qu'aucun runtime approprié n'a été trouvé et proposera ensuite d'ouvrir un navigateur à la page officielle WebView2 où le bootstrapper peut être téléchargé et installé. L'application quittera alors en laissant l'installation à l'utilisateur.
### Error
If no suitable runtime is found, an error is given to the user and no further action taken.
Si aucun runtime approprié n'est trouvé, une erreur sera transmise à l'utilisateur et aucune autre action ne sera prise.
## Fixed version runtime
## Version du runtime fixe
Another way of dealing with webview2 dependency is shipping it yourself. You can download [fixed version runtime](https://developer.microsoft.com/microsoft-edge/webview2/#download-section) and bundle or download it with your application.
Une autre façon de gérer la dépendance de webview2 est de l'intégrer vous-même. Vous pouvez télécharger [une version du runtime](https://developer.microsoft.com/microsoft-edge/webview2/#download-section) et l'intégrer avec votre application.
Also, you should specify path to fixed version of webview2 runtime in the `windows.Options` structure when launching wails.
En outre, vous devez spécifier le chemin vers la version corrigée de webview2 runtime dans la structure `windows.Options` lors du lancement de wails.
```go
wails.Run(&options.App{
@ -43,11 +43,11 @@ Also, you should specify path to fixed version of webview2 runtime in the `windo
})
```
Note: When `WebviewBrowserPath` is specified, `error` strategy will be forced in case of minimal required version mismatch or invalid path to a runtime.
Note: Quand `WebviewBrowserPath` est spécifié, une ` strategy error` sera lancée si la version minimale à utiliser n'est pas requise ou si le chemin vers le runtime est incorrect.
## Spawning other programs
## Faire apparaître d'autres programmes
When spawning other programs, such as scripts, you will see the window appear on the screen. To hide the window, you can use the following code:
Lorsque vous faites apparaître d'autres programmes, comme des scripts, vous verrez apparaître la fenêtre à l'écran. Pour masquer la fenêtre, vous pouvez utiliser le code suivant :
```go
cmd := exec.Command("your_script.exe")
@ -58,4 +58,4 @@ cmd.SysProcAttr = &syscall.SysProcAttr{
cmd.Start()
```
Solution provided by [sithembiso](https://github.com/sithembiso) on the [discussions board](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172).
Solution fournie par [sithembiso](https://github.com/sithembiso) dans les [discussions GitHub](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172).

View file

@ -182,6 +182,56 @@ Vous pouvez lier autant de structures que vous le souhaitez. Assurez-vous juste
```
You may bind enums types as well. In that case you should create array that will contain all possible enum values, instrument enum type and bind it to the app via `EnumBind`:
```go {16-18} title="app.go"
type Weekday string
const (
Sunday Weekday = "Sunday"
Monday Weekday = "Monday"
Tuesday Weekday = "Tuesday"
Wednesday Weekday = "Wednesday"
Thursday Weekday = "Thursday"
Friday Weekday = "Friday"
Saturday Weekday = "Saturday"
)
var AllWeekdays = []struct {
Value Weekday
TSName string
}{
{Sunday, "SUNDAY"},
{Monday, "MONDAY"},
{Tuesday, "TUESDAY"},
{Wednesday, "WEDNESDAY"},
{Thursday, "THURSDAY"},
{Friday, "FRIDAY"},
{Saturday, "SATURDAY"},
}
```
```go {10-12}
//...
err := wails.Run(&options.App{
Title: "Basic Demo",
Width: 1024,
Height: 768,
AssetServer: &assetserver.Options{
Assets: assets,
},
Bind: []interface{}{
app,
&mystruct1{},
&mystruct2{},
},
EnumBind: []interface{}{
AllWeekdays,
},
})
```
Lorsque vous exécutez `wails dev` (ou `wails generate module`), un module frontend sera généré contenant les éléments suivants :
- JavaScript bindings pour toutes les méthodes liées

View file

@ -21,14 +21,16 @@ Considérez cela comme une alternative légère et rapide d'Electron pour Go. Vo
- Une riche bibliothèque [runtime](/docs/reference/runtime/intro)
- Les applications construites avec Wails sont conformes aux Stores Apple & Microsoft
Ceci est varly - une application de bureau pour MacOS & Windows écrite à l'aide de Wails. Non seulement elle est belle, elle utilise les menus natifs et la translucidité - tout ce que vous pouvez attendre d'une application native moderne.
Ceci est [varly](https://varly.app) - une application de bureau pour MacOS & Windows écrite à l'aide de Wails. Non seulement elle est belle, elle utilise les menus natifs et la translucidité - tout ce que vous pouvez attendre d'une application native moderne.
```mdx-code-block
<p class="text--center">
<a href="https://varly.app/">
<img
src={require("@site/static/img/showcase/varly2.webp").default}
style={{ width: "75%", "max-width": "800px" }}
/>
</a>
</p>
```
@ -40,7 +42,7 @@ Wails est livré avec un certain nombre de modèles préconfigurés qui vous per
Wails utilise une bibliothèque conçue pour gérer les éléments natifs tels que les fenêtres, menus, boîtes de dialogues, etc, pour que vous puissiez construire des applications de bureau riches en fonctionnalités.
**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. Sous Windows, c'est la nouvelle bibliothèque Microsoft Webview2, construite sur Chromium.
**Il n'intègre pas un navigateur**, donc il délivre un petit runtime. Au lieu de cela, il réutilise le moteur de rendu natif pour la plate-forme. Sous Windows, c'est la nouvelle bibliothèque Microsoft Webview2, construite sur Chromium.
### Interopérabilité Go & Javascript

View file

@ -49,35 +49,35 @@ Si vous n'êtes pas sûr d'un modèle, inspectez les fichiers `package.json` et
`wails build` est utilisé pour compiler votre projet vers un binaire prêt à la production.
| Option | Description | Par défaut |
|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| -clean | Nettoie le répertoire `build/bin` | |
| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go |
| -debug | Conserve les informations de débogage dans l'application et affiche la console de débogage. Permet l'utilisation des outils de développement dans la fenêtre de l'application | |
| -devtools | Allows the use of the devtools in the application window in production (when -debug is not used). Ctrl/Cmd+Shift+F12 may be used to open the devtools window. *NOTE*: This option will make your application FAIL Mac appstore guidelines. Use for debugging only. | |
| -dryrun | Affiche la commande build sans l'exécuter | |
| -f | Forcer la compilation de l'application | |
| -garbleargs | Arguments à passer à garble | `-literals -tiny -seed=random` |
| -ldflags "flags" | Options supplémentaires à passer au compilateur | |
| -m | Permet d'ignorer mod tidy avant la compilation | |
| -nopackage | Ne pas empaqueter l'application | |
| -nocolour | Désactive la couleur des logs dans le terminal | |
| -nosyncgomod | Ne pas synchroniser go.mod avec la version Wails | |
| -nsis | Génère l'installateur NSIS pour Windows | |
| -o filename | Nom du fichier de sortie | |
| -obfuscated | Cacher le code de l'application en utilisant [garble](https://github.com/burrowers/garble) | |
| -platform | Construit pour les [plates-formes](../reference/cli.mdx#platforms) données (séparées par des virgules) par exemple. `windows/arm64`. Notez que si vous ne donnez pas l'architecture, `runtime.GOARCH` est utilisé. | platform = le contenu de la variable d'environnement `GOOS` si elle existe, autrement `runtime.GOOS`.<br/>arch = le contenu de la variable d'environnement `GOARCH` si elle existe, autrement `runtime.GOARCH`. |
| -race | Construire avec le détecteur Go race | |
| -s | Ignorer la construction du frontend | |
| -skipbindings | Ignorer la génération des liaisons | |
| -tags "extra tags" | Options de compilation à passer au compilateur Go. Doivent être entre guillemets. Séparés par un espace ou une virgule (pas les deux) | |
| -trimpath | Supprimer tous les chemins vers les fichiers système de l'exécutable final. | |
| -u | Met à jour le `go.mod de votre projet` pour utiliser la même version de Wails que le CLI | |
| -upx | Compresser le binaire final en utilisant "upx" | |
| -upxflags | Options à passer à upx | |
| -v int | Niveau de verbosité (0 - silencieux, 1 - par défaut, 2 - verbeux) | 1 |
| -webview2 | Stratégie d'installation WebView2 : download,embed,browser,error | download |
| -windowsconsole | Garder la fenêtre de la console lors de la construction d'une version pour Windows | |
| Option | Description | Par défaut |
|:-------------------- |:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| -clean | Nettoie le répertoire `build/bin` | |
| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go |
| -debug | Conserve les informations de débogage dans l'application et affiche la console de débogage. Permet l'utilisation des outils de développement dans la fenêtre de l'application | |
| -devtools | Permet l'utilisation des devtools dans la fenêtre d'application en production (quand -debug n'est pas utilisé). Ctrl/Cmd+Maj+F12 peut être utilisé pour ouvrir la fenêtre devtools. *NOTE*: Cette option fera que votre application ne suivra plus les guidelines de l'appstore Mac. Utiliser uniquement pour le débogage. | |
| -dryrun | Affiche la commande build sans l'exécuter | |
| -f | Forcer la compilation de l'application | |
| -garbleargs | Arguments à passer à garble | `-literals -tiny -seed=random` |
| -ldflags "flags" | Options supplémentaires à passer au compilateur | |
| -m | Permet d'ignorer mod tidy avant la compilation | |
| -nopackage | Ne pas empaqueter l'application | |
| -nocolour | Désactive la couleur des logs dans le terminal | |
| -nosyncgomod | Ne pas synchroniser go.mod avec la version Wails | |
| -nsis | Génère l'installateur NSIS pour Windows | |
| -o filename | Nom du fichier de sortie | |
| -obfuscated | Cacher le code de l'application en utilisant [garble](https://github.com/burrowers/garble) | |
| -platform | Construit pour les [plates-formes](../reference/cli.mdx#platforms) données (séparées par des virgules) par exemple. `windows/arm64`. Notez que si vous ne donnez pas l'architecture, `runtime.GOARCH` est utilisé. | platform = le contenu de la variable d'environnement `GOOS` si elle existe, autrement `runtime.GOOS`.<br/>arch = le contenu de la variable d'environnement `GOARCH` si elle existe, autrement `runtime.GOARCH`. |
| -race | Construire avec le détecteur Go race | |
| -s | Ignorer la construction du frontend | |
| -skipbindings | Ignorer la génération des liaisons | |
| -tags "extra tags" | Options de compilation à passer au compilateur Go. Doivent être entre guillemets. Séparés par un espace ou une virgule (pas les deux) | |
| -trimpath | Supprimer tous les chemins vers les fichiers système de l'exécutable final. | |
| -u | Met à jour le `go.mod de votre projet` pour utiliser la même version de Wails que le CLI | |
| -upx | Compresser le binaire final en utilisant "upx" | |
| -upxflags | Options à passer à upx | |
| -v int | Niveau de verbosité (0 - silencieux, 1 - par défaut, 2 - verbeux) | 1 |
| -webview2 | Stratégie d'installation WebView2 : download,embed,browser,error | download |
| -windowsconsole | Garder la fenêtre de la console lors de la construction d'une version pour Windows | |
Pour une description détaillée des options `webview2` , veuillez vous référer au Guide de [Windows](../guides/windows.mdx).
@ -227,6 +227,11 @@ Pour plus de détails sur la création de modèles, consultez le [Guide sur les
La commande `wails génère le module` vous permet de générer manuellement le répertoire `wailsjs` pour votre application.
| Option | Description | Par défaut |
|:-------------------- |:-------------------------------------------------------------------------------------------- |:---------- |
| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go |
| -tags "extra tags" | Options de construction à passer au compilateur (séparées par des guillemets et des espaces) | |
## update
`wails update` va mettre à jour la version du CLI Wails.

View file

@ -52,16 +52,22 @@ func main() {
CSSDragValue: "drag",
EnableDefaultContextMenu: false,
EnableFraudulentWebsiteDetection: false,
ZoomFactor: 1.0,
IsZoomControlEnabled: false,
Bind: []interface{}{
app,
},
EnumBind: []interface{}{
AllWeekdays,
},
ErrorFormatter: func(err error) any { return err.Error() },
SingleInstanceLock: &options.SingleInstanceLock{
UniqueId: "c9c8fd93-6758-4144-87d1-34bdb0a8bd60",
OnSecondInstanceLaunch: app.onSecondInstanceLaunch,
},
Windows: &windows.Options{
WebviewIsTransparent: false,
WindowIsTranslucent: false,
BackdropType: windows.Mica,
DisablePinchZoom: false,
DisableWindowIcon: false,
DisableFramelessWindowDecorations: false,
WebviewUserDataPath: "",
@ -75,12 +81,17 @@ func main() {
LightModeTitleText: windows.RGB(20, 20, 20),
LightModeBorder: windows.RGB(200, 200, 200),
},
// ZoomFactor is the zoom factor for the WebView2. Il s'agit de l'option correspondant au zoom avant ou arrière défini par l'utilisateur.
ZoomFactor: float64,
// IsZoomControlEnabled enables the zoom factor to be changed by the user.
IsZoomControlEnabled: bool,
// User messages that can be customised
Messages *windows.Messages
Messages: *windows.Messages
// OnSuspend is called when Windows enters low power mode
OnSuspend func()
OnSuspend: func()
// OnResume is called when Windows resumes from low power mode
OnResume func(),
OnResume: func(),
// Disable GPU hardware acceleration for the webview
WebviewGpuDisabled: false,
},
Mac: &mac.Options{
@ -91,6 +102,8 @@ func main() {
FullSizeContent: false,
UseToolbar: false,
HideToolbarSeparator: true,
OnFileOpen: app.onFileOpen,
OnUrlOpen: app.onUrlOpen,
},
Appearance: mac.NSAppearanceNameDarkAqua,
WebviewIsTransparent: true,
@ -267,6 +280,12 @@ Le gestionnaire sera appelé pour chaque requête GET qui ne peut pas être serv
- Requête GET : `http.StatusNotFound`
- Autre requête : `http.StatusMethodNotAllowed`
:::info
This does not work with vite v5.0.0+ and wails v2 due to changes in vite. Changes are planned in v3 to support similar functionality under vite v5.0.0+. If you need this feature, stay with vite v4.0.0+. See [issue 3240](https://github.com/wailsapp/wails/issues/3240) for details
:::
REMARQUE : Lorsqu'il est utilisé en combinaison avec un serveur de développement Frontend, il peut y avoir des limitations, par exemple. Vite affiche l'index.html sur chaque chemin qui ne contient pas d'extension de fichier.
Nom: AssetsHandler<br/> Type: `http.Handler`
@ -366,7 +385,7 @@ Nom: CSSDragValue<br/> Type: `string`
EnableDefaultContextMenu active le menu contextuel par défaut du navigateur en production.
By default, the browser's default context-menu is only available in development and in a `-debug` [build](../reference/cli.mdx#build) along with the devtools inspector, Using this option you can enable the default context-menu in `production` while the devtools inspector won't be available unless the `-devtools` build flag is used.
Par défaut, le menu contextuel par défaut du navigateur n'est disponible qu'en développement et dans un `-debug` ou [build](../reference/cli.mdx#build) avec l'inspecteur de devtools. En utilisant cette option, vous pouvez activer le menu contextuel par défaut en `production`, alors que l'inspecteur devtools ne sera pas disponible à moins que l'option `-devtools` ne soit utilisée.
Lorsque cette option est activée, par défaut, le menu contextuel ne sera affiché que pour du texte (où Couper/Copier/Coller est nécessaire), pour remplacer ce comportement, vous pouvez utiliser la propriété CSS `--default-contextmenu` sur n'importe quel élément HTML (y compris le corps ``) avec les valeurs suivantes :
@ -413,12 +432,37 @@ La liste des structs Go définissant des méthodes qui doivent être liées au f
Nom: Bind<br/> Type: `[]interface{}`
### EnumBind
A slice of Enum arrays that need to be bound to the frontend.
Name: EnumBind<br/> Type: `[]interface{}`
### ErrorFormatter
Une fonction qui détermine comment les erreurs sont formatées lorsqu'elles sont retournées par un appel de méthode JS-to-Go. La valeur retournée sera sous format JSON.
Nom: ErrorFormatter<br/> Type: `func (error) any`
### SingleInstanceLock
Enables single instance locking. This means that only one instance of your application can be running at a time.
Name: SingleInstanceLock<br/> Type: `*options.SingleInstanceLock`
#### UniqueId
This id is used to generate the mutex name on Windows and macOS and the dbus name on Linux. Use a UUID to ensure that the id is unique.
Name: UniqueId<br/> Type: `string`
#### OnSecondInstanceLaunch
Callback that is called when a second instance of your app is launched.
Name: OnSecondInstanceLaunch<br/> Type: `func(secondInstanceData SecondInstanceData)`
### Windows
Ceci définit les options [spécifiques à Windows](#windows).
@ -461,6 +505,12 @@ La valeur peut être l'une des valeurs suivantes :
| Mica | Utiliser l'effet [Mica](https://learn.microsoft.com/en-us/windows/apps/design/style/mica) |
| Tabbed | Utiliser Tabbed. C'est un arrière-plan qui est similaire à Mica. |
#### DisablePinchZoom
Setting this to `true` will disable pinch zoom gestures.
Name: DisablePinchZoom<br/> Type: `bool`
#### DisableWindowIcon
Définir ceci à `true` supprimera l'icône dans le coin supérieur gauche de la barre de titre.
@ -595,9 +645,9 @@ Nom: WebviewGpuIsDisabled<br/> Type: `bool`
#### EnableSwipeGestures
Setting this to `true` will enable swipe gestures for the webview.
Définir à `true` activera les gestes de balayage pour la webview.
Name: EnableSwipeGestures<br/> Type: `bool`
Nom: EnableSwipeGestures<br/> Type: `bool`
### Mac
@ -694,29 +744,41 @@ Définir ceci à `true` rendra l'arrière-plan de la fenêtre translucide. Souve
Nom: WindowIsTranslucent<br/> Type: `bool`
#### OnFileOpen
Callback that is called when a file is opened with the application.
Name: OnFileOpen<br/> Type: `func(filePath string)`
#### OnUrlOpen
Callback that is called when a URL is opened with the application.
Name: OnUrlOpen<br/> Type: `func(filePath string)`
#### Preferences
The Preferences struct provides the ability to configure the Webview preferences.
Preferences fournit la possibilité de configurer les préférences de la Webview.
Name: Preferences<br/> Type: [`*mac.Preferences`](#preferences-struct)
Nom: Preferences<br/> Type: [`*mac.Preferences`](#preferences-struct)
##### Preferences struct
##### Preferences
You can specify the webview preferences.
Vous pouvez spécifier les préférences de la webview.
```go
type Preferences struct {
TabFocusesLinks u.Bool
TextInteractionEnabled u.Bool
FullscreenEnabled u.Bool
FullscreenEnabled u.Bool
}
```
| Nom | Description |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TabFocusesLinks | A Boolean value that indicates whether pressing the tab key changes the focus to links and form controls. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/2818595-tabfocuseslinks?language=objc) |
| TextInteractionEnabled | A Boolean value that indicates whether to allow people to select or otherwise interact with text. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/3727362-textinteractionenabled?language=objc) |
| FullscreenEnabled | A Boolean value that indicates whether a web view can display content full screen. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/3917769-elementfullscreenenabled?language=objc) |
| Nom | Description |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TabFocusesLinks | Un booléen qui indique si la touche de tabulation change le focus vers liens et les boutons des formulaires. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/2818595-tabfocuseslinks?language=objc) |
| TextInteractionEnabled | Un booléen qui indique s'il faut permettre aux gens de sélectionner ou d'interagir autrement avec le texte. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/3727362-textinteractionenabled?language=objc) |
| FullscreenEnabled | Un booléen qui indique si le contenu peut être affiché en plein écran. [Apple Docs](https://developer.apple.com/documentation/webkit/wkpreferences/3917769-elementfullscreenenabled?language=objc) |
Exemple:
@ -831,11 +893,11 @@ Nom: WebviewGpuPolicy<br/> Type: [`options.WebviewGpuPolicy`](#webviewgpupolicy-
#### ProgramName
This option is used to set the program's name for the window manager via GTK's g_set_prgname(). This name should not be localized, [see the docs](https://docs.gtk.org/glib/func.set_prgname.html).
Cette option est utilisée pour définir le nom du programme pour le gestionnaire de fenêtres via la fonction g_set_prgname(). Ce nom ne doit pas être localisé, [voir la documentation](https://docs.gtk.org/glib/func.set_prgname.html).
When a .desktop file is created this value helps with window grouping and desktop icons when the .desktop file's `Name` property differs form the executable's filename.
Quand un fichier .desktop est créé, cette valeur aide avec le groupement de fenêtres et les icônes de bureau quand la propriété `Nom` est différente du nom de fichier de l'exécutable.
Name: ProgramName<br/> Type: string<br/>
Nom: ProgramName<br/> Type: string<br/>
### Debug

View file

@ -73,20 +73,57 @@ La configuration du projet se trouve dans le fichier `wails.json` du répertoire
// The copyright of the product. Default: 'Copyright.........'
"copyright": "",
// A short comment of the app. Default: 'Built using Wails (https://wails.app)'
"comments": ""
"comments": "",
// File associations for the app
"fileAssociations": [
{
// The extension (minus the leading period). e.g. png
"ext": "wails",
// The name. e.g. PNG File
"name": "Wails",
// Windows-only. The description. It is displayed on the `Type` column on Windows Explorer.
"description": "Wails file",
// The icon name without extension. Icons should be located in build folder. Proper icons will be generated from .png file for both macOS and Windows)
"iconName": "fileIcon",
// macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole.
"role": "Editor"
},
],
// Custom URI protocols that should be opened by the application
"protocols": [
{
// protocol scheme. e.g. myapp
"scheme": "myapp",
// Windows-only. The description. It is displayed on the `Type` column on Windows Explorer.
"description": "Myapp protocol",
// macOS-only. The apps role with respect to the type. Corresponds to CFBundleTypeRole.
"role": "Editor"
}
]
},
// 'multiple': One installer per architecture. 'single': Single universal installer for all architectures being built. Default: 'multiple'
"nsisType": "",
// Whether the app should be obfuscated. Default: false
"obfuscated": "",
// The arguments to pass to the garble command when using the obfuscated flag
"garbleargs": ""
"garbleargs": "",
// Bindings configurations
"bindings": {
// model.ts file generation config
"ts_generation": {
// All generated JavaScript entities will be prefixed with this value
"prefix": "",
// All generated JavaScript entities will be suffixed with this value
"suffix": "",
// Type of output to generate (classes|interfaces)
"outputType": "classes",
}
}
}
```
This file is read by the Wails CLI when running `wails build` or `wails dev`.
Ce fichier est lu par le CLI Wails lorsque vous exécutez `wails build` ou `wails dev`.
The `assetdir`, `reloaddirs`, `wailsjsdir`, `debounceMS`, `devserver` and `frontenddevserverurl` flags in `wails build/dev` will update the project config
and thus become defaults for subsequent runs.
Les options `assetdir`, `reloaddirs`, `wailsjsdir`, `debounceMS`, `devserver` et `frontenddevserverurl` dans `wails build/dev` vont mettre à jour les configs du projet et deviendront les valeurs par défaut des exécutions suivantes.
The JSON Schema for this file is located [here](https://wails.io/schemas/config.v2.json).
Le Schema JSON pour ce fichier se trouve [ici](https://wails.io/schemas/config.v2.json).

View file

@ -2,18 +2,18 @@
sidebar_position: 9
---
# Screen
# Écran
These methods provide information about the currently connected screens.
Ces méthodes fournissent des informations sur les écrans actuellement connectés.
### ScreenGetAll
Returns a list of currently connected screens.
Retourne une liste des écrans actuellement connectés.
Go: `ScreenGetAll(ctx context.Context) []screen`<br/>
JS: `ScreenGetAll()`
#### Screen
#### Écran
Go struct:
@ -26,7 +26,7 @@ type Screen struct {
}
```
Typescript interface:
Interface Typescript :
```ts
interface Screen {

View file

@ -202,7 +202,7 @@ Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`<br/> JS:
### WindowPrint
Opens tha native print dialog.
Ouvre la boîte de dialogue d'impression native.
Go: `WindowPrint(ctx context.Context)`<br/> JS: `WindowPrint()`

View file

@ -1,26 +0,0 @@
---
sidebar_position: 2
---
# Liens
Cette page sert de liste pour les liens liés à la communauté. Veuillez soumettre une PR (cliquez sur `Modifier cette page` en bas) pour soumettre des liens.
## Awesome Wails
La [liste définitive](https://github.com/wailsapp/awesome-wails) de liens relatifs à Wails.
## Canaux de support
- [Gophers Slack Channel](https://gophers.slack.com/messages/CJ4P9F7MZ/)
- [Gophers Slack Channel Invite](https://invite.slack.golangbridge.org/)
- [Github Issues](https://github.com/wailsapp/wails/issues)
- [canal de discussion sur la bêta v2](https://github.com/wailsapp/wails/discussions/828)
## Réseaux sociaux
- [Twitter](https://twitter.com/wailsapp)
- [Groupe QQ pour la communauté chinoise de Wails](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - Numéro de groupe : 1067173054
## Autres tutoriels et articles
- [Construction d'un Panneau d'Affichage](https://blog.customct.com/building-bulletin-board)

View file

@ -1,10 +0,0 @@
# EmailIt
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/emailit.webp").default} />
<br />
</p>
```
[EmailIt](https://github.com/raguay/EmailIt/) is a Wails 2 program that is a markdown based email sender only with nine notepads, scripts to manipulate the text, and templates. It also has a builtin [Node-Red](https://nodered.org/) server, scripts terminal, and the [ScriptBar](https://github.com/raguay/ScriptBarApp) program for displaying results from Node-Red or a script on your system. Documentation is very scarce, but the programs works. Its built using Wails2 and Svelte, and the download is a universal macOS application.

View file

@ -1,12 +0,0 @@
# EncryptEasy
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/encrypteasy.webp").default} />
<br />
</p>
```
**[EncryptEasy](https://www.encrypteasy.app) est un outil de chiffrement PGP simple et facile à utiliser, qui gère toutes vos clés et celles de vos contacts. Le chiffrement devrait être simple. Développé avec Wails.**
Chiffrer les messages à l'aide de PGP est la norme de l'industrie. Tout le monde a une clé privée et publique. Votre clé privée, eh bien, doit être privée afin que vous seul puissiez lire les messages. Votre clé publique est distribuée à toute personne qui veut vous envoyer des messages secrets, chiffrés. Gérer les clés, chiffrer les messages et déchiffrer les messages devrait être une expérience agréable. EncryptEasy a pour but de vous simplifier la tâche.

View file

@ -1,16 +0,0 @@
# Utilitaire d'exportation FileHound
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/filehound.webp").default} />
<br />
</p>
```
[L'utilitaire d'exportation FileHound](https://www.filehound.co.uk/) est une plate-forme de gestion de documents cloud conçue pour la conservation sécurisée de fichiers, l'automatisation des processus métier et les capacités de SmartCapture.
L'utilitaire d'exportation FileHound permet aux administrateurs FileHound d'exécuter des tâches sécurisées d'extraction de documents et de données à des fins alternatives de sauvegarde et de récupération. Cette application téléchargera tous les documents et/ou métadonnées enregistrés dans FileHound en fonction des filtres que vous avez choisis. Les métadonnées seront exportées dans les formats JSON et XML.
Backend construit avec: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2
Frontend avec: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6

View file

@ -1,14 +0,0 @@
# Minecraft Updater
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img
src={
require("@site/static/img/showcase/minecraft-mod-updater.webp").default
}
/>
<br />
</p>
```
[Minecraft Updater](https://github.com/Gurkengewuerz/MinecraftModUpdater) est un outil utilitaire pour mettre à jour et synchroniser les mods Minecraft pour votre base d'utilisateurs. Il a été conçu en utilisant Wails2 et React avec [antd](https://ant.design/) comme framework frontend.

View file

@ -1,14 +0,0 @@
# Modal File Manager
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img
src={require("@site/static/img/showcase/modalfilemanager.webp").default}
/>
<br />
</p>
```
[Modal File Manager](https://github.com/raguay/ModalFileManager) est un gestionnaire de fichiers à double volet utilisant des technologies web. Mon design original était basé sur NW.js et peut être trouvé [ici](https://github.com/raguay/ModalFileManager-NWjs). Cette version utilise le même code frontend basé sur Svelte (mais il a été grandement modifié depuis le départ de NW.js), mais le backend est une implémentation de [Wails 2](https://wails.io/). En utilisant cette implémentation, je n'utilise plus de commandes en ligne de commande `rm`, `cp`, etc. Il est entièrement codé en utilisant Go et fonctionne beaucoup plus rapidement que les versions précédentes.
Ce gestionnaire de fichiers est conçu autour du même principe que Vim: l'état est contrôlé par des actions via le clavier. Le nombre d'états n'est pas fixe, mais très programmable. Par conséquent, un nombre infini de configurations de clavier qui peuvent être créées et utilisées. C'est la principale différence par rapport aux autres gestionnaires de fichiers.

View file

@ -1,10 +0,0 @@
# Molley Wallet
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/mollywallet.webp").default} />
<br />
</p>
```
[Molly Wallet](https://github.com/grvlle/constellation_wallet/) le portefeuille officiel $DAG du Constellation Network. Cela permettra aux utilisateurs d'interagir avec le réseau Hypergraph de différentes manières, sans se limiter à la production de transactions en $DAG.

View file

@ -1,14 +0,0 @@
# October
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/october.webp").default} />
<br />
</p>
```
[Octobre](https://october.utf9k.net) est une petite application Wails qui rend vraiment facile d'extraire les surlignements de [Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader) puis de les transférer vers [Readwise](https://readwise.io).
Il a une taille relativement petite avec toutes les versions de la plate-forme pesant en moins de 10 Mo, et c'est sans activer la [compression UPX](https://upx.github.io/)!
En revanche, les précédentes tentatives de l'auteur avec Electron ont rapidement gonflé à plusieurs centaines de mégaoctets.

View file

@ -1,10 +0,0 @@
# Optimus
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/optimus.webp").default} />
<br />
</p>
```
[Optimus](https://github.com/splode/optimus) est une application d'optimisation d'image de bureau. Il supporte la conversion et la compression entre les formats dimages WebP, JPEG et PNG.

View file

@ -1,10 +0,0 @@
# Portfall
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/portfall.webp").default} />
<br />
</p>
```
[Portfall](https://github.com/rekon-oss/portfall) - Un portail de redirection de port k8 pour un accès facile à toutes les interfaces de votre instance

View file

@ -1,12 +0,0 @@
# Restic Browser
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img
src={require("@site/static/img/showcase/restic-browser-2.png").default}
/>
<br />
</p>
```
[Restic-Browser](https://github.com/emuell/restic-browser) - Une interface de sauvegarde simple et multiplateforme [restic](https://github.com/restic/restic) pour la navigation et la restauration de dépôts restic.

View file

@ -1,21 +0,0 @@
# RiftShare
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/riftshare-main.webp").default} />
<br />
</p>
```
Partage de fichiers facile, sécurisé et gratuit pour tout le monde. Apprenez-en plus sur [Riftshare.app](https://riftshare.app)
## Fonctionnalités
- Partage facile et sécurisé de fichiers entre ordinateurs à la fois sur le réseau local et via Internet
- Supporte l'envoi de fichiers ou de répertoires de manière sécurisée par le protocole [magic wormhole](https://magic-wormhole.readthedocs.io/en/latest/)
- Compatible avec toutes les autres applications utilisant magic wormhole (magic-wormhole or wormhole-william CLI, wormhole-gui, etc.)
- Compression automatique de plusieurs fichiers sélectionnés à envoyer en même temps
- Animations complètes, barre de progression et support d'annulation pour l'envoi et la réception
- Sélection de fichier natif au système d'exploitation
- Ouvrir les fichiers en un seul clic une fois reçus
- Mise à jour automatique - ne vous inquiétez pas d'avoir la dernière version!

View file

@ -1,10 +0,0 @@
# ScriptBar
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/scriptbar.webp").default} />
<br />
</p>
```
[Barre de scripts](https://GitHub.com/raguay/ScriptBarApp) est un programme pour afficher la sortie du serveur [Node-Red](https://nodered.org) intégré dans l'application [EmailIt](https://GitHub.com/raguay/EmailIt). Il affiche également la sortie des scripts sur votre système. ScriptBar ne les met pas dans la barre de menus, mais les a tous dans une fenêtre convenable pour une visualisation facile. Vous pouvez avoir plusieurs onglets pour voir plusieurs choses différentes. Vous pouvez également conserver les liens vers vos sites Web les plus visités.

View file

@ -1,10 +0,0 @@
# Surge
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/surge.png").default} />
<br />
</p>
```
[Surge](https://getsurge.io/) est une application de partage de fichiers p2p conçue pour utiliser les technologies blockchain afin d'activer les transferts de fichiers 100 % anonymes. Surge est chiffré de bout en bout, décentralisé et open source.

View file

@ -1,10 +0,0 @@
# Wally
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/wally.webp").default} />
<br />
</p>
```
[Wally](https://ergodox-ez.com/pages/wally) est le flasheur officiel du firmware pour les claviers [Ergodox](https://ergodox-ez.com/). C'est un excellent exemple de ce que vous pouvez réaliser avec Wails : la capacité de combiner la puissance de Go et les riches outils graphiques du monde du développement web.

View file

@ -1,10 +0,0 @@
# Wombat
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/wombat.webp").default} />
<br />
</p>
```
[Wombat](https://github.com/rogchap/wombat) est un client gRPC multi-plateforme.

View file

@ -1,10 +0,0 @@
# Ytd
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/ytd.webp").default} />
<br />
</p>
```
[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails) est une application pour télécharger des pistes depuis youtube, créer des listes de lecture hors ligne et les partager avec vos amis, vos amis seront en mesure de lire vos playlists ou de les télécharger pour l'écoute hors ligne, a un lecteur intégré.

View file

@ -1,56 +0,0 @@
---
sidebar_position: 1
---
# Modèles
Cette page sert de liste pour les modèles supportés par la communauté. Veuillez soumettre une PR (cliquez sur `Modifier cette page` en bas) pour inclure vos modèles. Pour construire votre propre modèle, veuillez consulter le guide [Modèles](../guides/templates.mdx).
Pour utiliser ces modèles, exécutez `wails init -n "Votre nom de projet" -t [le lien ci-dessous[@version]]`
S'il n'y a pas de suffixe de version, la branche principale du modèle de code sera alors utilisé par défaut. S'il y a un suffixe de version, le modèle de code correspondant au tag de cette version sera utilisé.
Exemple : `wails init -n "Votre nom de projet" -t https://github.com/misitebao/wails-template-vue`
:::warning Attention
**Le projet Wails n'entretient pas, et n'est pas responsable des modèles de tierces parties!**
Si vous n'êtes pas sûr d'un modèle, inspectez `package.json` et `wails.json` pour savoir quels scripts sont exécutés et quels paquets sont installés.
:::
## Vue
- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - Modèle de Wails basé sur Vue (TypeScript intégré, thème sombre, internationalisation, routage de page unique, TailwindCSS)
- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Vue 3 TypeScript avec Vite (et instructions pour ajouter des fonctionnalités)
- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vue 3 TypeScript avec Vite, Vuex, Vue Router, Sass, et ESLint + Prettier
- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - Un modèle utilisant JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier)
- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - Un modèle utilisant TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, Composition API avec &lt;script setup&gt;)
## Angular
- [wails-angular-template](https://github.com/TAINCER/wails-angular-template) - Angular avec TypeScript, Sass, rechargement à chaud, découpage dynamique de code et i18n
## React
- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - Un modèle utilisant reactjs
- [wails-react-template](https://github.com/flin7/wails-react-template) - Un modèle minimal pour React qui supporte le développement en direct
- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - Un modèle utilisant Next.js et TypeScript
- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - Un modèle pour React + TypeScript + Vite + TailwindCSS
## Svelte
- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - Un modèle utilisant Svelte
- [wails-vite-svelte-template](https://github.com/BillBuilt/wails-vite-svelte-template) - Un modèle utilisant Svelte et Vite
- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - Un modèle utilisant Svelte et Vite avec TailwindCSS v3
- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - Un modèle utilisant SvelteKit
## Elm
- [wails-elm-template](https://github.com/benjamin-thomas/wails-elm-template) - Développez votre application GUI avec de la programmation fonctionnelle et une configuration de développement en direct :tada: :rocket:
- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - Combine les puissances :muscle: d'Elm + Tailwind CSS + Wails ! Rechargement automatique pris en charge.
## Pure JavaScript (Vanilla)
- [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - Un modèle avec rien que du JavaScript, du HTML et du CSS de base

View file

@ -1,22 +0,0 @@
---
sidebar_position: 6
---
# Compiler votre projet
À partir du répertoire du projet, exécutez `wails build`. Cela compilera votre projet et sauvegardera le binaire prêt à la production dans le répertoire `build/bin`.
Si vous exécutez le binaire, vous devriez voir l'application par défaut :
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/defaultproject.webp").default}
width="50%"
class="screenshot"
/>
</div>
<br />
```
Pour plus de détails sur les options de compilation, veuillez vous référer à la [documentation du CLI](../reference/cli.mdx#build).

View file

@ -1,16 +0,0 @@
---
sidebar_position: 5
---
# Développez votre application
Vous pouvez exécuter votre application en mode développement en exécutant `wails dev` à partir du répertoire de votre projet. Cela fera les choses suivantes :
- Construire votre application et l'exécuter
- Lier votre code Go au frontend pour qu'il puisse être appelé à partir de JavaScript
- En utilisant la puissance de [Vite](https://vitejs.dev/), surveillera les modifications dans vos fichiers Go et reconstruira / ré-exécutera en cas de changement
- Mettra en place un [serveur web](http://localhost:34115) qui servira votre application via un navigateur. Cela vous permet d'utiliser les extensions de votre navigateur préféré. Vous pouvez même appeler votre code Go depuis la console
Pour commencer, exécutez `wails dev` dans le répertoire du projet. Plus d'informations à ce sujet peuvent être trouvées [ici](../reference/cli.mdx#dev).
Prochainement : Tutoriel

View file

@ -1,130 +0,0 @@
---
sidebar_position: 2
---
# Créer un projet
## Génération de projet
Maintenant que le CLI est installé, vous pouvez générer un nouveau projet en utilisant la commande `wails init`.
Choisissez votre framework favori :
```mdx-code-block
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
<Tabs
defaultValue="Svelte"
values={[
{label: "Svelte", value: "Svelte"},
{label: "React", value: "React"},
{label: "Vue", value: "Vue"},
{label: "Preact", value: "Preact"},
{label: "Lit", value: "Lit"},
{label: "Vanilla", value: "Vanilla"},
]}
>
<TabItem value="Svelte">
Générer un projet <a href={"https://svelte.dev/"}>Svelte</a> utilisant JavaScript avec:<br/><br/>
wails init -n myproject -t svelte
Si vous préférez utiliser TypeScript:<br/>
wails init -n myproject -t svelte-ts
</TabItem>
<TabItem value="React">
Générer un projet <a href={"https://reactjs.org/"}>React</a> utilisant JavaScript avec :<br/><br/>
wails init -n myproject -t react
Si vous préférez utiliser TypeScript:<br/>
wails init -n myproject -t react-ts
</TabItem>
<TabItem value="Vue">
Générer un projet <a href={"https://vuejs.org/"}>Vue</a> utilisant JavaScript avec:<br/><br/>
wails init -n myproject -t vue
Si vous préférez TypeScript:<br/>
wails init -n myproject -t vue-ts
</TabItem>
<TabItem value="Preact">
Générer un projet <a href={"https://preactjs.com/"}>Preact</a> utilisant JavaScript avec:<br/><br/>
wails init -n myproject -t preact
Si vous préférez TypeScript:<br/>
wails init -n myproject -t preact-ts
</TabItem>
<TabItem value="Lit">
Générer un projet <a href={"https://lit.dev/"}>Lit</a> utilisant JavaScript avec:<br/><br/>
wails init -n myproject -t lit
Si vous préférez TypeScript:<br/>
wails init -n myproject -t lit-ts
</TabItem>
<TabItem value="Vanilla">
Générer un projet Vanilla utilisant JavaScript avec :<br/><br/>
wails init -n myproject -t vanilla
Si vous préférez TypeScript:<br/>
wails init -n myproject -t vanilla-ts
</TabItem>
</Tabs>
```
<hr />
Il y a aussi [des modèles créés par la communauté](../community/templates.mdx) qui sont disponibles et qui offrent différentes possibilités.
Pour voir les autres options disponibles, vous pouvez exécuter `wails init -help`. Plus de détails peuvent être trouvés dans la [documentation du CLI](../reference/cli.mdx#init).
## Structure du projet
Les projets Wails ont la structure suivante:
```
.
├── build/
│ ├── appicon.png
│ ├── darwin/
│ └── windows/
├── frontend/
├── go.mod
├── go.sum
├── main.go
└── wails.json
```
### Récapitulatif de la structure du projet
- `/main.go` - L'application principale
- `/frontend/` - Fichiers de la partie frontend
- `/build/` - Répertoire de construction du projet
- `/build/appicon.png` - L'icône de l'application
- `/build/darwin/` - Fichiers spécifiques pour Mac
- `/build/windows/` - Fichiers spécifiques pour Windows
- `/wails.json` - La configuration du projet
- `/go.mod` - Le fichier du module Go
- `/go.sum` - Le checksum du fichier du module Go
Le répertoire `frontend` n'a rien de spécifique à Wails et n'importe quel outil de frontend peut être utilisé.
Le répertoire `build` est utilisé pendant le processus de compilation. Ces fichiers peuvent être mis à jour pour personnaliser vos builds. Si fichiers sont supprimés du répertoire de compilation, les versions par défaut seront régénérées.
Le nom du module par défaut dans `go.mod` est "changeme". Vous devriez changer cela pour quelque chose de plus approprié.

View file

@ -1,90 +0,0 @@
---
sidebar_position: 1
---
# Installation
## Plates-formes Prises en charge
- Windows 10/11 AMD64/ARM64
- MacOS 10.13+ AMD64
- MacOS 11.0+ ARM64
- Linux AMD64/ARM64
## Dépendances
Wails a un certain nombre de dépendances communes qui sont nécessaires avant l'installation :
- Go 1.18+
- NPM (Node 15+)
### Go
Télécharger Go à partir de la [Page de téléchargement](https://go.dev/dl/).
Assurez-vous que vous suivez les instructions officielles de [l'installation de Go](https://go.dev/doc/install). Vous devrez également vous assurer que votre variable d'environnement `PATH` inclut également le chemin vers votre répertoire `~/go/bin`. Redémarrez votre terminal et effectuez les vérifications suivantes :
- Vérifiez que Go est installé correctement : `go version`
- Vérifiez que "~/go/bin" est dans votre variable PATH : `echo $PATH | grep go/bin`
### NPM
Téléchargez le NPM à partir de la [page de téléchargement de Node](https://nodejs.org/en/download/). Il est préférable d'utiliser la dernière version car c'est avec celle-là que nous effectuons nos tests.
Exécutez `npm --version` pour vérifier.
## Dépendances spécifiques aux plateformes
Vous devrez également installer des dépendances spécifiques liés à la plateforme que vous utilisez :
```mdx-code-block
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
<Tabs
defaultValue="Windows"
values={[
{ label: "Windows", value: "Windows" },
{ label: "MacOS", value: "MacOS" },
{ label: "Linux", value: "Linux" },
]}
>
<TabItem value="MacOS">
Wails a besoin que les outils de command line xocde soient installés. Cela peut être fait
en exécutant <code>xcode-select --install</code>.
</TabItem>
<TabItem value="Windows">
Wails a besoin que <a href="https://developer.microsoft.com/en-us/microsoft-edge/webview2/">WebView2</a> runtime soit installé. Certaines installations de Windows auront déjà installé cette fonctionnalité. Vous pouvez vérifier en utilisant la commande <code>wails doctor</code>.
</TabItem>
<TabItem value={"Linux"}>
Linux a besoin de <code>gcc</code> build tools plus <code>libgtk3</code> et <code>libwebkit</code>. Plutôt que de lister une tonne de commandes pour différentes distributions, Wails peut essayer de déterminer ce que sont les commandes d'installation pour votre distribution spécifique. Exécutez <code>wails doctor</code> après l'installation pour voir de quelles dépendances vous avez besoin. Si votre gestionnaire de distribution/paquet n'est pas pris en charge, veuillez consulter le guide <a href={"/docs/guides/linux-distro-support"}>Ajouter une distribution Linux</a>.
</TabItem>
</Tabs>
```
## Dépendances optionnelles
- [UPX](https://upx.github.io/) pour compresser vos applications.
- [NSIS](https://wails.io/docs/guides/windows-installer/) pour générer des installateurs Windows.
## Installer Wails
Exécutez `go go install github.com/wailsapp/wails/v2/cmd/wails@latest` pour installer le CLI.
Note: Si vous obtenez une erreur similaire à ceci:
```shell
....\Go\pkg\mod\github.com\wailsapp\wails\v2@v2.1.0\pkg\templates\templates.go:28:12: pattern all:ides/*: no matching files found
```
vérifiez que vous avez installé Go 1.18+ :
```shell
go version
```
## Vérification du système
Exécuter `wails doctor` qui vérifiera si vous avez les bonnes dépendances installées. Si ce n'est pas le cas, il vous conseillera sur ce qui manque et vous aidera à corriger tout problème.
## La commande `wails` semble manquer ?
Si votre système signale que la commande `wails` est manquante, assurez-vous que vous avez suivi le guide d'installation correctement. Normalement, cela signifie que le répertoire `go/bin` du répertoire racine de votre utilisateur n'est pas dans la variable d'environnement `PATH` . Vous devrez également normalement fermer et réouvrir toutes les commandes ouvertes afin que les modifications apportées à l'environnement par l'installateur soient reflétées dans l'invite de commande.

View file

@ -1,14 +0,0 @@
# Angular
Bien que Wails n'ait pas de modèle Angular, il est possible d'utiliser Angular avec Wails.
## Dev Mode
Pour que le mode développeur fonctionne avec Angular, vous devez ajouter ce qui suit à votre fichier `wails.json`:
```json
"frontend:build": "npx ng build",
"frontend:install": "npm install",
"frontend:dev:watcher": "npx ng serve",
"frontend:dev:serverUrl": "http://localhost:4200",
```

View file

@ -1,194 +0,0 @@
# Développement d'applications
Il n'y a pas de règles gravées dans le marbre pour le développement d'applications avec Wails, mais il y a quelques lignes directrices de base.
## Configuration de l'application
The pattern used by the default templates are that `main.go` is used for configuring and running the application, whilst `app.go` is used for defining the application logic.
The `app.go` file will define a struct that has 2 methods which act as hooks into the main application:
```go title="app.go"
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) {
}
```
- The startup method is called as soon as Wails allocates the resources it needs and is a good place for creating resources, setting up event listeners and anything else the application needs at startup. It is given a `context.Context` which is usually saved in a struct field. This context is needed for calling the [runtime](../reference/runtime/intro.mdx). If this method returns an error, the application will terminate. In dev mode, the error will be output to the console.
- The shutdown method will be called by Wails right at the end of the shutdown process. This is a good place to deallocate memory and perform any shutdown tasks.
The `main.go` file generally consists of a single call to `wails.Run()`, which accepts the application configuration. The pattern used by the templates is that before the call to `wails.Run()`, an instance of the struct we defined in `app.go` is created and saved in a variable called `app`. This configuration is where we add our callbacks:
```go {3,9,10} title="main.go"
func main() {
app := NewApp()
err := wails.Run(&options.App{
Title: "My App",
Width: 800,
Height: 600,
OnStartup: app.startup,
OnShutdown: app.shutdown,
})
if err != nil {
log.Fatal(err)
}
}
```
More information on application lifecycle hooks can be found [here](../howdoesitwork.mdx#application-lifecycle-callbacks).
## Binding Methods
It is likely that you will want to call Go methods from the frontend. This is normally done by adding public methods to the already defined struct in `app.go`:
```go {16-18} title="app.go"
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) {
}
func (a *App) Greet(name string) string {
return fmt.Sprintf("Hello %s!", name)
}
```
In the main application configuration, the `Bind` key is where we can tell Wails what we want to bind:
```go {11-13} title="main.go"
func main() {
app := NewApp()
err := wails.Run(&options.App{
Title: "My App",
Width: 800,
Height: 600,
OnStartup: app.startup,
OnShutdown: app.shutdown,
Bind: []interface{}{
app,
},
})
if err != nil {
log.Fatal(err)
}
}
```
This will bind all public methods in our `App` struct (it will never bind the startup and shutdown methods).
### Dealing with context when binding multiple structs
If you want to bind methods for multiple structs but want each struct to keep a reference to the context so that you can use the runtime functions, a good pattern is to pass the context from the `OnStartup` method to your struct instances :
```go
func main() {
app := NewApp()
otherStruct := NewOtherStruct()
err := wails.Run(&options.App{
Title: "My App",
Width: 800,
Height: 600,
OnStartup: func(ctx context.Context){
app.SetContext(ctx)
otherStruct.SetContext(ctx)
},
OnShutdown: app.shutdown,
Bind: []interface{}{
app,
otherStruct
},
})
if err != nil {
log.Fatal(err)
}
}
```
More information on Binding can be found [here](../howdoesitwork.mdx#method-binding).
## Application Menu
Wails supports adding a menu to your application. This is done by passing a [Menu](../reference/menus.mdx#menu) struct to application config. It's common to use a method that returns a Menu, and even more common for that to be a method on the `App` struct used for the lifecycle hooks.
```go {11} title="main.go"
func main() {
app := NewApp()
err := wails.Run(&options.App{
Title: "My App",
Width: 800,
Height: 600,
OnStartup: app.startup,
OnShutdown: app.shutdown,
Menu: app.menu(),
Bind: []interface{}{
app,
},
})
if err != nil {
log.Fatal(err)
}
}
```
## Assets
The great thing about the way Wails v2 handles assets is that it doesn't! The only thing you need to give Wails is an `embed.FS`. How you get to that is entirely up to you. You can use vanilla html/css/js files like the vanilla template. You could have some complicated build system, it doesn't matter.
When `wails build` is run, it will check the `wails.json` project file at the project root. There are 2 keys in the project file that are read:
- "frontend:install"
- "frontend:build"
The first, if given, will be executed in the `frontend` directory to install the node modules. The second, if given, will be executed in the `frontend` directory to build the frontend project.
If these 2 keys aren't given, then Wails does absolutely nothing with the frontend. It is only expecting that `embed.FS`.
### AssetsHandler
A Wails v2 app can optionally define a `http.Handler` in the `options.App`, which allows hooking into the AssetServer to create files on the fly or process POST/PUT requests. GET requests are always first handled by the `assets` FS. If the FS doesn't find the requested file the request will be forwarded to the `http.Handler` for serving. Any requests other than GET will be directly processed by the `AssetsHandler` if specified. It's also possible to only use the `AssetsHandler` by specifiy `nil` as the `Assets` option.
## Built in Dev Server
Running `wails dev` will start the built in dev server which will start a file watcher in your project directory. By default, if any file changes, wails checks if it was an application file (default: `.go`, configurable with `-e` flag). If it was, then it will rebuild your application and relaunch it. If the changed file was in the assets, it will issue a reload after a short amount of time.
The dev server uses a technique called "debouncing" which means it doesn't reload straight away, as there may be multiple files changed in a short amount of time. When a trigger occurs, it waits for a set amount of time before issuing a reload. If another trigger happens, it resets to the wait time again. By default this value is `100ms`. If this value doesn't work for your project, it can be configured using the `-debounce` flag. If used, this value will be saved to your project config and become the default.
## External Dev Server
Some frameworks come with their own live-reloading server, however they will not be able to take advantage of the Wails Go bindings. In this scenario, it is best to run a watcher script that rebuilds the project into the build directory, which Wails will be watching. For an example, see the default svelte template that uses [rollup](https://rollupjs.org/guide/en/). For [create-react-app](https://create-react-app.dev/), it's possible to use [this script](https://gist.github.com/int128/e0cdec598c5b3db728ff35758abdbafd) to achieve a similar result.
## Go Module
The default Wails templates generate a `go.mod` file that contains the module name "changeme". You should change this to something more appropriate after project generation.

View file

@ -1,136 +0,0 @@
# Dynamic Assets
If you want to load or generate assets for your frontend dynamically, you can achieve that using the [AssetsHandler](../reference/options#assetshandler) option. The AssetsHandler is a generic `http.Handler` which will be called for any non GET request on the assets server and for GET requests which can not be served from the bundled assets because the file is not found.
By installing a custom AssetsHandler, you can serve your own assets using a custom asset server.
## Example
In our example project, we will create a simple assets handler which will load files off disk:
```go title=main.go {16-35,49}
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)
}
}
```
When we run the application in dev mode using `wails dev`, we will see the following output:
```
DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico'
DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler
Requesting file: favicon.ico
```
As you can see, the assets handler is called when the default assets server is unable to serve the `favicon.ico` file.
If you right click the main application and select "inspect" to bring up the devtools, you can test this feature out by typing the following into the console:
```
let response = await fetch('does-not-exist.txt');
```
This will generate an error in the devtools. We can see that the error is what we expect, returned by our custom assets handler:
```mdx-code-block
<p className="text--center">
<img
src={require("@site/static/img/assetshandler-does-not-exist.webp").default}
/>
</p>
```
However, if we request `go.mod`, we will see the following output:
```mdx-code-block
<p className="text--center">
<img src={require("@site/static/img/assetshandler-go-mod.webp").default} />
</p>
```
This technique can be used to load images directly into the page. If we updated our default vanilla template and replaced the logo image:
```html
<img id="logo" class="logo" />
```
with:
```html
<img src="build/appicon.png" style="width: 300px" />
```
Then we would see the following:
```mdx-code-block
<p className="text--center">
<img
src={require("@site/static/img/assetshandler-image.webp").default}
style={{ width: "75%" }}
/>
</p>
```
:::warning
Exposing your filesystem in this way is a security risk. It is recommended that you properly manage access to your filesystem.
:::

View file

@ -1,87 +0,0 @@
# Frameless Applications
Wails supports application that have no frames. This can be achieved by using the [frameless](../reference/options.mdx#frameless) field in [Application Options](../reference/options.mdx#application-options).
Wails offers a simple solution for dragging the window: Any HTML element that has the CSS style `--wails-draggable:drag` will act as a "drag handle". This property applies to all child elements. If you need to indicate that a nested element should not drag, then use the attribute '--wails-draggable:no-drag' on that element.
```html
<html>
<head>
<link rel="stylesheet" href="/main.css" />
</head>
<body style="--wails-draggable:drag">
<div id="logo"></div>
<div id="input" style="--wails-draggable:no-drag">
<input id="name" type="text" />
<button onclick="greet()">Greet</button>
</div>
<div id="result"></div>
<script src="/main.js"></script>
</body>
</html>
```
For some projects, using a CSS variable may not be possible due to dynamic styling. In this case, you can use the `CSSDragProperty` and `CSSDragValue` application options to define a property and value that will be used to indicate draggable regions:
```go title=main.go
package main
import (
"embed"
"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() {
// Create an instance of the app structure
app := NewApp()
// Create application with options
err := wails.Run(&options.App{
Title: "alwaysontop",
Width: 1024,
Height: 768,
AssetServer: &assetserver.Options{
Assets: assets,
},
Frameless: true,
CSSDragProperty: "widows",
CSSDragValue: "1",
Bind: []interface{}{
app,
},
})
if err != nil {
println("Error:", err)
}
}
```
```html title=index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>alwaysontop</title>
</head>
<body style="widows: 1">
<div id="app"></div>
<script src="./src/main.js" type="module"></script>
</body>
</html>
```
:::info Fullscreen
If you allow your application to go fullscreen, this drag functionality will be disabled.
:::

View file

@ -1,72 +0,0 @@
# Frontend
## Script Injection
When Wails serves your `index.html`, by default, it will inject 2 script entries into the `<body>` tag to load `/wails/ipc.js` and `/wails/runtime.js`. These files install the bindings and runtime respectively.
The code below shows where these are injected by default:
```html
<html>
<head>
<title>injection example</title>
<link rel="stylesheet" href="/main.css" />
<!-- <script src="/wails/ipc.js"></script> -->
<!-- <script src="/wails/runtime.js"></script> -->
</head>
<body data-wails-drag>
<div class="logo"></div>
<div class="result" id="result">Please enter your name below 👇</div>
<div class="input-box" id="input" data-wails-no-drag>
<input class="input" id="name" type="text" autocomplete="off" />
<button class="btn" onclick="greet()">Greet</button>
</div>
<script src="/main.js"></script>
</body>
</html>
```
### Overriding Default Script Injection
To provide more flexibility to developers, there is a meta tag that may be used to customise this behaviour:
```html
<meta name="wails-options" content="[options]" />
```
The options are as follows:
| Value | Description |
| ------------------- | ------------------------------------------------ |
| noautoinjectruntime | Disable the autoinjection of `/wails/runtime.js` |
| noautoinjectipc | Disable the autoinjection of `/wails/ipc.js` |
| noautoinject | Disable all autoinjection of scripts |
Multiple options may be used provided they are comma seperated.
This code is perfectly valid and operates the same as the autoinjection version:
```html
<html>
<head>
<title>injection example</title>
<meta name="wails-options" content="noautoinject" />
<link rel="stylesheet" href="/main.css" />
</head>
<body data-wails-drag>
<div class="logo"></div>
<div class="result" id="result">Please enter your name below 👇</div>
<div class="input-box" id="input" data-wails-no-drag>
<input class="input" id="name" type="text" autocomplete="off" />
<button class="btn" onclick="greet()">Greet</button>
</div>
<script src="/wails/ipc.js"></script>
<script src="/wails/runtime.js"></script>
<script src="/main.js"></script>
</body>
</html>
```

View file

@ -1,127 +0,0 @@
# IDEs
Wails aims to provide a great development experience. To that aim, we now support generating IDE specific configuration to provide smoother project setup.
Currently, we support [Visual Studio Code](https://code.visualstudio.com/) but aim to support other IDEs such as Goland.
## Visual Studio Code
```mdx-code-block
<p className="text--center">
<img
src={require("@site/static/img/vscode.webp").default}
style={{ width: "75%" }}
/>
</p>
```
When generating a project using the `-ide vscode` flags, IDE files will be created alongside the other project files. These files are placed into the `.vscode` directory and provide the correct configuration for debugging your application.
The 2 files generated are `tasks.json` and `launch.json`. Below are the files generated for the default vanilla project:
```json title="tasks.json"
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}"
},
"command": "go",
"args": [
"build",
"-tags",
"dev",
"-gcflags",
"all=-N -l",
"-o",
"build/bin/myproject.exe"
]
}
]
}
```
```json title="launch.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": {}
}
]
}
```
### Configuring the install and build steps
The `tasks.json` file is simple for the default project as there is no `npm install` or `npm run build` step needed. For projects that have a frontend build step, such as the svelte template, we would need to edit `tasks.json` to add the install and build steps:
```json title="tasks.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"]
}
]
}
```
:::info Future Enhancement
In the future, we hope to generate a `tasks.json` that includes the install and build steps automatically.
:::

View file

@ -1,103 +0,0 @@
# Linux Distro Support
## Overview
Wails offers Linux support but providing installation instructions for all available distributions is an impossible task. Instead, Wails tries to determine if the packages you need to develop applications are available via your system's package manager. Currently, we support the following package managers:
- apt
- dnf
- emerge
- eopkg
- nixpkgs
- pacman
- zypper
## Adding package names
There may be circumstances where your distro uses one of the supported package managers but the package name is different. For example, you may use an Ubuntu derivative, but the package name for gtk may be different. Wails attempts to find the correct package by iterating through a list of package names. The list of packages are stored in the packagemanager specific file in the `v2/internal/system/packagemanager` directory. In our example, this would be `v2/internal/system/packagemanager/apt.go`.
In this file, the list of packages are defined by the `Packages()` method:
```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},
},
}
}
```
Let's assume that in our linux distro, `libgtk-3` is packaged under the name `lib-gtk3-dev`. We could add support for this by adding the following line:
```go {5}
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},
},
}
}
```
## Adding new package managers
To add a new package manager, perform the following steps:
- Create a new file in `v2/internal/system/packagemanager` called `<pm>.go`, where `<pm>` is the name of the package manager.
- Define a struct that conforms to the package manager interface defined in `pm.go`:
```go
type PackageManager interface {
Name() string
Packages() packagemap
PackageInstalled(*Package) (bool, error)
PackageAvailable(*Package) (bool, error)
InstallCommand(*Package) string
}
```
- `Name()` should return the name of the package manager
- `Packages()` should return a `packagemap`, that provides candidate filenames for dependencies
- `PackageInstalled()` should return `true` if the given package is installed
- `PackageAvailable()` should return `true` if the given package is not installed but available for installation
- `InstallCommand()` should return the exact command to install the given package name
Take a look at the other package managers code to get an idea how this works.
:::info Remember
If you add support for a new package manager, don't forget to also update this page!
:::

View file

@ -1,18 +0,0 @@
# Linux
This page has miscellaneous guides related to developing Wails applications for Linux.
## Video tag doesn't fire "ended" event
When using a video tag, the "ended" event is not fired when the video is finished playing. This is a bug in WebkitGTK, however you can use the following workaround to fix it:
```js
videoTag.addEventListener("timeupdate", (event) => {
if (event.target.duration - event.target.currentTime < 0.2) {
let ended = new Event("ended");
event.target.dispatchEvent(ended);
}
});
```
Source: [Lyimmi](https://github.com/Lyimmi) on the [discussions board](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275)

View file

@ -1,55 +0,0 @@
# Local Development
## Overview
Wails is in constant development and new releases are regularly "tagged". This usually happens when all the newer code on `master` has been tested and confirmed working. If you need a bugfix or feature that has not yet made it to a release, it's possible to use the latest "bleeding edge" version using the following steps:
- `git clone https://github.com/wailsapp/wails`
- `cd wails/v2/cmd/wails`
- `go install`
NOTE: The directory that you cloned the project into will now be called "clonedir".
The Wails CLI will now be at the very latest version.
### Updating your project
To update projects to use the latest version of the Wails library, update the project's `go.mod` and ensure the following line is at the bottom of the file:
`replace github.com/wailsapp/wails/v2 => <clonedir>`
Example:
On Windows: `replace github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2`
On 'nix: `replace github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2`
To revert to a stable version, run:
`go install github.com/wailsapp/wails/v2/cmd/wails@latest`
## Testing a Branch
If you want to test a branch, follow the instructions above, but ensure you switch the branch you want to test before installing:
- `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`
Make sure you [update your project](#updating-your-project) as described above.
## Testing a PR
If you want to test a PR, follow the instructions above, but ensure you fetch the PR and switch the branch before installing. Please replace `[IDofThePR]` with the ID of the PR shown on github.com:
- `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`
Make sure you [update your project](#updating-your-project) as described above.

View file

@ -1,83 +0,0 @@
# Mac App Store Guide
This page gives a brief overview of how to submit your Wails App to the Mac App Store.
## Prerequisites
- You will need to have an Apple Developer account. Please find more information on the [Apple Developer Program](https://developer.apple.com/support/compare-memberships/) site
- You will need to have your Certificates, Identifiers, and App created on the developer portal. More on this below
- Xcode command line tools will need to be installed on your local machine
#### Create Certificates and Identifiers
1. Go to your [Apple Developer Account](https://developer.apple.com/account/)
2. Under `Certificates, Identifiers & Profiles`, click `Identifiers` and Register a New App ID. Use the format (com.example.app)
3. Under the same page click `Certificates` and generate new Certificates for Mac App Store Distribution. Download them and import the certificates into Keychain on your local machine.
#### Create App Submission
1. Go to the [App Store Connect Site](https://appstoreconnect.apple.com/apps)
2. Register a new application and link the bundle ID that you created in the previous step
3. Populate your app with the correct screen shots, descriptions, etc. as required by Apple
4. Create a new version of your app
## Mac App Store Process
#### Enable Apple's App Sandbox
Apps submitted to the Mac App Store must run under Apple's [App Sandbox](https://developer.apple.com/app-sandboxing/). You must create an `entitlements.plist` file for this to work. The recommendation is to create this file under this path `{PROJECT_DIR}/build/darwin/entitlements.plist`.
**Example Entitlements File**
This is an example entitlements file from the [RiftShare](https://github.com/achhabra2/riftshare) app. For reference please put in the entitlements your app requires. Refer to [this site](https://developer.apple.com/documentation/bundleresources/entitlements) for more information.
```xml title="entitlements.plist"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
</dict>
</plist>
```
#### Build and Sign the App Package
The following is an example script for building and signing your app for Mac App Store submission. It assumes you are running the script from your root project directory.
Note the certificates for signing the app and signing the installer are different. Please make sure both are imported into Keychain. Find the strings in Keychain and insert them below. Populate your certificate names, and app name below. Running the following script will generate a signed `app.pkg` file in the root directory of your app.
```bash title="macappstore-build.sh"
#!/bin/bash
APP_CERTIFICATE="3rd Party Mac Developer Application: YOUR NAME (CODE)"
PKG_CERTIFICATE="3rd Party Mac Developer Installer: YOUR NAME (CODE)"
APP_NAME="YourApp"
wails build -platform darwin/universal -clean
codesign --timestamp --options=runtime -s "$APP_CERTIFICATE" -v --entitlements ./build/darwin/entitlements.plist ./build/bin/$APP_NAME.app
productbuild --sign "$PKG_CERTIFICATE" --component ./build/bin/$APP_NAME.app /Applications ./$APP_NAME.pkg
```
#### Upload App Bundle
You will need to upload the generated package file and associate it to your Application before you will be able to submit it for review.
1. Download the [Transporter App](https://apps.apple.com/us/app/transporter/id1450874784) from the Mac App Store
2. Open it and sign in with your Apple ID
3. Click the + sign and select the `APP_NAME.pkg` file that you generated in the previous step. Upload it
4. Go back to the [App Store Connect](https://appstoreconnect.apple.com/apps) site and navigate back into your app submission. Select the version that you are ready to make available on the App Store. Under `Build` select the package that you uploaded via Transporter.
That's it! You can now use the site to submit your App for review. After a few business days if all goes well you should see your App live on the Mac App Store.

View file

@ -1,95 +0,0 @@
# Manual Builds
The Wails CLI does a lot of heavy lifting for the project, but sometimes it's desirable to manually build your project. This document will discuss the different operations the CLI does and how this may be achieved in different ways.
## Build Process
When either `wails build` or `wails dev` are used, the Wails CLI performs a common build process:
- Install frontend dependencies
- Build frontend project
- Generate build assets
- Compile application
- [optional] Compress application
### Install frontend dependencies
#### CLI Steps
- If the `-s` flag is given, this step is skipped
- Checks `wails.json` to see if there is an install command in the key `frontend:install`
- If there isn't, it skips this step
- If there is, it checks if `package.json` exists in the frontend directory. If it doesn't exist, it skips this step
- An MD5 sum is generated from the `package.json` file contents
- It checks for the existence of `package.json.md5` and if it exists, will compare the contents of it (an MD5 sum) with the one generated to see if the contents have changed. If they are the same, this step is skipped
- If `package.json.md5` does not exist, it creates it using the generated MD5 sum
- If a build is now required, or `node_modules` does not exist, or the `-f` flag is given, the install command is executed in the frontend directory
#### Manual Steps
This step could be done from the command line or a script with `npm install`.
### Build frontend project
#### Wails CLI
- If the `-s` flag is given, this step is skipped
- Checks `wails.json` to see if there is a build command in the key `frontend:build`
- If there isn't, it skips this step
- If there is, it is executed in the frontend directory
#### Manual Steps
This step could be done from the command line or a script with `npm run build` or whatever the frontend build script is.
### Generate assets
#### Wails CLI
- If `-nopackage` flag is set, this stage is skipped
- If the `build/appicon.png` file does not exist, a default one is created
- For Windows, see [Bundling for Windows](#windows)
- If `build/windows/icon.ico` does not exist, it will create it from the `build/appicon.png` image.
##### Windows
- If `build/windows/icon.ico` does not exist, it will create it from `build/appicon.png` using icon sizes of 256, 128, 64, 48, 32 and 16. This is done using [winicon](https://github.com/leaanthony/winicon).
- If the `build/windows/<projectname>.manifest` file does not exist, it creates it from a default version.
- Compiles the application as a production build (above)
- Uses [winres](https://github.com/tc-hib/winres) to bundle the icon and manifest into a `.syso` file ready for linking.
#### Manual Steps
- Create `icon.ico` using the [winicon](https://github.com/leaanthony/winicon) CLI tool (or any other tool).
- Create / Update a `.manifest` file for your application
- Use the [winres CLI](https://github.com/tc-hib/go-winres) to generate a `.syso` file.
### Compile application
#### Wails CLI
- If the `-clean` flag is provided, the `build` directory is deleted and recreated
- For `wails dev`, the following default Go flags are used: `-tags dev -gcflags "all=-N -l"`
- For `wails build`, the following default Go flags are used: `-tags desktop,production -ldflags "-w -s"`
- On Windows, `-ldflags "-w -h -H windowsgui"`
- Additional tags passed to the CLI using `-tags` are added to the defaults
- Additional ldflags passed to the CLI using `-ldflags` are added to the defaults
- The `-o` flag is passed through
- The Go compiler specified by `-compiler` will be used for compilation
#### Manual steps
- For dev build, the minimum command would be: `go build -tags dev -gcflags "all=-N -l"`
- For production build, the minimum command would be: `go build -tags desktop,production -ldflags "-w -s -H windowsgui"`
- Ensure that you compile in the same directory as the `.syso` file
### Compress application
#### Wails CLI
- If the `-upx` flag has been given, the `upx` program will be run to compress the application with the default settings
- If `-upxflags` is also passed, these flags are used instead of the default ones
#### Manual steps
- Run `upx [flags]` manually to compress the application.

View file

@ -1,191 +0,0 @@
# Migrating from v1
## Overview
Wails v2 is a significant change from v1. This document aims to highlight the changes and the steps in migrating an existing project.
### Creating the Application
In v1, the main application is created using `wails.CreateApp`, bindings are added with `app.Bind`, then the application is run using `app.Run()`.
Example:
```go title="v1"
app := wails.CreateApp(&wails.AppConfig{
Title: "MyApp",
Width: 1024,
Height: 768,
JS: js,
CSS: css,
Colour: "#131313",
})
app.Bind(basic)
app.Run()
```
In v2, there is just a single method, `wails.Run()`, that accepts [application options](../reference/options.mdx#application-options).
```go title="v2"
err := wails.Run(&options.App{
Title: "MyApp",
Width: 800,
Height: 600,
AssetServer: &assetserver.Options{
Assets: assets,
},
Bind: []interface{}{
basic,
},
})
```
### Binding
In v1, it was possible to bind both arbitrary functions and structs. In v2, this has been simplified to only binding structs. The struct instances that were previously passed to the `Bind()` method in v1, are now specified in the `Bind` field of the [application options](../reference/options.mdx#application-options):
```go title="v1"
app := wails.CreateApp(/* options */)
app.Bind(basic)
```
```go title="v2"
err := wails.Run(&options.App{
/* other options */
Bind: []interface{}{
basic,
},
})
```
In v1, bound methods were available to the frontend at `window.backend`. This has changed to `window.go`.``
### Application Lifecycle
In v1, there were 2 special methods in a bound struct: `WailsInit()` and `WailsShutdown()`. These have been replaced with 3 lifecycle hooks as part of the [application options](../reference/options.mdx#application-options):
- [OnStartup](../reference/options.mdx#onstartup)
- [OnShutdown](../reference/options.mdx#onshutdown)
- [OnDomReady](../reference/options.mdx#ondomready)
Note: [OnDomReady](../reference/options.mdx#ondomready) replaces the `wails:ready` system event in v1.
These methods can be standard functions, but a common practice is to have them part of a struct:
```go title="v2"
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
}
...
```
### Runtime
The runtime in v2 is much richer than v1 with support for menus, window manipulation and better dialogs. The signature of the methods has changed slightly - please refer the the [Runtime Reference](../reference/runtime/intro.mdx).
In v1, the [runtime](../reference/runtime/intro.mdx) was available via a struct passed to `WailsInit()`. In v2, the runtime has been moved out to its own package. Each method in the runtime takes the `context.Context` that is passed to the [OnStartup](../reference/options.mdx#onstartup) method.
```go title="Runtime Example"
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!")
}
```
### Assets
The _biggest_ change in v2 is how assets are handled.
In v1, assets were passed via 2 application options:
- `JS` - The application's JavaScript
- `CSS` - The application's CSS
This meant that the responsibility of generating a single JS and CSS file was on the developer. This essentially required the use of complicated packers such as webpack.
In v2, Wails makes no assumptions about your frontend assets, just like a webserver. All of your application assets are passed to the application options as an `embed.FS`.
**This means there is no requirement to bundle your assets, encode images as Base64 or attempt the dark art of bundler configuration to use custom fonts**.
At startup, Wails will scan the given `embed.FS` for `index.html` and use its location as the root path for all the other application assets - just like a webserver would.
Example: An application has the following project layout. All final assets are placed in the `frontend/dist` directory:
```shell
.
├── build/
├── frontend/
│ └── dist/
│ ├── index.html
│ ├── main.js
│ ├── main.css
│ └── logo.svg
├── main.go
└── wails.json
```
Those assets may be used by the application by simply creating an `embed.FS`:
```go title="Assets Example"
//go:embed all:frontend/dist
var assets embed.FS
func main() {
err := wails.Run(&options.App{
/* Other Options */
AssetServer: &assetserver.Options{
Assets: assets,
},
})
}
```
Of course, bundlers can be used if you wish to. The only requirement is to pass the final application assets directory to Wails using an `embed.FS` in the `Assets` key of the [application options](../reference/options.mdx#application-options).
### Project Configuration
In v1, the project configuration was stored in the `project.json` file in the project root. In v2, the project configuration is stored in the `wails.json` file in the project root.
The format of the file is slightly different. Here is a comparison:
<p align="center">
| v1 | v2 | Notes |
| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | name | |
| description | | Removed |
| author / name | author / name | |
| author / email | author / email | |
| version | version | |
| binaryname | outputfilename | Changed |
| frontend / dir | | Removed |
| frontend / install | frontend:install | Changed |
| frontend / build | frontend:build | Changed |
| frontend / bridge | | Removed |
| frontend / serve | | Removed |
| tags | | Removed |
| | wailsjsdir | The directory to generate wailsjs modules |
| | assetdir | The directory of the compiled frontend assets for `dev` mode. This is normally inferred and could be left empty. |
| | reloaddirs | Comma separated list of additional directories to watch for changes and to trigger reloads in `dev` mode. This is only needed for some more advanced asset configurations. |
</p>

View file

@ -1,25 +0,0 @@
# Mouse Buttons
The Wails runtime intercepts mouse clicks to determine whether a frameless window needs resizing or a window needs to be moved. It has been asked how to detect when a mouse click has occurred, because `window.onclick` doesn't report the mouse buttons correctly. The following code shows how to detect mouse clicks:
```javascript
window.addEventListener("mousedown", handleMouseButtonDown);
function handleMouseButtonDown(event) {
if (event.button === 0) {
// left mouse button
} else if (event.button === 1) {
// middle mouse button
} else if (event.button === 2) {
// right mouse button
} else if (event.button === 3) {
// back mouse button
} else if (event.button === 4) {
// forward mouse button
} else {
// other mouse button
}
}
```
Reference: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

View file

@ -1,40 +0,0 @@
# Obfuscated Builds
Wails includes support for obfuscating your application using [garble](https://github.com/burrowers/garble).
To produce an obfuscated build, you can use the `-obfuscate` flag with the `wails build` command:
```bash
wails build -obfuscated
```
To customise the obfuscation settings, you can use the `-garbleargs` flag:
```bash
wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed"
```
These settings may be persisted in your [project config](../reference/project-config).
## How it works
In a standard build, all bound methods are available in the frontend under the `window.go` variable. When these methods are called, the corresponding backend method is called using the fully qualified function name. When using an obfuscated build, methods are bound using an ID instead of a name. The bindings generated in the `wailsjs` directory use these IDs to call the backend functions.
:::note
To ensure that your application will work in obfuscated mode, you must use the generated bindings under the `wailsjs` directory in your application.
:::
## Example
Importing the "Greet" method from the bindings like this:
```js
import { Greet } from "../../wailsjs/go/main/App";
// snip
Greet("World");
```
will ensure that the method will work correctly in obfuscated mode, as the bindings will be regenerated with IDs and the call mechanism updated.

View file

@ -1,10 +0,0 @@
# Overscroll
[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) is the "bounce effect" you sometimes get when you scroll beyond a page's content boundaries. This is common in mobile apps. This can be disabled using CSS:
```css
html {
height: 100%;
overflow: hidden;
}
```

View file

@ -1,47 +0,0 @@
# Routing
Routing is a popular way to switch views in an application. This page offers some guidance around how to do that.
## Vue
The recommended approach for routing in Vue is [Hash Mode](https://next.router.vuejs.org/guide/essentials/history-mode.html#hash-mode):
```js
import { createRouter, createWebHashHistory } from "vue-router";
const router = createRouter({
history: createWebHashHistory(),
routes: [
//...
],
});
```
## Angular
The recommended approach for routing in Angular is [HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies#_hashlocationstrategy):
```ts
RouterModule.forRoot(routes, { useHash: true });
```
## React
The recommended approach for routing in React is [HashRouter](https://reactrouter.com/docs/en/v6/routers/hash-router):
```jsx
import { HashRouter } from "react-router-dom";
ReactDOM.render(
<HashRouter basename={"/"}>
{/* The rest of your app goes here */}
<Routes>
<Route path="/" element={<Page0 />} exact />
<Route path="/page1" element={<Page1 />} />
<Route path="/page2" element={<Page2 />} />
{/* more... */}
</Routes>
</HashRouter>,
root
);
```

View file

@ -1,387 +0,0 @@
# Code Signing
This is a guide on how you can sign your binaries generated with Wails on MacOS and Windows. The guide will target CI environments, more specifically GitHub Actions.
## Windows
First off you need a code signing certificate. If you do not already have one, Microsoft's info page lists some providers [here](https://docs.microsoft.com/en-us/windows-hardware/drivers/dashboard/get-a-code-signing-certificate). Please note that an EV certificate is not required unless you need to write kernel-level software such as device drivers. For signing your Wails app, a standard code signing certificate will do just fine.
It may be a good idea to check with your certificate provider how to sign your binaries on your local machine before targeting automated build systems, just so you know if there are any special requirements. For instance, [here](https://www.ssl.com/how-to/using-your-code-signing-certificate/) is SSL.com's code signing guide for Windows. If you know how to sign locally, it will be easier to troubleshoot any potential issues in a CI environment. For instance, SSL.com code signing certificates require the `/tr` flag for [SignTool.exe](https://docs.microsoft.com/en-us/windows/win32/seccrypto/signtool) while other providers may only need the `/t` flag for providing the timestamping server. Popular GitHub Actions for signing Windows binaries like [this one](https://github.com/Dana-Prajea/code-sign-action) does not support the `/tr` flag on SignTool.exe. Therefore this guide will focus on signing our app manually with PowerShell commands, but you can use actions like the [code-sign-action](https://github.com/Dana-Prajea/code-sign-action) Action if you prefer.
First off, let's make sure we are able to build our Wails app in our GitHub CI. Here is a small workflow template:
```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/*
```
Next we need to give the GitHub workflow access to our signing certificate. This is done by encoding your .pfx or .p12 certificate into a base64 string. To do this in PowerShell, you can use the following command assuming your certificate is called 'my-cert.p12':
```PowerShell
certutil -encode .\my-cert.p12 my-cert-base64.txt
```
You should now have your .txt file with the base64 encoded certificate. It should start with _-----BEGIN CERTIFICATE-----_ and end with _-----END CERTIFICATE-----_. Now you need to make two action secrets on GitHub. Navigate to _Settings -> Secrets -> Actions_ and create the two following secrets:
- **WIN_SIGNING_CERT** with the contents of your base64 encoded certificate text.
- **WIN_SIGNING_CERT_PASSWORD** with the contents of your certificate password.
Now we're ready to implement the signing in our workflow using one of the two methods:
### Method 1: signing with commands
This method uses PowerShell commands to sign our app, and leaves you control over the entire signing process.
After the `"Build Wails app"` step, we can add the following step to our workflow:
```yaml
- 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 <signing algorithm> /t <timestamping server> /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' <path to binary>
```
This script creates a new directory for your certificate file, creates the certificate file from our base64 secret, converts it to a .pfx file, and finally signs the binary. The following variables needs to be replaced in the last line:
- **signing algorithm**: usually sha256.
- **timestamping server**: URL to the timestamping server to use with your certificate.
- **path to binary**: path to the binary you want to sign.
Given that our Wails config has `outputfilename` set to "app.exe" and that we have a certificate from SSL.com, this would be our workflow:
```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/*
```
### Method 2: automatically signing with Action
It is possible to use a Windows code signing Action like [this](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate) one, but note it requires a SHA1 hash for the certificate and a certificate name. View an example of how to configure it on the Action's [marketplace](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate).
---
## MacOS
First off you need your code signing certificate from Apple. If you do not have one, a simple Google search will help you acquire one. Once you have your certificate, you need to export it and encode it to base64. [This tutorial](https://localazy.com/blog/how-to-automatically-sign-macos-apps-using-github-actions) shows you how to do that in an easy manner. Once you have exported your .p12 certificate file, you can encode it to base64 as seen in the tutorial with the following command:
```bash
base64 Certificates.p12 | pbcopy
```
Now you're ready to create some GitHub project secrets, just as with Windows:
- **APPLE_DEVELOPER_CERTIFICATE_P12_BASE64** with the contents of your newly copied base64 certificate.
- **APPLE_DEVELOPER_CERTIFICATE_PASSWORD** with the contents of your certificate password.
- **APPLE_PASSWORD** with the contents of an App-Specific password to your Apple-ID account which you can generate [here](https://appleid.apple.com/account/manage).
Let's make sure we are able to build our Wails app in our GitHub Action workflow. Here is a small template:
```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: 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/*
```
For code signing on macOS, [gon](https://github.com/mitchellh/gon) is a very handy tool for code signing and communicating with Apple servers, also written in Go, and will be used in this guide.
After the `Build Wails app` step, add the following to the workflow:
```yaml
- name: MacOS download gon for code signing and app notarization
if: matrix.platform == 'macos-latest'
run: |
brew install mitchellh/gon/gon
```
Now we need to configure some gon config files in our `build/darwin` directory:
1. gon-sign.json:
```json
{
"source": ["./build/bin/app.app"],
"bundle_id": "app.myapp",
"apple_id": {
"username": "my-appleid@email.com",
"password": "@env:APPLE_PASSWORD"
},
"sign": {
"application_identity": "Developer ID Application: My Name"
}
}
```
Where `source` is your Wails binary, `bundle_id` is your bundle ID, `apple_id` contains your Apple ID username and App-Specific password which you created earlier, and `sign.application_identity` is your identity which you can find by running the following command:
```bash
security find-identity -v -p codesigning
```
2. entitlements.plist:
```plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.network.client</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
</dict>
</plist>
```
In this file you configure the entitlements you need for you app, e.g. camera permissions if your app uses the camera. Read more about entitlements [here](https://developer.apple.com/documentation/bundleresources/entitlements).
Make sure you have updated your `Info.plist` file with the same bundle ID as you entered in `gon-sign.json`. Here's an example `Info.plist` file:
```plist
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleName</key><string>MyApp</string>
<key>CFBundleExecutable</key><string>app</string>
<key>CFBundleIdentifier</key><string>app.myapp</string>
<key>CFBundleVersion</key><string>0.1.0</string>
<key>CFBundleGetInfoString</key><string>My app is cool and nice and chill and</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>CFBundleIconFile</key><string>iconfile</string>
<key>LSMinimumSystemVersion</key><string>10.13.0</string>
<key>NSHighResolutionCapable</key><string>true</string>
<key>LSApplicationCategoryType</key><string>public.app-category.utilities</string>
<key>NSHumanReadableCopyright</key><string>© Me</string>
</dict></plist>
```
Now we're ready to add the signing step in our workflow after building the Wails app:
```yaml
- 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
```
Please note that signing binaries with Apple could take anywhere from minutes to hours.
## Combined workflow file:
Here is our GitHub workflow file with Windows + macOS combined:
```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 mitchellh/gon/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/*
```
# End notes
This guide inspired by the RiftShare project and its workflow, which is highly recommended to check out [here](https://github.com/achhabra2/riftshare/blob/main/.github/workflows/build.yaml).

View file

@ -1,97 +0,0 @@
# Templates
Wails generates projects from pre-created templates. In v1, this was a difficult to maintain set of projects that were subject to going out of date. In v2, to empower the community, a couple of new features have been added for templates:
- Ability to generate projects from [Remote Templates](../reference/cli.mdx#remote-templates)
- Tooling to help create your own templates
## Creating Templates
To create a template, you can use the `wails generate template` command. To generate a default template, run:
`wails generate template -name mytemplate`
This creates the directory "mytemplate" with default files:
```shell title=mytemplate/
.
|-- NEXTSTEPS.md
|-- README.md
|-- app.tmpl.go
|-- frontend
| `-- dist
| |-- assets
| | |-- fonts
| | | |-- OFL.txt
| | | `-- nunito-v16-latin-regular.woff2
| | `-- images
| | `-- logo-dark.svg
| |-- index.html
| |-- main.css
| `-- main.js
|-- go.mod.tmpl
|-- main.tmpl.go
|-- template.json
`-- wails.tmpl.json
```
### Template Overview
The default template consists of the following files and directories:
| Filename / Dir | Description |
| --------------- | -------------------------------------------- |
| NEXTSTEPS.md | Instructions on how to complete the template |
| README.md | The README published with the template |
| app.tmpl.go | `app.go` template file |
| frontend/ | The directory containing frontend assets |
| go.mod.tmpl | `go.mod` template file |
| main.tmpl.go | `main.go` template file |
| template.json | The template metadata |
| wails.tmpl.json | `wails.json` template file |
At this point it is advisable to follow the steps in `NEXTSTEPS.md`.
## Creating a Template from an Existing Project
It's possible to create a template from an existing frontend project by passing the path to the project when generating the template. We will now walk through how to create a Vue 3 template:
- Install the vue cli: `npm install -g @vue/cli`
- Create the default project: `vue create vue3-base`
- Select `Default (Vue 3) ([Vue 3] babel, eslint)`
- After the project has been generated, run:
```shell
> wails generate template -name wails-vue3-template -frontend .\vue3-base\
Extracting base template files...
Migrating existing project files to frontend directory...
Updating package.json data...
Renaming package.json -> package.tmpl.json...
Updating package-lock.json data...
Renaming package-lock.json -> package-lock.tmpl.json...
```
- The template may now be customised as specified in the `NEXTSTEPS.md` file
- Once the files are ready, it can be tested by running: `wails init -n my-vue3-project -t .\wails-vue3-template\`
- To test the new project, run: `cd my-vue3-project` then `wails build`
- Once the project has compiled, run it: `.\build\bin\my-vue3-project.exe`
- You should have a fully functioning Vue3 application:
```mdx-code-block
<div className="text--center">
<img
src={require("@site/static/img/vue3-template.png").default}
width="50%"
/>
</div>
```
## Publishing Templates
Publishing a template is simply pushing the files to GitHub. The following best practice is encouraged:
- Remove any unwanted files and directories (such as `.git`) from your frontend directory
- Ensure that `template.json` is complete, especially `helpurl`
- Push the files to GitHub
- Create a PR on the [Community Templates](../community/templates.mdx) page
- Announce the template on the [Template Announcement](https://github.com/wailsapp/wails/discussions/825) discussion board

View file

@ -1,162 +0,0 @@
# Troubleshooting
An assortment of troubleshooting tips.
## The `wails` command appears to be missing?
If your system is reporting that the `wails` command is missing, make sure you have followed the Go installation guide correctly. Normally, it means that the `go/bin` directory in your User's home directory is not in the `PATH` environment variable. You will also normally need to close and reopen any open command prompts so that changes to the environment made by the installer are reflected at the command prompt.
## My application is displaying a white/blank screen
Check that your application includes the assets from the correct directory. In your `main.go` file, you will have something similar to the following code:
```go
//go:embed all:frontend/dist
var assets embed.FS
```
Check that `frontend/dist` contains your application assets.
### Mac
If this happens on Mac, try adding the following to your `Info.plist`:
```xml
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
```
Reference: https://github.com/wailsapp/wails/issues/1504#issuecomment-1174317433
## Mac application not valid
If your built application looks like this in finder:
```mdx-code-block
<p className="text--center">
<img
src={
require("@site/static/img/troubleshooting/invalid_mac_app.png").default
}
/>
</p>
```
it's likely that your application's `info.plist` is invalid. Update the file in `build/<yourapp>.app/Contents/info.plist` and check if the data is valid, EG check the binary name is correct. To persist the changes, copy the file back to the `build/darwin` directory.
## Cannot call backend method from frontend with variadic arguments
If you have a backend method defined with variadic parameters, eg:
```go
func (a *App) TestFunc(msg string, args ...interface{}) error {
// Code
}
```
calling this method from the frontend like this will fail:
```js
var msg = "Hello: ";
var args = ["Go", "JS"];
window.go.main.App.TestFunc(msg, ...args)
.then((result) => {
//do things here
})
.catch((error) => {
//handle error
});
```
Workaround:
```js
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
});
```
Credit: https://github.com/wailsapp/wails/issues/1186
## I'm having getting proxy errors when trying to install Wails
If you are getting errors like this:
```
"https://proxy.golang.org/github.com/wailsapp/wails/cmd/wails/@v/list": dial tcp 172.217.163.49:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
```
it's probably because the official Go Proxy is being blocked (Users in China have reported this). The solution is to set up the proxy manually, eg:
```
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
```
Source: https://github.com/wailsapp/wails/issues/1233
## The generated TypeScript doesn't have the correct types
Sometimes the generated TypeScript doesn't have the correct types. To mitigate this, it is possible to specify what types should be generated using the `ts_type` struct tag. For more details, please read [this](https://github.com/tkrajina/typescriptify-golang-structs#custom-types).
## When I navigate away from `index.html`, I am unable to call methods on the frontend
If you navigate away from `index.html` to a new html file, the context will be lost. This can be fixed by adding the following imports to the `<head>` section of any new page you navigate to:
```html
<head>
<script src="/wails/ipc.js"></script>
<script src="/wails/runtime.js"></script>
</head>
```
Source: https://github.com/wailsapp/wails/discussions/1512
## I get `too many open files` errors on my Mac when I run `wails dev`
By default, macOS will only allow you to open a maximum of 256 files. This can affect the `wails dev` command. This limit can be increased by running: `ulimit -n 1024` in the terminal.
FSNotify is [looking to move to Apple's fsevents](https://github.com/fsnotify/fsnotify/issues/11) for Mac. If this isn't completed soon, we will create our own implementation, tracked [here](https://github.com/wailsapp/wails/issues/1733).
## My Mac app gives me weird compilation errors
A few users have reported seeing compilation errors such as the following:
```shell
# github.com/wailsapp/wails/v2/internal/frontend/desktop/darwin
In file included from ../../pkg/mod/github.com/wailsapp/wails/v2@v2.0.0-beta.44.2/internal/frontend/desktop/darwin/callbacks.go:9:
In file included from /Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:12:
/Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSBundle.h:91:143: error: function does not return NSString
- (NSAttributedString *)localizedAttributedStringForKey:(NSString *)key value:(nullable NSString *)value table:(nullable NSString *)tableName NS_FORMAT_ARGUMENT(1) NS_REFINED_FOR_SWIFT API_AVAILABLE(macos(12.0), ios(15.0), watchos(8.0), tvos(15.0));
~~~~~~~~~~~~~~ ^ ~
/Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSObjCRuntime.h:103:48: note: expanded from macro 'NS_FORMAT_ARGUMENT'
#define NS_FORMAT_ARGUMENT(A) __attribute__ ((format_arg(A)))
```
This is _normally_ due to a mismatch with the OS version you are running and the version of the XCode Command Line Tools installed. If you see an error like this, try upgrading your XCode Command Line Tools to the latest version.
If reinstalling Xcode Command Tools still fails, you can check the path where the toolkit is located using:
`xcode-select -p`
If `/Applications/Xcode.app/Contents/Developer` is displayed, run `sudo xcode-select --switch /Library/Developer/CommandLineTools`
Sources: https://github.com/wailsapp/wails/issues/1806 and https://github.com/wailsapp/wails/issues/1140#issuecomment-1290446496
--
## Cannot start service: Host version "x.x.x does not match binary version "x.x.x"
It's preferable to add `frontend/node_modules` and `frontend/package-lock.json` to your `.gitignore`. Otherwise when opening your repository on another machine that may have different versions of Node installed, you may not be able to run your application.
If this does happen, simply delete `frontend/node_modules` and `frontend/package-lock.json` and run your `wails build` or `wails dev` command again.

View file

@ -1,82 +0,0 @@
# Visual Studio Code
This page is for miscellaneous tips and tricks when using Visual Studio Code with Wails.
## Vetur Configuration
Many thanks to [@Lyimmi](https://github.com/Lyimmi) for this tip. Originally posted [here](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349).
Vetur is a popular plugin for Visual Studio Code that provides syntax highlighting and code completion for Vue projects. When loading a Wails project in VSCode, Vetur will throw an error as it is expecting to find the frontend project in the root directory. To fix this, you can do the following:
Create a file named `vetur.config.js` in the project's root.
```javascript
// vetur.config.js
/** @type {import('vls').VeturConfig} */
module.exports = {
// **optional** default: `{}`
// override vscode settings
// Notice: It only affects the settings used by Vetur.
settings: {
"vetur.useWorkspaceDependencies": true,
"vetur.experimental.templateInterpolationService": true
},
// **optional** default: `[{ root: './' }]`
// support monorepos
projects: [
{
// **required**
// Where is your project?
// It is relative to `vetur.config.js`.
// root: './packages/repo1',
root: './frontend',
// **optional** default: `'package.json'`
// Where is `package.json` in the project?
// We use it to determine the version of vue.
// It is relative to root property.
package: './package.json',
// **optional**
// Where is TypeScript config file in the project?
// It is relative to root property.
tsconfig: './tsconfig.json',
// **optional** default: `'./.vscode/vetur/snippets'`
// Where is vetur custom snippets folders?
snippetFolder: './.vscode/vetur/snippets',
// **optional** default: `[]`
// Register globally Vue component glob.
// If you set it, you can get completion by that components.
// It is relative to root property.
// Notice: It won't actually do it. You need to use `require.context` or `Vue.component`
globalComponents: [
'./src/components/**/*.vue'
]
}
]
}
```
Next, configure `frontend/tsconfig.json`:
```javascript
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outFile": "../../built/local/tsc.js",
"allowJs": true
},
"exclude": [
"node_modules",
"**/*.spec.ts"
],
"include": [
"src/**/*",
"wailsjs/**/*.ts"
]
}
```
This should enable you to now use Vetur as expected.

View file

@ -1,58 +0,0 @@
# NSIS installer
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img
src={require("@site/static/img/nsis.webp").default}
style={{ "max-width": "50%" }}
/>
<br />
</p>
```
Wails supports generating Windows installers using the [NSIS installer](https://nsis.sourceforge.io/).
## Installing NSIS
### Windows
The installer is available on the [NSIS Download](https://nsis.sourceforge.io/Download) page.
If you use the chocolatey package manager, run the following script:
```
choco install nsis
```
If you install NSIS manually, you need to add the _Bin_ folder, which contains `makensis.exe`, in your NSIS installation to your path. [Here](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) is a good tutorial on how to add to path on Windows.
### Linux
The `nsis` package should be available through your distribution's package manager.
### MacOS
NSIS is available to install through homebrew: `brew install nsis`.
## Generating the installer
When a new project is created, Wails generates the NSIS configuration files in `build/windows/installer`. The config data is read from `installer/info.json` and that is configured to use the project's `wails.json` Info section:
```json
// ...
"Info": {
"companyName": "My Company Name",
"productName": "Wails Vite",
"productVersion": "1.0.0",
"copyright": "Copyright.........",
"comments": "Built using Wails (https://wails.io)"
},
```
To generate an installer for your application, use the `-nsis` flag with `wails build`:
```
wails build -nsis
```
The installer will now be available in the `build/bin` directory.

View file

@ -1,61 +0,0 @@
# Windows
This page has miscellaneous guides related to developing Wails applications for Windows.
## Handling the WebView2 Runtime Dependency
Wails applications built for Windows have a runtime requirement on the Microsoft [WebView2 Runtime](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). Windows 11 will have this installed by default, but some machines won't. Wails offers an easy approach to dealing with this dependency.
By using the `-webview2` flag when building, you can decide what your application will do when a suitable runtime is not detected (including if the installed runtime is too old). The four options are:
1. Download
2. Embed
3. Navigateur
4. Error
### Download
This option will prompt the user that no suitable runtime has been found and then offer to download and run the official bootstrapper from Microsoft's WebView2 site. If the user proceeds, the official bootstrapper will be downloaded and run.
### Embed
This option embeds the official bootstrapper within the application. If no suitable runtime has been found, the application will offer to run the bootstrapper. This adds ~150k to the binary size.
### Navigateur
This option will prompt the user that no suitable runtime has been found and then offer to open a browser to the official WebView2 page where the bootstrapper can be downloaded and installed. The application will then exit, leaving the installation up to the user.
### Error
If no suitable runtime is found, an error is given to the user and no further action taken.
## Fixed version runtime
Another way of dealing with webview2 dependency is shipping it yourself. You can download [fixed version runtime](https://developer.microsoft.com/microsoft-edge/webview2/#download-section) and bundle or download it with your application.
Also, you should specify path to fixed version of webview2 runtime in the `windows.Options` structure when launching wails.
```go
wails.Run(&options.App{
Windows: &windows.Options{
WebviewBrowserPath: "",
},
})
```
Note: When `WebviewBrowserPath` is specified, `error` strategy will be forced in case of minimal required version mismatch or invalid path to a runtime.
## Spawning other programs
When spawning other programs, such as scripts, you will see the window appear on the screen. To hide the window, you can use the following code:
```go
cmd := exec.Command("your_script.exe")
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: 0x08000000,
}
cmd.Start()
```
Solution provided by [sithembiso](https://github.com/sithembiso) on the [discussions board](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172).

View file

@ -1,369 +0,0 @@
---
sidebar_position: 20
---
# Comment ça marche ?
Une application Wails est une application Go standard, avec une interface graphique webkit. La partie Go de l'application se compose du code de l'application et d'une bibliothèque d'exécution qui fournit un certain nombre d'opérations utiles, comme le contrôle de la fenêtre de l'application. Le frontend est une fenêtre webkit qui affichera les ressources graphiques. Une version de la bibliothèque runtime de Javascript est aussi disponible depuis le frontend. Enfin, il est possible de lier les méthodes Go au frontend, et ceux-ci apparaîtront comme des méthodes Javascript qui peuvent être appelées, comme s'il s'agissait de méthodes locales Javascript.
```mdx-code-block
<div className="text--center">
<img src={require("@site/static/img/architecture.webp").default} style={{"width":"75%", "max-width":"800px"}} />
</div>
```
## L'Application Principale
### Vue densemble
L'application principale consiste en un seul appel à `wails.Run()`. Il accepte la configuration de l'application qui décrit la taille de la fenêtre d'application, le titre de la fenêtre, qu'elles sont les ressources à utiliser, etc. Une application de base pourrait ressembler à ceci :
```go title="main.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)
}
```
### Description des options
Cet exemple a les options suivantes :
- `Title` - Le texte qui devrait apparaître dans la barre de titre de la fenêtre
- `Width` & `Height` - Les dimensions de la fenêtre
- `Assets` - Les ressources du frontend de l'application
- `OnStartup` - Nom de la fonction à appeler quand la fenêtre est créée et est sur le point de commencer à charger les ressources du frontend
- `OnShutdown` - Nom de la fonction à appeler quand la fenêtre est sur le point d'être fermée
- `Bind` - La liste des structures Go à exposer au frontend
Une liste complète des options d'application peut être trouvée dans la [Référence d'options](reference/options).
#### Ressources
The `Assets` option is mandatory as you can't have a Wails application without frontend assets. Those assets can be any files you would expect to find in a web application - html, js, css, svg, png, etc. **There is no requirement to generate asset bundles** - plain files will do. When the application starts, it will attempt to load `index.html` from your assets and the frontend will essentially work as a browser from that point on. It is worth noting that there is no requirement on where in the `embed.FS` the files live. It is likely that the embed path uses a nested directory relative to your main application code, such as `frontend/dist`:
```go title="main.go"
//go:embed all:frontend/dist
var assets embed.FS
```
At startup, Wails will iterate the embedded files looking for the directory containing `index.html`. All other assets will be loaded relative to this directory.
As production binaries use the files contained in `embed.FS`, there are no external files required to be shipped with the application.
When running in development mode using the `wails dev` command, the assets are loaded off disk, and any changes result in a "live reload". The location of the assets will be inferred from the `embed.FS`.
More details can be found in the [Application Development Guide](guides/application-development.mdx).
#### Application Lifecycle Callbacks
Just before the frontend is about to load `index.html`, a callback is made to the function provided in [OnStartup](reference/options.mdx#onstartup). A standard Go context is passed to this method. This context is required when calling the runtime so a standard pattern is to save a reference to in this method. Just before the application shuts down, the [OnShutdown](reference/options.mdx#onshutdown) callback is called in the same way, again with the context. There is also an [OnDomReady](reference/options.mdx#ondomready) callback for when the frontend has completed loading all assets in `index.html` and is equivalent of the [`body onload`](https://www.w3schools.com/jsref/event_onload.asp) event in JavaScript. It is also possible to hook into the window close (or application quit) event by setting the option [OnBeforeClose](reference/options.mdx#onbeforeclose).
#### Method Binding
The `Bind` option is one of the most important options in a Wails application. It specifies which struct methods to expose to the frontend. Think of structs like "controllers" in a traditional web application. When the application starts, it examines the struct instances listed in the `Bind` field in the options, determines which methods are public (starts with an uppercase letter) and will generate JavaScript versions of those methods that can be called by the frontend code.
:::info Note
Wails requires that you pass in an _instance_ of the struct for it to bind it correctly
:::
In this example, we create a new `App` instance and then add this instance to the `Bind` option in `wails.Run`:
```go {16,24} title="main.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,
},
Bind: []interface{}{
app,
},
})
if err != nil {
log.Fatal(err)
}
}
type App struct {
ctx context.Context
}
func (a *App) Greet(name string) string {
return fmt.Sprintf("Hello %s!", name)
}
```
You may bind as many structs as you like. Just make sure you create an instance of it and pass it in `Bind`:
```go {8-10}
//...
err := wails.Run(&options.App{
Title: "Basic Demo",
Width: 1024,
Height: 768,
AssetServer: &assetserver.Options{
Assets: assets,
},
Bind: []interface{}{
app,
&mystruct1{},
&mystruct2{},
},
})
```
When you run `wails dev` (or `wails generate module`), a frontend module will be generated containing the following:
- JavaScript bindings for all bound methods
- TypeScript declarations for all bound methods
- TypeScript definitions for all Go structs used as inputs or outputs by the bound methods
This makes it incredibly simple to call Go code from the frontend, using the same strongly typed datastructures.
## Le frontend
### Vue densemble
The frontend is a collection of files rendered by webkit. It's like a browser and webserver in one. There is virtually[^1] no limit to which frameworks or libraries you can use. The main points of interaction between the frontend and your Go code are:
- Calling bound Go methods
- Calling runtime methods
### Calling bound Go methods
When you run your application with `wails dev`, it will automatically generate JavaScript bindings for your structs in a directory called `wailsjs/go` (You can also do this by running `wails generate module`). The generated files mirror the package names in your application. In the example above, we bind `app`, which has one public method `Greet`. This will lead to the generation of the following files:
```bash
wailsjs
└─go
└─main
├─App.d.ts
└─App.js
```
Here we can see that there is a `main` package that contains the JavaScript bindings for the bound `App` struct, as well as the TypeScript declaration file for those methods. To call `Greet` from our frontend, we simply import the method and call it like a regular JavaScript function:
```javascript
// ...
import { Greet } from "../wailsjs/go/main/App";
function doGreeting(name) {
Greet(name).then((result) => {
// Do something with result
});
}
```
The TypeScript declaration file gives you the correct types for the bound methods:
```ts
export function Greet(arg1: string): Promise<string>;
```
The generated methods return a Promise. A successful call will result in the first return value from the Go call to be passed to the `resolve` handler. An unsuccessful call is when a Go method that has an error type as it's second return value, passes an error instance back to the caller. This is passed back via the `reject` handler. In the example above, `Greet` only returns a `string` so the JavaScript call will never reject - unless invalid data is passed to it.
All data types are correctly translated between Go and JavaScript. Even structs. If you return a struct from a Go call, it will be returned to your frontend as a JavaScript class.
:::info Note
Struct fields *must* have a valid `json` tag to be included in the generated TypeScript.
Anonymous nested structs are not supported at this time.
:::
It is possible to send structs back to Go. Any JavaScript map/class passed as an argument that is expecting a struct, will be converted to that struct type. To make this process a lot easier, in `dev` mode, a TypeScript module is generated, defining all the struct types used in bound methods. Using this module, it's possible to construct and send native JavaScript objects to the Go code.
There is also support for Go methods that use structs in their signature. All Go structs specified by a bound method (either as parameters or return types) will have TypeScript versions auto generated as part of the Go code wrapper module. Using these, it's possible to share the same data model between Go and JavaScript.
Example: We update our `Greet` method to accept a `Person` instead of a string:
```go title="main.go"
type Person struct {
Name string `json:"name"`
Age uint8 `json:"age"`
Address *Address `json:"address"`
}
type Address struct {
Street string `json:"street"`
Postcode string `json:"postcode"`
}
func (a *App) Greet(p Person) string {
return fmt.Sprintf("Hello %s (Age: %d)!", p.Name, p.Age)
}
```
The `wailsjs/go/main/App.js` file will still have the following code:
```js title="App.js"
export function Greet(arg1) {
return window["go"]["main"]["App"]["Greet"](arg1);
}
```
But the `wailsjs/go/main/App.d.ts` file will be updated with the following code:
```ts title="App.d.ts"
import { main } from "../models";
export function Greet(arg1: main.Person): Promise<string>;
```
As we can see, the "main" namespace is imported from a new "models.ts" file. This file contains all the struct definitions used by our bound methods. In this example, this is a `Person` struct. If we look at `models.ts`, we can see how the models are defined:
```ts title="models.ts"
export namespace main {
export class Address {
street: string;
postcode: string;
static createFrom(source: any = {}) {
return new Address(source);
}
constructor(source: any = {}) {
if ("string" === typeof source) source = JSON.parse(source);
this.street = source["street"];
this.postcode = source["postcode"];
}
}
export class Person {
name: string;
age: number;
address?: Address;
static createFrom(source: any = {}) {
return new Person(source);
}
constructor(source: any = {}) {
if ("string" === typeof source) source = JSON.parse(source);
this.name = source["name"];
this.age = source["age"];
this.address = this.convertValues(source["address"], Address);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice) {
return (a as any[]).map((elem) => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
}
```
So long as you have TypeScript as part of your frontend build configuration, you can use these models in the following way:
```js title="mycode.js"
import { Greet } from "../wailsjs/go/main/App";
import { main } from "../wailsjs/go/models";
function generate() {
let person = new main.Person();
person.name = "Peter";
person.age = 27;
Greet(person).then((result) => {
console.log(result);
});
}
```
The combination of generated bindings and TypeScript models makes for a powerful development environment.
More information on Binding can be found in the [Binding Methods](guides/application-development.mdx#binding-methods) section of the [Application Development Guide](guides/application-development.mdx).
### Appeler les méthodes runtime
The JavaScript runtime is located at `window.runtime` and contains many methods to do various tasks such as emit an event or perform logging operations:
```js title="mycode.js"
window.runtime.EventsEmit("my-event", 1);
```
More details about the JS runtime can be found in the [Runtime Reference](reference/runtime/intro).
[^1]: There is a very small subset of libraries that use features unsupported in WebViews. There are often alternatives and workarounds for such cases.

View file

@ -1,73 +0,0 @@
---
sidebar_position: 1
---
# Introduction
Wails est un projet qui vous permet d'écrire des applications de bureau en utilisant les technologies Go et web.
Considérez cela comme une alternative légère et rapide d'Electron pour Go. Vous pouvez facilement construire des applications avec la flexibilité et la puissance de Go, combinée à un frontend riche et moderne.
### Fonctionnalités
- Menus natifs, Boîtes de dialogues, Thèmes et Translucidité
- Prise en charge de Windows, macOS et Linux
- Modèles intégrés pour Svelte, React, Preact, Vue, Lit et Vanilla JS
- Appeler facilement les méthodes Go depuis JavaScript
- Génération automatique du modèle TypeScript à partir des struct Go
- Aucun CGO ou DLL externe requis sous Windows
- Mode développement en direct en utilisant la puissance de [Vite](https://vitejs.dev/)
- CLI puissant pour créer, construire et empaqueter facilement des applications
- Une riche bibliothèque [runtime](/docs/reference/runtime/intro)
- Les applications construites avec Wails sont conformes aux Stores Apple & Microsoft
Ceci est varly - une application de bureau pour MacOS & Windows écrite à l'aide de Wails. Non seulement elle est belle, elle utilise les menus natifs et la translucidité - tout ce que vous pouvez attendre d'une application native moderne.
```mdx-code-block
<p class="text--center">
<img
src={require("@site/static/img/showcase/varly2.webp").default}
style={{ width: "75%", "max-width": "800px" }}
/>
</p>
```
### Modèles de créations rapides
Wails est livré avec un certain nombre de modèles préconfigurés qui vous permettent de faire fonctionner votre application rapidement. Il y a des modèles pour les frameworks suivants : Svelte, React, Vue, Preact, Lit et Vanilla. Il existe à la fois des versions JavaScript et TypeScript pour chaque modèle.
### Éléments natifs
Wails utilise une bibliothèque conçue pour gérer les éléments natifs tels que les fenêtres, menus, boîtes de dialogues, etc, pour que vous puissiez construire des applications de bureau riches en fonctionnalités.
**Il n'embarque pas de navigateur**, il est donc efficace sur les ressources. Au lieu de cela, il utilise le moteur de rendu natif de la plate-forme. Sous Windows, c'est la nouvelle bibliothèque Microsoft Webview2, construite sur Chromium.
### Interopérabilité Go & Javascript
Wails met automatiquement vos méthodes Go à la disposition de Javascript, afin que vous puissiez les appeler par nom depuis votre frontend ! Il génère même des modèles Typescript pour les structures utilisées par vos méthodes Go, pour que vous puissiez passer les mêmes structures de données entre Go et Javascript.
### Librairie d'exécution
Wails fournit une bibliothèque runtime, pour Go et Javascript, qui gère beaucoup de choses dont les applications modernes ont besoin, comme Logging, Boîtes de dialogue, etc.
### Expérience de développement en direct
#### Reconstructions automatiques
Lorsque vous exécutez votre application en mode "dev", Wails construira votre application en tant qu'application de bureau native, mais lira vos ressources depuis le disque. Il détectera toutes les modifications apportées à votre code Go, puis reconstruira et relancera automatiquement votre application .
#### Rechargement automatique
Lorsque des changements sont détectés dans les ressources de votre application, votre application en cours d'exécution sera "rechargée", reflétant presque immédiatement vos modifications .
#### Développez votre application dans un navigateur
Si vous préférez déboguer et vous développer dans un navigateur, Wails vous couvre. L'application en cours d'exécution a également un serveur web qui exécutera votre application depuis n'importe quel navigateur qui s'y connecte. Il sera aussi actualisé lorsque vos fichiers seront modifiés.
### Binaires natifs prêts à la production
Lorsque vous êtes prêt à faire une version finale de votre application, le CLI le compilera en un seul exécutable, avec tous les actifs qui y sont intégrés. Sous Windows et MacOS, il est possible de créer un paquet natif pour la distribution. Les ressources utilisées dans la compilation de l'application (icône, info. list, fichier manifest, etc) font partie de votre projet et peuvent être personnalisés, ce qui vous donne le contrôle total sur la façon dont vos applications sont construites.
### Outils
Le CLI Wails fournit un moyen sans tracas de générer, de construire et de regrouper vos applications. Il s'occupera de la lourde tâche de créer des icônes, de compiler votre application avec des paramètres optimaux et de fournir un binaire distribuable et prêt à la production. Choisissez parmi un certain nombre de modèles de démarrage pour démarrer rapidement !

View file

@ -1,229 +0,0 @@
---
sidebar_position: 2
---
# CLI
Le CLI Wails a un certain nombre de commandes qui sont utilisées pour gérer vos projets. Toutes les commandes sont exécutées de la manière suivante:
`wails <commande> <options>`
## init
`wails init` est utilisé pour générer des projets.
| Option | Description | Par défaut |
|:------------------------- |:---------------------------------------------------------------------------------------------------------------------- |:-------------:|
| -n "nom du projet" | Nom du projet. **Obligatoire**. | |
| -d "Répertoire du projet" | Dossier de projet à créer | Nom du projet |
| -g | Initialisation du dépôt git | |
| -l | Liste des modèles de projet disponibles | |
| -q | Supprimer les logs dans la console | |
| -t "nom du modèle" | Modèle de projet à utiliser. Cela peut être le nom d'un modèle par défaut ou d'une URL d'un projet hébergé sur github. | vanilla |
| -ide | Générer les fichiers du projet IDE | |
| -f | Forcer la compilation de l'application | false |
Exemple: `wails init -n test -d mytestproject -g -ide vscode -q`
Cela va générer un projet appelé "test" dans le répertoire "mytestproject", initialiser git, générer des fichiers de projet vscode et le faire silencieusement.
Plus d'informations sur l'utilisation des IDEs avec Wails peuvent être trouvées [ici](../guides/ides.mdx).
### Modèles à distance
Les modèles distants (hébergés sur GitHub) sont pris en charge et peuvent être installés en utilisant l'URL du projet du modèle.
Exemple : `wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]`
Une liste de modèles gérés par la communauté peut être trouvée [ici](../community/templates.mdx)
:::warning Attention
**Le projet Wails n'entretient pas, n'est pas responsable ni responsable des modèles tiers !**
Si vous n'êtes pas sûr d'un modèle, inspectez les fichiers `package.json` et `wails.json` pour savoir quels scripts sont exécutés et quels paquets sont installés.
:::
## build
`wails build` est utilisé pour compiler votre projet vers un binaire prêt à la production.
| Option | Description | Par défaut |
|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| -platform | Construit pour les [plates-formes](../reference/cli.mdx#platforms) données (séparées par des virgules) par exemple. `windows/arm64`. Notez que si vous ne donnez pas l'architecture, `runtime.GOARCH` est utilisé. | platform = le contenu de la variable d'environnement `GOOS` si elle existe, autrement `runtime.GOOS`.<br/>arch = le contenu de la variable d'environnement `GOARCH` si elle existe, autrement `runtime.GOARCH`. |
| -clean | Nettoie le répertoire `build/bin` | |
| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go |
| -ldflags "flags" | Options supplémentaires à passer au compilateur | |
| -nopackage | Ne pas empaqueter l'application | |
| -o filename | Nom du fichier de sortie | |
| -s | Ignorer la construction du frontend | false |
| -f | Forcer la compilation de l'application | false |
| -tags "extra tags" | Options de compilation à passer au compilateur Go. Doivent être entre guillemets. Séparés par un espace ou une virgule (pas les deux) | |
| -upx | Compresser le binaire final en utilisant "upx" | |
| -upxflags | Options à passer à upx | |
| -v int | Niveau de verbosité (0 - silencieux, 1 - par défaut, 2 - verbeux) | 1 |
| -webview2 | Stratégie d'installation WebView2 : download,embed,browser,error | download |
| -u | Met à jour le `go.mod de votre projet` pour utiliser la même version de Wails que le CLI | |
| -debug | Conserve les informations de débogage dans l'application. Permet l'utilisation des outils de développement dans la fenêtre de l'application | false |
| -trimpath | Supprimer tous les chemins vers les fichiers système de l'exécutable final. | false |
| -race | Construire avec le détecteur Go race | false |
| -windowsconsole | Garder la fenêtre de la console lors de la construction d'une version pour Windows | |
| -obfuscate | Cacher le code de l'application en utilisant [garble](https://github.com/burrowers/garble) | false |
| -garbleargs | Arguments à passer à garble | `-literals -tiny -seed=random` |
Pour une description détaillée des options `webview2` , veuillez vous référer au Guide de [Windows](../guides/windows.mdx).
Si vous préférez construire en utilisant l'outil Go standard, veuillez consulter le guide [Constructions manuelles](../guides/manual-builds.mdx) .
Exemple:
`wails build -clean -o myproject.exe`
:::Info
Sur Mac, l'application sera livrée avec `Info.plist`, pas `Info.dev.plist`.
:::
:::info UPX sur Apple Silicon
Il y a [problèmes](https://github.com/upx/upx/issues/446) avec l'utilisation de UPX avec Apple Silicon.
:::
:::info UPX sur Windows
Certains antivirus marquent de manière erronée les binaires compressés d'`upx` comme virus, voir [la description du problème](https://github.com/upx/upx/issues/437).
:::
### Platformes
Plateformes supportées:
| Plateforme | Description |
|:---------------- |:-------------------------------------------------- |
| darwin | MacOS + Architecture de la machine de construction |
| darwin/amd64 | MacOS 10.13+ AMD64 |
| darwin/arm64 | MacOS 11.0+ ARM64 |
| darwin/universal | Application universelle MacOS AMD64+ARM64 |
| windows | Windows 10/11 + architecture de la machine |
| windows/amd64 | Windows 10/11 AMD64 |
| windows/arm64 | Windows 10/11 ARM64 |
| linux | Linux + architecture de la machine |
| linux/amd64 | Linux AMD64 |
| linux/arm64 | Linux ARM64 |
## doctor
`wails doctor` effectuera des diagnostics pour vous assurer que votre système est prêt pour développer avec wails.
Exemple:
```
Wails CLI v2.0.0-beta
Scanning system - Please wait (this may take a long time)...Done.
System
------
OS: Windows 10 Pro
Version: 2009 (Build: 19043)
ID: 21H1
Go Version: go1.18
Platform: windows
Architecture: amd64
Dependency Package Name Status Version
---------- ------------ ------ -------
WebView2 N/A Installed 93.0.961.52
npm N/A Installed 6.14.15
*upx N/A Installed upx 3.96
* - Optional Dependency
Diagnosis
---------
Your system is ready for Wails development!
```
## dev
`wails dev` est utilisé pour exécuter votre application en mode « développement en direct ». Ceci signifie que :
- Le fichier `go.mod` de l'application sera mis à jour pour utiliser la même version de Wails que le CLI
- L'application est compilée et exécutée automatiquement
- A watcher is started and will trigger a rebuild of your dev app if it detects changes to your go files
- A webserver is started on `http://localhost:34115` which serves your application (not just frontend) over http. This allows you to use your favourite browser development extensions
- All application assets are loaded from disk. If they are changed, the application will automatically reload (not rebuild). All connected browsers will also reload
- A JS module is generated that provides the following:
- JavaScript wrappers of your Go methods with autogenerated JSDoc, providing code hinting
- TypeScript versions of your Go structs, that can be constructed and passed to your go methods
- A second JS module is generated that provides a wrapper + TS declaration for the runtime
- On macOS, it will bundle the application into a `.app` file and run it. It will use a `build/darwin/Info.dev.plist` for development.
| Option | Description | Par défaut |
|:---------------------------- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:--------------------- |
| -assetdir "./path/to/assets" | Serve assets from the given directory instead of using the provided asset FS | Value in `wails.json` |
| -browser | Opens a browser to `http://localhost:34115` on startup | |
| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go |
| -e | Extensions to trigger rebuilds (comma separated) | go |
| -reloaddirs | Additional directories to trigger reloads (comma separated) | Value in `wails.json` |
| -ldflags "flags" | Options supplémentaires à passer au compilateur | |
| -tags "extra tags" | Build tags to pass to compiler (quoted and space separated) | |
| -loglevel "loglevel" | Loglevel to use - Trace, Debug, Info, Warning, Error | Debug |
| -noreload | Disable automatic reload when assets change | |
| -nocolour | Turn off colour cli output | false |
| -nogen | Disable generate module | |
| -v | Verbosity level (0 - silent, 1 - standard, 2 - verbose) | 1 |
| -wailsjsdir | The directory to generate the generated Wails JS modules | Value in `wails.json` |
| -debounce | The time to wait for reload after an asset change is detected | 100 (milliseconds) |
| -devserver "host:port" | The address to bind the wails dev server to | "localhost:34115" |
| -frontenddevserverurl "url" | Use 3rd party dev server url to serve assets, EG Vite | "" |
| -appargs "args" | Arguments passed to the application in shell style | |
| -save | Saves the given `assetdir`, `reloaddirs`, `wailsjsdir`, `debounce`, `devserver` and `frontenddevserverurl` flags in `wails.json` to become the defaults for subsequent invocations. | |
| -race | Construire avec le détecteur Go race | false |
| -s | Ignorer la construction du frontend | false |
Exemple:
`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser`
This command will do the following:
- Build the application and run it (more details [here](../guides/manual-builds.mdx)
- Generate the Wails JS modules in `./frontend/src`
- Watch for updates to files in `./frontend/dist` and reload on any change
- Open a browser and connect to the application
There is more information on using this feature with existing framework scripts [here](../guides/application-development.mdx#live-reloading).
## generate
### template
Wails uses templates for project generation. The `wails generate template` command helps scaffold a template so that it may be used for generating projects.
| Option | Description |
|:---------------- |:------------------------------------------- |
| -name | The template name (Mandatory) |
| -frontend "path" | Path to frontend project to use in template |
For more details on creating templates, consult the [Templates guide](../guides/templates.mdx).
### module
The `wails generate module` command allows you to manually generate the `wailsjs` directory for your application.
## update
`wails update` will update the version of the Wails CLI.
| Option | Description |
|:------------------ |:------------------------------------- |
| -pre | Update to latest pre-release version |
| -version "version" | Install a specific version of the CLI |
## version
`wails version` will simply output the current CLI version.

View file

@ -1,227 +0,0 @@
---
sidebar_position: 4
---
# Menus
It is possible to add an application menu to Wails projects. This is achieved by defining a [Menu](#menu) struct and setting it in the [`Menu`](../reference/options.mdx#menu) application config, or by calling the runtime method [MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu).
An example of how to create a menu:
```go
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()
})
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,
Bind: []interface{}{
app,
},
)
// ...
```
It is also possible to dynamically update the menu, by updating the menu struct and calling [MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu).
The example above uses helper methods, however it's possible to build the menu structs manually.
## Menu
A Menu is a collection of MenuItems:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
type Menu struct {
Items []*MenuItem
}
```
For the Application menu, each MenuItem represents a single menu such as "Edit".
A simple helper method is provided for building menus:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu
```
This makes the layout of the code more like that of a menu without the need to add the menu items manually after creating them. Alternatively, you can just create the menu items and add them to the menu manually.
## MenuItem
A MenuItem represents an item within a Menu.
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
// MenuItem represents a menu item contained in a menu
type MenuItem struct {
Label string
Role Role
Accelerator *keys.Accelerator
Type Type
Disabled bool
Hidden bool
Checked bool
SubMenu *Menu
Click Callback
}
```
| Field | Type | Notes |
| ----------- | ------------------------------------ | ------------------------------------------------------------- |
| Label | string | The menu text |
| Accelerator | [\*keys.Accelerator](#accelerator) | Key binding for this menu item |
| Type | [Type](#type) | Type of MenuItem |
| Disabled | bool | Disables the menu item |
| Hidden | bool | Hides this menu item |
| Checked | bool | Adds check to item (Checkbox & Radio types) |
| SubMenu | [\*Menu](#menu) | Sets the submenu |
| Click | [Callback](#callback) | Callback function when menu clicked |
| Role | string | Defines a [role](#role) for this menu item. Mac only for now. |
### Accelerator
Accelerators (sometimes called keyboard shortcuts) define a binding between a keystroke and a menu item. Wails defines an Accelerator as a combination or key + [Modifier](#modifier). They are available in the `"github.com/wailsapp/wails/v2/pkg/menu/keys"` package.
Example:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut := keys.CmdOrCtrl("o")
```
Keys are any single character on a keyboard with the exception of `+`, which is defined as `plus`. Some keys cannot be represented as characters so there are a set of named characters that may be used:
| | | | |
|:-----------:|:-----:|:-----:|:---------:|
| `backspace` | `f1` | `f16` | `f31` |
| `tab` | `f2` | `f17` | `f32` |
| `return` | `f3` | `f18` | `f33` |
| `enter` | `f4` | `f19` | `f34` |
| `escape` | `f5` | `f20` | `f35` |
| `left` | `f6` | `f21` | `numlock` |
| `right` | `f7` | `f22` | |
| `up` | `f8` | `f23` | |
| `down` | `f9` | `f24` | |
| `space` | `f10` | `f25` | |
| `delete` | `f11` | `f36` | |
| `home` | `f12` | `f37` | |
| `end` | `f13` | `f38` | |
| `page up` | `f14` | `f39` | |
| `page down` | `f15` | `f30` | |
Wails also supports parsing accelerators using the same syntax as Electron. This is useful for storing accelerators in config files.
Example:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines cmd+o on Mac and ctrl-o on Window/Linux
myShortcut, err := keys.Parse("Ctrl+Option+A")
```
#### Modifier
The following modifiers are keys that may be used in combination with the accelerator key:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
const (
// CmdOrCtrlKey represents Command on Mac and Control on other platforms
CmdOrCtrlKey Modifier = "cmdorctrl"
// OptionOrAltKey represents Option on Mac and Alt on other platforms
OptionOrAltKey Modifier = "optionoralt"
// ShiftKey represents the shift key on all systems
ShiftKey Modifier = "shift"
// ControlKey represents the control key on all systems
ControlKey Modifier = "ctrl"
)
```
A number of helper methods are available to create Accelerators using modifiers:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
func CmdOrCtrl(key string) *Accelerator
func OptionOrAlt(key string) *Accelerator
func Shift(key string) *Accelerator
func Control(key string) *Accelerator
```
Modifiers can be combined using `keys.Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)`:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys"
// Defines "Ctrl+Option+A" on Mac and "Ctrl+Alt+A" on Window/Linux
myShortcut := keys.Combo("a", ControlKey, OptionOrAltKey)
```
### Type
Each menu item must have a type and there are 5 types available:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
const (
TextType Type = "Text"
SeparatorType Type = "Separator"
SubmenuType Type = "Submenu"
CheckboxType Type = "Checkbox"
RadioType Type = "Radio"
)
```
For convenience, helper methods are provided to quickly create a menu item:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func Text(label string, accelerator *keys.Accelerator, click Callback) *MenuItem
func Separator() *MenuItem
func Radio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func Checkbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func SubMenu(label string, menu *Menu) *Menu
```
You can also create menu items directly on a menu by using the "Add" helpers:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
func (m *Menu) AddText(label string, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddSeparator() *MenuItem
func (m *Menu) AddRadio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddCheckbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem
func (m *Menu) AddSubMenu(label string, menu *Menu) *MenuI
```
A note on radio groups: A radio group is defined as a number of radio menu items that are next to each other in the menu. This means that you do not need to group items together as it is automatic. However, that also means you cannot have 2 radio groups next to each other - there must be a non-radio item between them.
### Callback
Each menu item may have a callback that is executed when the item is clicked:
```go title="Package: github.com/wailsapp/wails/v2/pkg/menu"
type Callback func(*CallbackData)
type CallbackData struct {
MenuItem *MenuItem
}
```
The function is given a `CallbackData` struct which indicates which menu item triggered the callback. This is useful when using radio groups that may share a callback.
### Role
:::info Roles
Roles are currently supported on Mac only.
:::
A menu item may have a role, which is essentially a pre-defined menu item. We currently support the following roles:
| Role | Description |
| ------------ | ------------------------------------------------------------------------ |
| AppMenuRole | The standard Mac application menu. Can be created using `menu.AppMenu()` |
| EditMenuRole | The standard Mac edit menu. Can be created using `menu.EditMenu()` |

View file

@ -1,737 +0,0 @@
---
sidebar_position: 3
---
# Options
## Application Options
The `Options.App` struct contains the application configuration. It is passed to the `wails.Run()` method:
```go title="Example"
import (
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/assetserver"
"github.com/wailsapp/wails/v2/pkg/options/linux"
"github.com/wailsapp/wails/v2/pkg/options/mac"
"github.com/wailsapp/wails/v2/pkg/options/windows"
)
func main() {
err := wails.Run(&options.App{
Title: "Menus Demo",
Width: 800,
Height: 600,
DisableResize: false,
Fullscreen: false,
WindowStartState: options.Maximised,
Frameless: true,
MinWidth: 400,
MinHeight: 400,
MaxWidth: 1280,
MaxHeight: 1024,
StartHidden: false,
HideWindowOnClose: false,
BackgroundColour: &options.RGBA{R: 0, G: 0, B: 0, A: 255},
AlwaysOnTop: false,
AssetServer: &assetserver.Options{
Assets: assets,
Handler: assetsHandler,
Middleware: assetsMidldeware,
},
Menu: app.applicationMenu(),
Logger: nil,
LogLevel: logger.DEBUG,
LogLevelProduction: logger.ERROR,
OnStartup: app.startup,
OnDomReady: app.domready,
OnShutdown: app.shutdown,
OnBeforeClose: app.beforeClose,
CSSDragProperty: "--wails-draggable",
CSSDragValue: "drag",
ZoomFactor: 1.0,
IsZoomControlEnabled: false,
Bind: []interface{}{
app,
},
Windows: &windows.Options{
WebviewIsTransparent: false,
WindowIsTranslucent: false,
BackdropType: windows.Mica,
DisableWindowIcon: false,
DisableFramelessWindowDecorations: false,
WebviewUserDataPath: "",
WebviewBrowserPath: "",
Theme: windows.SystemDefault,
CustomTheme: &windows.ThemeSettings{
DarkModeTitleBar: windows.RGB(20, 20, 20),
DarkModeTitleText: windows.RGB(200, 200, 200),
DarkModeBorder: windows.RGB(20, 0, 20),
LightModeTitleBar: windows.RGB(200, 200, 200),
LightModeTitleText: windows.RGB(20, 20, 20),
LightModeBorder: windows.RGB(200, 200, 200),
},
// User messages that can be customised
Messages *windows.Messages
// OnSuspend is called when Windows enters low power mode
OnSuspend func()
// OnResume is called when Windows resumes from low power mode
OnResume func()
},
Mac: &mac.Options{
TitleBar: &mac.TitleBar{
TitlebarAppearsTransparent: true,
HideTitle: false,
HideTitleBar: false,
FullSizeContent: false,
UseToolbar: false,
HideToolbarSeparator: true,
},
Appearance: mac.NSAppearanceNameDarkAqua,
WebviewIsTransparent: true,
WindowIsTranslucent: false,
About: &mac.AboutInfo{
Title: "My Application",
Message: "© 2021 Me",
Icon: icon,
},
},
Linux: &linux.Options{
Icon: icon,
WindowIsTranslucent: false,
},
Debug: options.Debug{
OpenInspectorOnStartup: false,
},
})
if err != nil {
log.Fatal(err)
}
}
```
### Title
The text shown in the window's title bar.
Name: Title<br/> Type: `string`
### Width
The initial width of the window.
Name: Width<br/> Type: `int`<br/> Default: 1024.
### Height
The initial height of the window.
Name: Height<br/> Type: `int`<br/> Default: 768
### DisableResize
By default, the main window is resizable. Setting this to `true` will keep it a fixed size.
Name: DisableResize<br/> Type: `bool`
### Fullscreen
Deprecated: Please use [WindowStartState](#windowstartstate).
### WindowStartState
Defines how the window should present itself at startup.
| Value | Win | Mac | Lin |
| ---------- | --- | --- | --- |
| Fullscreen | ✅ | ✅ | ✅ |
| Maximised | ✅ | ✅ | ✅ |
| Minimised | ✅ | ❌ | ✅ |
Name: WindowStartState<br/> Type: `options.WindowStartState`
### Frameless
When set to `true`, the window will have no borders or title bar. Also see [Frameless Windows](../guides/frameless.mdx).
Name: Frameless<br/> Type: `bool`
### MinWidth
This sets the minimum width for the window. If the value given in `Width` is less than this value, the window will be set to `MinWidth` by default.
Name: MinWidth<br/> Type: `int`
### MinHeight
This sets the minimum height for the window. If the value given in `Height` is less than this value, the window will be set to `MinHeight` by default.
Name: MinHeight<br/> Type: `int`
### MaxWidth
This sets the maximum width for the window. If the value given in `Width` is more than this value, the window will be set to `MaxWidth` by default.
Name: MaxWidth<br/> Type: `int`
### MaxHeight
This sets the maximum height for the window. If the value given in `Height` is more than this value, the window will be set to `MaxHeight` by default.
Name: MaxHeight<br/> Type: `int`
### StartHidden
When set to `true`, the application will be hidden until [WindowShow](../reference/runtime/window.mdx#windowshow) is called.
Name: StartHidden<br/> Type: `bool`
### HideWindowOnClose
By default, closing the window will close the application. Setting this to `true` means closing the window will
hide the window instead.
Name: HideWindowOnClose<br/> Type: `bool`
### BackgroundColour
This value is the default background colour of the window. Example: options.NewRGBA(255,0,0,128) - Red at 50% transparency
Name: BackgroundColour<br/> Type: `*options.RGBA`<br/> Default: white
### AlwaysOnTop
Indicates that the window should stay above other windows when losing focus.
Name: AlwaysOnTop<br/> Type: `bool`
### Assets
Deprecated: Please use Assets on [AssetServer specific options](#assetserver).
### AssetsHandler
Deprecated: Please use AssetsHandler on [AssetServer specific options](#assetserver).
### AssetServer
This defines AssetServer specific options. It allows to customize the AssetServer with static assets, serving assets dynamically with an `http.Handler` or hook into the request chain with an `assetserver.Middleware`.
Not all features of an `http.Request` are currently supported, please see the following feature matrix:
| Feature | Win | Mac | Lin |
| ----------------------- | --- | --- | ------ |
| GET | ✅ | ✅ | ✅ |
| POST | ✅ | ✅ | ✅ [^1] |
| PUT | ✅ | ✅ | ✅ [^1] |
| PATCH | ✅ | ✅ | ✅ [^1] |
| DELETE | ✅ | ✅ | ✅ [^1] |
| Request Headers | ✅ | ✅ | ✅ [^1] |
| Request Body | ✅ | ✅ | ❌ |
| Request Body Streaming | ❌ | ❌ | ❌ |
| Response StatusCodes | ✅ | ✅ | ✅ [^1] |
| Response Headers | ✅ | ✅ | ✅ [^1] |
| Response Body | ✅ | ✅ | ✅ |
| Response Body Streaming | ❌ | ❌ | ✅ |
| WebSockets | ❌ | ❌ | ❌ |
| HTTP Redirects 30x | ✅ | ❌ | ❌ |
Name: AssetServer<br/> Type: `*assetserver.Options`
#### Assets
The static frontend assets to be used by the application.
A GET request is first tried to be served from this `fs.FS`. If the `fs.FS` returns `os.ErrNotExist` for that file, the request handling will fallback to the [Handler](#handler) and tries to serve the GET request from it.
If set to nil, all GET requests will be forwarded to [Handler](#handler).
Name: Assets<br/> Type: `fs.FS`
#### Handler
The assets handler is a generic `http.Handler` for fallback handling of assets that can't be found.
The handler will be called for every GET request that can't be served from [Assets](#assets), due to `os.ErrNotExist`. Furthermore all non GET requests will always be served from this Handler. If not defined, the result is the following in cases where the Handler would have been called:
- GET request: `http.StatusNotFound`
- Other request: `http.StatusMethodNotAllowed`
NOTE: When used in combination with a Frontend DevServer there might be limitations, eg. Vite serves the index.html on every path, that does not contain a file extension.
Name: AssetsHandler<br/> Type: `http.Handler`
#### Middleware
Middleware is a HTTP Middleware which allows to hook into the AssetServer request chain. It allows to skip the default request handler dynamically, e.g. implement specialized Routing etc. The Middleware is called to build a new `http.Handler` used by the AssetSever and it also receives the default handler used by the AssetServer as an argument.
If not defined, the default AssetServer request chain is executed.
Name: Middleware<br/> Type: `assetserver.Middleware`
### Menu
The menu to be used by the application. More details about Menus in the [Menu Reference](../reference/runtime/menu.mdx).
:::note
On Mac, if no menu is specified, a default menu will be created.
:::
Name: Menu<br/> Type: `*menu.Menu`
### Logger
The logger to be used by the application. More details about logging in the [Log Reference](../reference/runtime/log.mdx).
Name: Logger<br/> Type: `logger.Logger`<br/> Default: Logs to Stdout
### LogLevel
The default log level. More details about logging in the [Log Reference](../reference/runtime/log.mdx).
Name: LogLevel<br/> Type: `logger.LogLevel`<br/> Default: `Info` in dev mode, `Error` in production mode
### LogLevelProduction
The default log level for production builds. More details about logging in the [Log Reference](../reference/runtime/log.mdx).
Name: LogLevelProduction<br/> Type: `logger.LogLevel`<br/> Default: `Error`
### OnStartup
This callback is called after the frontend has been created, but before `index.html` has been loaded. It is given the application context.
Name: OnStartup<br/> Type: `func(ctx context.Context)`
### OnDomReady
This callback is called after the frontend has loaded `index.html` and its resources. It is given the application context.
Name: OnDomReady<br/> Type: `func(ctx context.Context)`
### OnShutdown
This callback is called after the frontend has been destroyed, just before the application terminates. It is given the application context.
Name: OnShutdown<br/> Type: `func(ctx context.Context)`
### OnBeforeClose
If this callback is set, it will be called when the application is about to quit, either by clicking the window close button or calling `runtime.Quit`. Returning true will cause the application to continue, false will continue shutdown as normal. This is good for confirming with the user that they wish to exit the program.
Example:
```go title=windowsapp.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"
}
```
Name: OnBeforeClose<br/> Type: `func(ctx context.Context) bool`
### CSSDragProperty
Indicates the CSS property to use to identify which elements can be used to drag the window. Default: `--wails-draggable`.
Name: CSSDragProperty<br/> Type: `string`
### CSSDragValue
Indicates what value the `CSSDragProperty` style should have to drag the window. Default: `drag`.
Name: CSSDragValue<br/> Type: `string`
### ZoomFactor
Name: ZoomFactor<br/> Type: `float64`
This defines the zoom factor for the WebView2. This is the option matching the Edge user activated zoom in or out.
### IsZoomControlEnabled
Name: IsZoomControlEnabled<br/> Type: `bool`
This enables the zoom factor to be changed by the user. Please note that the zoom factor can be set in the options while disallowing the user to change it at runtime (f.e. for a kiosk application or similar).
### Bind
A slice of struct instances defining methods that need to be bound to the frontend.
Name: Bind<br/> Type: `[]interface{}`
### Windows
This defines [Windows specific options](#windows).
Name: Windows<br/> Type: `*windows.Options`
#### WebviewIsTransparent
Setting this to `true` will make the webview background transparent when an alpha value of `0` is used. This means that if you use `rgba(0,0,0,0)` for `background-color` in your CSS, the host window will show through. Often combined with [WindowIsTranslucent](#WindowIsTranslucent) to make frosty-looking applications.
Name: WebviewIsTransparent<br/> Type: `bool`
#### WindowIsTranslucent
Setting this to `true` will make the window background translucent. Often combined with [WebviewIsTransparent](#WebviewIsTransparent).
For Windows 11 versions before build 22621, this will use the [BlurBehind](https://learn.microsoft.com/en-us/windows/win32/dwm/blur-ovw) method for translucency, which can be slow. For Windows 11 versions after build 22621, this will enable the newer translucency types that are much faster. By default, the type of translucency used will be determined by Windows. To configure this, use the [BackdropType](#BackdropType) option.
Name: WindowIsTranslucent<br/> Type: `bool`
#### BackdropType
:::note
Requires Windows 11 build 22621 or later.
:::
Sets the translucency type of the window. This is only applicable if [WindowIsTranslucent](#WindowIsTranslucent) is set to `true`.
Name: BackdropType<br/> Type `windows.BackdropType`
The value can be one of the following:
| Value | Description |
| ------- | ----------------------------------------------------------------------------------------- |
| Auto | Let Windows decide which backdrop to use |
| None | Do not use translucency |
| Acrylic | Use [Acrylic](https://learn.microsoft.com/en-us/windows/apps/design/style/acrylic) effect |
| Mica | Use [Mica](https://learn.microsoft.com/en-us/windows/apps/design/style/mica) effect |
| Tabbed | Use Tabbed. This is a backdrop that is similar to Mica. |
#### DisableWindowIcon
Setting this to `true` will remove the icon in the top left corner of the title bar.
Name: DisableWindowIcon<br/> Type: `bool`
#### DisableFramelessWindowDecorations
Setting this to `true` will remove the window decorations in [Frameless](#Frameless) mode. This means there will be no 'Aero Shadow' and no 'Rounded Corners' shown for the window. Please note that 'Rounded Corners' are only supported on Windows 11.
Name: DisableFramelessWindowDecorations<br/> Type: `bool`
#### WebviewUserDataPath
This defines the path where the WebView2 stores the user data. If empty `%APPDATA%\[BinaryName.exe]` will be used.
Name: WebviewUserDataPath<br/> Type: `string`
#### WebviewBrowserPath
This defines the path to a directory with WebView2 executable files and libraries. If empty, webview2 installed in the system will be used.
Important information about distribution of fixed version runtime:
- [How to get and extract runtime](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#details-about-the-fixed-version-runtime-distribution-mode)
- [Known issues for fixed version](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#known-issues-for-fixed-version)
- [The path of fixed version of the WebView2 Runtime should not contain \Edge\Application\.](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/webview2-idl?view=webview2-1.0.1245.22#createcorewebview2environmentwithoptions)
Name: WebviewBrowserPath<br/> Type: `string`
#### Theme
Minimum Windows Version: Windows 10 2004/20H1
This defines the theme that the application should use:
| Value | Description |
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| SystemDefault | _Default_. The theme will be based on the system default. If the user changes their theme, the application will update to use the new setting |
| Dark | The application will use a dark theme exclusively |
| Light | The application will use a light theme exclusively |
Name: Theme<br/> Type: `windows.Theme`
#### CustomTheme
:::note
Minimum Windows Version: Windows 10/11 2009/21H2 Build 22000
:::
Allows you to specify custom colours for TitleBar, TitleText and Border for both light and dark mode, as well as when the window is active or inactive.
Name: CustomTheme<br/> Type: `windows.CustomTheme`
##### CustomTheme type
The CustomTheme struct uses `int32` to specify the colour values. These are in the standard(!) Windows format of: `0x00BBGGAA`. A helper function is provided to do RGB conversions into this format: `windows.RGB(r,g,b uint8)`.
NOTE: Any value not provided will default to black.
```go
type ThemeSettings struct {
DarkModeTitleBar int32
DarkModeTitleBarInactive int32
DarkModeTitleText int32
DarkModeTitleTextInactive int32
DarkModeBorder int32
DarkModeBorderInactive int32
LightModeTitleBar int32
LightModeTitleBarInactive int32
LightModeTitleText int32
LightModeTitleTextInactive int32
LightModeBorder int32
LightModeBorderInactive int32
}
```
Example:
```go
CustomTheme: &windows.ThemeSettings{
// Theme to use when window is active
DarkModeTitleBar: windows.RGB(255, 0, 0), // Red
DarkModeTitleText: windows.RGB(0, 255, 0), // Green
DarkModeBorder: windows.RGB(0, 0, 255), // Blue
LightModeTitleBar: windows.RGB(200, 200, 200),
LightModeTitleText: windows.RGB(20, 20, 20),
LightModeBorder: windows.RGB(200, 200, 200),
// Theme to use when window is inactive
DarkModeTitleBarInactive: windows.RGB(128, 0, 0),
DarkModeTitleTextInactive: windows.RGB(0, 128, 0),
DarkModeBorderInactive: windows.RGB(0, 0, 128),
LightModeTitleBarInactive: windows.RGB(100, 100, 100),
LightModeTitleTextInactive: windows.RGB(10, 10, 10),
LightModeBorderInactive: windows.RGB(100, 100, 100),
},
```
#### Messages
A struct of strings used by the webview2 installer if a valid webview2 runtime is not found.
Name: Messages<br/> Type: `*windows.Messages`
Customise this for any language you choose to support.
#### ResizeDebounceMS
ResizeDebounceMS is the amount of time to debounce redraws of webview2 when resizing the window. The default value (0) will perform redraws as fast as it can.
Name: ResizeDebounceMS<br/> Type: `uint16`
#### OnSuspend
If set, this function will be called when Windows initiates a switch to low power mode (suspend/hibernate)
Name: OnSuspend<br/> Type: `func()`
#### OnResume
If set, this function will be called when Windows resumes from low power mode (suspend/hibernate)
Name: OnResume<br/> Type: `func()`
### Mac
This defines [Mac specific options](#mac).
Name: Mac<br/> Type: `*mac.Options`
#### TitleBar
The TitleBar struct provides the ability to configure the look and feel of the title bar.
Name: TitleBar<br/> Type: [`*mac.TitleBar`](#titlebar-struct)
##### Titlebar struct
The titlebar of the application can be customised by using the TitleBar options:
```go
type TitleBar struct {
TitlebarAppearsTransparent bool
HideTitle bool
HideTitleBar bool
FullSizeContent bool
UseToolbar bool
HideToolbarSeparator bool
}
```
| Name | Description |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| TitlebarAppearsTransparent | Makes the titlebar transparent. This has the effect of hiding the titlebar and the content fill the window. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindow/1419167-titlebarappearstransparent?language=objc) |
| HideTitle | Hides the title of the window. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindowtitlevisibility?language=objc) |
| HideTitleBar | Removes [NSWindowStyleMaskTitled](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktitled/) from the style mask |
| FullSizeContent | Makes the webview fill the entire window. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemaskfullsizecontentview) |
| UseToolbar | Adds a default toolbar to the window. [Apple Docs](https://developer.apple.com/documentation/appkit/nstoolbar?language=objc) |
| HideToolbarSeparator | Removes the line beneath the toolbar. [Apple Docs](https://developer.apple.com/documentation/appkit/nstoolbar/1516954-showsbaselineseparator?language=objc) |
Preconfigured titlebar settings are available:
| Setting | Example |
| --------------------------- | ---------------------------------------------- |
| `mac.TitleBarDefault()` | ![](/img/reference/titlebar-default.webp) |
| `mac.TitleBarHidden()` | ![](/img/reference/titlebar-hidden.webp) |
| `mac.TitleBarHiddenInset()` | ![](/img/reference/titlebar-hidden-inset.webp) |
Example:
```go
Mac: &mac.Options{
TitleBar: mac.TitleBarHiddenInset(),
}
```
Click [here](https://github.com/lukakerr/NSWindowStyles) for some inspiration on customising the titlebar.
#### Appearance
Appearance is used to set the style of your app in accordance with Apple's [NSAppearance](https://developer.apple.com/documentation/appkit/nsappearancename?language=objc) names.
Name: Appearance<br/> Type: [`mac.AppearanceType`](#appearance-type)
##### Appearance type
You can specify the application's [appearance](https://developer.apple.com/documentation/appkit/nsappearance?language=objc).
| Value | Description |
| ----------------------------------------------------- | --------------------------------------------------------------- |
| DefaultAppearance | DefaultAppearance uses the default system value |
| NSAppearanceNameAqua | The standard light system appearance |
| NSAppearanceNameDarkAqua | The standard dark system appearance |
| NSAppearanceNameVibrantLight | The light vibrant appearance |
| NSAppearanceNameAccessibilityHighContrastAqua | A high-contrast version of the standard light system appearance |
| NSAppearanceNameAccessibilityHighContrastDarkAqua | A high-contrast version of the standard dark system appearance |
| NSAppearanceNameAccessibilityHighContrastVibrantLight | A high-contrast version of the light vibrant appearance |
| NSAppearanceNameAccessibilityHighContrastVibrantDark | A high-contrast version of the dark vibrant appearance |
Example:
```go
Mac: &mac.Options{
Appearance: mac.NSAppearanceNameDarkAqua,
}
```
#### WebviewIsTransparent
Setting this to `true` will make the webview background transparent when an alpha value of `0` is used. This means that if you use `rgba(0,0,0,0)` for `background-color` in your CSS, the host window will show through. Often combined with [WindowIsTranslucent](#WindowIsTranslucent) to make frosty-looking applications.
Name: WebviewIsTransparent<br/> Type: `bool`
#### WindowIsTranslucent
Setting this to `true` will make the window background translucent. Often combined with [WebviewIsTransparent](#WebviewIsTransparent) to make frosty-looking applications.
Name: WindowIsTranslucent<br/> Type: `bool`
#### About
This configuration lets you set the title, message and icon for the "About" menu item in the app menu created by the "AppMenu" role.
Name: About<br/> Type: [`*mac.AboutInfo`](#about-struct)
##### About struct
```go
type AboutInfo struct {
Title string
Message string
Icon []byte
}
```
If these settings are provided, an "About" menu item will appear in the app menu (when using the `AppMenu` role). Given this configuration:
```go
//go:embed build/appicon.png
var icon []byte
func main() {
err := wails.Run(&options.App{
...
Mac: &mac.Options{
About: &mac.AboutInfo{
Title: "My Application",
Message: "© 2021 Me",
Icon: icon,
},
},
})
```
The "About" menu item will appear in the app menu:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/reference/about-menu.webp").default}
class="screenshot"
/>
</div>
<br />
```
When clicked, that will open an about message box:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/reference/about-dialog.webp").default}
width="40%"
class="screenshot"
/>
</div>
<br />
```
### Linux
This defines [Linux specific options](#linux).
Name: Linux<br/> Type: `*linux.Options`
#### Icon
Sets up the icon representing the window. This icon is used when the window is minimized (also known as iconified).
Name: Icon<br/> Type: `[]byte`
Some window managers or desktop environments may also place it in the window frame, or display it in other contexts. On others, the icon is not used at all, so your mileage may vary.
NOTE: Gnome on Wayland at least does not display this icon. To have a application icon there, a `.desktop` file has to be used. On KDE it should work.
The icon should be provided in whatever size it was naturally drawn; that is, dont scale the image before passing it. Scaling is postponed until the last minute, when the desired final size is known, to allow best quality.
#### WindowIsTranslucent
Setting this to `true` will make the window background translucent. Some window managers may ignore it, or result in a black window.
Name: WindowIsTranslucent<br/> Type: `bool`
### Debug
This defines [Debug specific options](#Debug) that apply to debug builds.
Name: Debug<br/> Type: `options.Debug`
#### OpenInspectorOnStartup
Setting this to `true` will open the WebInspector on startup of the application.
Name: OpenInspectorOnStartup<br/> Type: `bool`
[^1]: This requires WebKit2GTK 2.36+ support and your app needs to be build with the build tag `webkit2_36` to activate support for this feature. This also bumps the minimum requirement of WebKit2GTK to 2.36 for your app.

View file

@ -1,57 +0,0 @@
---
sidebar_position: 5
---
# Configuration du projet
La configuration du projet se trouve dans le fichier `wails.json` du répertoire du projet. La structure de la configuration est :
```json
{
"name": "[Le nom du projet]",
"assetdir": "[Chemin relatif vers le répertoire contenant les ressources compilées, ceci est normalement déduit et pourrait être laissé vide]",
"reloaddirs": "[Répertoires supplémentaires pour déclencher des recharges automatiques (séparés par des virgules), ceci n'est utilisé que pour certaines configurations d'actifs avancées]",
"build:dir": "[Le répertoire où se trouvent les fichiers de compilation. Par défaut, 'build']",
"frontend:dir": "[Chemin relatif vers le répertoire du frontend. Par défaut, 'frontend']',
"frontend:install": "[La commande pour installer les dépendances de node, exécuté dans le répertoire du frontend - souvent `npm install`]",
"frontend:build": "[La commande pour construire l'application, exécuté dans le répertoire frontend - souvent `npm run build`]",
"frontend:dev": "[Cette commande a été remplacée par frontend:dev:build. Si frontend:dev:build n'est pas spécifié, cela retombera dans cette commande. \nSi cette commande n'est pas non plus spécifiée va revenir sur frontend:build]",
"frontend:dev:build": "[Cette commande est l'équivalent en dev de frontend:build. Si non spécifié, revient à frontend:dev]",
"frontend:dev:install": "[Cette commande est l'équivalent en dev de frontend:install. Si non spécifié, revient à frontend:install]",
"frontend:dev:watcher": "[Cette commande est exécutée dans un processus séparé sur `wails dev`. Utile pour les observateurs tiers ou les serveurs de développement de parties tierces]",
"frontend:dev:serverUrl": "[URL vers un serveur de développement tiers pour exposer l'application, EG Vite. \nSi cette valeur est définie à 'auto', alors le devServerUrl sera déduit de la sortie Vite]",
"wailsjsdir": "[Chemin relatif au répertoire qui vont contenir les modules JS automatiquement créés]",
"version": "[Version de configuration du projet]",
"outputfilename": "[Le nom du binaire]",
"debounceMS": 100, // Nombre de millisecondes durant lesquelles le serveur de dev attend de se recharger quand il détecte un changement dans les ressourcces
"devServer": "[Adresse pour se connecter au serveur de dev de wails. Par défaut: localhost:34115]",
"appargs": "[Arguments passés à l'application en mode shell lors du mode dev]",
"runNonNativeBuildHooks": false, // Définit si les évènements de compilation doivent être exécutés même s'ils sont définis pour un système d'exploitation autre que le système d'exploitation hôte.
"preBuildHooks": {
"GOOS/GOARCH": "[La commande qui sera exécutée avant une compilation du GOOS/GOARCH: ${platform} est remplacée par le "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook.]",
"GOOS/*": "[The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook.]",
"*/*": "[The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH".]"
},
"postBuildHooks": {
"GOOS/GOARCH": "[The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook.]",
"GOOS/*": "[The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook.]",
"*/*": "[The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary.]"
},
"info": { // Data used to populate manifests and version info.
"companyName": "[The company name. Default: [The project name]]",
"productName": "[The product name. Default: [The project name]]",
"productVersion": "[The version of the product. Default: '1.0.0']",
"copyright": "[The copyright of the product. Default: 'Copyright.........']",
"comments": "[A short comment of the app. Default: 'Built using Wails (https://wails.app)']"
},
"nsisType": "['multiple': One installer per architecture. 'single': Single universal installer for all architectures being built. Default: 'multiple']",
"obfuscated": "[Whether the app should be obfuscated. Default: false]",
"garbleargs": "[The arguments to pass to the garble command when using the obfuscated flag]"
}
```
This file is read by the Wails CLI when running `wails build` or `wails dev`.
The `assetdir`, `reloaddirs`, `wailsjsdir`, `debounceMS`, `devserver` and `frontenddevserverurl` flags in `wails build/dev` will update the project config and thus become defaults for subsequent runs.
The JSON Schema for this file is located [here](https://wails.io/schemas/config.v2.json).

View file

@ -1,13 +0,0 @@
---
sidebar_position: 7
---
# Navigateur
Ces méthodes sont liées au navigateur du système.
### BrowserOpenURL
Ouvre l'URL donnée dans le navigateur système.
Go: `BrowserOpenURL(ctx context.Context, url string)`<br/> JS: `BrowserOpenURL(url string)`

View file

@ -1,302 +0,0 @@
---
sidebar_position: 5
---
# Boîte de dialogue
Cette partie du runtime fournit un accès aux boîtes de dialogue natives, telles que les sélecteurs de fichiers et les boîtes de messages.
:::info JavaScript
La boîte de dialogue n'est actuellement pas prise en charge dans l'exécuteur JS.
:::
### OpenDirectoryDialog
Ouvre une boîte de dialogue qui invite l'utilisateur à sélectionner un répertoire. Peut être personnalisé en utilisant [OpenDialogOptions](#opendialogoptions).
Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)`
Renvoie : le répertoire sélectionné (vide si l'utilisateur a annulé) ou une erreur
### OpenFileDialog
Ouvre une boîte de dialogue qui invite l'utilisateur à sélectionner un fichier. Peut être personnalisé en utilisant [OpenDialogOptions](#opendialogoptions).
Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)`
Renvoie : le fichier sélectionné (vide si l'utilisateur a annulé) ou une erreur
### OpenFileDialog
Ouvre une boîte de dialogue qui invite l'utilisateur à sélectionner plusieurs fichiers. Peut être personnalisé en utilisant [OpenDialogOptions](#opendialogoptions).
Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)`
Renvoie : les fichiers sélectionnés (nil si l'utilisateur a annulé) ou une erreur
### SaveFileDialog
Ouvre une boîte de dialogue qui invite l'utilisateur à saisir un nom pour le fichier à enregistrer. Peut être personnalisé en utilisant [SaveDialogOptions](#savedialogoptions).
Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)`
Renvoie : le fichier sélectionné (vide si l'utilisateur a annulé) ou une erreur
### MessageDialog
Affiche un message en utilisant une boîte de dialogue. Peut être personnalisé en utilisant [MessageDialogOptions](#messagedialogoptions).
Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)`
Renvoie : Le texte du bouton sélectionné ou une erreur
## Options
### OpenDialogOptions
```go
type OpenDialogOptions struct {
DefaultDirectory string
DefaultFilename string
Title string
Filters []FileFilter
ShowHiddenFiles bool
CanCreateDirectories bool
ResolvesAliases bool
TreatPackagesAsDirectories bool
}
```
| Champ | Description | Win | Mac | Lin |
| -------------------------- | -------------------------------------------------------------- | --- | --- | --- |
| DefaultDirectory | Le répertoire que la boîte de dialogue affichera à l'ouverture | ✅ | ✅ | ✅ |
| DefaultFilename | Le nom du fichier par défaut | ✅ | ✅ | ✅ |
| Title | Titre pour la boite de dialogue | ✅ | ✅ | ✅ |
| [Filters](#filefilter) | Une liste de filtres de fichiers | ✅ | ✅ | ✅ |
| ShowHiddenFiles | Afficher les fichiers cachés par le système | | ✅ | ✅ |
| CanCreateDirectories | Autoriser l'utilisateur de créer des dossiers | | ✅ | |
| ResolvesAliases | Si vrai, retourne le fichier et non l'alias | | ✅ | |
| TreatPackagesAsDirectories | Autoriser la navigation dans les dossiers | | ✅ | |
### SaveDialogOptions
```go
type SaveDialogOptions struct {
DefaultDirectory string
DefaultFilename string
Title string
Filters []FileFilter
ShowHiddenFiles bool
CanCreateDirectories bool
TreatPackagesAsDirectories bool
}
```
| Champ | Description | Win | Mac | Lin |
| -------------------------- | -------------------------------------------------------------- | --- | --- | --- |
| DefaultDirectory | Le répertoire que la boîte de dialogue affichera à l'ouverture | ✅ | ✅ | ✅ |
| DefaultFilename | Le nom du fichier par défaut | ✅ | ✅ | ✅ |
| Title | Titre pour la boite de dialogue | ✅ | ✅ | ✅ |
| [Filters](#filefilter) | Une liste de filtres de fichiers | ✅ | ✅ | ✅ |
| ShowHiddenFiles | Afficher les fichiers cachés par le système | | ✅ | ✅ |
| CanCreateDirectories | Autoriser l'utilisateur de créer des dossiers | | ✅ | |
| TreatPackagesAsDirectories | Autoriser la navigation dans les dossiers | | ✅ | |
### MessageDialogOptions
```go
type MessageDialogOptions struct {
Type DialogType
Title string
Message string
Buttons []string
DefaultButton string
CancelButton string
}
```
| Champ | Description | Win | Mac | Lin |
| ------------- | ---------------------------------------------------------------------------------------------- | -------------- | --- | --- |
| Type | Le type de boîte de dialogue de message: question, info... | ✅ | ✅ | ✅ |
| Title | Titre pour la boite de dialogue | ✅ | ✅ | ✅ |
| Message | Le message à afficher à l'utilisateur | ✅ | ✅ | ✅ |
| Buttons | La liste des noms des boutons | | ✅ | |
| DefaultButton | Le bouton avec ce texte doit être traité comme le bouton par défaut. Lié à la touche `entrée`. | ✅[*](#windows) | ✅ | |
| CancelButton | Le bouton avec ce texte doit être traité permettant d'annuler. Lié à la touche `echap` | | ✅ | |
#### Windows
Windows has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" or "Continue".
For Question dialogs, the default button is "Yes" and the cancel button is "No". This can be changed by setting the `DefaultButton` value to `"No"`.
Example:
```go
result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "Question",
Message: "Do you want to continue?",
DefaultButton: "No",
})
```
#### Linux
Linux has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Yes", "No"
#### Mac
A message dialog on Mac may specify up to 4 buttons. If no `DefaultButton` or `CancelButton` is given, the first button is considered default and is bound to the `return` key.
For the following code:
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
})
```
the first button is shown as default:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_no_defaults.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
```
And if we specify `DefaultButton` to be "two":
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
DefaultButton: "two",
})
```
the second button is shown as default. When `return` is pressed, the value "two" is returned.
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_default_button.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
```
If we now specify `CancelButton` to be "three":
```go
selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{
Title: "It's your turn!",
Message: "Select a number",
Buttons: []string{"one", "two", "three", "four"},
DefaultButton: "two",
CancelButton: "three",
})
```
the button with "three" is shown at the bottom of the dialog. When `escape` is pressed, the value "three" is returned:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_default_cancel.png").default}
width="30%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### DialogType
```go
const (
InfoDialog DialogType = "info"
WarningDialog DialogType = "warning"
ErrorDialog DialogType = "error"
QuestionDialog DialogType = "question"
)
```
### FileFilter
```go
type FileFilter struct {
DisplayName string // Filter information EG: "Image Files (*.jpg, *.png)"
Pattern string // semi-colon separated list of extensions, EG: "*.jpg;*.png"
}
```
#### Windows
Windows allows you to use multiple file filters in dialog boxes. Each FileFilter will show up as a separate entry in the dialog:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_win_filters.png").default}
width="50%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### Linux
Linux allows you to use multiple file filters in dialog boxes. Each FileFilter will show up as a separate entry in the dialog:
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/runtime/dialog_lin_filters.png").default}
width="50%"
class="screenshot"
/>
</div>
<br />
<br />
<br />
```
#### Mac
Mac dialogs only have the concept of a single set of patterns to filter files. If multiple FileFilters are provided, Wails will use all the Patterns defined.
Exemple:
```go
selection, err := runtime.OpenFileDialog(b.ctx, runtime.OpenDialogOptions{
Title: "Select File",
Filters: []runtime.FileFilter{
{
DisplayName: "Images (*.png;*.jpg)",
Pattern: "*.png;*.jpg",
}, {
DisplayName: "Videos (*.mov;*.mp4)",
Pattern: "*.mov;*.mp4",
},
},
})
```
This will result in the Open File dialog using `*.png,*.jpg,*.mov,*.mp4` as a filter.

View file

@ -1,37 +0,0 @@
---
sidebar_position: 2
---
# Events
The Wails runtime provides a unified events system, where events can be emitted or received by either Go or JavaScript. Optionally, data may be passed with the events. Listeners will receive the data in the local data types.
### EventsOn
This method sets up a listener for the given event name. When an event of type `eventName` is [emitted](#EventsEmit), the callback is triggered. Any additional data sent with the emitted event will be passed to the callback. It returns a function to cancel the listener.
Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`<br/> JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void`
### EventsOff
This method unregisters the listener for the given event name, optionally multiple listeneres can be unregistered via `additionalEventNames`.
Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`<br/> JS: `EventsOff(eventName string, ...additionalEventNames)`
### EventsOnce
This method sets up a listener for the given event name, but will only trigger once. It returns a function to cancel the listener.
Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`<br/> JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void`
### EventsOnMultiple
This method sets up a listener for the given event name, but will only trigger a maximum of `counter` times. It returns a function to cancel the listener.
Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`<br/> JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void`
### EventsEmit
This method emits the given event. Optional data may be passed with the event. This will trigger any event listeners.
Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`<br/> JS: `EventsEmit(ctx context, optionalData function(optionalData?: any))`

View file

@ -1,84 +0,0 @@
---
sidebar_position: 1
---
# Introduction
The runtime is a library that provides utility methods for your application. There is both a Go and JavaScript runtime and the aim is to try and keep them at parity where possible.
It has utility methods for:
- [Window](window.mdx)
- [Menu](menu.mdx)
- [Boîte de dialogue](dialog.mdx)
- [Événements](events.mdx)
- [Browser](browser.mdx)
- [Log](log.mdx)
The Go Runtime is available through importing `github.com/wailsapp/wails/v2/pkg/runtime`. All methods in this package take a context as the first parameter. This context should be obtained from the [OnStartup](../options.mdx#onstartup) or [OnDomReady](../options.mdx#ondomready) hooks.
:::info Note
Whilst the context will be provided to the [OnStartup](../options.mdx#onstartup) method, there's no guarantee the runtime will work in this method as the window is initialising in a different thread. If you wish to call runtime methods at startup, use [OnDomReady](../options.mdx#ondomready).
:::
The JavaScript library is available to the frontend via the `window.runtime` map. There is a runtime package generated when using `dev` mode that provides TypeScript declarations for the runtime. This should be located in the `wailsjs` directory in your frontend directory.
### Cacher
Go: `Hide(ctx context.Context)`<br/> JS: `Hide()`
Cache l'application.
:::info Note
On Mac, this will hide the application in the same way as the `Hide` menu item in standard Mac applications. This is different to hiding the window, but the application still being in the foreground. For Windows and Linux, this is currently the same as `WindowHide`.
:::
### Afficher
Affiche l'application.
:::info Note
On Mac, this will bring the application back into the foreground. For Windows and Linux, this is currently the same as `WindowShow`.
:::
Go: `Show(ctx context.Context)`<br/> JS: `Show()`
### Quitter
Quitte l'application.
Go: `Quit(ctx context.Context)`<br/> JS: `Quit()`
### Environnement
Renvoie les détails de l'environnement actuel.
Go: `Environment(ctx context.Context) EnvironmentInfo`<br/> JS: `Environment(): Promise<EnvironmentInfo>`
#### EnvironmentInfo
Go:
```go
type EnvironmentInfo struct {
BuildType string
Platform string
Arch string
}
```
JS:
```ts
interface EnvironmentInfo {
buildType: string;
platform: string;
arch: string;
}
```

View file

@ -1,130 +0,0 @@
---
sidebar_position: 3
---
# Log
The Wails runtime provides a logging mechanism that may be called from Go or JavaScript. Comme la plupart des loggers, il y a un certain nombre de niveaux de log :
- Trace
- Debug
- Info
- Warning
- Error
- Fatal
Le logger affichera tous les messages de log au niveau actuel ou supérieur. Exemple : Le niveau `Debug` affichera tous les messages sauf ceux du niveau `Trace`.
### LogPrint
Ajoute le message donné dans les logs en tant que message brut.
Go: `LogPrint(ctx context.Context, message string)`<br/> JS: `LogPrint(message: string)`
### LogPrintf
Ajoute le message donné dans les logs en tant que message brut.
Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`<br/>
### LogTrace
Ajoute le message donné dans les logs avec le niveau de log `Trace`.
Go: `LogTrace(ctx context.Context, message string)`<br/> JS: `LogTrace(message: string)`
### LogTracef
Ajoute le message donné dans les logs avec le niveau de log `Trace`.
Go: `LogTracef(ctx context.Context, format string, args ...interface{})`<br/>
### LogDebug
Ajoute le message donné dans les logs avec le niveau de log `Debug`.
Go: `LogDebug(ctx context.Context, message string)`<br/> JS: `LogDebug(message: string)`
### LogDebugf
Ajoute le message donné dans les logs avec le niveau de log `Debug`.
Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`<br/>
### LogInfo
Ajoute le message donné dans les logs avec le niveau de log `Info`.
Go: `LogInfo(ctx context.Context, message string)`<br/> JS: `LogInfo(message: string)`
### LogInfof
Ajoute le message donné dans les logs avec le niveau de log `Info`.
Go: `LogInfof(ctx context.Context, format string, args ...interface{})`<br/>
### LogWarning
Ajoute le message donné dans les logs avec le niveau de log `Warning`.
Go: `LogWarning(ctx context.Context, message string)`<br/> JS: `LogWarning(message: string)`
### LogWarningf
Ajoute le message donné dans les logs avec le niveau de log `Warning`.
Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`<br/>
### LogError
Ajoute le message donné dans les logs avec le niveau de log `Error`.
Go: `LogError(ctx context.Context, message string)`<br/> JS: `LogError(message: string)`
### LogErrorf
Ajoute le message donné dans les logs avec le niveau de log `Error`.
Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`<br/>
### LogFatal
Ajoute le message donné dans les logs avec le niveau de log `Fatal`.
Go: `LogFatal(ctx context.Context, message string)`<br/> JS: `LogFatal(message: string)`
### LogFatalf
Ajoute le message donné dans les logs avec le niveau de log `Fatal`.
Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`<br/>
### LogSetLogLevel
Définit le niveau des logs. In JavaScript, the number relates to the following log levels:
| Valeur | Niveau de log |
| ------ | ------------- |
| 1 | Trace |
| 2 | Debug |
| 3 | Info |
| 4 | Warning |
| 5 | Error |
Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`<br/> JS: `LogSetLogLevel(level: number)`
## Utiliser un Logger Personnalisé
Un logger personnalisé peut être utilisé en le définissant dans l'option de l'application [Logger](../options.mdx#logger) . La seule condition est que le logger implémente l'interface `logger.Logger` définie dans `github.com/wailsapp/wails/v2/pkg/logger`:
```go title="logger.go"
type Logger interface {
Print(message string)
Trace(message string)
Debug(message string)
Info(message string)
Warning(message string)
Error(message string)
Fatal(message string)
}
```

View file

@ -1,25 +0,0 @@
---
sidebar_position: 6
---
# Menu
Ces méthodes sont liées au menu de l'application.
:::info JavaScript
Le menu n'est actuellement pas pris en charge lors de l'exécution de JS.
:::
### MenuSetApplicationMenu
Définit le menu de l'application dans le [menu](../menus.mdx) donné.
Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)`
### MenuUpdateApplicationMenu
Met à jour le menu de l'application, avec toutes les autres modifications déjà appliquées via `MenuSetApplicationMenu`.
Go: `MenuUpdateApplicationMenu(ctx context.Context)`

View file

@ -1,221 +0,0 @@
---
sidebar_position: 4
---
# Fenêtre
Ces méthodes donnent le contrôle de la fenêtre de l'application.
### WindowSetTitle
Définit le texte dans la barre de titre de la fenêtre.
Go: `WindowSetTitle(ctx context.Context, title string)`<br/> JS: `WindowSetTitle(title: string)`
### WindowFullscreen
Mets la fenêtre en plein écran.
Go: `WindowFullscreen(ctx context.Context)`<br/> JS: `WindowFullscreen()`
### WindowUnfullscreen
Restaure les dimensions et la position de la fenêtre avant le plein écran.
Go: `WindowUnfullscreen(ctx context.Context)`<br/> JS: `WindowUnfullscreen()`
### WindowIsFullscreen
Renvoie vrai si la fenêtre est en plein écran.
Go: `WindowIsFullscreen(ctx context.Context) bool`<br/> JS: `WindowIsFullscreen() bool`
### WindowCenter
Centre la fenêtre sur le moniteur sur laquelle la fenêtre est actuellement ouverte.
Go: `WindowCenter(ctx context.Context)`<br/> JS: `WindowCenter()`
### WindowExecJS
Exécute du code JS dans la fenêtre.
Cette méthode exécute le code dans le navigateur de manière asynchrone et retourne immédiatement le résultat. Si le script cause des erreurs, elles ne seront disponibles que dans la console du navigateur.
Go: `WindowExecJS(ctx context.Context, js string)`
### WindowReload
Effectue un "rechargement" (Recharge la page courante).
Go: `WindowReload(ctx context.Context)`<br/> JS: `WindowReload()`
### WindowReloadApp
Recharge le frontend de l'application.
Go: `WindowReloadApp(ctx context.Context)`<br/> JS: `WindowReloadApp()`
### WindowSetSystemDefaultTheme
Windows seulement.
Go: `WindowSetSystemDefaultTheme(ctx context.Context)`<br/> JS: `WindowSetSystemDefaultTheme()`
Définit le thème de fenêtre à la valeur par défaut du système (sombre/clair).
### WindowSetLightTheme
Windows seulement.
Go: `WindowSetLightTheme(ctx context.Context)`<br/> JS: `WindowSetLightTheme()`
Définit le thème clair à la fenêtre.
### WindowSetDarkTheme
Windows seulement.
Go: `WindowSetDarkTheme(ctx context.Context)`<br/> JS: `WindowSetDarkTheme()`
Définit le thème sombre à la fenêtre.
### WindowShow
Affiche la fenêtre, si elle est actuellement masquée.
Go: `WindowShow(ctx context.Context)`<br/> JS: `WindowShow()`
### WindowHide
Masque la fenêtre, si elle est actuellement visible.
Go: `WindowHide(ctx context.Context)`<br/> JS: `WindowHide()`
### WindowIsNormal
Renvoie vrai si la fenêtre n'est pas minimisée, maximisée ou plein écran.
Go: `WindowIsNormal(ctx context.Context) bool`<br/> JS: `WindowIsNormal() bool`
### WindowSetSize
Définit la largeur et la hauteur de la fenêtre.
Go: `WindowSetSize(ctx context.Context, width int, height int)`<br/> JS: `WindowSetSize(size: Size)`
### WindowGetSize
Retourne la largeur et la hauteur de la fenêtre.
Go: `WindowGetSize(ctx context.Context) (width int, height int)`<br/> JS: `WindowGetSize() : Size`
### WindowSetMinSize
Définit la taille minimale de la fenêtre. Redimensionnera la fenêtre si la fenêtre est actuellement plus petite que les dimensions données.
Définir une taille de `0,0` désactivera cette contrainte.
Go: `WindowSetMinSize(ctx context.Context, width int, height int)`<br/> JS: `WindowSetMinSize(size: Size)`
### WindowSetMaxSize
Définit la taille maximale de la fenêtre. Redimensionnera la fenêtre si la fenêtre est actuellement plus grande que les dimensions données.
Définir une taille de `0,0` désactivera cette contrainte.
Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`<br/> JS: `WindowSetMaxSize(size: Size)`
### WindowSetAlwaysOnTop
Paramètre pour faire en sorte que la fenêtre soit toujours au dessus des autres ou non.
Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`<br/> JS: `WindowSetAlwaysOnTop(b: Boolen)`
### WindowSetPosition
Définit la position de la fenêtre par rapport au moniteur sur lequel la fenêtre est activée.
Go: `WindowSetPosition(ctx context.Context, x int, y int)`<br/> JS: `WindowSetPosition(position: Position)`
### WindowGetPosition
Récupère la position de la fenêtre relative au moniteur sur lequel la fenêtre est activée.
Go: `WindowGetPosition(ctx context.Context) (x int, y int)`<br/> JS: `WindowGetPosition() : Position`
### WindowMaximiseWindowMaximise
Maximise la fenêtre pour remplir l'écran.
Go: `WindowMaximise(ctx context.Context)`<br/> JS: `WindowMaximise()`
### WindowUnmaximise
Restaure la fenêtre aux dimensions et à la position avant qu'elle soit maximisée.
Go: `WindowUnmaximise(ctx context.Context)`<br/> JS: `WindowUnmaximise()`
### WindowIsMaximised
Renvoie vrai si la fenêtre est maximisée.
Go: `WindowIsMaximised(ctx context.Context) bool`<br/> JS: `WindowIsMaximised() bool`
### WindowToggleMaximise
Option permettant de basculer entre la maximisation de la fenêtre et sa non maximisation.
Go: `WindowToggleMaximise(ctx context.Context)`<br/> JS: `WindowToggleMaximise()`
### WindowMinimise
Minimise la fenêtre.
Go: `WindowMinimise(ctx context.Context)`<br/> JS: `WindowMinimise()`
### WindowUnminimise
Restaure la fenêtre aux dimensions et à la position avant qu'elle soit minimisée.
Go: `WindowUnminimise(ctx context.Context)`<br/> JS: `WindowUnminimise()`
### WindowIsMinimised
Renvoie vrai si la fenêtre est minimisée.
Go: `WindowIsMinimised(ctx context.Context) bool`<br/> JS: `WindowIsMinimised() bool`
### WindowSetBackgroundColour
Définit la couleur de fond de la fenêtre avec la couleur RGBA donnée. Cette couleur sera visible au travers de tous les pixels transparents.
Les valeurs valides pour R, G, B et A sont entre 0 et 255 inclus.
:::info Windows
Sous Windows, seules les valeurs 0 et 255 sont prises en charge pour A. Toute valeur qui n'est pas 0 sera considérée comme 255.
:::
Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`<br/> JS: `WindowSetBackgroundColour(R, G, B, A)`
## TypeScript Object Definitions
### Position
```ts
interface Position {
x: number;
y: number;
}
```
### Size (taille)
```ts
interface Size {
w: number;
h: number;
}
```

View file

@ -1,245 +0,0 @@
---
sidebar_position: 20
---
# API Chiens
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/tutorials/dogsapi/img.webp").default}
width="50%"
className="screenshot"
/>
</div>
<br />
```
:::note
Ce tutoriel a été gracieusement fourni par [@tatadan](https://twitter.com/tatadan) et fait partie de leur [dépôt d'exemples Wails](https://github.com/tataDan/wails-v2-examples).
:::
Dans ce tutoriel, nous allons développer une application qui récupère des photos de chiens du web et les affiche.
### Créer le projet
Créons l'application. Depuis un terminal saisissez : `wails init -n dogs-api -t svelte`
Note: Nous pouvons ajouter l'une des options suivantes `-ide vscode` ou `-ide goland` à la fin de la commande si vous voulez ajouter le support d'un IDE.
Maintenant, exécutons `cd dogs-api` et commençons à éditer les fichiers du projet.
### Retirer le code inutilisé
Nous allons commencer par supprimer certains éléments que nous savons que nous n'utiliserons pas :
- Ouvrez `app.go` et supprimez les lignes suivantes :
```go
// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
return fmt.Sprintf("Hello %s, It's show time!", name)
}
```
- Ouvrez `frontend/src/App.svelte` et supprimez toutes les lignes.
- Supprimer le fichier `frontend/src/assets/images/logo-universal.png`
### Créer notre application
Ajoutons maintenant notre nouveau code Go.
Ajoutez les déclarations struct suivantes dans `app.go` avant la déclaration des fonctions:
```go
type RandomImage struct {
Message string
Status string
}
type AllBreeds struct {
Message map[string]map[string][]string
Status string
}
type ImagesByBreed struct {
Message []string
Status string
}
```
Ajouter les fonctions suivantes dans `app.go` (après la déclaration de la fonction déjà existante):
```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
}
```
Modifiez la section `import` de `app.go` pour ressembler à ceci :
```go
import (
"context"
"fmt"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"sort"
)
```
Ajouter les lignes suivantes dans `frontend/src/App.svelte`:
<!-- prettier-ignore-start -->
```html
<script>
import { GetRandomImageUrl } from "../wailsjs/go/main/App.js";
import { GetBreedList } from "../wailsjs/go/main/App.js";
import { GetImageUrlsByBreed } from "../wailsjs/go/main/App.js";
let randomImageUrl = "";
let breeds = [];
let photos = [];
let selectedBreed;
let showRandomPhoto = false;
let showBreedPhotos = false;
function init() {
getBreedList();
}
init();
function getRandomImageUrl() {
showRandomPhoto = false;
showBreedPhotos = false;
GetRandomImageUrl().then((result) => (randomImageUrl = result));
showRandomPhoto = true;
}
function getBreedList() {
GetBreedList().then((result) => (breeds = result));
}
function getImageUrlsByBreed() {
init();
showRandomPhoto = false;
showBreedPhotos = false;
GetImageUrlsByBreed(selectedBreed).then((result) => (photos = result));
showBreedPhotos = true;
}
</script>
<h3>Dogs API</h3>
<div>
<button class="btn" on:click={getRandomImageUrl}>
Fetch a dog randomly
</button>
Click on down arrow to select a breed
<select bind:value={selectedBreed}>
{#each breeds as breed}
<option value={breed}>
{breed}
</option>
{/each}
</select>
<button class="btn" on:click={getImageUrlsByBreed}>
Fetch by this breed
</button>
</div>
<br />
{#if showRandomPhoto}
<img id="random-photo" src={randomImageUrl} alt="No dog found" />
{/if}
{#if showBreedPhotos}
{#each photos as photo}
<img id="breed-photos" src={photo} alt="No dog found" />
{/each}
{/if}
<style>
#random-photo {
width: 600px;
height: auto;
}
#breed-photos {
width: 300px;
height: auto;
}
.btn:focus {
border-width: 3px;
}
</style>
```
<!-- prettier-ignore-end -->
### Tester l'application
Pour générer les liaisons et tester l'application, exécutez `wails dev`.
### Compiler l'application
Pour compiler l'application en un seul binaire, exécutez `wails build`.

View file

@ -1,122 +0,0 @@
---
sidebar_position: 10
---
# Hello World
Le but de ce tutoriel est de vous faire créer l'application la plus basique en utilisant Wails. Vous serez capables de :
- Créer une nouvelle application Wails
- Compiler l'application
- Démarrer l'application
:::note
Ce tutoriel utilise Windows comme plate-forme cible. La sortie variera légèrement selon votre système d'exploitation.
:::
## Créer une nouvelle application Wails
Pour créer une nouvelle application Wails utilisant le template Vanilla JS par défaut, vous devez exécuter la commande suivante :
```bash
wails init -n helloworld
```
Vous devriez voir quelque chose de similaire à ce qui suit :
```
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.
```
Cela va créer un nouveau dossier nommé `helloworld` dans le dossier actuel. Dans ce dossier, vous trouverez un certain nombre de fichiers :
```
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
```
## Compiler l'application
Pour compiler l'application, déplacez-vous dans le dossier du nouveau projet `helloworld` et exécutez la commande suivante :
```bash
wails build
```
Vous devriez voir quelque chose comme ça :
```
Wails CLI v2.0.0
App Type: desktop
Platforms: windows/amd64
Compiler: C:\Users\leaan\go\go1.18.3\bin\go.exe
Build Mode: Production
Skip Frontend: false
Compress: false
Package: true
Clean Build Dir: false
LDFlags: ""
Tags: []
Race Detector: false
Building target: windows/amd64
------------------------------
- Installing frontend dependencies: Done.
- Compiling frontend: Done.
- Generating bundle assets: Done.
- Compiling application: Done.
Built 'C:\Users\leaan\tutorial\helloworld\build\bin\helloworld.exe' in 10.616s.
```
Cela a compilé l'application et l'a enregistré dans le dossier `build/bin`.
## Démarrer l'application
Si on voit le dossier `build/bin` dans l'explorateur Windows, nous devrions voir le binaire de notre projet :
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/helloworld-app-icon.webp").default}
width="134px"
/>
</div>
<br />
```
On peut l'exécuter en simplement double-cliquant sur le fichier `helloworld.exe`.
Sur Max, Wails va générer un fichier `helloworld.app` qui peut être exécuté en simplement double-cliquant dessus.
Sur Linux, vous pouvez exécuter l'application en utilisant `./helloworld` depuis le répertoire `build/bin`.
Vous devriez voir l'application fonctionner comme prévu :
```mdx-code-block
<div class="text--center">
<img
src={require("@site/static/img/windows-default-app.webp").default}
width="50%"
className="screenshot"
/>
</div>
<br />
```

View file

@ -1,25 +0,0 @@
---
sidebar_position: 2
---
# Liens
Cette page sert de liste pour les liens liés à la communauté. Veuillez soumettre une PR (cliquez sur `Modifier cette page` en bas) pour soumettre des liens.
## Awesome Wails
La [liste définitive](https://github.com/wailsapp/awesome-wails) de liens relatifs à Wails.
## Canaux de support
- [Wails Discord Server](https://discord.gg/JDdSxwjhGf)
- [Github Issues](https://github.com/wailsapp/wails/issues)
- [canal de discussion sur la bêta v2](https://github.com/wailsapp/wails/discussions/828)
## Réseaux sociaux
- [Twitter](https://twitter.com/wailsapp)
- [Groupe QQ pour la communauté chinoise de Wails](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - Numéro de groupe : 1067173054
## Autres tutoriels et articles
- [Construction d'un Panneau d'Affichage](https://blog.customct.com/building-bulletin-board)

View file

@ -1,10 +0,0 @@
# EmailIt
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/emailit.webp").default} />
<br />
</p>
```
[EmailIt](https://github.com/raguay/EmailIt/) is a Wails 2 program that is a markdown based email sender only with nine notepads, scripts to manipulate the text, and templates. It also has a builtin [Node-Red](https://nodered.org/) server, scripts terminal, and the [ScriptBar](https://github.com/raguay/ScriptBarApp) program for displaying results from Node-Red or a script on your system. Documentation is very scarce, but the programs works. Its built using Wails2 and Svelte, and the download is a universal macOS application.

View file

@ -1,12 +0,0 @@
# EncryptEasy
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/encrypteasy.webp").default} />
<br />
</p>
```
**[EncryptEasy](https://www.encrypteasy.app) est un outil de chiffrement PGP simple et facile à utiliser, qui gère toutes vos clés et celles de vos contacts. Le chiffrement devrait être simple. Développé avec Wails.**
Chiffrer les messages à l'aide de PGP est la norme de l'industrie. Tout le monde a une clé privée et publique. Votre clé privée, eh bien, doit être privée afin que vous seul puissiez lire les messages. Votre clé publique est distribuée à toute personne qui veut vous envoyer des messages secrets, chiffrés. Gérer les clés, chiffrer les messages et déchiffrer les messages devrait être une expérience agréable. EncryptEasy a pour but de vous simplifier la tâche.

View file

@ -1,16 +0,0 @@
# Utilitaire d'exportation FileHound
```mdx-code-block
<p style={{ "text-align": "center" }}>
<img src={require("@site/static/img/showcase/filehound.webp").default} />
<br />
</p>
```
[L'utilitaire d'exportation FileHound](https://www.filehound.co.uk/) est une plate-forme de gestion de documents cloud conçue pour la conservation sécurisée de fichiers, l'automatisation des processus métier et les capacités de SmartCapture.
L'utilitaire d'exportation FileHound permet aux administrateurs FileHound d'exécuter des tâches sécurisées d'extraction de documents et de données à des fins alternatives de sauvegarde et de récupération. Cette application téléchargera tous les documents et/ou métadonnées enregistrés dans FileHound en fonction des filtres que vous avez choisis. Les métadonnées seront exportées dans les formats JSON et XML.
Backend construit avec: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2
Frontend avec: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6

Some files were not shown because too many files have changed in this diff Show more