From 8b215a9b4c3b98a7a13c1035c5ce70b701b0f9aa Mon Sep 17 00:00:00 2001 From: Lea Anthony Date: Sun, 16 Jun 2024 10:34:01 +1000 Subject: [PATCH] v2.9.0 --- v2/cmd/wails/internal/version.txt | 2 +- .../version-v2.9.0.json | 38 + .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 42 + .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 0 .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../version-v2.9.0/community/templates.mdx | 69 ++ .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 90 ++ .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 191 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0}/guides/routing.mdx | 0 .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0/reference/cli.mdx | 241 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 853 +++++++++++++++++ .../reference/project-config.mdx | 92 ++ .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ .../version-v2.9.0}/appendix/_category_.json | 0 .../version-v2.9.0}/community/_category_.json | 0 .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/_category_.json | 0 .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 39 + .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../version-v2.9.0/community/templates.mdx | 69 ++ .../gettingstarted/_category_.json | 0 .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 89 ++ .../version-v2.9.0}/guides/_category_.json | 0 .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 191 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0/guides/routing.mdx | 47 + .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0}/reference/_category_.json | 0 .../version-v2.9.0/reference/cli.mdx | 240 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 853 +++++++++++++++++ .../reference/project-config.mdx | 91 ++ .../reference/runtime/_category_.json | 0 .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0}/tutorials/_category_.json | 0 .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/bulletinboard.mdx | 0 .../community/showcase/cfntracker.mdx | 39 + .../community/showcase/emailit.mdx | 0 .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 0 .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 0 .../community/showcase/riftshare.mdx | 0 .../community/showcase/scriptbar.mdx | 0 .../community/showcase/surge.mdx | 0 .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 0 .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../community/showcase/ytd.mdx | 0 .../version-v2.9.0/community/templates.mdx | 69 ++ .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 89 ++ .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 191 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0/guides/routing.mdx | 47 + .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0/reference/cli.mdx | 240 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 853 +++++++++++++++++ .../reference/project-config.mdx | 92 ++ .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 41 + .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../version-v2.9.0/community/templates.mdx | 69 ++ .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 90 ++ .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 191 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0/guides/routing.mdx | 47 + .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0/reference/cli.mdx | 240 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 853 +++++++++++++++++ .../reference/project-config.mdx | 92 ++ .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 41 + .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../version-v2.9.0/community/templates.mdx | 69 ++ .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 90 ++ .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 191 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0/guides/routing.mdx | 47 + .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0/reference/cli.mdx | 240 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 853 +++++++++++++++++ .../reference/project-config.mdx | 92 ++ .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ .../version-v2.9.0/appendix/_category_.json | 4 + .../version-v2.9.0/community/_category_.json | 4 + .../version-v2.9.0/community/links.mdx | 26 + .../community/showcase/_category_.json | 4 + .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 35 + .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 12 + .../community/showcase/espstudio.mdx | 13 + .../community/showcase/filehound.mdx | 16 + .../community/showcase/hiposter.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 14 + .../community/showcase/modalfilemanager.mdx | 14 + .../community/showcase/mollywallet.mdx | 10 + .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 10 + .../community/showcase/portfall.mdx | 10 + .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 19 + .../community/showcase/wombat.mdx | 10 + .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../version-v2.9.0/community/templates.mdx | 69 ++ .../contributing/developing-new-features.mdx | 34 + .../contributing/documenting.mdx | 34 + .../contributing/fixing-bugs.mdx | 29 + .../setting-up-a-dev-environment.mdx | 30 + .../contributing/ways-of-contributing.mdx | 18 + .../gettingstarted/_category_.json | 4 + .../gettingstarted/building.mdx | 22 + .../gettingstarted/development.mdx | 16 + .../gettingstarted/firstproject.mdx | 130 +++ .../gettingstarted/installation.mdx | 89 ++ .../version-v2.9.0/guides/_category_.json | 4 + .../version-v2.9.0/guides/angular.mdx | 14 + .../guides/application-development.mdx | 215 +++++ .../guides/crossplatform-build.mdx | 66 ++ .../guides/custom-protocol-schemes.mdx | 204 ++++ .../version-v2.9.0/guides/dynamic-assets.mdx | 136 +++ .../guides/file-association.mdx | 244 +++++ .../version-v2.9.0/guides/frameless.mdx | 87 ++ .../version-v2.9.0/guides/frontend.mdx | 72 ++ .../version-v2.9.0/guides/ides.mdx | 127 +++ .../guides/linux-distro-support.mdx | 103 +++ .../version-v2.9.0/guides/linux.mdx | 18 + .../guides/local-development.mdx | 55 ++ .../version-v2.9.0/guides/mac-appstore.mdx | 97 ++ .../version-v2.9.0/guides/manual-builds.mdx | 95 ++ .../version-v2.9.0/guides/migrating.mdx | 193 ++++ .../version-v2.9.0/guides/mouse-buttons.mdx | 25 + .../version-v2.9.0/guides/obfuscated.mdx | 40 + .../version-v2.9.0/guides/overscroll.mdx | 10 + .../version-v2.9.0/guides/routing.mdx | 47 + .../version-v2.9.0/guides/signing.mdx | 387 ++++++++ .../guides/single-instance-lock.mdx | 81 ++ .../version-v2.9.0/guides/sveltekit.mdx | 153 +++ .../version-v2.9.0/guides/templates.mdx | 97 ++ .../version-v2.9.0/guides/troubleshooting.mdx | 368 ++++++++ .../version-v2.9.0/guides/vscode.mdx | 82 ++ .../guides/windows-installer.mdx | 58 ++ .../version-v2.9.0/guides/windows.mdx | 61 ++ .../version-v2.9.0/howdoesitwork.mdx | 369 ++++++++ .../version-v2.9.0/introduction.mdx | 73 ++ .../version-v2.9.0/reference/_category_.json | 4 + .../version-v2.9.0/reference/cli.mdx | 240 +++++ .../version-v2.9.0/reference/menus.mdx | 230 +++++ .../version-v2.9.0/reference/options.mdx | 869 ++++++++++++++++++ .../reference/project-config.mdx | 104 +++ .../reference/runtime/_category_.json | 4 + .../reference/runtime/browser.mdx | 13 + .../reference/runtime/clipboard.mdx | 23 + .../reference/runtime/dialog.mdx | 302 ++++++ .../reference/runtime/events.mdx | 37 + .../reference/runtime/intro.mdx | 85 ++ .../version-v2.9.0/reference/runtime/log.mdx | 130 +++ .../version-v2.9.0/reference/runtime/menu.mdx | 25 + .../reference/runtime/screen.mdx | 38 + .../reference/runtime/window.mdx | 227 +++++ .../version-v2.9.0/tutorials/_category_.json | 4 + .../version-v2.9.0/tutorials/dogsapi.mdx | 245 +++++ .../version-v2.9.0/tutorials/helloworld.mdx | 123 +++ website/src/pages/changelog.mdx | 2 + .../version-v2.9.0/appendix/_category_.json | 4 + .../version-v2.9.0/community/_category_.json | 4 + .../community/links.mdx | 0 .../community/showcase/_category_.json | 4 + .../community/showcase/bulletinboard.mdx | 10 + .../community/showcase/cfntracker.mdx | 0 .../community/showcase/emailit.mdx | 10 + .../community/showcase/encrypteasy.mdx | 0 .../community/showcase/espstudio.mdx | 0 .../community/showcase/filehound.mdx | 0 .../community/showcase/hiposter.mdx | 0 .../community/showcase/mchat.mdx | 10 + .../community/showcase/minecraftupdater.mdx | 0 .../community/showcase/modalfilemanager.mdx | 0 .../community/showcase/mollywallet.mdx | 0 .../community/showcase/october.mdx | 14 + .../community/showcase/optimus.mdx | 0 .../community/showcase/portfall.mdx | 0 .../community/showcase/restic-browser.mdx | 12 + .../community/showcase/riftshare.mdx | 21 + .../community/showcase/scriptbar.mdx | 10 + .../community/showcase/snippetexpander.mdx | 0 .../community/showcase/surge.mdx | 10 + .../community/showcase/tinyrdm.mdx | 11 + .../community/showcase/wally.mdx | 10 + .../community/showcase/warmine.mdx | 0 .../community/showcase/wombat.mdx | 0 .../version-v2.9.0/community/showcase/ytd.mdx | 10 + .../community/templates.mdx | 8 +- .../gettingstarted/_category_.json | 4 + .../gettingstarted/building.mdx | 0 .../gettingstarted/development.mdx | 0 .../gettingstarted/firstproject.mdx | 0 .../gettingstarted/installation.mdx | 0 .../version-v2.9.0/guides/_category_.json | 4 + .../guides/angular.mdx | 0 .../guides/application-development.mdx | 0 .../guides/crossplatform-build.mdx | 0 .../guides/custom-protocol-schemes.mdx | 0 .../guides/dynamic-assets.mdx | 9 + .../guides/file-association.mdx | 0 .../guides/frameless.mdx | 0 .../guides/frontend.mdx | 0 .../guides/ides.mdx | 2 +- .../guides/linux-distro-support.mdx | 0 .../guides/linux.mdx | 0 .../guides/local-development.mdx | 0 .../guides/mac-appstore.mdx | 0 .../guides/manual-builds.mdx | 0 .../guides/migrating.mdx | 2 +- .../guides/mouse-buttons.mdx | 0 .../version-v2.9.0/guides/nixos-font.mdx | 10 + .../guides/obfuscated.mdx | 2 +- .../guides/overscroll.mdx | 0 .../version-v2.9.0/guides/routing.mdx | 68 ++ .../guides/signing.mdx | 0 .../guides/single-instance-lock.mdx | 0 .../guides/sveltekit.mdx | 0 .../guides/templates.mdx | 0 .../guides/troubleshooting.mdx | 0 .../guides/vscode.mdx | 0 .../guides/windows-installer.mdx | 2 +- .../guides/windows.mdx | 0 .../howdoesitwork.mdx | 6 +- .../introduction.mdx | 0 .../version-v2.9.0/reference/_category_.json | 4 + .../reference/cli.mdx | 2 +- .../reference/menus.mdx | 0 .../reference/options.mdx | 69 +- .../reference/project-config.mdx | 0 .../reference/runtime/_category_.json | 4 + .../reference/runtime/browser.mdx | 0 .../reference/runtime/clipboard.mdx | 0 .../reference/runtime/dialog.mdx | 0 .../reference/runtime/draganddrop.mdx | 38 + .../reference/runtime/events.mdx | 0 .../reference/runtime/intro.mdx | 0 .../reference/runtime/log.mdx | 0 .../reference/runtime/menu.mdx | 0 .../reference/runtime/screen.mdx | 0 .../reference/runtime/window.mdx | 14 +- .../version-v2.9.0/tutorials/_category_.json | 4 + .../tutorials/dogsapi.mdx | 0 .../tutorials/helloworld.mdx | 0 ...bars.json => version-v2.9.0-sidebars.json} | 0 website/versions.json | 2 +- 542 files changed, 41766 insertions(+), 28 deletions(-) create mode 100644 website/i18n/en/docusaurus-plugin-content-docs/version-v2.9.0.json create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/tinyrdm.mdx (100%) create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0}/guides/routing.mdx (100%) create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/appendix/_category_.json (100%) rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/community/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/gettingstarted/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/guides/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/reference/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/reference/runtime/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0}/tutorials/_category_.json (100%) create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/bulletinboard.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/emailit.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/october.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/restic-browser.mdx (100%) rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/riftshare.mdx (100%) rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/scriptbar.mdx (100%) rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/surge.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/wally.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx rename website/{versioned_docs/version-v2.8.0 => i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0}/community/showcase/ytd.mdx (100%) create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/developing-new-features.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/documenting.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/fixing-bugs.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/setting-up-a-dev-environment.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/ways-of-contributing.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx create mode 100644 website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx create mode 100644 website/versioned_docs/version-v2.9.0/appendix/_category_.json create mode 100644 website/versioned_docs/version-v2.9.0/community/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/links.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/_category_.json create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/bulletinboard.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/cfntracker.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/emailit.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/encrypteasy.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/espstudio.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/filehound.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/hiposter.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/mchat.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/minecraftupdater.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/modalfilemanager.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/mollywallet.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/october.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/optimus.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/portfall.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/restic-browser.mdx create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/riftshare.mdx create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/scriptbar.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/snippetexpander.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/surge.mdx create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/tinyrdm.mdx create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/wally.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/warmine.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/showcase/wombat.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/community/showcase/ytd.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/community/templates.mdx (90%) create mode 100644 website/versioned_docs/version-v2.9.0/gettingstarted/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/gettingstarted/building.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/gettingstarted/development.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/gettingstarted/firstproject.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/gettingstarted/installation.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/guides/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/angular.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/application-development.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/crossplatform-build.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/custom-protocol-schemes.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/dynamic-assets.mdx (92%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/file-association.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/frameless.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/frontend.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/ides.mdx (98%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/linux-distro-support.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/linux.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/local-development.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/mac-appstore.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/manual-builds.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/migrating.mdx (99%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/mouse-buttons.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/guides/nixos-font.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/obfuscated.mdx (98%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/overscroll.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/guides/routing.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/signing.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/single-instance-lock.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/sveltekit.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/templates.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/troubleshooting.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/vscode.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/windows-installer.mdx (98%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/guides/windows.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/howdoesitwork.mdx (99%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/introduction.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/reference/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/cli.mdx (99%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/menus.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/options.mdx (95%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/project-config.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/reference/runtime/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/browser.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/clipboard.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/dialog.mdx (100%) create mode 100644 website/versioned_docs/version-v2.9.0/reference/runtime/draganddrop.mdx rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/events.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/intro.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/log.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/menu.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/screen.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/reference/runtime/window.mdx (94%) create mode 100644 website/versioned_docs/version-v2.9.0/tutorials/_category_.json rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/tutorials/dogsapi.mdx (100%) rename website/versioned_docs/{version-v2.8.0 => version-v2.9.0}/tutorials/helloworld.mdx (100%) rename website/versioned_sidebars/{version-v2.8.0-sidebars.json => version-v2.9.0-sidebars.json} (100%) diff --git a/v2/cmd/wails/internal/version.txt b/v2/cmd/wails/internal/version.txt index 4f00f11bc2b..ed51b084034 100644 --- a/v2/cmd/wails/internal/version.txt +++ b/v2/cmd/wails/internal/version.txt @@ -1 +1 @@ -v2.8.2 \ No newline at end of file +v2.9.0 \ No newline at end of file diff --git a/website/i18n/en/docusaurus-plugin-content-docs/version-v2.9.0.json b/website/i18n/en/docusaurus-plugin-content-docs/version-v2.9.0.json new file mode 100644 index 00000000000..5416a15af63 --- /dev/null +++ b/website/i18n/en/docusaurus-plugin-content-docs/version-v2.9.0.json @@ -0,0 +1,38 @@ +{ + "version.label": { + "message": "v2.9.0", + "description": "The label for version v2.9.0" + }, + "sidebar.docs.category.Getting Started": { + "message": "Getting Started", + "description": "The label for category Getting Started in sidebar docs" + }, + "sidebar.docs.category.Reference": { + "message": "Reference", + "description": "The label for category Reference in sidebar docs" + }, + "sidebar.docs.category.Runtime": { + "message": "Runtime", + "description": "The label for category Runtime in sidebar docs" + }, + "sidebar.docs.category.Community": { + "message": "Community", + "description": "The label for category Community in sidebar docs" + }, + "sidebar.docs.category.Showcase": { + "message": "Showcase", + "description": "The label for category Showcase in sidebar docs" + }, + "sidebar.docs.category.Guides": { + "message": "Guides", + "description": "The label for category Guides in sidebar docs" + }, + "sidebar.docs.category.Tutorials": { + "message": "Tutorials", + "description": "The label for category Tutorials in sidebar docs" + }, + "sidebar.docs.link.Contributing": { + "message": "Contributing", + "description": "The label for link Contributing in sidebar docs, linking to /community-guide#ways-of-contributing" + } +} diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..d6b742435e4 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +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 + +- [Serveur Discord Wails](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) diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..2c56a2e836c --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +L'application [BulletinBoard](https://github.com/raguay/BulletinBoard) est un panneau de messages versitaux pour les messages statiques ou les boîtes de dialogue pour obtenir des informations de l'utilisateur pour un script. Il a une TUI pour créer de nouvelles boîtes de dialogue qui peuvent être utilisées pour obtenir des informations de l'utilisateur. Son design est de rester en fonctionnement sur votre système et de montrer les informations au besoin, puis de se cacher. J'ai un processus pour surveiller un fichier sur mon système et pour envoyer le contenu à BulletinBoard une fois modifié. Cela fonctionne très bien avec mes workflows. Il y a auss un [workflow Alfred](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow) pour envoyer les informations au programme. Le workflow fonctionne aussi avec [EmailIt](https://github.com/raguay/EmailIt). diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..568c964b70e --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,42 @@ +# CFN Tracker + +```mdx-code-block +

+ +
+

+``` + +[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. + +## Caractéristiques + +- 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 + +### Technologie majeure utilisée aux côtés de 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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..ac64e25acce --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[EmailIt](https://github.com/raguay/EmailIt/) est un programme Wails 2 qui est un expéditeur de courrier électronique basé sur le markdown uniquement avec neuf blocs-notes, pour manipuler le texte et les modèles. Il a également un terminal pour exécuter des scripts dans EmailIt sur les fichiers de votre système. Les scripts et modèles peuvent être utilisés depuis la ligne de commande elle-même ou avec les extensions Alfred, Keyboard Maestro, Dropzone ou PopClip. Il supporte également les scripts et thèmes téléchargés sous GitHub. La documentation n'est pas complète, mais le programme fonctionne. Il est construit en utilisant Wails2 et Svelte, et le téléchargement est une application macOS universelle. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..7f4bd7a634a --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..aae652e2c3c --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[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 \ No newline at end of file diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..7522afa6ecf --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# Utilitaire d'exportation FileHound + +```mdx-code-block +

+ +
+

+``` + +[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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..21fd4b11743 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter) est un outil client de test d'API http simple et efficace. Basé sur les Wails, Go et sveltejs. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..5966e75fa63 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Minecraft Updater + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..fe644bd7bb5 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Modal File Manager + +```mdx-code-block +

+ +
+

+``` + +[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 la ligne de commande `rm`, `cp`, etc. , mais une installation de git doit être présente sur le système pour télécharger des thèmes et des extensions. 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. Il y a des thèmes et des extensions disponibles à télécharger à partir de GitHub. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..70a6cd1f44d --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..5a9789d8711 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..41744234d37 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# Optimus + +```mdx-code-block +

+ +
+

+``` + +[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 d’images WebP, JPEG et PNG. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..acdc682becf --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# Portfall + +```mdx-code-block +

+ +
+

+``` + +[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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..b6597166852 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..e47b2397e63 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +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! diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..d7215d66126 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp) est un programme pour afficher la sortie de scripts ou d'un serveur [Node-Red](https://nodered.org). Il exécute des scripts définis dans le programme EmailIt et affiche la sortie. Des scripts de xBar ou TextBar peuvent être utilisés. Actuellement sur les scripts TextBar fonctionnent bien. 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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..b5917484303 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/tinyrdm.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/tinyrdm.mdx rename to website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..ba2a7fccc45 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..2e427433069 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# Lanceur Minecraft pour WarMine + +```mdx-code-block +

+ + +
+

+``` + +[Lanceur Minecraft pour WarMine](https://warmine.ru/) est une application Wails qui vous permet facilement de rejoindre le serveur de jeu contenant les mods, ainsi que la gestion de vos comptes de jeu. + +Le Launcher télécharge les fichiers du jeu, vérifie leur intégrité et lance le jeu avec une large gamme d'options de personnalisation. + +Le frontend est écrit en Svelte, le lanceur entier tient dans 9Mo et prend en charge Windows 7-11. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..c431f691952 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# Wombat + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat) est un client gRPC multi-plateforme. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..4f5bd993cb1 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[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é. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..6baf0941b8c --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +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 <script setup>) +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Modèle Wails basé sur Naive UI (Librairie de composants Vue 3) + +## Angular + +- [wails-template-angular](https://github.com/mateothegreat/wails-template-angular) - Modèle Angular 15+ prêt à être utilisé en production. +- [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 +- [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 + +## 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-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - Un modèle mis à jour en utilisant Svelte v4.2.0 et Vite avec TailwindCSS v3.3.3 +- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - Un modèle utilisant SvelteKit + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - Un modèle utilisant Solid + Ts + Vite +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-js) - Un modèle utilisant Solid + Js + Vite + +## 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. + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - Utilisez une combinaison unique de htmx pour interactivité, et de templ pour créer des composants et des formes + +## 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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..eb43f4aae2c --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +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 +
+ +
+
+``` + +Pour plus de détails sur les options de compilation, veuillez vous référer à la [documentation du CLI](../reference/cli.mdx#build). diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..307029141d4 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..383925af1e6 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +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"; + + + + Générer un projet Svelte utilisant JavaScript avec:

+ + wails init -n myproject -t svelte + +Si vous préférez utiliser TypeScript:
+ + wails init -n myproject -t svelte-ts + +
+ + Générer un projet React utilisant JavaScript avec :

+ + wails init -n myproject -t react + +Si vous préférez utiliser TypeScript:
+ + wails init -n myproject -t react-ts + +
+ + Générer un projet Vue utilisant JavaScript avec:

+ + wails init -n myproject -t vue + +Si vous préférez TypeScript:
+ + wails init -n myproject -t vue-ts + +
+ + Générer un projet Preact utilisant JavaScript avec:

+ + wails init -n myproject -t preact + +Si vous préférez TypeScript:
+ + wails init -n myproject -t preact-ts + +
+ + Générer un projet Lit utilisant JavaScript avec:

+ + wails init -n myproject -t lit + +Si vous préférez TypeScript:
+ + wails init -n myproject -t lit-ts + +
+ + Générer un projet Vanilla utilisant JavaScript avec :

+ + wails init -n myproject -t vanilla + +Si vous préférez TypeScript:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +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é. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..86ffde34bde --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,90 @@ +--- +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"; + + + + Wails a besoin que les outils de command line xocde soient installés. Cela peut être fait + en exécutant xcode-select --install. + + + Wails a besoin que WebView2 runtime soit installé. Certaines installations de Windows auront déjà installé cette fonctionnalité. Vous pouvez vérifier en utilisant la commande wails doctor. + + + Linux a besoin de gcc comme outil de compilation en plus de libgtk3 et libwebkit. 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. Exécutez wails doctor 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 Ajouter une distribution Linux. + + +``` + +## 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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..1fe2f199ffe --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# 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", +``` \ No newline at end of file diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..411853fd6f1 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# 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 + +Le modèle utilisé par défaut défini que `main.go` est utilisé pour configurer et démarrer l'application, tandis que `app.go` est utilisé pour définir la logique de l'application. + +Le fichier `app.go` va définir une structure qui a 2 méthodes qui agissent comme crochets dans l'application principale: + +```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) { +} +``` + +- La méthode startup est appelée d-s que Wails a donné les ressources nécessaires et qu'il est dans un bon état pour créer les ressources, mettre en place les event listeners et tout ce dont l'application peut avoir besoin pour démarrer. Il est donné un `context.Context` qui est généralement sauvegardé dans un champ struct. Ce contexte est nécessaire pour appeler le [runtime](../reference/runtime/intro.mdx). Si cette méthode renvoie une erreur, l'application se fermera. En mode développement, l'erreur sera affichée dans la console. + +- La méthode d'arrêt sera appelée par Wails à la fin du processus d'arrêt. C'est un bon endroit pour vider la mémoire et effectuer toutes les tâches d'arrêt. + +Le fichier `main.go` consiste généralement en un seul appel à `wails.Run()`, qui accepte la configuration de l'application. Le modèle utilisé par les templates fait qu'avant l'appel à `wails.Run()`, une instance du struct que l'on a définie dans `app.go` est créée et instanciée dans une variable appelée `app`. Cette configuration est l'endroit où nous ajoutons nos 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) + } +} + +``` + +Plus d'informations sur les crochets du cycle de vie des applications peuvent être trouvées [ici](../howdoesitwork.mdx#application-lifecycle-callbacks). + +## Méthodes de liaison + +Il est probable que vous vouliez appeler les méthodes Go depuis le frontend. Cela se fait normalement en ajoutant des méthodes publiques à le struct déjà défini dans `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) +} +``` + +Dans la configuration principale de l'application, le paramètre `Bind` est l'endroit où nous pouvons dire à Wails ce que nous voulons lier : + +```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) + } +} + +``` + +Cela liera toutes les méthodes publiques de notre structure `App` (cela ne liera jamais les méthodes de démarrage et d'arrêt du système). + +### Traiter avec le contexte lors de la liaison de plusieurs structures + +Si vous voulez lier des méthodes pour des structures multiples, mais que vous voulez que chaque struct conserve une référence au contexte pour que vous puissiez utiliser les fonctions d'exécution... Un bon choix est de passer le contexte de la méthode `OnStartup` à vos instances struct : + +```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) + } +} +``` + +Plus d'informations à sur Binding peuvent être trouvées [ici](../howdoesitwork.mdx#method-binding). + +## Menu de l’application + +Wails prend en charge l'ajout d'un menu à votre application. Ceci est fait en passant un [Menu](../reference/menus.mdx#menu) structuré à la configuration de l'application. Il est courant d'utiliser une méthode qui renvoie un Menu, et encore plus courant pour que cela soit une méthode sur la struct de l'`app` qui soit utilisée pour les hooks du cycle de vie. + +```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) + } +} + +``` + +## Ressources + +La grande chose à propos de la façon dont Wails v2 gère les ressources pour le frontend, est que ce n'est pas le cas! La seule chose que vous devez donner à Wails est un `embed.FS`. C'est à vous de décider comment vous y arrivez. Vous pouvez utiliser les fichiers html/css/js vanilla comme dans le modèle vanilla. Vous pourriez avoir un système de compilation compliqué, peu importe. + +Quand la commande `wails dev` est exécutée, elle vérifiera le fichier de projet `wails.json` à la racine du projet. Il y a 2 clés dans le fichier du projet qui sont lues : + +- "frontend:install" +- "frontend:build" + +Le premier, si fourni, sera exécuté dans le répertoire `frontend` pour installer les modules. Le second, si fourni, sera exécuté dans le répertoire `frontend` pour construire le projet frontend. + +Si ces 2 clés ne sont pas fournies, alors Wails ne fait absolument rien avec le frontend. Il n'attend que `embed.FS`. + +### AssetsHandler + +Une application Wails v2 peut éventuellement définir un `http.Handler` dans `options.app`, qui permet de se connecter à l'AssetServer pour créer des fichiers à la volée ou traiter les requêtes POST/PUT. Les requêtes GET sont toujours traitées d'abord par le `assets` FS. Si le FS ne trouve pas le fichier demandé, la requête sera transmise au `http.Handler`. Toute requête autre que GET sera traitée directement par le `AssetsHandler` si spécifié. Il est également possible d'utiliser le `AssetsHandler` uniquement en spécifiant `nil` dans l'option `Assets`. + +## Serveur de développement embarqué + +Exécuter `wails dev` démarrera le serveur de développement intégré qui démarrera un observateur de fichiers dans votre répertoire de projet. Par par défaut, si un fichier change, wails vérifie s'il s'agit d'un fichier d'application (par défaut: `.go`, configurable avec l'option `-e`). Si c'est le cas, il reconstruira votre application et la relancera. Si le fichier modifié se trouvait dans les actifs, il lancera un rechargement après un court laps de temps. + +Le serveur de développement utilise une technique appelée "debouncing", ce qui signifie qu'il ne se recharge pas tout de suite, comme il peut y avoir plusieurs fichiers modifiés en un court laps de temps. Lorsqu'un déclencheur se produit, il attend un temps défini avant d'émettre un rechargement. Si un autre déclencheur se produit, le temps d'attente se réinitialise avant un prochain rechargement. Par défaut, cette période est définie à `100ms`. Si cette valeur ne fonctionne pas pour votre projet, elle peut être configurée en utilisant l'option `-debounce`. Si elle est utilisée, cette valeur sera enregistrée dans la configuration de votre projet et deviendra la valeur par défaut. + +## Serveur de développement externe + +Certains frameworks sont fournis avec leur propre serveur de rechargement en direct, cependant ils ne seront pas en mesure de tirer parti des liaisons Wails Go. Dans ce scénario, il est préférable d'exécuter un script qui va surveiller le projet dans dossier build, dossier que Wails surveille aussi. Pour un exemple, voir le modèle svelte par défaut qui utilise [rollup](https://rollupjs.org/guide/en/). + +### Créer une application React + +Le processus pour créer un projet Reactest un peu plus compliqué. Afin de prendre en charge le rechargement du frontend en direct, la configuration suivante doit être ajoutée à votre `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +La commande `frontend:dev:watcher` démarrera le serveur de développement React (hébergé sur le port `3000` typiquement). La commande `frontend:dev:serverUrl` demande ensuite à Wails d'exposer les ressources depuis le serveur de développement lors du chargement du frontend, plutôt que depuis le dossier de construction. En plus de ce qui précède, le fichier `index.html` doit être mis à jour avec les éléments suivants : + +```html + + + + + +``` + +Ceci est nécessaire, car la commande watcher qui reconstruit le frontend empêche Wails de les injecter. Ça contourne le problème en assurant les scripts sont toujours injectés. Avec cette configuration, `wails dev` peut être exécuté, ce qui construira le frontend et le backend de manière appropriée avec le rechargement à chaud activé. De plus, lorsque vous accédez à l'application à partir d'un navigateur, les outils de développement de React peuvent maintenant être utilisés sur une version non minifiée de l'application pour le débogage. Enfin, pour des compilations plus rapides, `wails dev -s` peut être exécuté pour passer la construction par défaut du frontend par Wails car c'est une étape inutile. + +## Module Go + +Les modèles Wails par défaut génèrent un fichier `go.mod` qui contient le nom de module "changeme". Vous devriez changer ceci pour quelque chose de plus approprié après la génération du projet. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..97f81432dc2 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# Ressources dynamiques + +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é. + +## Exemple + +Dans notre exemple de projet, nous allons créer un gestionnaire de ressources simple qui chargera les fichiers à partir du disque: + +```go title=main.go {17-36,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) + } +} +``` + +Lorsque nous exécutons l'application en mode dev en utilisant `wails dev`, nous verrons la sortie suivante : + +``` +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler +Requesting file: favicon.ico +``` + +Comme vous pouvez le voir, le gestionnaire d'actifs est appelé lorsque le serveur d'assets par défaut est incapable de servir le fichier `favicon.ico`. + +Si vous faites un clic droit sur l'application principale et sélectionnez "inspecter" pour afficher les devtools, vous pouvez tester cette fonctionnalité en tapant ce qui suit dans la console : + +``` +let response = await fetch('does-not-exist.txt'); +``` + +Cela générera une erreur dans les devtools. Nous pouvons voir que l'erreur est ce que nous attendons est retourné par notre gestionnaire de ressources personnalisées : + +```mdx-code-block +

+ +

+``` + +Cependant, si nous demandons `go.mod`, nous verrons la sortie suivante : + +```mdx-code-block +

+ +

+``` + +Cette technique peut être utilisée pour charger des images directement dans la page. Si nous avons mis à jour notre modèle vanilla par défaut et a remplacé l'image du logo : + +```html + +``` + +avec : + +```html + +``` + +Nous verrions ensuite ce qui suit: + +```mdx-code-block +

+ +

+``` + +:::warning + +Exposer votre système de fichiers de cette manière est un risque de sécurité. Il est recommandé de gérer correctement l'accès à votre système de fichiers. + +::: diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..bbeb338f1b6 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# Applications sans cadre + +Wails prend en charge la création d'applications qui n'ont pas de cadres. Ceci peut être réalisé en utilisant le champ [frameless](../reference/options.mdx#frameless) dans [Application Options](../reference/options.mdx#application-options). + +Wails offre une solution simple pour faire glisser la fenêtre: N'importe quel élément HTML qui a le style CSS `--wails-draggable:drag` agira comme une "poignée de glisser". Cette propriété s'applique à tous les éléments enfants. Si vous devez indiquer qu'un élément imbriqué ne doit pas glisser, alors utilisez l'attribut '--wails-draggable:no-drag' sur cet élément. + +```html + + + + + + + +
+ + +
+
+ + + + +``` + +Pour certains projets, l'utilisation d'une variable CSS peut ne pas être possible en raison du style dynamique. Dans ce cas, vous pouvez utiliser les options `CSSDragProperty` et `CSSDragValue` pour définir une propriété et une valeur qui seront utilisées pour indiquer régions glissables : + +```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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info Plein écran + +Si vous autorisez votre application à être en plein écran, cette fonctionnalité de glissement sera désactivée. + +::: diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..ea101019ad8 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# Frontend + +## Injection de script + +Quand Wails sert votre fichier `index.html`, par défaut, il injectera 2 entrées de script dans la balise `` pour charger `/wails/ipc.js` et `/wails/runtime.js`. Ces fichiers installent respectivement les bindings et les runtime. + +Le code ci-dessous montre où ils sont injectés par défaut : + +```html + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### Remplacer l'injection de script par défaut + +Pour fournir plus de flexibilité aux développeurs, il y a une balise meta qui peut être utilisée pour personnaliser ce comportement: + +```html + +``` + +Les options sont les suivantes : + +| Valeur | Description | +| ------------------- | -------------------------------------------------------------- | +| noautoinjectruntime | Pour désactiver l'injection automatique de `/wails/runtime.js` | +| noautoinjectipc | Pour désactiver l'injection automatique de `/wails/ipc.js` | +| noautoinject | Pour désactiver l'injection automatique de tous les scripts | + +Plusieurs options peuvent être utilisées à condition qu'elles soient séparées par des virgules. + +Ce code est parfaitement valide et fonctionne de la même manière que la version avec l'auto-injection : + +```html + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..f35b2f57f77 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# IDEs + +Wails vise à fournir une grande expérience de développement. À cet effet, nous supportons maintenant la génération d'une configuration spécifique IDE pour fournir une configuration plus souple du projet. + +Actuellement, nous prenons en charge [Visual Studio Code](https://code.visualstudio.com/) mais nous visons à prendre en charge d'autres IDE comme Goland. + +## Visual Studio Code + +```mdx-code-block +

+ +

+``` + +Lors de la génération d'un projet en utilisant l'option `-ide vscode` , les fichiers IDE seront créés à côté des autres fichiers du projet. Ces fichiers sont placés dans le répertoire `.vscode` et fournissent la configuration correcte pour déboguer votre application. + +Les 2 fichiers générés sont `tasks.json` et `launch.json`. Ci-dessous se trouvent les fichiers générés par défaut : + +```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": {} + } + ] +} +``` + +### Configuration des étapes d'installation et de construction + +Le fichier `tasks.json` est simple pour le projet par défaut car il n'y a pas d'étapes `npm install` ou `npm build` nécessaire. Pour les projets qui ont une étape de construction en frontend comme avec Svelte, nous devrions modifier `tasks.json` pour ajouter les étapes d'installation et de construction suivantes : + +```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 Améliorations futures + +Dans le futur, nous espérons générer un `tasks.json` qui inclut les étapes d'installation et de construction automatiquement. + +::: diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..6bd2002fce7 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# Prise en charge des distributions Linux + +## Vue d'ensemble + +Wails offre le support de Linux, mais fournir des instructions d'installation pour toutes les distributions disponibles est une tâche impossible. À la place, Wails essaie de déterminer si les paquets dont vous avez besoin pour développer des applications sont disponibles via le gestionnaire de paquets de votre système. Actuellement, nous supportons les gestionnaires de paquets suivants : + +- apt +- dnf +- emerge +- eopkg +- nixpkgs +- pacman +- zypper + +## Ajout des noms de paquets + +Il peut y avoir des cas où votre distribution de linux utilise un des gestionnaires de paquets pris en charge mais le nom du paquet est différent. Par exemple, vous pouvez utiliser un dérivé Ubuntu, mais le nom du paquet pour gtk peut être différent. Wails tente de trouver le paquet correct en itérant une liste de noms de paquets. La liste des paquets est stockée dans un fichier spécifique dans le dossier `v2/internal/system/packagemanager` . Dans notre exemple, ce serait `v2/internal/system/packagemanager/apt.go`. + +Dans ce fichier, la liste des paquets est définie par la méthode `Packages()`: + +```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}, + }, + } +} +``` + +Supposons que dans notre distribution linux, `libgtk-3` est empaqueté sous le nom `lib-gtk3-dev`. Nous pourrions ajouter le support de ce paquet en ajoutant la ligne suivante : + +```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}, + }, + } +} +``` + +## Ajout de nouveaux gestionnaires de paquets + +Pour ajouter un nouveau gestionnaire de paquets, effectuez les étapes suivantes : + +- Créez un nouveau fichier dans `v2/internal/system/packagemanager` appelé `.go`, où `` est le nom du gestionnaire de paquets. +- Définit une structure conforme à l'interface du gestionnaire de paquets définie dans `pm.go`: + +```go +type PackageManager interface { + Name() string + Packages() packagemap + PackageInstalled(*Package) (bool, error) + PackageAvailable(*Package) (bool, error) + InstallCommand(*Package) string +} +``` + +- `Name()` doit retourner le nom du gestionnaire de paquets +- `Packages()` doit retourner une `packagemap`, qui fournit des noms de fichiers candidats pour les dépendances +- `PackageInstalled()` devrait retourner `true` si le paquet donné est installé +- `PackageAvailable()` devrait retourner `true` si le paquet donné n'est pas installé mais disponible pour l'installation +- `InstallCommand()` doit retourner la commande exacte pour installer le nom du paquet donné + +Jetez un coup d'œil au code des autres gestionnaires de paquets pour avoir une idée de comment cela fonctionne. + +:::info Rappel + +Si vous ajoutez le support d'un nouveau gestionnaire de paquets, n'oubliez pas de mettre également à jour cette page ! + +::: diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..19e45313a44 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# Linux + +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é" + +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 : + +```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) sur le [forum de discussion](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275) diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..0c3878d7888 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# Développement local + +## Vue d'ensemble + +Wails est en développement constant et les nouvelles versions sont régulièrement "tagguées". Cela se produit généralement lorsque tout le nouveau code sur `master` a été testé et confirmé fonctionnel. Si vous avez besoin d'un correctif ou d'une fonctionnalité qui ne l'a pas encore fait pour une version, il est possible d'utiliser la dernière version "non validée" en utilisant les étapes suivantes : + +- `git clone https://github.com/wailsapp/wails` +- `cd wails/v2/cmd/wails` +- `go install` + +REMARQUE : Le répertoire dans lequel vous avez cloné le projet sera maintenant appelé "clonedir". + +Le CLI de Wails sera maintenant à la dernière version. + +### Mise à jour du projet + +Pour mettre à jour vos projets pour utiliser la dernière version de la bibliothèque Wails, mettez à jour le fichier `go.mod` et assurez-vous que la ligne suivante est en bas du fichier : + +`replace github.com/wailsapp/wails/v2 => ` + +Exemple: + +Sur Windows: `replace github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2` + +Sur 'nix: `replace github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2` + +Pour revenir à une version stable, exécutez : + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` + +## Tester une branche + +Si vous voulez tester une branche, suivez les instructions ci-dessus, mais assurez-vous de bien vous mettre sur la branche que vous voulez tester avant d'installer : + +- `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` + +Assurez-vous de [mettre à jour votre projet](#updating-your-project) comme décrit ci-dessus. + +## Tester une PR + +Si vous voulez tester une PR, suivez les instructions ci-dessus, mais assurez-vous de récupérer la PR et d'être sur la branche de la PR avant de faire l'installation. Veuillez remplacer `[IDofThePR]` par l'ID de la PR affiché sur 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` + +Assurez-vous de [mettre à jour votre projet](#updating-your-project) comme décrit ci-dessus. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..fe040591634 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# Guide pour Mac App Store + +Cette page donne un bref aperçu de la façon de soumettre votre application Wails au Mac App Store. + +## Prérequis + +- Vous devrez avoir un compte développeur Apple. Veuillez trouver plus d'informations sur le site [Apple Developer Program](https://developer.apple.com/support/compare-memberships/) +- Vous aurez besoin que vos certificats, identifiants et applications soient créés sur le portail développeur. Plus d'infos sur ce sujet ci-dessous +- L'utilitaire Xcode devront être installés sur votre machine locale pour être utilisé en ligne de commandes + +#### Créer des certificats et des identifiants + +1. Allez sur votre [Compte Développeur Apple](https://developer.apple.com/account/) +2. Sous `Certificats, Identificateurs & Profils`, cliquez sur `Identifiants` et Enregistrez un nouvel identifiant d'application. Utiliser le format (com.example.app) +3. Sous la même page, cliquez sur `Certificats` et générez de nouveaux certificats pour la distribution de l'App Store Mac. Téléchargez-les et importez les certificats dans votre trousseau sur votre machine locale. + +#### Créer une soumission d'application + +1. Allez sur le [site de connexion de l'App Store](https://appstoreconnect.apple.com/apps) +2. Enregistrez une nouvelle application et liez l'ID du lot que vous avez créé à l'étape précédente +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. + +## Processus Mac App Store + +#### Activation du Sandbox Apple + +Les applications soumises au Mac App Store doivent tourner dans la [Sandbox](https://developer.apple.com/app-sandboxing/) Apple. Vous devez créer un fichier `entitlements.plist` pour que cela fonctionne. La recommandation est de créer ce fichier sous ce chemin `{PROJECT_DIR}/build/darwin/entitlements.plist`. + +**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. + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +**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. + +#### Construire et signer le package de l'application + +Ce qui suit est un exemple de script pour construire et signer votre application pour la soumission de l'App Store Mac. Il suppose que vous exécutez le script depuis la racine de votre projet. + +Notez que les certificats pour signer l'application et l'installateur sont différents. Veuillez vous assurer que les deux sont importés dans votre trousseau. Trouvez les chaînes de caractères dans Trousseau et insérez-les ci-dessous. Remplissez le nom de votre certificat et le nom de l'application ci-dessous. Exécuter le script suivant générera un fichier `app.pkg` signé à la racine de votre application. + +```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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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 +``` + +#### Télécharger l'application + +Vous devrez télécharger le fichier de package généré et l'associer à votre application avant de pouvoir le soumettre pour vérification. + +1. Téléchargez l' [App Transporter](https://apps.apple.com/us/app/transporter/id1450874784) depuis le Mac App Store +2. Ouvrez-le et connectez-vous avec votre identifiant Apple +3. Cliquez sur le signe + et sélectionnez le fichier `APP_NAME.pkg` que vous avez généré à l'étape précédente. Télécharger le +4. Retournez sur le site [App Store Connect](https://appstoreconnect.apple.com/apps) et retournez dans la soumission de votre application. Sélectionnez la version que vous êtes prêt à mettre à disposition sur l'App Store. Sous `Build` sélectionnez le package que vous avez téléchargé via Transporter. + +C'est terminé ! Vous pouvez maintenant utiliser le site pour soumettre votre application pour vérification. Après quelques jours ouvrables si tout se passe bien, vous devriez voir votre application en direct sur le Mac App Store. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..98457d19cc9 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# Compilations manuelles + +Le CLI Wails fait beaucoup de travail pour le projet, mais il est parfois souhaitable de construire manuellement votre projet. Ce document discutera des différentes opérations que fait le CLI et des différentes façons d'y parvenir. + +## Processus de construction + +Lorsque `wails build` ou `wails dev` sont utilisés, le CLI Wails effectue un processus de construction commun: + + - Installation des dépendances frontend + - Construire le projet frontend + - Générer des ressources de construction + - Compiler l'application + - [optionnel] Compresser l'application + +### Installation des dépendances frontend + +#### Étapes CLI + +- Si l'option `-s` est donné, cette étape est ignorée +- Vérifie `wails.json` pour voir s'il y a une commande install dans `frontend:install` +- S'il n'y en a pas, il saute cette étape +- Si le fichier existe, vérifie si `package.json` existe dans le répertoire du frontend. S'il n'existe pas, il saute cette étape +- Un hash MD5 est générée à partir du contenu du fichier `package.json` +- Il vérifie l'existence de `package.json.md5` et, s'il existe, compare son contenu (une somme MD5) avec celui généré pour voir si le contenu a changé. S'ils sont les mêmes, cette étape est ignorée +- Si `package.json.md5` n'existe pas, il le crée en utilisant la somme MD5 générée +- Si une compilation est maintenant requise, ou si `node_modules` n'existe pas, ou si l'option `-f` est donnée, la commande install est exécutée dans le répertoire frontend + +#### Étapes manuelles + +Cette étape peut être réalisée à partir de la ligne de commande ou d'un script avec `npm install`. + +### Construire le projet frontend + +#### CLI Wails + +- Si l'option `-s` est donné, cette étape est ignorée +- Vérifie `wails.json` pour voir s'il y a une commande de construction dans la clé `frontend:build` +- S'il n'y en a pas, il saute cette étape +- S'il existe, il est exécuté dans le répertoire du frontend + +#### Étapes manuelles + +Cette étape peut être réalisée à partir de la ligne de commande ou d'un script avec `npm run build` ou quel que soit le script de construction du frontend. + +### Générer les ressources + +#### CLI Wails + +- Si l'option `-nopackage` est activée, cette étape est ignorée +- Si le fichier `build/appicon.png` n'existe pas, un fichier par défaut est créé +- Pour Windows, voir [ Empaquetage pour Windows](#windows) +- Si `build/windows/icon.ico` n'existe pas, il la créera à partir de l'image `build/appicon.png`. + +##### 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/.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. + +#### É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. + +### 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 + +#### 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 + +#### 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 + +#### Manual steps + +- Run `upx [flags]` manually to compress the application. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..7123cbe6b60 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,191 @@ +# 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: + +

+ +| 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. | + +

diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..4a3de2a61b5 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# 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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..21f7875e389 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# 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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..9d1d772d0fb --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# 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; +} +``` diff --git a/website/versioned_docs/version-v2.8.0/guides/routing.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/routing.mdx rename to website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..4c7cf45ba99 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# 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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +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 + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +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 + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +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). diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..4651c422ed1 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +This guide will go into: + +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. Minimal Installation Steps + +##### Install Wails for Svelte. + +- `wails init -n myapp -t svelte` + +##### Delete the svelte frontend. + +- Navigate into your newly created myapp folder. +- Delete the folder named "frontend" + +##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts. + +- `npm create svelte@latest frontend` + +##### Modify 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. + +##### Modify main.go. + +- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build` + +##### Install/remove dependencies using your favorite package manager. + +- Navigate into your "frontend" folder. +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Change adapter in svelte.config.js + +- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Put SvelteKit into SPA mode with prerendering. + +- 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` + +##### Test 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. + +## 2. Install Script + +##### 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. + +- 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` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Important Notes + +##### Server files will cause build failures. + +- \+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. + +##### The Wails runtime unloads with full page navigations! + +- Anything that causes full page navigations: `window.location.href = '//'` 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('//')` 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 `` of myapp/frontend/src/app.html + +``` + +... + + + +... + +``` + +See https://wails.io/docs/guides/frontend for more information. + +##### Inital data can be loaded and refreshed from +page.ts/+page.js to +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. + +##### Error Handling + +- 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. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Using Forms and handling functions + +- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `
` +- 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: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..790e3107f04 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# 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 +
+ +
+``` + +## 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 diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..1c3b6a9cc52 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# 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 +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +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 +

+ +

+``` + +it's likely that your application's `info.plist` is invalid. Update the file in `build/.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. + +## My application is not displaying the correct icon in Windows Explorer + +If your application is not displaying the correct icon, try deleting the hidden `IconCache.db` file located in the `C:\Users\<your username>\AppData\Local` directory. This will force Windows to rebuild the icon cache. + +Source: https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## 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 `` section of any new page you navigate to: + +```html + + + + +``` + +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 + +## My application won't compile on Mac + +If you are getting errors like this: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## 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. + +## Build process stuck on "Generating bindings" + +Bindings generation process runs your application in a special mode. If application, intentionally or unintentionally, contains an endless loop (i.e. not exiting after `wails.Run()` finished), this can lead to build process stuck on the stage of bindings generation. Please make sure your code exits properly. + +## Mac application flashes white at startup + +This is due to the default background of the webview being white. If you want to use the window background colour instead, you can make the webview background transparent using the following config: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..ed258656d63 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# 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. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..a819d070d3e --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# Installateur NSIS + +```mdx-code-block +

+ +
+

+``` + +Wails prend en charge la génération d'installateurs Windows en utilisant l'installateur [NSIS](https://nsis.sourceforge.io/). + +## Installation de NSIS + +### Windows + +L'installateur est disponible sur la page [de téléchargement NSIS](https://nsis.sourceforge.io/Download). + +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. + +### Linux + +Le paquet `nsis` devrait être disponible via le gestionnaire de paquets de votre distribution. + +### MacOS + +NSIS est disponible via homebrew en utilisant : `brew install nsis`. + +## Génération de l'installateur + +Lorsqu'un nouveau projet est créé, Wails génère les fichiers de configuration NSIS dans `build/windows/installer`. La configuration est lue dans `installer/info.json`, et est configuré pour utiliser la section info du fichier `wails.json` : + +```json +// ... + "Info": { + "companyName": "My Company Name", + "productName": "Wails Vite", + "productVersion": "1.0.0", + "copyright": "Copyright.........", + "comments": "Built using Wails (https://wails.io)" + }, +``` + +Pour générer l'installateur de votre application, utilisez l'option `-nsis` avec la commande `wails build`: + +``` +wails build -nsis +``` + +L'installateur sera ensuite disponible dans le dossier `build/bin`. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..6b24979d741 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# 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). diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..0a6544735ee --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +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 +
+ +
+``` + +## L'Application Principale + +### Vue d’ensemble + +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 + +L'option `Assets` est obligatoire car vous ne pouvez pas avoir d'application Wails sans ressources en frontend. Ces ressources peuvent être n'importe quel fichier que vous attendriez à trouver dans une application web - html, js, css, svg, png, etc. **Il n'y a aucune obligation d'utiliser un générateur de code ou framework** - des fichiers bruts suffisent. Lorsque l'application démarre, elle tentera de charger le fichier `index.html` à partir de vos ressources et le frontend fonctionnera essentiellement comme un navigateur à partir de ce point. Il est intéressant de noter que il n'y a pas de condition sur l'emplacement de `embed.FS`. Il est probable que le chemin d'intégration utilise un répertoire imbriqué par rapport au code de votre application principale, comme `frontend/dist`: + +```go title="main.go" +//go:embed all:frontend/dist +var assets embed.FS +``` + +Au démarrage, Wails va itérer les fichiers embarqués à la recherche du répertoire contenant `index.html`. Tous les autres actifs seront chargés par rapport à à ce répertoire. + +Comme les binaires de production utilisent les fichiers contenus dans `embed.FS`, il n'y a aucun fichier externe requis pour être expédié avec l'application. + +Lorsque vous exécutez en mode développement en utilisant la commande `wails dev` , les assets sont chargés à partir du disque, et tous les changements résultent en un "rechargement en direct". L'emplacement des actifs sera déduit de la `embed.FS`. + +Plus de détails peuvent être trouvés dans le [Guide de développement d'applications](guides/application-development.mdx). + +#### Callbacks du cycle de vie de l'application + +Juste avant que le frontend ne soit sur le point de charger `index.html`, un callback est fait à la fonction fournie dans [OnStartup](reference/options.mdx#onstartup). Un contexte standard Go est passé à cette méthode. Ce contexte est requis lors de l'appel à l'exécution, donc une bonne pratique est de sauvegarder une référence dans cette méthode. Juste avant que l'application ne s'arrête, la fonction de rappel [OnShutdown](reference/options.mdx#onshutdown) est appelée de la même manière, à nouveau avec le contexte. Il y a aussi un callback [OnDomReady](reference/options.mdx#ondomready) pour quand le frontend a terminé le chargement de tous les assets de `index.html` et est équivalent à l'événement [`body onload`](https://www.w3schools.com/jsref/event_onload.asp) en JavaScript. Il est également possible de s'accrocher à l'événement de fermeture de la fenêtre (ou de quitter l'application) en définissant l'option [OnBeforeClose](reference/options.mdx#onbeforeclose). + +#### Binding de méthodes + +L'option `Bind` est l'une des options les plus importantes dans une application Wails. Il spécifie quelles méthodes de structs sont à exposer au frontend. Pensez à des "contrôleurs" dans une application web traditionnelle. Quand l'application démarre, elle examine les instances structurées listées dans l'option `Bind`, détermine quelles méthodes sont publiques (commence par une lettre majuscule) et générera des versions JavaScript de ces méthodes qui peuvent être appelées par le code en frontend. + +:::info Note + +Wails exige que vous passiez dans une _instance_ du struct pour qu'il le lie correctement + +::: + +Dans cet exemple, nous créons une nouvelle instance `App` puis ajoutons cette instance à l'option `Bind` dans `wails.Run`: + +```go {17,27} 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) +} +``` + +Vous pouvez lier autant de structures que vous le souhaitez. Assurez-vous juste de créer une instance de celle-ci et de la passer dans `Bind`: + +```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{}, + }, + }) + +``` + +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 +- Déclarations TypeScript pour toutes les méthodes liées +- Définitions TypeScript pour toutes les structures Go utilisées comme entrées ou sorties par les méthodes liées + +Cela rend incroyablement simple d'appeler le code Go depuis le frontend, en utilisant les mêmes structures de données. + +## Le frontend + +### Vue d’ensemble + +Le frontend est une collection de fichiers rendus par webkit. C'est comme un navigateur et un serveur web en un. Il y a virtuellement[^1] aucune limite vis à vis des frameworks ou des bibliothèques que vous pouvez utiliser. Les principaux points d'interaction entre le frontend et votre code Go sont: + +- L'appel des méthodes Go liées +- L'appel des méthodes d'exécution + +### L'appel des méthodes Go liées + +Lorsque vous exécutez votre application avec `wails dev`, il générera automatiquement des liaisons JavaScript pour vos structures dans un répertoire appelé `wailsjs/go` (Vous pouvez aussi le faire en exécutant `wails generate module`). Les fichiers générés reflètent les noms de paquets dans votre application. Dans l'exemple ci-dessus, nous associons `app`, qui a une méthode publique `Greet`. Cela conduira à la génération des fichiers suivants : + +```bash +wailsjs + └─go + └─main + ├─App.d.ts + └─App.js +``` + +Ici nous pouvons voir qu'il y a un dossier `main` qui contient les liaisons JavaScript pour la structure `App` liée, ainsi que que le fichier de déclaration TypeScript pour ces méthodes. Pour appeler `Greet` depuis notre frontend, nous importons simplement la méthode et l'appelons comme une fonction JavaScript régulière: + +```javascript +// ... +import { Greet } from "../wailsjs/go/main/App"; + +function doGreeting(name) { + Greet(name).then((result) => { + // Do something with result + }); +} +``` + +La déclaration en TypeScript vous donne les bons types pour les méthodes paramètres et la valeur retournée : + +```ts +export function Greet(arg1: string): Promise; +``` + +Les méthodes générées retournent une Promise. Un appel réussi entraînera la première valeur de retour de l'appel Go à passer au `resolve` handler. Un appel infructueux est quand une méthode Go qui a un type d'erreur comme valeur de deuxième retour, passe une erreur à l'appelant. Ceci est passé en arrière via le handler `reject`. Dans l'exemple ci-dessus, `Greet` ne retourne qu'un `string` donc l'appel JavaScript ne sera jamais rejeté - à moins que des données non valides ne lui soient passées. + +Tous les types de données sont correctement traduits entre Go et JavaScript. Même les structs. Si vous renvoyez un struct d'un appel Go, il sera retourné à votre frontend en tant que classe JavaScript. + +:::info Note + +Les champs Struct _doivent avoir_ le champ `json` de défini afin de pouvoir l'inclure dans le TypeScript généré. + +Les structures imbriquées anonymes ne sont pas supportées pour le moment. + +::: + +Il est possible d'envoyer des structures à Go. N'importe quelle map/classe JavaScript passée comme argument, sera convertie en son équivalent. Pour faciliter ce processus, en mode `dev` un module TypeScript est généré, définissant tous les types de structures utilisés dans les méthodes liées. En utilisant ce module, il est possible de construire et envoyer des objets JavaScript natifs au code Go. + +Il y a aussi le support des méthodes Go qui utilisent les structures dans leur signature. Toutes les structures Go spécifiées par une méthode liée (que ce soit en tant que paramètres ou types de retour) auront les versions TypeScript automatiques générées dans le module de gestion de code Go. En utilisant ceux-ci, il est possible de partager le même modèle de données entre Go et JavaScript. + +Exemple: Nous mettons à jour notre méthode `Greet` pour accepter une `Person` au lieu d'une chaîne de caractères : + +```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) +} +``` + +Le fichier `wailsjs/go/main/App.js` aura toujours le code suivant : + +```js title="App.js" +export function Greet(arg1) { + return window["go"]["main"]["App"]["Greet"](arg1); +} +``` + +Mais le fichier `wailsjs/go/main/App.d.ts` sera mis à jour avec le code suivant : + +```ts title="App.d.ts" +import { main } from "../models"; + +export function Greet(arg1: main.Person): Promise; +``` + +Comme nous pouvons le voir, le namespace "main" est importé à partir du nouveau fichier "models.ts". Ce fichier contient toutes les définitions de struct utilisées par nos méthodes liées. Dans cet exemple, c'est une struct `Person`. Si nous regardons `models.ts`, nous pouvons voir comment les modèles sont définis : + +```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; + } + } +} +``` + +Tant que vous avez TypeScript dans votre configuration de compilation en frontend, vous pouvez utiliser ces modèles de la manière suivante: + +```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); + }); +} +``` + +La combinaison des liaisons générées et des modèles TypeScript crée un environnement de développement puissant. + +Plus d'informations sur la liaison peuvent être trouvées dans la section [Méthodes de liaison](guides/application-development.mdx#binding-methods) de la [Guide de développement d'applications](guides/application-development.mdx). + +### Appeler les méthodes runtime + +Le runtime JavaScript se trouve dans `window.runtime` et contient de nombreuses méthodes pour faire diverses tâches telles qu'émettre un événement ou effectuer des opérations de journalisation : + +```js title="mycode.js" +window.runtime.EventsEmit("my-event", 1); +``` + +Plus de détails sur l'exécutable JS peuvent être trouvés dans la [Référence d'exécution](reference/runtime/intro). + +[^1]: Il y a un très petit sous-ensemble de bibliothèques qui utilisent des fonctionnalités non prises en charge dans WebViews. Il y a souvent des alternatives et des solutions de contournement pour de tels cas. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..65268c410a7 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +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 +

+ +

+``` + +### 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. + +**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. + +### 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 ! diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..30721c11204 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,241 @@ +--- +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 ` + +## 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 | +|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| -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`.
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). + +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 + +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 +- Un observateur est démarré et déclenchera une reconstruction de votre application de développement s'il détecte des changements dans vos fichiers go +- Un serveur web est lancé sur `http://localhost:34115` qui sert votre application (et pas seulement le frontend) sur http. Cela vous permet d'utiliser les extensions de développement de votre navigateur favori +- Tous les assets de l'application sont chargés à partir du disque. Si elles sont modifiées, l'application se rechargera automatiquement (pas de recompilation). Tous les navigateurs connectés rechargeront également +- Un module JS est généré fournissant les éléments suivants : +- Les méthodes Javascript permettant d'appeler vos méthodes Go avec JSDoc autogénérée, vous fournissant des indications sur les méthodes +- Les versions TypeScript de vos structures Go, qui peuvent être construites et transmises à vos méthodes +- Un second module JS est généré qui fournit une déclaration des méthodes et structures pour l'exécutable +- Sur macOS, il regroupera l'application dans un fichier `.app` et l'exécutera. Il utilisera un `build/darwin/Info.dev.plist` pour le développement. + +| Option | Description | Par défaut | +|:------------------------------------ |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:------------------------ | +| -appargs "args" | Arguments passés à l'application en style shell | | +| -assetdir "./chemin/vers/les/assets" | Sert les assets depuis le répertoire donné au lieu d'utiliser le fichier FS fourni | Valeur dans `wails.json` | +| -browser | Ouvre un navigateur à `http://localhost:34115` au démarrage | | +| -compiler "compiler" | Utiliser un autre compilateur pour compiler, par exemple go1.15beta1 | go | +| -debounce | Le temps d'attente pour le rechargement après qu'une modification d'actif est détectée | 100 (millisecondes) | +| -devserver "host:port" | L'adresse à laquelle lier le serveur de développement wails | "localhost:34115" | +| -extensions | Extensions pour déclencher les rebuilds (séparés par des virgules) | go | +| -forcebuild | Force la compilation de l'application | | +| -frontenddevserverurl "url" | Utiliser l'url du serveur de développement tiers pour servir les actifs, EG Vite | "" | +| -ldflags "flags" | Options supplémentaires à passer au compilateur | | +| -loglevel "loglevel" | Niveau de log à utiliser - Trace, Debug, Info, Warning, Error | Debug | +| -nocolour | Désactiver la couleur dans le terminal | false | +| -noreload | Désactiver le rechargement automatique lorsque les actifs changent | | +| -nosyncgomod | Ne pas synchroniser go.mod avec la version Wails | false | +| -race | Construire avec le détecteur Go race | false | +| -reloaddirs | Répertoires supplémentaires pour déclencher les recharges (séparés par des virgules) | Valeur dans `wails.json` | +| -s | Ignorer la construction du frontend | false | +| -save | Sauvegarde les options `assetdir`, `reloaddirs`, `wailsjsdir`, `debounce`, `devserver` and `frontenddevserverurl` dans `wails.json` pour quelles deviennent les informations par défaut pour les prochaines utilisations. | | +| -skipbindings | Ignorer la génération des liaisons | | +| -tags "extra tags" | Options de construction à passer au compilateur (séparées par des guillemets et des espaces) | | +| -v | Niveau de verbosité (0 - silencieux, 1 - par défaut, 2 - verbeux) | 1 | +| -wailsjsdir | Le répertoire où stocker les modules JS Wails générés | Valeur dans `wails.json` | + +Exemple: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +Cette commande fera ce qui suit : + +- Construisez l'application et exécutez-la (plus de détails [ici](../guides/manual-builds.mdx) +- Générer les modules JS Wails dans `./frontend/src` +- Surveillez les mises à jour des fichiers dans `./frontend/dist` et rechargez en cas de changement +- Ouvre un navigateur et se connecte à l'application + +Il y a plus d'informations sur l'utilisation de cette fonctionnalité avec les scripts de framework existants [ici](../guides/application-development.mdx#live-reloading). + +## generate + +### template + +Wails utilise des modèles pour la génération de projets. La commande `wails génère le template` aide à échafauder un modèle afin que il puisse être utilisé pour générer des projets. + +| Option | Description | +|:---------------- |:-------------------------------------------------------- | +| -name | Le nom du modèle (Obligatoire) | +| -frontend "path" | Chemin vers le projet frontend à utiliser dans le modèle | + +Pour plus de détails sur la création de modèles, consultez le [Guide sur les modèles](../guides/templates.mdx). + +### module + +La commande `wails génère le module` vous permet de générer manuellement le répertoire `wailsjs` pour votre application. + +## update + +`wails update` va mettre à jour la version du CLI Wails. + +| Option | Description | +|:------------------ |:----------------------------------------------------- | +| -pre | Mettre à jour la version avec la dernière pre-release | +| -version "version" | Installer une version spécifique du CLI | + +## version + +`wails version` va simplement afficher la version actuelle du CLI. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..80dbaa0c5cf --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# Menus + +Il est possible d'ajouter un menu applicatif aux projets Wails. Ceci est réalisé en définissant une structure [Menu](#menu) et en la définissant dans la configuration de l'application [`Menu`](../reference/options.mdx#menu) , ou en appelant la méthode d'exécution [MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu). + +Un exemple de définition d'un menu : + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +Il est également possible de mettre à jour dynamiquement le menu, en mettant à jour le menu struct et en appelant [MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu). + +L'exemple ci-dessus utilise des méthodes d'aide, cependant il est possible de construire le menu manuellement. + +## Menu + +Un Menu est une collection de MenuItems: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +Pour le menu de l'application, chaque MenuItem représente un seul menu tel que "Edit". + +Une méthode simple d'aide est fournie pour les menus de construction : + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +Cela rend la mise en page du code plus semblable à celle d'un menu sans avoir à ajouter les éléments de menu manuellement après leur création. Vous pouvez également créer les liens de menu et les ajouter au menu manuellement. + +## MenuItem + +Un MenuItem représente un élément dans un 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 +} +``` + +| Champ | Type | Notes | +| ----------- | ------------------------------------ | --------------------------------------------------------------------------------------- | +| Label | string | Le texte du menu | +| Accelerator | [\*keys.Accelerator](#accelerator) | Raccourci pour ce lien de menu | +| Type | [Type](#type) | Type de MenuItem | +| Disabled | bool | Désactive l'élément de menu | +| Hidden | bool | Masque cet élément de menu | +| Checked | bool | Ajoute une coche à l'élément (case à cocher & Types de radio) | +| SubMenu | [\*Menu](#menu) | Définit un sous-menu | +| Click | [Callback](#callback) | Fonction à appeler quand un click est fait sur cet élément du menu. | +| Role | string | Définit un rôle [](#role) pour cet élément de menu. Pour Mac seulement, pour le moment. | + +### Accelerator + +Les accélérateurs (parfois appelés raccourcis clavier) définissent une liaison entre une clé et un élément du menu. Wails définit un accélérateur comme une combinaison ou une clé + [modificateur](#modifier). Ils sont disponibles dans le paquet `"github.com/wailsapp/wails/v2/pkg/menu/keys"`. + +Exemple: + +```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") +``` + +Les clés sont n'importe quel caractère sur un clavier à l'exception de `+`, qui est défini comme `plus`. Certaines clés ne peuvent pas être représentées comme des caractères, il y a donc un ensemble de caractères nommés qui peuvent être utilisés : + +| | | | | +|:----------------:|:-----:|:-----:|:---------:| +| `retour arrière` | `f1` | `f16` | `f31` | +| `tabulation` | `f2` | `f17` | `f32` | +| `retour` | `f3` | `f18` | `f33` | +| `entrée` | `f4` | `f19` | `f34` | +| `echap` | `f5` | `f20` | `f35` | +| `gauche` | `f6` | `f21` | `numlock` | +| `droite` | `f7` | `f22` | | +| `haut` | `f8` | `f23` | | +| `bas` | `f9` | `f24` | | +| `espace` | `f10` | `f25` | | +| `suppr` | `f11` | `f36` | | +| `début` | `f12` | `f37` | | +| `fin` | `f13` | `f38` | | +| `page haut` | `f14` | `f39` | | +| `page bas` | `f15` | `f30` | | + +Wails prend également en charge l'analyse des accélérateurs en utilisant la même syntaxe qu'Electron. Ceci est utile pour stocker les accélérateurs dans les fichiers de configuration . + +Exemple: + +```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 + +Les modificateurs suivants sont des touches qui peuvent être utilisées en combinaison avec la touche accélérateur: + +```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" +) +``` + +Un certain nombre de méthodes d'aide sont disponibles pour créer des accélérateurs en utilisant des modificateurs: + +```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 +``` + +Les modificateurs peuvent être combinés en utilisant `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 + +Chaque lien de menu doit avoir un type et il y a 5 types disponibles: + +```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" +) +``` + +Pour plus de commodité, des méthodes d'aide sont fournies pour créer rapidement un lien de menu : + +```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 +``` + +Vous pouvez également créer des liens directement dans un menu en utilisant les méthodes "Add" : + +```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 +``` + +Une note sur les groupes radio : Un groupe radio est défini comme un certain nombre d'éléments du menu radio qui sont à côté l'un de l'autre dans le menu. Cela signifie que vous n'avez pas besoin de regrouper les éléments car il est automatique. Cependant, cela signifie également que vous ne pouvez pas avoir 2 groupes radio les uns à côté des autres - il doit y avoir un élément non-radio entre eux. + +### Callback + +Chaque lien de menu peut avoir une fonction qui est exécutée lorsque l'élément est cliqué : + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +La fonction reçoit une structure `CallbackData` qui indique quel élément de menu a été cliqué. Ceci est utile lorsque utilise des groupes radio qui peuvent partager une fonction. + +### Role + +:::info Roles + +Les rôles ne sont actuellement pris en charge que sur Mac. + +::: + +Un lien de menu peut avoir un rôle, qui est essentiellement un lien de menu prédéfini. Nous supportons actuellement les rôles suivants : + +| Role | Description | +| ------------ | ----------------------------------------------------------------------------------- | +| AppMenuRole | Le menu standard de l'application Mac. Peut être créé en utilisant `menu.AppMenu()` | +| EditMenuRole | Le menu d'édition standard pour Mac. Peut être créé en utilisant `menu.EditMenu()` | diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..a80e3526732 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,853 @@ +--- +sidebar_position: 3 +--- + +# Options + +## Options de l'application + +La structure `Options.App` contient la configuration de l'application. Il est passé à la méthode `wails.Run()`: + +```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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### Title + +Le texte affiché dans la barre de titre de la fenêtre. + +Nom : Title
Type : `string` + +### Width + +La largeur initiale de la fenêtre. + +Nom: Width
Type: `int`
Défaut: 1024. + +### Height + +La hauteur initiale de la fenêtre. + +Nom: Height
Type: `int`
Défaut: 768 + +### DisableResize + +Par défaut, la fenêtre principale est redimensionnable. Mettre ceci à `true` le conservera une taille fixe. + +Nom: DisableResize
Type: `bool` + +### Fullscreen + +Obsolète: Veuillez utiliser [WindowStartState](#windowstartstate). + +### WindowStartState + +Définit comment la fenêtre devrait se présenter au démarrage. + +| Valeur | Win | Mac | Lin | +| ---------- | --- | --- | --- | +| Fullscreen | ✅ | ✅ | ✅ | +| Maximised | ✅ | ✅ | ✅ | +| Minimised | ✅ | ❌ | ✅ | + +Nom: WindowStartState
Type: `options.WindowStartState` + +### Frameless + +Quand réglé sur `true`, la fenêtre n'aura pas de bordure ou de barre de titre. Voir aussi les [fenêtres sans cadre sous Windows](../guides/frameless.mdx). + +Nom: Frameless
Type: `bool` + +### MinWidth + +Définit la largeur minimale de la fenêtre. Si la valeur donnée dans `Width` est inférieure à cette valeur, la fenêtre sera définie à `MinWidth` par défaut. + +Nom: MinWidth
Type: `int` + +### MinHeight + +Définit la hauteur minimale de la fenêtre. Si la valeur donnée dans `Height` est inférieure à cette valeur, la fenêtre sera définie à `MinHeight` par défaut. + +Nom: MinHeight
Type: `int` + +### MaxWidth + +Définit la largeur maximale de la fenêtre. Si la valeur donnée dans `Width` est supérieure à cette valeur, la fenêtre sera définie à `MaxWidth` par défaut. + +Nom: MaxWidth
Type: `int` + +### MaxHeight + +Définit la hauteur maximale de la fenêtre. Si la valeur donnée en `Height` est supérieure à cette valeur, la fenêtre sera définie à `MaxHeight` par défaut. + +Nom: MaxHeight
Type: `int` + +### StartHidden + +Lorsque réglé sur `true`, l'application sera masquée jusqu'à ce que [WindowShow](../reference/runtime/window.mdx#windowshow) soit appelé. + +Nom: StartHidden
Type: `bool` + +### HideWindowOnClose + +Par défaut, la fermeture de la fenêtre fermera l'application. Définir ceci à `true` signifie que + +la fenêtre sera cachée à la place. + +Nom: HideWindowOnClose
Type: `bool` + +### BackgroundColour + +Cette valeur est la couleur de fond par défaut de la fenêtre. Exemple: options.NewRGBA(255,0,0,128) - Rouge à 50% de transparence + +Nom: BackgroundColour
Type: `*options.RGBA`
Défaut: white + +### AlwaysOnTop + +Indique que la fenêtre doit rester au-dessus des autres fenêtres lors de la perte de focus. + +Nom: AlwaysOnTop
Type: `bool` + +### Assets + +Obsolète: Veuillez utiliser des actifs sur les options [AssetServer spécifiques](#assetserver). + +### AssetsHandler + +Obsolète : Veuillez utiliser AssetsHandler sur [Options spécifiques à AssetServer](#assetserver). + +### AssetServer + +Ceci définit les options spécifiques à AssetServer. Il permet de personnaliser l'AssetServer avec des actifs statiques, servant les assets dynamiquement avec un `http.Handler` ou brancher dans la chaîne de requêtes avec un `assetserver.Middleware`. + +Toutes les fonctionnalités d'une `http.Request` ne sont pas actuellement prises en charge, veuillez consulter la matrice de fonctionnalité suivante : + +| Fonctionalité | Win | Mac | Lin | +| ----------------------- | --- | --- | ------ | +| GET | ✅ | ✅ | ✅ | +| POST | ✅ | ✅ | ✅ [^1] | +| PUT | ✅ | ✅ | ✅ [^1] | +| PATCH | ✅ | ✅ | ✅ [^1] | +| DELETE | ✅ | ✅ | ✅ [^1] | +| Request Headers | ✅ | ✅ | ✅ [^1] | +| Request Body | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +Nom: AssetServer
Type: `*assetserver.Options` + +#### Assets + +Les ressources statiques du frontend à être utilisées par l'application. + +Une requête GET est d'abord tentée d'être servie à partir de ce `fs.FS`. Si le `fs.FS` retourne `os. rrNotExist` pour ce fichier, le traitement des requêtes va revenir au [Handler](#handler) et essaie de répondre à la requête GET. + +Si la valeur est nulle, toutes les requêtes GET seront envoyées à [Handler](#handler). + +Nom: Assets
Type: `fs.FS` + +#### Handler + +Le gestionnaire d'assets est un `http.Handler` générique pour la gestion de secours des assets qui ne peuvent pas être trouvés. + +Le gestionnaire sera appelé pour chaque requête GET qui ne peut pas être servie à partir de [Assets](#assets), en raison de `os.ErrNotExist`. De plus, toutes les requêtes non GET seront toujours servies par ce gestionnaire. Si non défini, le résultat est le suivant dans les cas où le Gestionnaire aurait été appelé : + +- Requête GET : `http.StatusNotFound` +- Autre requête : `http.StatusMethodNotAllowed` + +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
Type: `http.Handler` + +#### Middleware + +Middleware est un Middleware HTTP qui permet de se connecter à la chaîne de requêtes AssetServer. Il permet de sauter dynamiquement le gestionnaire de requête par défaut, par exemple implémenter un routage spécialisé, etc. Le Middleware est appelé pour construire un nouveau `http.Handler` utilisé par l'AssetSever et reçoit également le gestionnaire par défaut utilisé par le serveur AssetServer comme argument. + +Si elle n'est pas définie, la chaîne de requête AssetServer par défaut est exécutée. + +Nom: Middleware
Type: `assetserver.Middleware` + +### Menu + +Le menu à utiliser par l'application. Plus de détails sur les menus dans la [Référence des Menu](../reference/runtime/menu.mdx). + +:::note + +Sur Mac, si aucun menu n'est spécifié, un menu par défaut sera créé. + +::: + +Nom: Menu
Type: `*menu.Menu` + +### Logger + +Le logger à utiliser par l'application. Plus de détails sur la connexion dans la [Référence du logger](../reference/runtime/log.mdx). + +Nom: Logger
Type: `logger.Logger`
Défaut: Logs envoyé à Stdout + +### LogLevel + +Le niveau de log par défaut. Plus de détails sur la connexion dans la [Référence du logger](../reference/runtime/log.mdx). + +Nom: LogLevel
Type: `logger.LogLevel`
Défaut: `Info` en mode dev, `Error` en mode production + +### LogLevelProduction + +Le niveau de log par défaut pour les compilations de production. Plus de détails sur la connexion dans la [Référence du logger](../reference/runtime/log.mdx). + +Nom: LogLevelProduction
Type: `logger.LogLevel`
Défaut: `Error` + +### OnStartup + +Ce callback est appelé après la création du frontend, mais avant que `index.html` n'ait été chargé. Il lui donne le contexte de l'application. + +Nom: OnStartup
Type: `func(ctx context.Context)` + +### OnDomReady + +Ce callback est appelé après que le frontend ait chargé `index.html` et ses ressources. Il lui donne le contexte de l'application. + +Nom: OnDomReady
Type: `func(ctx context.Context)` + +### OnShutdown + +Ce calllback est appelé après que le frontend ait été détruit, juste avant la fin de l'application. Il lui donne le contexte de l'application. + +Nom: OnShutdown
Type: `func(ctx context.Context)` + +### OnBeforeClose + +Si ce callback est défini, il sera appelé lorsque l'application est sur le point de quitter, soit en cliquant sur la fenêtre fermez le bouton ou en appelant `runtime.Quit`. Retourner "true" dans cette méthode entraînera la poursuite de l'application, "false" continuera à éteindre comme d'habitude. C'est un bon exemple pour confirmer avec l'utilisateur si il souhaite quitter le programme. + +Exemple: + +```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" +} +``` + +Nom: OnBeforeClose
Type: `func(ctx context.Context) bool` + +### CSSDragProperty + +Indique la propriété CSS à utiliser pour identifier quels éléments peuvent être utilisés pour faire glisser la fenêtre. Par défaut : `--wails-draggable`. + +Nom: CSSDragProperty
Type: `string` + +### CSSDragValue + +Indique quelle valeur le style `CSSDragProperty` doit avoir pour faire glisser la fenêtre. Par défaut: `drag`. + +Nom: CSSDragValue
Type: `string` + +### EnableDefaultContextMenu + +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. + +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 : + +| Style CSS | Comportement | +| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--default-contextmenu: auto;` | (**défaut**) n'affichera le menu contextuel par défaut que si :
contentEditable est vrai OU le texte a été sélectionné OU l'élément est entrée ou la zone de texte | +| `--default-contextmenu: show;` | affichera toujours le menu de contexte par défaut | +| `--default-contextmenu: hide;` | masquera toujours le menu contextuel par défaut | + +Cette règle est héritée comme n'importe quelle règle CSS normale, donc l'imbrication fonctionne comme prévu. + +:::note +Cette fonctionnalité de filtrage n'est activée qu'en production, donc en développement et en construction de débogage, le menu contextuel complet est toujours disponible partout. +::: + +:::warning +Cette fonctionnalité de filtrage n'est PAS une mesure de sécurité, le développeur devrait s'attendre à ce que le menu contextuel complet puisse être divulgué à tout moment qui pourrait contenir des commandes comme (Télécharger l'image, Recharger, Enregistrer la page web), si c'est une préoccupation, le développeur DEVRAIT NE PAS activer le menu contextuel par défaut. +::: + + +Nom: EnableDefaultContextMenu
Type: `bool` + +### EnableFraudulentWebsiteDetection + +EnableFraudulentWebWebDetection permet de rechercher des contenus frauduleux, tels que des programmes malveillants ou des tentatives d'hameçonnage. Ces services peuvent envoyer des informations à partir de votre application, telles que les URL vers lesquelles vous avez navigué et éventuellement d'autres contenus vers le cloud, des services d'Apple et de Microsoft. + +Nom: EnableFraudulentWebsiteDetection
Type: `bool` + +### ZoomFactor + +Nom: ZoomFactor
Type: `float64` + +Ceci définit le facteur de zoom pour WebView2. Il s'agit de l'option correspondant au zoom avant ou arrière défini par l'utilisateur. + +### IsZoomControlEnabled + +Nom : IsZoomControlEnabled
Type : `bool` + +Cela permet de modifier le facteur de zoom par l'utilisateur. Veuillez noter que le facteur de zoom peut être défini dans les options tandis que ne permet pas à l'utilisateur de le modifier à l'exécution (f.e. pour une application vitrine ou similaire). + +### Bind + +La liste des structs Go définissant des méthodes qui doivent être liées au frontend. + +Nom: Bind
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
Type: `func (error) any` + +### Windows + +Ceci définit les options [spécifiques à Windows](#windows). + +Nom: Windows
Type: `*windows.Options` + +#### WebviewIsTransparent + +Mettre ceci à `true` rendra l'arrière-plan du webview transparent quand une valeur alpha de `0` est utilisée. Cela signifie que si vous utilisez `rgba(0,0,0,0)` pour `la couleur d'arrière-plan` dans votre CSS, la fenêtre d'hôte sera affichée. Souvent combiné avec [WindowIsTranslucent](#WindowIsTranslucent) pour faire des applications d'apparence de givre. + +Nom : WebviewIsTransparent
Type : `bool` + +#### WindowIsTranslucent + +Définir ceci à `true` rendra l'arrière-plan de la fenêtre translucide. Souvent combiné avec [WebviewIsTransparent](#WebviewIsTransparent). + +Pour les versions de Windows 11 avant la version 22621, cela utilisera la méthode [BlurBehind](https://learn.microsoft.com/en-us/windows/win32/dwm/blur-ovw) pour la translucidité, qui peut être lente. Pour les versions de Windows 11 après la version 22621, cela activera les nouveaux types de transparence qui sont beaucoup plus rapides. Par défaut, le type de transparence utilisé sera déterminé par Windows. Pour configurer ceci, utilisez l'option [BackdropType](#BackdropType). + +Nom: WindowIsTranslucent
Type: `bool` + +#### BackdropType + +:::note + +Nécessite Windows 11 version 22621 ou supérieure. + +::: + +Définit le type de transparence de la fenêtre. Ceci n'est applicable que si [WindowIsTranslucent](#WindowIsTranslucent) est défini à `true`. + +Nom: BackdropType
Type `windows.BackdropType` + +La valeur peut être l'une des valeurs suivantes : + +| Valeur | Description | +| ------- | ------------------------------------------------------------------------------------------------- | +| Auto | Laisser Windows décider quel arrière-plan utiliser | +| None | Ne pas utiliser de transparence | +| Acrylic | Utilisez l'effet [Acrylique](https://learn.microsoft.com/en-us/windows/apps/design/style/acrylic) | +| 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. | + +#### DisableWindowIcon + +Définir ceci à `true` supprimera l'icône dans le coin supérieur gauche de la barre de titre. + +Nom: DisableWindowIcon
Type: `bool` + +#### DisableFramelessWindowDecorations + +Définir ceci à `true` supprimera les décorations de fenêtre en mode [sans cadre](#Frameless). Cela signifie qu'il n'y aura pas de « Aero Shadow» et aucun « Coins arrondis» ne sera affiché pour la fenêtre. Veuillez noter que les "coins arrondis" ne sont pris en charge que sur Windows 11. + +Nom: DisableFramelessWindowDecorations
Type: `bool` + +#### WebviewUserDataPath + +Ceci définit le chemin où WebView2 stocke les données de l'utilisateur. Si vide, `%APPDATA%\[BinaryName.exe]` sera utilisé. + +Nom: WebviewUserDataPath
Type: `string` + +#### WebviewBrowserPath + +Ceci définit le chemin vers un répertoire avec les fichiers exécutables et bibliothèques WebView2. Si l'option est vide, l'instance de webview2 installé dans le système sera utilisé. + +Informations importantes sur la version corrigée : + +- [Comment récupérer et extraire l'exécutable](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#details-about-the-fixed-version-runtime-distribution-mode) +- [Problèmes connus pour la version corrigée](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#known-issues-for-fixed-version) +- [Le chemin de la version corrigée du runtime WebView2 ne doit pas contenir \Edge\Application\.](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/webview2-idl?view=webview2-1.0.1245.22#createcorewebview2environmentwithoptions) + +Nom: WebviewBrowserPath
Type: `string` + +#### Theme + +Version minimale de Windows : Windows 10 2004/20H1 + +Ceci définit le thème que l'application doit utiliser : + +| Valeur | Description | +| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| SystemDefault | _Default_. Le thème sera basé sur la valeur par défaut du système. Si l'utilisateur change de thème, l'application se mettra à jour pour utiliser le nouveau paramètre | +| Dark | L'application utilisera uniquement un thème sombre | +| Light | L'application utilisera uniquement un thème clair | + +Nom: Theme
Type: `windows.Theme` + +#### CustomTheme + +:::note + +Version minimale de Windows : Windows 10/11 2009/21H2 Build 22000 + +::: + +Vous permet de spécifier des couleurs personnalisées pour la barre de titre, le texte de titre et la bordure pour le mode clair et foncé. ainsi que lorsque la fenêtre est active ou inactive. + +Nom: CustomTheme
Type: `windows.CustomTheme` + +##### Type CustomTheme + +Le struct CustomTheme utilise `int32` pour spécifier les valeurs de couleurs. Celles-ci sont au format standard(!) Windows soit : `0x00BBGGAA`. Une fonction d'aide est fournie pour effectuer les conversions de RGB dans ce format : `windows.RGB(r,g,b uint8)`. + +NOTE : Toute valeur non fournie sera par défaut noire. + +```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 +} +``` + +Exemple: + +```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 + +Un struct de chaînes utilisées par l'installateur webview2 si un runtime webview2 valide n'est pas trouvé. + +Nom: Messages
Type: `*windows.Messages` + +Personnalisez ceci pour n'importe quelle langue que vous choisissez de supporter. + +#### ResizeDebounceMS + +ResizeDebounceMS est le temps entre deux réajustements du contenu de la fenêtre lors du redimensionnement de la fenêtre. La valeur par défaut (0) effectuera des réajustements aussi vite qu'il le peut. + +Nom: ResizeDebounceMS
Type: `uint16` + +#### OnSuspend + +Si défini, cette fonction sera appelée lorsque Windows passera en mode économie d'énergie + +Nom: OnSuspend
Type: `func()` + +#### OnResume + +Si défini, cette fonction sera appelée lorsque Windows sortira du mode économie d'énergie + +Nom: OnResume
Type: `func()` + +#### WebviewGpuIsDisabled + +Définir ceci à `true` désactivera l'accélération matérielle GPU pour la webview. + +Nom: WebviewGpuIsDisabled
Type: `bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +Ceci définit [les options spécifiques à Mac](#mac). + +Nom: Mac
Type: `*mac.Options` + +#### TitleBar + +La structure TitleBar permet de configurer l'apparence de la barre de titre. + +Nom: TitleBar
Type: [`*mac.TitleBar`](#titlebar-struct) + +##### Struct de la Titlebar + +La barre de titre de l'application peut être personnalisée en utilisant les options suivantes de TitleBar : + +```go +type TitleBar struct { + TitlebarAppearsTransparent bool + HideTitle bool + HideTitleBar bool + FullSizeContent bool + UseToolbar bool + HideToolbarSeparator bool +} +``` + +| Nom | Description | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| TitlebarAppearsTransparent | Rend la barre de titre transparente. Cela a pour effet de masquer la barre de titre et le contenu remplit la fenêtre. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindow/1419167-titlebarappearstransparent?language=objc) | +| HideTitle | Masque le titre de la fenêtre. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindowtitlevisibility?language=objc) | +| HideTitleBar | Supprime [NSWindowStyleMaskTitled](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktitled/) du style | +| FullSizeContent | Fait que la webview remplisse toute la fenêtre. [Apple Docs](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemaskfullsizecontentview) | +| UseToolbar | Ajoute une barre d'outils par défaut à la fenêtre. [Apple Docs](https://developer.apple.com/documentation/appkit/nstoolbar?language=objc) | +| HideToolbarSeparator | Supprime la ligne située sous la barre d'outils. [Apple Docs](https://developer.apple.com/documentation/appkit/nstoolbar/1516954-showsbaselineseparator?language=objc) | + +Des paramètres préconfigurés sont disponibles : + +| Configuration | Exemple | +| --------------------------- | ---------------------------------------------- | +| `mac.TitleBarDefault()` | ![](/img/reference/titlebar-default.webp) | +| `mac.TitleBarHidden()` | ![](/img/reference/titlebar-hidden.webp) | +| `mac.TitleBarHiddenInset()` | ![](/img/reference/titlebar-hidden-inset.webp) | + +Exemple: + +```go +Mac: &mac.Options{ + TitleBar: mac.TitleBarHiddenInset(), +} +``` + +Cliquez sur [ici](https://github.com/lukakerr/NSWindowStyles) si vous voulez de l'inspiration sur la personnalisation de la barre de titre. + +#### Appearance + +L'apparence est utilisée pour définir le style de votre application en accord avec les noms [NSAppearance](https://developer.apple.com/documentation/appkit/nsappearancename?language=objc) d'Apple. + +Nom: Appearance
Type: [`mac.AppearanceType`](#appearance-type) + +##### Type d'Appearance + +Vous pouvez spécifier l'apparence [de l'application](https://developer.apple.com/documentation/appkit/nsappearance?language=objc). + +| Valeur | Description | +| ----------------------------------------------------- | ------------------------------------------------------------------- | +| DefaultAppearance | DefaultAppararance utilise la valeur système par défaut | +| NSAppearanceNameAqua | Utilise l'apparence thème clair standard | +| NSAppearanceNameDarkAqua | Utilise l'apparence thème sombre standard | +| NSAppearanceNameVibrantLight | Utilise une apparence avec une lumière vibrante | +| NSAppearanceNameAccessibilityHighContrastAqua | Utilise l'apparence thème clair standard avec un constrate élevé | +| NSAppearanceNameAccessibilityHighContrastDarkAqua | Utilise l'apparence thème sombre standard avec un contraste élevé | +| NSAppearanceNameAccessibilityHighContrastVibrantLight | Utilise l'apparence lumière vibrante avec un constrate élevé | +| NSAppearanceNameAccessibilityHighContrastVibrantDark | Utilise l'apparence du thème sombre vibrant avec un constrate élevé | + +Exemple: + +```go +Mac: &mac.Options{ + Appearance: mac.NSAppearanceNameDarkAqua, +} +``` + +#### WebviewIsTransparent + +Mettre ceci à `true` rendra l'arrière-plan du webview transparent quand une valeur alpha de `0` est utilisée. Cela signifie que si vous utilisez `rgba(0,0,0,0)` pour `la couleur d'arrière-plan` dans votre CSS, la fenêtre d'hôte sera affichée. Souvent combiné avec [WindowIsTranslucent](#WindowIsTranslucent) pour faire des applications d'apparence de givre. + +Nom : WebviewIsTransparent
Type : `bool` + +#### WindowIsTranslucent + +Définir ceci à `true` rendra l'arrière-plan de la fenêtre translucide. Souvent combiné avec [WebviewIsTransparent](#WebviewIsTransparent) pour donner un aspect givré à la fenêtre. + +Nom: WindowIsTranslucent
Type: `bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled 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) | + +Exemple: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### About + +Cette configuration vous permet de définir le titre, le message et l'icône pour l'élément de menu "À propos" dans le menu de l'application créé par le rôle "AppMenu". + +Nom: About
Type: [`*mac.AboutInfo`](#about-struct) + +##### Struct de About + +```go + +type AboutInfo struct { + Title string + Message string + Icon []byte +} +``` + +Si ces paramètres sont fournis, un lien de menu "À propos" apparaîtra dans le menu de l'application (lors de l'utilisation du rôle `AppMenu`). Exemple: + +```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, + }, + }, + }) +``` + +L'élément de menu "À propos" apparaîtra dans le menu de l'application: + +```mdx-code-block +
+ +
+
+``` + +Lorsqu'il est cliqué, cela ouvrira la boîte de message "à propos" : + +```mdx-code-block +
+ +
+
+``` + +### Linux + +Ceci définit [les options spécifiques à Linux](#linux). + +Nom: Linux
Type: `*linux.Options` + +#### Icon + +Définit l'icône représentant la fenêtre. Cette icône est utilisée lorsque la fenêtre est réduite (aussi appelée iconified). + +Nom: Icon
Type: `[]byte` + +Certains gestionnaires de fenêtres ou environnements de bureau peuvent également le placer dans le cadre de la fenêtre, ou l'afficher dans d'autres contextes. Sur d'autres, l'icône n'est pas du tout utilisée, donc son utilisation peut varier. + +NOTE : Gnome sur Wayland n'affiche pas cette icône. Pour y avoir une icône d'application, un fichier `.desktop` doit être utilisé. Sous KDE, cela devrait fonctionner. + +L’icône doit être fournie dans la taille qu’elle a été dessinée naturellement, c’est-à-dire ne pas redimensionner l’image avant de la passer. La mise à l'échelle est reportée à la dernière minute, lorsque la taille finale désirée est connue, pour permettre une meilleure qualité. + +#### WindowIsTranslucent + +Définir ceci à `true` rendra l'arrière-plan de la fenêtre translucide. Certains gestionnaires de fenêtres peuvent l'ignorer, ou résulter en une fenêtre noire. + +Nom: WindowIsTranslucent
Type: `bool` + +#### WebviewGpuPolicy + +Cette option est utilisée pour déterminer la politique d'accélération matérielle effectuée par webview. + +Nom: WebviewGpuPolicy
Type: [`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
Défaut: `WebviewGpuPolicyAlways` + +##### Type de WebviewGpuPolicy + +| Valeur | Description | +| ------------------------ | ---------------------------------------------------------------------------- | +| WebviewGpuPolicyAlways | L'accélération matérielle est toujours activée | +| WebviewGpuPolicyOnDemand | L'accélération matérielle est activée/désactivée à la demande du contenu web | +| WebviewGpuPolicyNever | L'accélération matérielle est toujours désactivée | + +#### 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). + +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. + +Name: ProgramName
Type: string
+ +### Debug + +Ceci définit [les options spécifiques au débogage](#Debug) qui s'appliquent aux compilations de débogage. + +Nom: Debug
Type: `options.Debug` + +#### OpenInspectorOnStartup + +Définir cette option à `true` ouvrira l'inspecteur Web au démarrage de l'application. + +Nom: OpenInspectorOnStartup
Type: `bool` + +[^1]: Cela nécessite la prise en charge de WebKit2GTK 2.36+ et votre application doit être construite avec la balise de compilation `webkit2_36` pour activer le support de cette fonctionnalité. Cela augmente aussi la version minnimale de WebKit2GTK à 2.36 pour votre application. +[^2]: Cela nécessite la prise en charge de WebKit2GTK 2.40+ et votre application doit être construite avec la balise de compilation `webkit2_40` pour activer le support de cette fonctionnalité. Cela augmente aussi la version minnimale de WebKit2GTK à 2.40 pour votre application. [ [ ↩](#fnref2:2){.footnote-backref} ↩](#fnref:2){.footnote-backref} diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..a5f067dd870 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,92 @@ +--- +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 : + +```json5 +{ + // Project config version + "version": "", + // The project name + "name": "", + // Relative path to the directory containing the compiled assets, this is normally inferred and could be left empty + "assetdir": "", + // Additional directories to trigger reloads (comma separated), this is only used for some advanced asset configurations + "reloaddirs": "", + // The directory where the build files reside. Defaults to 'build' + "build:dir": "", + // Relative path to the frontend directory. Defaults to 'frontend' + "frontend:dir": "", + // The command to install node dependencies, run in the frontend directory - often `npm install` + "frontend:install": "", + // The command to build the assets, run in the frontend directory - often `npm run build` + "frontend:build": "", + // This command has been replaced by frontend:dev:build. If frontend:dev:build is not specified will falls back to this command. \nIf this command is also not specified will falls back to frontend:build + "frontend:dev": "", + // This command is the dev equivalent of frontend:build. If not specified falls back to frontend:dev + "frontend:dev:build": "", + // This command is the dev equivalent of frontend:install. If not specified falls back to frontend:install + "frontend:dev:install": "", + // This command is run in a separate process on `wails dev`. Useful for 3rd party watchers or starting 3d party dev servers + "frontend:dev:watcher": "", + // URL to a 3rd party dev server to be used to serve assets, EG Vite. \nIf this is set to 'auto' then the devServerUrl will be inferred from the Vite output + "frontend:dev:serverUrl": "", + // Relative path to the directory that the auto-generated JS modules will be created + "wailsjsdir": "", + // The name of the binary + "outputfilename": "", + // The default time the dev server waits to reload when it detects a change in assets + "debounceMS": 100, + // Address to bind the wails dev sever to. Default: localhost:34115 + "devServer": "", + // Arguments passed to the application in shell style when in dev mode + "appargs": "", + // Defines if build hooks should be run though they are defined for an OS other than the host OS. + "runNonNativeBuildHooks": false, + "preBuildHooks": { + // The command that will be executed before a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH". + "*/*": "" + }, + "postBuildHooks": { + // The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. + "*/*": "" + }, + // Data used to populate manifests and version info. + "info": { + // The company name. Default: [The project name] + "companyName": "", + // The product name. Default: [The project name] + "productName": "", + // The version of the product. Default: '1.0.0' + "productVersion": "", + // The copyright of the product. Default: 'Copyright.........' + "copyright": "", + // A short comment of the app. Default: 'Built using Wails (https://wails.app)' + "comments": "" + }, + // '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": "" +} +``` + +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). diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..ab2da957dd4 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +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)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..c37399d0bf0 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# Clipboard + +Cette partie du runtime fournit un accès au presse-papiers du système d'exploitation.
L'implémentation actuelle ne gère que le texte. + +### ClipboardGetText + +Cette méthode lit le texte actuellement stocké dans le presse-papiers. + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
Retourne: une chaîne de caractères (si le presse papier est vide, il retournera une chaîne vide) ou une erreur. + +JS: `ClipboardGetText(): Promise`
Retourne : Un promise d'une chaine de caractères (si le presse papier est vide, il retournera une chaîne vide). + +### ClipboardSetText + +Cette méthode écrit du texte dans le presse-papiers. + +Go: `ClipboardSetText(ctx context.Context, text string) error`
Retourne: Une erreur si il y en a une. + +JS: `ClipboardSetText(text: string): Promise`
Retourne: Un promise avec true si le texte a été écrit avec succès dans le presse papier, autrement il contiendra false. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..1bbc6522e0f --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +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 a des boites de dialogue standard dans lesquels les boutons ne sont pas personnalisables. La valeur retournée sera une des valeurs suivantes : "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" ou "Continue". + +Pour les boites de dialogues pour les questions, le bouton par défaut est "Oui" et le bouton d'annulation est "Non". Cela peut être modifié en définissant la valeur `DefaultButton` à `"No"`. + +Exemple: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linux a des boites de dialogue standard dans lesquels les boutons ne sont pas personnalisables. La valeur retournée sera de :"Ok", "Cancel", "Yes", "No" + +#### Mac + +Une boîte de dialogue sur Mac peut avoir jusqu'à 4 boutons. Si aucun `DefaultButton` ou `CancelButton` n'est donné, le premier bouton est considéré comme par défaut et est lié à la touche `entrée`. + +Pour le code suivant : + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "C'est ton tour", + Message: "Choisi un nombre", + Buttons: []string{"un", "deux", "trois", "quatre"}, +}) +``` + +le premier bouton est affiché comme étant celui par défaut : + +```mdx-code-block +
+ +
+
+``` + +Et si nous spécifions que le `DefaultButton` est "deux": + +```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", +}) +``` + +le deuxième bouton est affiché comme étant la réponse par défaut. Lorsque la touche `entrée` est appuyée, la valeur "deux" est retournée. + +```mdx-code-block +
+ +
+
+``` + +Si nous spécifions maintenant `CancelButton` à "trois": + +```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", +}) +``` + +le bouton avec "trois" est affiché en bas de la boîte de dialogue. Si la touche `echap` est appuyée, la valeur "trois" est retournée: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### 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 vous permet d'utiliser plusieurs filtres de fichiers dans les boîtes de dialogue. Chaque FileFilter s'affichera comme une entrée séparée dans la boîte de dialogue : + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Linux + +Linux vous permet d'utiliser plusieurs filtres de fichiers dans les boîtes de dialogue. Chaque FileFilter s'affichera comme une entrée séparée dans la boîte de dialogue : + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Mac + +Les dialogues Mac n'ont qu'un ensemble unique de motifs pour filtrer les fichiers. Si plusieurs filtres de fichiers sont fournis, Wails utilisera tous les modèles définis. + +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", + }, + }, + }) +``` + +Cela se traduira par l'ouverture de la boîte de dialogue "Ouvrir un fichier" en utilisant `*.png,*.jpg,*.mov,*.mp4` comme filtres. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..43d72885ea7 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +sidebar_position: 2 +--- + +# Événements + +Le runtime Wails fournit un système d'événements unifiés, où les événements peuvent être émis ou reçus par Go ou JavaScript. En option, des données peuvent être transmises avec les événements. Les écouteurs vont recevoir les données dans les types de donnée du langage correspondant. + +### EventsOn + +Cette méthode définit un listener pour le nom d'événement donné. Lorsqu'un événement de type `eventName` est [émis](#EventsEmit), la méthode définie en callback est déclenchée. Toutes les données supplémentaires envoyées avec l'événement émis seront passées en paramètre à la méthode définie en callback. Il renvoie une fonction pour annuler l'écouteur. + +Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOff + +Cette méthode désactive l'évènement correspondant au nom donné, éventuellement plusieurs évènements peuvent être désinscrits via `additionalEventNames`. + +Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`
JS: `EventsOff(eventName string, ...additionalEventNames)` + +### EventsOnce + +Cette méthode définit un évènement pour le nom donné, mais ne se déclenchera qu'une seule fois. Il renvoie une fonction pour annuler l'évènement. + +Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOnMultiple + +Cette méthode définit un évènement pour le nom donné, mais ne se déclenchera au maximum qu'un certain nombre de fois, définit avec le paramètre `counter`. Il renvoie une fonction pour annuler l'écouteur. + +Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`
JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void` + +### EventsEmit + +Cette méthode émet l'événement donné. En option, des données peuvent être transmises avec l'événement. Cela déclenchera tous les événements. + +Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..915ebc4ec9c --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# Introduction + +Le runtime est une bibliothèque qui fournit des méthodes utilitaires pour votre application. Il y a à la fois un runtime Go et JavaScript et le but est d'essayer de les maintenir à parité dans la mesure du possible. + +Il a des méthodes utilitaires pour : + +- [Fenêtre](window.mdx) +- [Menu](menu.mdx) +- [Boîte de dialogue](dialog.mdx) +- [Événements](events.mdx) +- [Navigateur](browser.mdx) +- [Log](log.mdx) +- [Clipboard](clipboard.mdx) + +Le Go Runtime est disponible en important `github.com/wailsapp/wails/v2/pkg/runtime`. Toutes les méthodes de ce paquet prennent un contexte comme premier paramètre. Ce contexte doit être obtenu à partir des méthodes [OnStartup](../options.mdx#onstartup) ou [OnDomReady](../options.mdx#ondomready). + +:::info Note + +Alors que le contexte sera fourni à la méthode [OnStartup](../options.mdx#onstartup) , il n'y a aucune garantie que l'exécution fonctionnera dans cette méthode car la fenêtre s'initialise dans un autre thread. Si vous souhaitez appeler des méthodes d'exécution au démarrage, utilisez [OnDomReady](../options.mdx#ondomready). + +::: + +La bibliothèque JavaScript est disponible sur le frontend via la carte `window.runtime`. Il y a un package d'exécution généré lors de l'utilisation du mode `dev` qui fournit des déclarations TypeScript pour l'exécution. Ceci devrait être situé dans le répertoire `wailsjs` dans votre répertoire frontend. + +### Cacher + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +Cache l'application. + +:::info Note + +Sur Mac, cela masquera l'application de la même manière que le bouton `Masquer` du menu des applications Mac standard. C'est une manière différente de cacher l'application, mais elle sera toujours au premier plan. Pour Windows et Linux, c'est actuellement la même chose que `WindowHide`. + +::: + +### Afficher + +Affiche l'application. + +:::info Note + +Sur Mac, cela va ramener l'application au premier plan. Pour Windows et Linux, c'est actuellement la même chose que `WindowShow`. + +::: + +Go: `Show(ctx context.Context)`
JS: `Show()` + +### Quitter + +Quitte l'application. + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### Environnement + +Renvoie les détails de l'environnement actuel. + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### EnvironmentInfo + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..45b7a07ed27 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# Log + +Le runtime Wails fournit un mécanisme de journalisation qui peut être appelé depuis Go ou 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)`
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{})`
+ +### LogTrace + +Ajoute le message donné dans les logs avec le niveau de log `Trace`. + +Go: `LogTrace(ctx context.Context, message string)`
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{})`
+ +### LogDebug + +Ajoute le message donné dans les logs avec le niveau de log `Debug`. + +Go: `LogDebug(ctx context.Context, message string)`
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{})`
+ +### LogInfo + +Ajoute le message donné dans les logs avec le niveau de log `Info`. + +Go: `LogInfo(ctx context.Context, message string)`
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{})`
+ +### LogWarning + +Ajoute le message donné dans les logs avec le niveau de log `Warning`. + +Go: `LogWarning(ctx context.Context, message string)`
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{})`
+ +### LogError + +Ajoute le message donné dans les logs avec le niveau de log `Error`. + +Go: `LogError(ctx context.Context, message string)`
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{})`
+ +### LogFatal + +Ajoute le message donné dans les logs avec le niveau de log `Fatal`. + +Go: `LogFatal(ctx context.Context, message string)`
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{})`
+ +### LogSetLogLevel + +Définit le niveau des logs. En JavaScript, le nombre se rapporte aux niveaux de log suivants : + +| Valeur | Niveau de log | +| ------ | ------------- | +| 1 | Trace | +| 2 | Debug | +| 3 | Info | +| 4 | Warning | +| 5 | Error | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
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) +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..cd78d31aa31 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +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)` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..457c92ebff9 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# Screen + +These methods provide information about the currently connected screens. + +### ScreenGetAll + +Returns a list of currently connected screens. + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### Screen + +Go struct: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript interface: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..e9d915a4f9b --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +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)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen + +Mets la fenêtre en plein écran. + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen + +Restaure les dimensions et la position de la fenêtre avant le plein écran. + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen + +Renvoie vrai si la fenêtre est en plein écran. + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter + +Centre la fenêtre sur le moniteur sur laquelle la fenêtre est actuellement ouverte. + +Go: `WindowCenter(ctx context.Context)`
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)`
JS: `WindowReload()` + +### WindowReloadApp + +Recharge le frontend de l'application. + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme + +Windows seulement. + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
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)`
JS: `WindowSetLightTheme()` + +Définit le thème clair à la fenêtre. + +### WindowSetDarkTheme + +Windows seulement. + +Go: `WindowSetDarkTheme(ctx context.Context)`
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)`
JS: `WindowShow()` + +### WindowHide + +Masque la fenêtre, si elle est actuellement visible. + +Go: `WindowHide(ctx context.Context)`
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`
JS: `WindowIsNormal() bool` + +### WindowSetSize + +Définit la largeur et la hauteur de la fenêtre. + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize + +Retourne la largeur et la hauteur de la fenêtre. + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
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)`
JS: `WindowSetMinSize(width: number, height: number)` + +### 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)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### 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)`
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)`
JS: `WindowSetPosition(x: number, y: number)` + +### 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)`
JS: `WindowGetPosition() : Position` + +### WindowMaximiseWindowMaximise + +Maximise la fenêtre pour remplir l'écran. + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise + +Restaure la fenêtre aux dimensions et à la position avant qu'elle soit maximisée. + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised + +Renvoie vrai si la fenêtre est maximisée. + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise + +Option permettant de basculer entre la maximisation de la fenêtre et sa non maximisation. + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise + +Minimise la fenêtre. + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise + +Restaure la fenêtre aux dimensions et à la position avant qu'elle soit minimisée. + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised + +Renvoie vrai si la fenêtre est minimisée. + +Go: `WindowIsMinimised(ctx context.Context) bool`
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)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +Opens tha native print dialog. + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## Définitions d'objets TypeScript + +### Position + +```ts +interface Position { + x: number; + y: number; +} +``` + +### Size (taille) + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..cb2b780b665 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# API Chiens + +```mdx-code-block +
+ +
+
+``` + +:::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`: + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### 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`. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..2beff220ec5 --- /dev/null +++ b/website/i18n/fr/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +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 +Devtools: false +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 +
+ +
+
+``` + +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 +
+ +
+
+``` diff --git a/website/versioned_docs/version-v2.8.0/appendix/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/appendix/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json diff --git a/website/versioned_docs/version-v2.8.0/community/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..b7b80b83939 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +sidebar_position: 2 +--- + +# リンク + +このページは、コミュニティ関連のリンクの一覧です。 リンクを追加したい場合は、プルリクエストを送信(ページ下部の`このページを編集`をクリック) してください。 + +## Awesome Wails + +Wailsに関する[最高のリンク一覧](https://github.com/wailsapp/awesome-wails)です。 + +## サポートチャネル + +- [Wails Discordサーバ](https://discord.gg/JDdSxwjhGf) +- [Github Issues](https://github.com/wailsapp/wails/issues) +- [v2ベータディスカッションボード](https://github.com/wailsapp/wails/discussions/828) + +## ソーシャルメディア + +- [Twitter](https://twitter.com/wailsapp) +- [Wails中国語コミュニティQQグループ](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - グループナンバー: 1067173054 + +## その他のチュートリアルや記事 + +- [掲示板を作ってみる](https://blog.customct.com/building-bulletin-board) diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..7cf3d52b5a6 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +[BulletinBoard](https://github.com/raguay/BulletinBoard)は、静的なメッセージや、スクリプト用にユーザから情報を得るためのダイアログを表示する、汎用的なメッセージボードアプリケーションです。 後者はユーザから情報を取得するために使用でき、新しいダイアログを作成するためのTUIを備えています。 システム上で動作し続け、必要に応じて情報を表示・非表示できるように設計されています。 システム上のファイルを監視し、内容が変更されたときにBulletinBoardに送信するという処理もできます。 これは、私のワークフローと相性が良いのです。 なお、プログラムに情報を送信するための[Alfredワークフロー](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow)があります。 また、[EmailIt](https://github.com/raguay/EmailIt)と連携するためのワークフローもあります。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..e451971b98c --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,39 @@ +# CFN トラッカー + +```mdx-code-block +

+ +
+

+``` + +[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) - ストリートファイ +ター 6 または V CFN プロフィールのライブマッチを追跡します。 開始するには +、[Web サイト](https://cfn.williamsjokvist.se/) を確認してください。 + +## 特徴 + +- リアルタイムの試合追跡 +- 試合ログと統計の保存 +- ブラウザソース経由で OBS にライブ統計を表示するためのサポート +- SF6 と SFV の両方をサポート +- ユーザーが CSS を使用して独自の OBS ブラウザ テーマを作成できる機能 + +### Wails とともに使用される主要なテクノロジー + +- [タスク](https://github.com/go-task/task) - Wails CLI をラップして一般的なコマ + ンドを使いやすくする +- [React](https://github.com/facebook/react) - 豊富なエコシステム (基数、フレー + マーモーション) で選ばれました +- [Bun](https://github.com/oven-sh/bun) - 依存関係の高速解決とビルド時間に使用さ + れます。 +- [Rod](https://github.com/go-rod/rod) - 認証とポーリングの変更のためのヘッドレ + スブラウザ自動化 +- [SQLite](https://github.com/mattn/go-sqlite3) - 一致、セッション、プロファイル + の保存に使用されます +- [サーバー送信イベント](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - + 追跡更新を OBS ブラウザ ソースに送信するための http ストリーム +- [i18next](https://github.com/i18next/) - Go レイヤーからローカリゼーション オ + ブジェクトを提供するバックエンド コネクタを使用 +- [xstate](https://github.com/statelyai/xstate) - 認証プロセスと追跡のためのステ + ート マシン diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..970e632a2d7 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[EmailIt](https://github.com/raguay/EmailIt/)はWails 2で作成されており、9個のノートパット、テキスト操作のためのスクリプト、およびテンプレートを備えた、マークダウンベースのEメール送信ソフトです。 また、システム内のファイルに対してEmailItのスクリプトを実行するためのスクリプトターミナルを備えています。 スクリプトとテンプレートは、コマンドライン自体から、またはAlfred、Keyboard Maestro、Dropzone、PopClipの拡張機能から使用することができます。 さらに、GitHubからダウンロードしたスクリプトやテーマにも対応しています。 ドキュメントは未完成ですが、ブログラム自体は動作します。 Wails 2とSvelteを使用して構築されており、ユニバーサルmacOSアプリケーションとしてダウンロードできます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..b6395c7abd0 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[EncryptEasy](https://www.encrypteasy.app)は、シンプルで使いやすいPGP暗号化ツールで、すべての連絡先の鍵を管理することができます。 暗号化は簡単にできるべきです。 Wailsで開発されました。** + +PGPを使用したメッセージの暗号化は、業界の標準です。 誰もが、秘密鍵と公開鍵を所持しています。 あなたの秘密鍵は、あなただけがメッセージを読めるように、常に秘密にしておく必要があります。 あなたの公開鍵は、暗号化されたメッセージを送信したい人に配布します。 鍵の管理、メッセージの暗号化、およびメッセージの復号化は、スムーズにできなければなりません。 EncryptEasyはそれらを簡単に実現します。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..4e4295b26ab --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[ESP Studio](https://github.com/torabian/esp-studio) - クロスプラットフォーム、デスクトップ、クラウド、組み込みソフトウェア +ESP/Arduino デバイスの制御、複雑な IOT ワークフローと制御システムの構築用 \ No newline at end of file diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..a9d9ad651ef --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# FileHound Export Utility + +```mdx-code-block +

+ +
+

+``` + +[FileHound Export Utility](https://www.filehound.co.uk/) FileHoundは、安全なファイル保管、ビジネスプロセスの自動化、およびSmartCapture機能のための、クラウドドキュメント管理プラットフォームです。 + +FileHound Export Utilityを使用すると、FileHoundの管理者はバックアップやリカバリのために、安全なドキュメントとデータ抽出タスクを実行できます。 このアプリケーションは、選択したフィルタにもとづいて、FileHoundに保存されているすべての文書やメタデータをダウンロードします。 メタデータはJSON形式とXML形式の両方でエクスポートされます。 + +バックエンド: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2 + +フロントエンド: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..611c60d5fac --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter)は、シンプルで効率的に使用できる、http APIテストクライアントツールです。 Wails、Go、sveltejsで構築されました。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..668173ebe9e --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Minecraft Updater + +```mdx-code-block +

+ +
+

+``` + +[Minecraft Updater](https://github.com/Gurkengewuerz/MinecraftModUpdater)は、ユーザベースMinecraft Modを更新および同期するためのユーティリティツールです。 Wails2とReactで構築されており、フロントエンドフレームワークには[antd](https://ant.design/)を使用しています。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..a8020f6be3a --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Modal File Manager + +```mdx-code-block +

+ +
+

+``` + +[Modal File Manager](https://github.com/raguay/ModalFileManager)は、Web技術を使用した、デュアルペインファイルマネージャです。 [こちら](https://github.com/raguay/ModalFileManager-NWjs)でもともと公開していたNW.jsで構築されたものをベースとしています。 本バージョンでは、フロントエンドのコードには前と同様にSvelteを使用(NW.jsを使用していた時から大幅な修正はありました)しましたが、バックエンドの実装にはWails 2を使用しました。 この実装によって、コマンドラインの`rm`、`cp`などのコマンドを使用しなくなりましたが、テーマや拡張機能のダウンロードのために、システム上でgitのインストールは必要となります。 Goで完全にコード化されており、以前のバージョンよりもはるかに高速に実行されます。 + +このファイルマネージャは、Vimと同じ、状態制御キーボード操作の原理に基づいて設計されています。 状態の数に制限はなく、とてもプログラマブルです。 つまり、無数にキーボード構成を作成・使用することができます。 この点は、他のファイルマネージャとの主な違いと言えるでしょう。 また、GitHubからテーマや拡張機能をダウンロードできます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..00159268f08 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[Molly Wallet](https://github.com/grvlle/constellation_wallet/)は、Constellation Networkの公式$DAGウォレットです。 ユーザは、$DAGトランザクションの生成に限らず、様々な方法でHypergraph Networkとやり取りすることができます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..7b5f59d15fb --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[October](https://october.utf9k.net)は、[Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader)からハイライトを抽出し、簡単に[Readwise](https://readwise.io)へ転送できる、シンプルなWailsアプリケーションです。 + +[UPX圧縮](https://upx.github.io/)なしで、すべてのプラットフォームで10MB以下という、比較的小さなサイズとなっています! + +これとは対照的に、開発者が以前にElectronで作成したものは、簡単に数百MBにまで膨らんでしまいました。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..b02394d2779 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# Optimus + +```mdx-code-block +

+ +
+

+``` + +[Optimus](https://github.com/splode/optimus)は、画像最適化のためのデスクトップアプリケーションです。 WebP、JPEG、PNG形式画像の相互変換や圧縮をサポートしています。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..3066a9799e9 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# Portfall + +```mdx-code-block +

+ +
+

+``` + +[Portfall](https://github.com/rekon-oss/portfall) - すべてのクラスタUIに簡単にアクセスできる、デスクトップk8s port-forwardingポータルです。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..348ffdd5290 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[Restic-Browser](https://github.com/emuell/restic-browser) - resticリポジトリを参照およびリストアするための、シンプルでクロスプラットフォームな[restic](https://github.com/restic/restic)バックアップGUIツールです。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..b1e66ae7b8c --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +誰にとっても簡単、安全、そして無料のファイル共有。 詳しくは[Riftshare.app](https://riftshare.app)をご覧ください。 + +## 機能 + +- ローカルネットワーク内またはインターネット経由で、簡単にセキュアなコンピュータ間ファイル共有が可能 +- [magic wormhole プロトコル](https://magic-wormhole.readthedocs.io/en/latest/)を介したファイル・ディレクトリのセキュアな送信をサポート +- magic wormholeを使用する他のすべてのアプリ(magic-wormhole、wormhole-william CLI、wormhole-guiなど) との互換性 +- 選択された複数ファイルを自動圧縮して一括送信 +- フルアニメーション、プログレスバー、および送受信のキャンセルをサポート +- OSネイティブのファイル選択UIを利用可能 +- 受信したファイルをワンクリックで開ける +- 自動アップデート - 最新のリリースを気にする必要はありません! diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..9ab6d88d51e --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp)は、スクリプトまたは[Node-Red](https://nodered.org)サーバの出力を表示するためのプログラムです。 EmailItプログラムで定義されたプログラムを実行し、出力を表示します。 xBarやTextBarのスクリプトも使用できますが、現時点ではTextBarのスクリプトが正常に動作します。 また、システム上にスクリプトの出力を表示できます。 ScriptBarはそれらの情報をメニューバーには表示させず、簡単に参照できる便利なウィンドウ上に表示されます。 複数のタブを使用して、様々な情報を表示できます。 よくアクセスするWebサイトへのリンクを配置することもできます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..bcca578edcc --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[Surge](https://getsurge.io/)は、ブロックチェーン技術を使用して、100%匿名でのファイル転送ができるように設計された、p2pファイル共有アプリです。 エンドツーエンド暗号化に対応、分散型、そしてオープンソースである点が、Surgeの特徴です。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..d44b2280183 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[Wally](https://ergodox-ez.com/pages/wally)は、[Ergodox](https://ergodox-ez.com/)キーボード公式の、ファームウェアフラッシャーです。 とても見栄えが良く、GoのパワーとWeb開発技術の豊富なグラフィカルツールを組み合わせるという、Wailsで達成できる機能を示す良い例となるアプリです。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..6674a7d1652 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# Minecraft launcher for WarMine + +```mdx-code-block +

+ + +
+

+``` + +[Minecraft launcher for WarMine](https://warmine.ru/)は、Modを導入したゲームサーバに簡単にアクセスしたり、ゲームアカウントを管理できるWailsアプリケーションです。 + +ランチャーでは、ゲームファイルをダウンロードし、その整合性のチェックして、様々なカスタマイズが可能なバックエンドからの起動引数を使用してゲームを起動します。 + +フロントエンドはSvelteで記述され、ランチャー全体は9MBに収まり、Windows 7-11をサポートしています。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..eedc72d97e8 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# Wombat + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat)はクロスプラットフォーム対応のgRPCクライアントです。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..94e0e09f2ab --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails)はYouTubeからトラックをダウンロードしたり、オフラインプレイリストを作成して友達と共有するためのアプリです。友達は、あなたのプレイリストを内蔵プレーヤーで再生したり、オフラインで聴くためにダウンロードしたりできます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..3dc92d2fbd9 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +--- + +# テンプレート + +このページでは、コミュニティがサポートしているテンプレートを紹介しています。 このページに新たにテンプレートを含めたい場合は、このページの下側にある`このページを編集`をクリックして、プルリクエストを出してください。 独自テンプレートの作成方法については、[テンプレート](../guides/templates.mdx)ガイドをご覧ください。 + +これらのテンプレートを使用するには、`wails init -n "プロジェクト名" -t [テンプレートのリンク[@バージョン]]`コマンドを実行してください。 + +バージョンサフィックスが無い場合は、デフォルトで、メインブランチのコードテンプレートが使用されます。 バージョンサフィックスがある場合は、当該バージョンのタグに対応するコードテンプレートが使用されます。 + +例: `wails init -n "プロジェクト名" -t https://github.com/misitebao/wails-template-vue` + +:::warning 注意 + +**Wailsプロジェクトでは、サードパーティ製テンプレートのメンテナンスは行っておらず、責任も負いません!** + +テンプレートについてよく分からない場合は、`package.json`および`wails.json`を確認し、どのようなスクリプトが実行されるのかや、どのようなパッケージがインストールされるのかを調べてください。 + +::: + +## Vue + +- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - VueのエコシステムをベースにしたWailsテンプレート (TypeScript、ダークテーマ、i18n、シングルページルーティング、TailwindCSSを統合) +- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Viteを使用したVue 3 TypeScript (および機能を追加する手順) +- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vite、Vuex、Vue Router、SaaS、ESLint + Prettier を使用した Vue 3 TypeScript +- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier) を使用したテンプレート +- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, <script setup>によるComposition API) を使用したテンプレート +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Naive UI(Vue3のコンポーネントライブラリ)をベースにしたWailsテンプレート + +## Angular + +- [wails-template-angular](https://github.com/mateothegreat/wails-template-angular) - 15以上のAngularアクションを含み、すぐに実装に取り掛かれるテンプレート +- [wails-angular-template](https://github.com/TAINCER/wails-angular-template) - TypeScript、Sass、ホットリロード、コード分割、i18n を使用した Angular + +## React + +- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - reactjsを使用したテンプレート +- [wails-react-template](https://github.com/flin7/wails-react-template) - ライブ開発をサポートしたReactの最小テンプレート +- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - Next.js、TypeScript を使用したテンプレート +- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - React + TypeScript + Vite + TailwindCSSを使用したテンプレート +- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - Vite、React、TypeScript、TailwindCSS、shadcn/uiを使用したテンプレート + +## Svelte + +- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - Svelteを使用したテンプレート +- [wails-vite-svelte-template](https://github.com/BillBuilt/wails-vite-svelte-template) - SvelteおよびViteを使用したテンプレート +- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - TailwindCSS v3を含んだ、SvelteおよびViteを使用したテンプレート +- [wails-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - Svelte v4.2.0、Vite、TailwindCSS v3.3.3を使用したテンプレート +- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - SvelteKitを使用したテンプレート + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - Solid + Ts + Viteを使用したテンプレート +- [wails-template-vite-solid-js](https://github.com/xijaja/wails-template-solid-js) - Solid + Js + Viteを使用したテンプレート + +## Elm + +- [wails-elm-template](https://github.com/benjamin-thomas/wails-elm-template) - 関数型プログラミングと**高速な**ホットリロードを使ったGUIアプリ開発 :tada: :rocket: +- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - Elm + Tailwind CSS + Wailsのパワー:muscle:を組み合わせたテンプレート (ホットリロードサポートあり) + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - インタラクティビティを実現するためのピュアなhtmxに、コンポーネントおよびフォームを作成するためのテンプレートが合わさったテンプレート + +## ピュアJavaScript (バニラ) + +- [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - 基本的なJavaScript、HTML、CSSのみを含むテンプレート diff --git a/website/versioned_docs/version-v2.8.0/gettingstarted/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/gettingstarted/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..dfab958b4e8 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +sidebar_position: 6 +--- + +# プロジェクトのコンパイル + +プロジェクトディレクトリ上で、`wails build`コマンドを実行しましょう。 そうすることで、プロジェクトがコンパイルされ、`build/bin`ディレクトリ内に本番配布用のバイナリが出力されます。 + +バイナリを起動すると、デフォルト仕様のアプリを確認することができます: + +```mdx-code-block +
+ +
+
+``` + +コンパイルオプションについて詳しくは、[CLIリファレンス](../reference/cli.mdx#build)をご覧ください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..5fbc7ab19cc --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 5 +--- + +# アプリの開発 + +プロジェクトディレクトリのルート上で`wails dev`コマンドを実行すると、アプリを開発モードで起動することができます。 コマンドを実行すると下記の処理が実行されます: + +- アプリをビルドしたのち、起動する +- Goのコードをフロントエンドにバインドして、JavaScriptから呼び出せるようにする +- [Vite](https://vitejs.dev/)の機能を使用して、Goファイルの変更を監視し、変更された際には自動的にリビルド/再起動する +- ブラウザからアプリを操作できるようにする[Webサーバ](http://localhost:34115)を立ち上げる。 これにより、任意のブラウザ拡張機能を利用できる。 JavascriptのコンソールからGoのコードを呼び出すこともできる + +アプリ開発を始めるときは、プロジェクトディレクトリ上で`wails dev`コマンドを実行しましょう。 詳しくは、[こちら](../reference/cli.mdx#dev)をご覧ください。 + +近日中にチュートリアルを公開予定です。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..5dce70b33ea --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 2 +--- + +# プロジェクトの開始 + +## プロジェクトの生成 + +CLIのインストールが終わったら、`wails init`コマンドで新しいプロジェクトを生成しましょう。 + +好きなフレームワークを選択してください: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + JavaScriptによるSvelteプロジェクトを生成する場合:

+ + wails init -n myproject -t svelte + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t svelte-ts + +
+ + JavaScriptによるReactプロジェクトを生成する場合:

+ + wails init -n myproject -t react + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t react-ts + +
+ + JavaScriptによるVueプロジェクトを生成する場合:

+ + wails init -n myproject -t vue + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t vue-ts + +
+ + JavaScriptによるPreactプロジェクトを生成する場合:

+ + wails init -n myproject -t preact + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t preact-ts + +
+ + JavaScriptによるLitプロジェクトを生成する場合:

+ + wails init -n myproject -t lit + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t lit-ts + +
+ + JavaScriptによるバニラなプロジェクトを生成する場合:

+ + wails init -n myproject -t vanilla + +TypeScriptによるプロジェクトを生成する場合:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +様々な機能やフレームワークを提供する[コミュニティテンプレート](../community/templates.mdx)を利用することもできます。 + +プロジェクト生成時に使用可能なオプションを確認するには、`wails init -help`を実行してください。 詳しくは、[CLIリファレンス](../reference/cli.mdx#init)を参照してください。 + +## プロジェクトのディレクトリ構成 + +Wailsのプロジェクトディレクトリの構成は次のとおりです: + +``` +. +├── build/ +│ ├── appicon.png +│ ├── darwin/ +│ └── windows/ +├── frontend/ +├── go.mod +├── go.sum +├── main.go +└── wails.json +``` + +### プロジェクトの構造 + +- `/main.go` - アプリのメインコード +- `/frontend/` - フロントエンドのプロジェクトディレクトリ +- `/build/` - ビルドディレクトリ +- `/build/appicon.png` - アプリアイコン +- `/build/darwin/` - Mac固有のプロジェクトディレクトリ +- `/build/windows/` - Windows固有のプロジェクトディレクトリ +- `/wails.json` - プロジェクト構成ファイル +- `/go.mod` - Goモジュール定義ファイル +- `/go.sum` - Goモジュールチェックサムファイル + +`frontend`ディレクトリ内は、Wailsで決まったファイル構成等は無く、お好きなフロントエンドプロジェクトを配置することができます。 + +`build`ディレクトリは、アプリのビルド時に使用されます。 この中のファイルは、ビルドの挙動をカスタマイズするために、適宜ファイル内容を書き換えることができます。 buildディレクトリ内のファイルを削除すると、デフォルトのファイルが再生成されます。 + +`go.mod`のモジュール名は、最初は"changeme"になっています。 このモジュール名は、あなたのプロジェクトに適切な名前に変更しましょう。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..bb00dbe8fd5 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +--- + +# インストール + +## サポートされているプラットフォーム + +- Windows 10/11 AMD64/ARM64 +- MacOS 10.13+ AMD64 +- MacOS 11.0+ ARM64 +- Linux AMD64/ARM64 + +## 依存関係 + +Wailsをインストールする前に、下記のものを導入しておく必要があります。 + +- Go 1.18+ +- NPM (Node 15+) + +### Go + +[Goのダウンロードページ](https://go.dev/dl/)からGoをダウンロードしてください。 + +公式の[Goインストール手順](https://go.dev/doc/install)に従って、Goをインストールしてください。 その際、`PATH`環境変数に`~/go/bin`ディレクトリへのパスが含まれていることも確認してください。 それらが終わったら、ターミナルを再起動し、以下の確認をしてください: + +- Goが正しくインストールされているかを確認する: `go version` +- "~/go/bin"のディレクトリパスがPATH環境変数に含まれているか確認する: `echo $PATH | grep go/bin` + +### NPM + +[Nodeダウンロードページ](https://nodejs.org/ja/download/)からNPMをダウンロードしてください。 最新版を利用することをお勧めします。なぜなら、私たちは最新版に対してテストを実施しているためです。 + +`npm --version`を実行して、インストールが完了しているかを確認してください。 + +## プラットフォーム固有の依存関係 + +開発作業を行うプラットフォームによって、必要な依存関係が存在します: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Wailsを使用するには、xcodeのコマンドラインツールがインストールされている必要があります。 xcode-select --installコマンドを実行することでインストールできます。 + + + Wailsを使用するには、WebView2ランタイムがインストールされている必要があります。 最新のWindowsでは、すでにインストールされている場合もあります。 wails doctorコマンドで、インストール状況を確認できます。 + + + Linuxでは、標準のgccビルドツール、libgtk3libwebkitが必要です。 Wailsは、様々なディストリビューション向けに大量のコマンドを列挙することはせず、現在使用されているディストリビューションのインストールコマンドを自動的に判定します。 Wailsをインストールした後に、wails doctorコマンドを実行して、別途インストールが必要な依存関係を確認してください。 あなたが利用しているディストリビューションやパッケージマネージャーがサポートされていない場合は、Linuxディストリビューションサポートガイドを参照してください。 + + +``` + +## 任意の依存関係 + +- [UPX](https://upx.github.io/)を導入することで、構築したアプリを圧縮できます。 +- [NSIS](https://wails.io/docs/guides/windows-installer/)を導入することで、Windowsのインストーラを生成できます。 + +## Wailsのインストール + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest`を実行して、Wails CLIをインストールしてください。 + +注意: 次のようなエラーが発生した場合: + +```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 +``` +下記コマンドで、Go 1.18以上がインストールされているかを確認してください: +```shell +go version +``` + +## システムチェック + +`wails doctor`を実行すると、必要な依存関係が正しくインストールされているかを確認することができます。 正しくインストールされていない場合は、その内容をあなたにお知らせして、どうすれば解決できるかを教えてくれます。 + +## `wails`コマンドが見つからないのですが? + +`wails`コマンドが見つからないとシステムに怒られた場合は、Goが、公式のGoインストール手順に従って導入されているかを確認してください。 コマンドが見つからないほとんどの理由は、あなたのホームディレクトリ配下にある`go/bin`ディレクトリのパスが、`PATH`環境変数に含まれていないからです。 また、インストールによって行われた環境変更を反映させるために、もともと開いていたコマンドプロンプト(ターミナル)がある場合はそれらをいったん閉じて、再度開きなおしてください。 diff --git a/website/versioned_docs/version-v2.8.0/guides/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..2a049fd1e58 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# Angular + +Wailsでは、Angular向けのテンプレートは用意されていませんが、Angular自体を使用することはできます。 + +## 開発モード + +Angularで開発モードを使用するには、`wails.json`で下記のように設定してください: + +```json + "frontend:build": "npx ng build", + "frontend:install": "npm install", + "frontend:dev:watcher": "npx ng serve", + "frontend:dev:serverUrl": "http://localhost:4200", +``` \ No newline at end of file diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..850d85f382b --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# アプリケーション開発 + +Wailsでアプリケーションを作成する際に、厳格なルールはありませんが、基本的なガイドラインがいくつかあります。 + +## アプリケーションセットアップ + +デフォルトのテンプレートを使用した場合、`main.go`にはアプリケーションの構成および起動コードが記述され、`app.go`にはアプリケーションのロジック定義が記述されています。 + +`app.go`ファイルには、メインアプリケーションのフックとして機能する2つのメソッドを持った構造体を定義します。 + +```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) { +} +``` + +- startupメソッドは、Wailsが起動時に、必要リソースの割り当てが完了した際にすぐに呼び出されます。このメソッド内は、リソースの作成、イベントリスナーの設定、その他アプリケーションに必要な初期処理を実施するのに適しています。 メソッド呼び出し時に与えられる`context.Context`は、通常は、構造体のフィールドに格納するようにしてください。 なぜならば、このcontextは[runtime](../reference/runtime/intro.mdx)を呼び出す際に必要なためです。 このstartupメソッドがエラーを返却した場合、アプリケーションは終了します。 開発モードの場合、コンソールにエラーが出力されます。 + +- shutdownメソッドは、シャットダウンプロセスの最後に、Wailsによって呼び出されます。 このメソッド内は、メモリを解放し、任意のシャットダウンタスクを実施するのに適しています。 + +通常、`main.go`ファイルでは、アプリケーション構成を受け取る`wails.Run()`メソッドを1回だけ呼び出すようにします。 テンプレートでは、`wails.Run()`を呼び出す前に、`app.go`で定義した構造体のインスタンスを作成して、`app`に格納しています。 アプリケーション構成では、コールバックを追加できます: + +```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) + } +} + +``` + +アプリケーションのライフサイクルフックについて詳しくは、[こちら](../howdoesitwork.mdx#application-lifecycle-callbacks)をご覧ください。 + +## メソッドのバインディング + +フロントエンドからGoのメソッドを呼び出したいことがありますよね。 そのようなときは、`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) +} +``` + +アプリケーション構成の`Bind`キーで、Wailsに何をバインドさせたいかを指定できます: + +```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) + } +} + +``` + +これにより、`App`構造体のすべてのパブリックメソッドがバインドされます(startupメソッド・shutdownメソッドはバインドされません)。 + +### 複数の構造体をバインドするときのcontextの扱い + +もし、複数の構造体のメソッドをバインドしたくて、かつ、各構造体でランタイム関数を呼び出せるようにcontextを共有したい場合は、`OnStartup`のコールバック内で、各構造体にcontextを渡してあげるのが良いでしょう: + +```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) + } +} +``` + +バインディングの詳細については、[こちら](../howdoesitwork.mdx#method-binding)をご覧ください。 + +## アプリケーションメニュー + +Wailsでは、アプリケーションにメニューを追加することができます。 追加したい場合は、アプリケーション構成に[Menu](../reference/menus.mdx#menu)構造体を渡してください。 通常は、Menuを返すようなメソッドを使用するようにします。ライフサイクルフックに使用される`App`構造体のメソッドとして用意するのが良いでしょう。 + +```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) + } +} + +``` + +## アセット + +Wails v2にアセットを処理させるための方法は複雑ではありません。 Wailsに与える必要があるのは、`embed.FS`だけです。 任意の方法で与えてあげてください。 バニラテンプレートで使用されているように、素のhtml/css/jsファイルをアセットとして使用できます。 もちろん、複雑なビルドシステムを使用することも可能ですが、必須要件ではありません。 + +`wails build`コマンドを実行すると、プロジェクトルートディレクトリに存在するプロジェクト構成ファイルである`wails.json`のチェックが行われます。 プロジェクトファイルには、次の2つのキーを含めることができます: + +- "frontend:install" +- "frontend:build" + +1番目のキーは、`frontend`ディレクトリにおいて、nodeモジュールをインストールするためのコマンドを指定します。 2番目のキーは、`frontend`ディレクトリにおいて、フロントエンドをビルドするためのコマンドを指定します。 + +2つのキーのどちらともが指定されていない場合、Wailsはフロントエンドプロジェクトに対する操作を一切行いません。 `embed.FS`で指定されたディレクトリを参照するのみとなります。 + +### アセットハンドラ + +Wails v2では必要に応じて、`options.App`の中に`http.Handler`を定義することができます。これにより、アセットサーバにフックして、その場でファイルを作成したり、POST/PUTリクエストを処理したりすることができます。 GETリクエストが要求されたときは、まず初めに、`assets` FSにハンドリングされます。 リクエストされたファイルをFSが見つけられなかった場合、そのリクエストは`http.Handler`に転送されます。 GET以外のリクエストは、`AssetsHandler`が指定されていれば、当該ハンドラによって直接処理されます。 なお、`Assets`オプションに`nil`を指定することで、`AssetsHandler`のみを使用することも可能です。 + +## ビルトイン開発サーバ + +`wails dev`コマンドを実行すると、ビルトイン開発サーバが起動し、プロジェクトディレクトリ内のファイル監視が開始されます。 デフォルトでは、ファイルの中身が変更された場合、Wailsはそのファイルがアプリケーションファイルであるかどうかをチェックします(デフォルト: `.go`、 `-e`フラグで制御可能)。 アプリケーションファイルであった場合は、アプリケーションをリビルドして再起動します。 アセットディレクトリ内でファイルが変更された場合は、少し経ってからリロードが実行されます。 + +開発サーバは"デバウンシング"と呼ばれるテクニックを使用しています。これにより、短時間で複数のファイルが更新されたとしても、すぐに再読み込みされることはありません。 トリガーが起動すると、再読み込みを実行する前に一定時間待機します。 待機中に別のトリガーが起動した場合、待機時間はリセットされます。 デフォルトでは、待機時間は`100ms`です。 この待機時間の値があなたのプロジェクトで適切ではない場合、`-debounce`フラグを使用して変更することができます。 このフラグを使用すると、値がプロジェクト構成ファイルに保存され、次回以降のデフォルト値となります。 + +## 外部開発サーバ + +フレームワークによっては独自のライブリロードサーバが付属しているものがありますが、それらはWailsのGoバインディングを使用することができません。 このような場面では、Wailsが監視するビルドディレクトリ内で、プロジェクトをリビルドする監視スクリプトを実行すると良いでしょう。 例としては、[rollup](https://rollupjs.org/guide/en/)を使用するデフォルトのsvelteテンプレートをご覧ください。 + +### Create React App + +The process for a Create-React-App project is slightly more complicated. In order to support live frontend reloading the following configuration needs to be added to your `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +The `frontend:dev:watcher` command will start the Create-React-App development server (hosted on port `3000` typically). The `frontend:dev:serverUrl` command then instructs Wails to serve assets from the development server when loading the frontend rather than from the build folder. In addition to the above, the `index.html` needs to be updated with the following: + +```html + + + + + +``` + +This is required as the watcher command that rebuilds the frontend prevents Wails from injecting the required scripts. This circumvents that issue by ensuring the scripts are always injected. With this configuration, `wails dev` can be run which will appropriately build the frontend and backend with hot-reloading enabled. Additionally, when accessing the application from a browser the React developer tools can now be used on a non-minified version of the application for straightforward debugging. Finally, for faster builds, `wails dev -s` can be run to skip the default building of the frontend by Wails as this is an unnecessary step. + +## Goモジュール + +デフォルトのWailsテンプレートは、モジュール名が"changeme"となっている`go.mod`ファイルを生成します。 プロジェクトの生成が完了したら、適切なモジュール名に変更してください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..a765cff58f6 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# 動的アセット + +[AssetsHandler](../reference/options#assetshandler)オプションを使用することで、フロントエンドアセットを動的に読み込んだり生成させることができます。 AssetsHandlerは、ジェネリックな`http.Handler`です。アセットサーバへのGET以外のすべてのリクエスト、および、アセットファイルとして存在しなかったがために転送されてきたGETリクエストに対して、ハンドラが呼び出されます。 + +カスタムされたAssetsHandlerを導入すると、カスタムアセットサーバを使用して独自のアセットを提供することができます。 + +## 例 + +このサンプルプロジェクトでは、ディスクからファイルを読み込むシンプルなアセットハンドラを作成します: + +```go title=main.go {17-36,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() { + // App構造体のインスタンスを作成 + app := NewApp() + + // オプション付きでアプリケーションを作成 + 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) + } +} +``` + +`wails dev`コマンドでアプリケーションを開発モードで実行すると、次のように出力されます: + +``` +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler +Requesting file: favicon.ico +``` + +これを見ると分かるように、アセットハンドラは、デフォルトのアセットサーバが`favicon.ico`を提供できない場合に呼び出されています。 + +メインアプリケーションをクリックし、"検証(開発者ツールで調査する)"を選択して、開発者ツールを起動します。そして、コンソールに次のように入力して実行することで、機能をテストできます: + +``` +let response = await fetch('does-not-exist.txt'); +``` + +これにより、開発者ツールでエラーが発生します。 カスタムアセットハンドラによって、想定どおりのエラーが返却されていることが分かります。 + +```mdx-code-block +

+ +

+``` + +もし、`go.mod`をリクエストした場合は、次のような出力となります: + +```mdx-code-block +

+ +

+``` + +このテクニックを使用して、ページ上に画像を直接読み込ませることができます。 デフォルトのバニラテンプレートで、ロゴ画像を指定している、下記コードを、 + +```html + +``` + +次のように書き換えます: + +```html + +``` + +すると、画面上は次のような表示となります: + +```mdx-code-block +

+ +

+``` + +:::warning + +この例のようにファイルシステムを公開することは、セキュリティ上のリスクとなります。 ファイルシステムへのアクセスは、適切に管理することを推奨します。 + +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..b6218d81e1e --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# フレームレスアプリケーション + +Wailsでは、フレームのないアプリケーションの作成をサポートしています。 [アプリケーションオプション](../reference/options.mdx#application-options)の[frameless](../reference/options.mdx#frameless)フィールドで設定することが可能です。 + +Wailsでは、フレームレスウィンドウをドラッグできるようにするための簡単な仕組みを提供しています。`--wails-draggable:drag`というCSSスタイルをもつ任意のHTML要素は、"ドラッグハンドル"として機能します。 このプロパティは、すべての子要素にも継承されます。 ネストされている子要素で、ドラッグを明示的に無効化したい場合は、当該子要素で'--wails-draggable:no-drag'を指定します。 + +```html + + + + + + + +
+ + +
+
+ + + + +``` + +一部のプロジェクトでは、動的なスタイリングが原因で、これらのCSSプロパティが使用できない場合があるでしょう。 そのような場合、アプリケーションオプションの`CSSDragProperty`および`CSSDragValue`を使用して、ドラッグ可能な領域を示すプロパティ名と値を独自に定義することができます。 + +```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() { + // アプリケーション構造体のインスタンスを作成 + app := NewApp() + + // オプション付きでアプリケーションを作成 + 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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info フルスクリーン + +アプリケーションをフルスクリーン状態にすると、このドラッグ機能は無効になります。 + +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..2d976fbf741 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# フロントエンド + +## スクリプトの注入 + +Wailsが`index.html`を提供するとき、デフォルトでは、``タグ内に`/wails/ipc.js`および`/wails/runtime.js`の2つのスクリプトを読み込む行を注入します。 これらのスクリプトファイルは、バインディングおよびランタイムを提供しています。 + +デフォルトでどの位置にスクリプトが注入されるかを、下記のコードに示します: + +```html + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### デフォルトのスクリプト注入の上書き + +開発者がより柔軟に対応できるように、これらの動作をカスタマイズするためのメタタグが用意されています: + +```html + +``` + +オプションは次のとおりです: + +| 値 | 説明 | +| ------------------- | ------------------------------- | +| noautoinjectruntime | `/wails/runtime.js`の自動注入を無効化します | +| noautoinjectipc | `/wails/ipc.js`の自動注入を無効化します | +| noautoinject | すべてのスクリプトの自動注入を無効化します | + +カンマで区切ることで、複数のオプションを指定できます。 + +次のコードは、自動注入版のコードと完全に同じ挙動となります: + +```html + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..daf0c4802fa --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# 統合開発環境 + +Wailsでは、優れた開発体験の提供を目指しています。 その一環として、統合開発環境特有の構成設定の生成をサポートしており、より快適にプロジェクトをセットアップできるようになっています。 + +現在は[Visual Studio Code](https://code.visualstudio.com/)をサポートしていますが、今後、Golandなど他の統合開発環境もサポートしていく予定です。 + +## Visual Studio Code + +```mdx-code-block +

+ +

+``` + +プロジェクト生成時のコマンドに`-ide vscode`フラグを付与すると、統合開発環境用の構成ファイルが、他のプロジェクトファイルと共に作成されます。 これらのファイルは`.vscode`ディレクトリ内に配置され、アプリケーションをデバッグするための正しい構成設定が記述されています。 + +生成されるのは`tasks.json`ファイルおよび`launch.json`ファイルの2つです。 デフォルトのバニラプロジェクトの場合、次のような内容となります: + +```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": {} + } + ] +} +``` + +### インストールおよびビルドステップの構成 + +デフォルトのプロジェクトでは、`npm install`や`npm run build`などのステップが必要ないため、`tasks.json`ファイルの内容なシンプルなものになっています。 Svelteテンプレートのように、フロントエンドのビルドステップが必要なプロジェクトの場合、`tasks.json`を編集して、インストールおよびビルドのステップを追加する必要があります。 + +```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"] + } + ] +} +``` + +今後の機能強化予定 + +将来的に、インストールおよびビルドステップを含んだ`tasks.json`を自動生成できるように計画しています。 + +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..4d9b9640025 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# Linuxディストリビューションサポート + +## 概要 + +WailsはLinuxをサポートしていますが、すべてのLinuxディストリビューションに対してインストール手段を提供することは困難であるため、行っていません。 その代わりにWailsでは、アプリケーション開発に必要なパッケージが、システムのパッケージマネージャを介して利用可能かどうかを判断します。 現在、以下のパッケージマネージャをサポートしています: + +- apt +- dnf +- emerge +- eopkg +- nixpkgs +- pacman +- zypper + +## パッケージ名の追加 + +あなたが使用しているディストリビューションが、Wailsがサポートしているパッケージマネージャを使用していたとしても、パッケージ名が想定と異なっている場合があります。 例えば、Ubuntuの派生ディストリビューションを使用している場合、gtkのパッケージ名が異なる場合があります。 Wailsは、パッケージ名のリストを繰り返し処理することで、正しいパッケージを見つけようと試みます。 パッケージ名のリストは、`v2/internal/system/packagemanager`ディレクトリ内に、パッケージマネージャごとのファイルで格納されています。 下記は、`v2/internal/system/packagemanager/apt.go`の例です。 + +このファイルでは、パッケージのリストは`Packages()`メソッドによって定義されています: + +```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}, + }, + } +} +``` + +お使いのLinuxディストリビューションが、`libgtk-3`パッケージが`lib-gtk3-dev`という名前で配布されていると仮定しましょう。 その場合、次の行を追加することで、対応することができます: + +```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}, + }, + } +} +``` + +## パッケージマネージャの追加 + +新しいパッケージマネージャを追加するには、次の手順を実行します: + +- `v2/internal/system/packagemanager`に、`.go`という名前の新しいファイルを作成します。``はパッケージマネージャの名前です。 +- `pm.go`の中で、PackageManagerインターフェースを実装した構造体を定義します: + +```go +type PackageManager interface { + Name() string + Packages() packagemap + PackageInstalled(*Package) (bool, error) + PackageAvailable(*Package) (bool, error) + InstallCommand(*Package) string +} +``` + +- `Name()`メソッドで、パッケージマネージャの名前を返すように実装します。 +- `Packages()`メソッドで、依存関係の候補ファイル名を提供する`packagemap`を返すように実装します。 +- `PackageInstalled()`メソッドで、引数で渡されたパッケージがすでにインストールされている場合は`true`を返すように実装します。 +- `PackageAvailable()`メソッドで、引数で指定されたパッケージがインストールはされていないけれどもインストール可能であるなら`true`を返すように実装します。 +- `InstallCommand()`メソッドで、引数で指定されたパッケージをインストールするための正確なコマンドを返すように実装します。 + +他のパッケージマネージャのコードを参考にして、これらのコードがどのように動作するか把握してください。 + +:::info リマインド + +新しいパッケージマネージャを追加した場合は、このページも忘れずに更新してください。 + +::: diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..e726244fc6e --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# Linux + +このページでは、Linux向けのWailsアプリケーション開発に関する、様々なガイドを掲載しています。 + +## videoタグが"ended"イベントを発火しない + +videoタグを使用している場合、ビデオの再生が終了しても"ended"イベントが発火しません。 これはWebkitのバグであり、次のような回避策を講じることで修正できます: + +```js +videoTag.addEventListener("timeupdate", (event) => { + if (event.target.duration - event.target.currentTime < 0.2) { + let ended = new Event("ended"); + event.target.dispatchEvent(ended); + } +}); +``` + +出典: [ディスカッションボード](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275)における[Lyimmi](https://github.com/Lyimmi)のコメント diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..f01fba42878 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# ローカル開発 + +## 概要 + +Wailsは現在も継続的に開発されており、定期的に、新しいリリースに対して"タグ付け"が行われています。 "タグ付け"は通常、`master`ブランチに存在する新しいコードがすべてテストされ、正常な動作が確認されたときに行われます。 まだリリースされていない新機能やバグフィックスを利用したい場合、以下の手順で"ブリーディング・エッジ"版を使用できます: + +- `git clone https://github.com/wailsapp/wails` +- `cd wails/v2/cmd/wails` +- `go install` + +注意: このページでは、Wailsプロジェクトをクローンしたディレクトリのことを"clonedir"と記します。 + +この手順により、Wails CLIは一番最新のバージョンとなります。 + +### 自身のプロジェクトの更新 + +クローンした最新バージョンのWailsライブラリを自身のプロジェクトで使用させたい場合、`go.mod`ファイルの末尾に次の行を追記してください: + +`replace github.com/wailsapp/wails/v2 => ` + +例: + +Windowsの場合: `replace github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2` + +'nixの場合: `replace github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2` + +安定バージョンに戻す場合は、次のコマンドを実行します: + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` + +## ブランチのテスト + +先述の手順に従えば、ブランチをテストすることができますが、インストールを実行する前に、テスト対象のブランチに切り替えるようにしてください: + +- `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` + +そして、先述のとおり[自身のプロジェクトを更新](#updating-your-project)してください。 + +## プルリクエストのテスト + +先述の手順に従えば、プルリクエストをテストすることができますが、インストールを実行する前に、テスト対象のプルリクエストを取得してブランチを切り替えるようにしてください。 下記手順の`[IDofThePR]`の部分は、github.comで表示されているプルリクエストのIDに置き換えてください: + +- `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` + +そして、先述のとおり[自身のプロジェクトを更新](#updating-your-project)してください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..b9cbf912aa2 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# Mac App Storeガイド + +このページでは、WailsアプリをMac App Storeで公開する方法について、概要を説明します。 + +## 前提条件 + +- Apple Developerアカウントを所持しておく必要があります。 詳しくは、[Apple Developer Program](https://developer.apple.com/support/compare-memberships/)のサイトを確認してください。 +- 開発者ポータルで、証明書、ID、アプリを作成しておく必要があります。 詳しくは以下の手順に従ってください。 +- Xcodeコマンドラインツールを、あなたのローカルマシンにインストールしておく必要があります。 + +#### 証明書とIDの作成 + +1. [Apple Developerアカウント](https://developer.apple.com/account/)へアクセスします。 +2. `Certificates, Identifiers & Profiles`内にある`Identifiers`をクリックし、新しいApp IDを登録します。 (com.example.app) のような形式にしてください。 +3. 同じページで`Certificates`をクリックし、Mac App Storeディストリビューション用の新しい証明書を生成します。 それらの証明書をダウンロードし、ローカルマシンのKeychainにインポートしてください。 + +#### アプリ提出物の作成 + +1. [App Store Connectサイト](https://appstoreconnect.apple.com/apps)へアクセスします。 +2. 新しいアプリケーションを登録し、前のステップで作成済みのバンドルIDをリンクします。 +3. Appleの要求する正規のスクリーンショットや説明文などを、アプリに追加します。 +4. アプリの新しいバージョンを作成します。 + +#### プロビジョニングプロファイルの作成 +1. [Apple Developerプロフィール](https://developer.apple.com/account/resources/profiles/list)ページへアクセスします。 +2. Mac App Storeへの配布用に、新しいプロビジョニングプロファイルを追加します。 +3. プロファイルタイプをMacに設定し、先ほど作成したアプリケーションのApp IDを選択します。 +4. Mac App Distribution証明書を選択します。 +5. 埋め込みプロビジョニングプロファイルに名前をつけ、作成されたプロファイルをダウンロードします。 + +## Mac App Storeへの公開手順 + +#### AppleのApp Sandboxの有効化 + +Mac App Storeへ提出されるアプリは、Appleの[App Sandbox](https://developer.apple.com/app-sandboxing/)内で動作する必要があります。 そのためには、`entitlements.plist`ファイルを作成しておく必要があります。 ファイルは、`{PROJECT_DIR}/build/darwin/entitlements.plist`配下に作成することを推奨します。 + +**entitlementsファイルの例** + +ここでは、[RiftShare](https://github.com/achhabra2/riftshare)というアプリのentitlementsファイルを例として示します。 参考として、アプリが必要とする権限を入力してください。 詳しくは、[こちらのサイト](https://developer.apple.com/documentation/bundleresources/entitlements)をご覧ください。 チーム ID とアプリケーション名を上記で登録したものに置き換える必要があります。 + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +**組み込みプロビジョニング プロファイルの追加** 上記で作成したプロビジョニング プロファイルは、アプリケーションのルートに追加する必要があります。 embedded.provisionprofile という名前にする必要があります。 + +#### アプリパッケージのビルドと署名 + +以下は、Mac App Storeへの提出用に、アプリをビルドおよび署名するスクリプトの例です。 プロジェクトのルートディレクトリからスクリプトを実行することを前提としています。 + +アプリへ署名するための証明書と、インストーラへ署名するための証明書は異なりますので、ご注意ください。 両方の証明書がKeychainにインポートされていることを確認してください。 Keychainで文字列を探し、下記スクリプトに挿入してください。 具体的には、証明書名およびアプリ名を入力します。 以下のスクリプトを実行すると、アプリケーションのルートディレクトリに、署名済みの`app.pkg`ファイルが生成されます。 + +```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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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 +``` + +#### アプリバンドルのアップロード + +審査向けに提出が可能となる前に、生成されたパッケージファイルをアップロードし、アプリケーションに関連付ける必要があります。 + +1. Mac App Storeから[Transporter App](https://apps.apple.com/us/app/transporter/id1450874784)をダウンロードします。 +2. アプリを起動し、Apple IDでサインインします。 +3. +マークをクリックし、前のステップで生成済みの`APP_NAME.pkg`ファイルを選択します。 そしてアップロードします。 +4. [App Store Connect](https://appstoreconnect.apple.com/apps)サイトへ戻り、アプリ提出物ページへ戻ります。 App Storeで公開する準備できているバージョンを選択します。 `Build`内で、Transporter経由でアップロードしたパッケージを選択します。 + +以上で終了です! サイトで、アプリを審査のために提出できるようになりました。 数営業日後、審査結果に問題が無ければ、アプリがMac App Storeに公開されます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..884f9e8c3a0 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# 手動ビルド + +Wails CLIは、プロジェクトに関する様々な面倒な作業を担ってくれていますが、ときにはプロジェクトを手動でビルドできたほうが望ましい場合もあるでしょう。 このドキュメントでは、CLIが実行する多くの操作や、これらの操作を別の手段で実現するための方法について説明します。 + +## ビルドプロセス + +Wails CLIは、`wails build`コマンドまたは`wails dev`コマンドが使用されると、共通のビルドプロセスを実行します: + + - フロントエンド依存関係のインストール + - フロントエンドのビルド + - ビルドアセットの生成 + - アプリケーションのコンパイル + - [任意] アプリケーションの圧縮 + +### フロントエンド依存関係のインストール + +#### CLIが実行する手順 + +- `-s`フラグが指定された場合、この手順をスキップします。 +- `wails.json`ファイル内で、`frontend:install`キーにインストールコマンドが記述されているかを確認します。 +- 記述されていない場合、この手順をスキップします。 +- 記述されている場合、フロントエンドディレクトリ内に`package.json`ファイルが存在するか確認します。 存在しない場合、この手順をスキップします。 +- `package.json`ファイルの内容をもとに、MD5チェックサムを生成します。 +- `package.json.md5`ファイルが存在するか確認し、存在する場合は、さきほど生成したMD5チェックサムと比較して、内容が変更されていないかどうかを確認します。 内容が同じ場合、この手順をスキップします。 +- `package.json.md5`ファイルが存在しない場合、ファイルを作成し、さきほど生成したMD5チェックサムを書き込みます。 +- この時点でビルドが必要と判断された場合、`node_modules`ディレクトリが存在しない場合、または`-f`フラグが指定された場合は、フロントエンドディレクトリ内でインストールコマンドを実行します。 + +#### 手動で実行する手順 + +コマンドライン、または`npm install`のスクリプトを用いて、この手順を実行してください。 + +### フロントエンドのビルド + +#### Wails CLIでの手順 + +- `-s`フラグが指定された場合、この手順をスキップします。 +- `wails.json`ファイル内で、`frontend:build`キーにビルドコマンドが記述されているかを確認します。 +- 記述されていない場合、この手順をスキップします。 +- 記述されている場合、フロントエンドディレクトリ内でコマンドが実行されます。 + +#### 手動で実行する手順 + +コマンドライン、`npm run build`のスクリプト、またはフロントエンドのビルドスクリプトを用いて、この手順を実行してください。 + +### アセットの生成 + +#### Wails CLIでの手順 + +- `-nopackage`フラグが指定された場合、この手順をスキップします。 +- `build/appicon.png`ファイルが存在しない場合、デフォルトのファイルを作成します。 +- Windowsの場合、[Windowsバンドル](#windows)の節を参照してください。 +- `build/windows/icon.ico`ファイルが存在しない場合、`build/appicon.png`画像ファイルから新規作成します。 + +##### Windows + +- `build/windows/icon.ico`ファイルが存在しない場合、`build/appicon.png`ファイルをもとに、256、128、64、48、32、16サイズのアイコンを新規作成します。 この処理は[winicon](https://github.com/leaanthony/winicon)によって実現しています。 +- `build/windows/.manifest`ファイルが存在しない場合、デフォルトバージョンから新規作成します。 +- アプリケーションを本番ビルドとしてコンパイルします(上記のとおり)。 +- [winres](https://github.com/tc-hib/winres)を使用して、アイコンとマニフェストをリンクできる`.syso`ファイルにバンドルします。 + +#### 手動で実行する手順 + +- [winicon](https://github.com/leaanthony/winicon)のCLIツール(または他の任意ツール)を使用して、`icon.ico`を作成します。 +- アプリケーションの`.manifest`ファイルを作成または更新します。 +- [winres CLI](https://github.com/tc-hib/go-winres)を使用して、`.syso`ファイルを生成します。 + +### アプリケーションのコンパイル + +#### Wails CLIでの手順 + +- `-clean`フラグが指定された場合、`build`ディレクトリを削除して再作成します。 +- `wails dev`コマンドの場合、デフォルトで次のGoフラグを使用するようにします: `-tags dev -gcflags "all=-N -l"` +- `wails build`コマンドの場合、デフォルトで次のGoフラグを使用するようにします: `-tags desktop,production -ldflags "-w -s"` + - Windowsの場合: `-ldflags "-w -h -H windowsgui"` +- `-tags`フラグを使用してCLIに指定された追加タグを、デフォルトのタグに追記します。 +- `-ldflags`フラグを使用してCLIに指定された追加のldflagsを、デフォルトのタグに追記します。 +- `-o`フラグのパラメータをパススルーさせます。 +- `-compiler`フラグで指定されたGoコンパイラを、コンパイル時に使用するようにします。 + +#### 手動で実行する手順 + +- 開発ビルドの場合、最小のコマンドは次のとおりです: `go build -tags dev -gcflags "all=-N -l"` +- 本番ビルドの場合、最小のコマンドは次のとおりです: `go build -tags desktop,production -ldflags "-w -s -H windowsgui"` +- `.syso`ファイルと同じディレクトリでコンパイルするようにしてください。 + +### アプリケーションの圧縮 + +#### Wails CLIでの手順 + +- `-upx`フラグが指定された場合、アプリケーションを圧縮するために、`upx`プログラムをデフォルト設定で実行します。 +- `-upxflags`フラグも指定された場合、デフォルト設定の代わりにこれらのフラグを使用します。 + +#### 手動で実行する手順 + +- `upx [flags]`を手動で実行して、アプリケーションを圧縮します。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..68319030e81 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,191 @@ +# v1からの移行 + +## 概要 + +Wails v2は、v1から大幅に変更されています。 このドキュメントでは、変更点、および既存のプロジェクトを移行する方法に焦点をあてて説明します。 + +### アプリケーションの作成 + +v1では、`wails.CreateApp`でメインアプリケーションを作成して、`app.Bind`でバインディングを追加し、`app.Run()`でアプリケーションを起動していました。 + +例: + +```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() +``` + +v2では、`wails.Run()`メソッドだけが、[アプリケーションオプション](../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, + }, + }) +``` + +### バインディング + +v1では、任意の関数と構造体の両方をバインドすることが可能でした。 v2では、構造体のみバインドできるようになり、シンプルになりました。 v1において`Bind()`メソッドに渡していた構造体のインスタンスは、[アプリケーションオプション](../reference/options.mdx#application-options)の`Bind`フィールドで指定できます。 + +```go title="v1" + app := wails.CreateApp(/* options */) + app.Bind(basic) +``` + +```go title="v2" + err := wails.Run(&options.App{ + /* other options */ + Bind: []interface{}{ + basic, + }, + }) +``` + +v1では、バインドされたメソッドをフロントエンドから利用するには`window.backend`を使用していました。 これは`window.go`に変更されました。 + +### アプリケーションライフサイクル + +v1では、バインドされた構造体の中に、`WailsInit()`および`WailsShutdown()`という2つの特別なメソッドが存在しました。 これらは、[アプリケーションオプション](../reference/options.mdx#application-options)の一部として、3つのライフサイクルフックに置き換えられています: + +- [OnStartup](../reference/options.mdx#onstartup) +- [OnShutdown](../reference/options.mdx#onshutdown) +- [OnDomReady](../reference/options.mdx#ondomready) + +注意: [OnDomReady](../reference/options.mdx#ondomready)は、v1での`wails:ready`システムイベントに代わるものです。 + +これらのメソッドは標準的な関数を指定できますが、一般的には、それらのメソッドを構造体の一部として保持しておきます: + +```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 +} +... +``` + +### ランタイム + +v2のランタイムはv1よりも非常に充実しており、メニュー、ウィンドウ操作、優れたダイアログをサポートしています。 メソッドのシグネチャが若干変更されていますので、詳しくは[ランタイムのリファレンス](../reference/runtime/intro.mdx)を参照してください。 + +v1では、`WailsInit()`に渡された構造体を介して[ランタイム](../reference/runtime/intro.mdx)を利用できていました。 v2では、ランタイムは独自のパッケージとして移植されています。 ランタイムの各メソッドは、[OnStartup](../reference/options.mdx#onstartup)メソッドで受け渡される`context.Context`を引数に取ります。 + +```go title="Runtime Example" +package main + +import "github.com/wailsapp/wails/v2/pkg/runtime" + +type Basic struct { + ctx context.Context +} + +// startupはアプリケーション起動時に呼び出される +func (a *App) startup(ctx context.Context) { + a.ctx = ctx + runtime.LogInfo(ctx, "Application Startup called!") +} + +``` + +### アセット + +v2での_最も大きな_変更は、アセットの取り扱い方です。 + +v1では、2つのアプリケーションオプションを介してアセットを指定していました: + +- `JS` - アプリケーションのJavaScript +- `CSS` - アプリケーションのCSS + +これは、単一のJSファイルおよびCSSファイルを、開発者が責任をもって作成する必要があることを意味していました。 基本的には、webpackのような複雑なパッカーを使用する必要がありました。 + +v2では、Wailsは一般的なWebサーバと同じように、フロントエンドアセットは何でも構いません。 すべてのアプリケーションアセットは、`embed.FS`インスタンスとしてアプリケーションオプションに渡されます。 + +**つまりアセットをバンドルしたり、画像をBase64でエンコードしたり、カスタムフォントを使用するためにバンドラーの設定を工夫したりする必要は一切ありません**。 + +アプリケーション起動時に、Wailsは、あらかじめ`embed.FS`で指定されたディレクトリ内をスキャンして`index.html`を探し、Webサーバの挙動のように、その場所をすべてのアプリケーションアセットのルートパスとみなします。 + +例: とあるアプリケーションのプロジェクトディレクトリの構成が次のようになっているとします。 この場合、最終的に必要なすべてのアセットは`frontend/dist`ディレクトリ配下に配置される必要があります: + +```shell +. +├── build/ +├── frontend/ +│ └── dist/ +│ ├── index.html +│ ├── main.js +│ ├── main.css +│ └── logo.svg +├── main.go +└── wails.json +``` + +これらのアセットは、`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, + }, + }) +} +``` + +もちろん、必要に応じてバンドラを使用することもできます。 唯一行わなければいけないことは、[アプリケーションオプション](../reference/options.mdx#application-options)の`Assets`キーに`embed.FS`インスタンスを指定して、Wailsにアプリケーションアセットディレクトリを教えてあげることです。 + +### プロジェクト構成 + +v1では、プロジェクトルートに存在する`project.json`ファイルで、プロジェクト構成を管理していました。 v2では、プロジェクトルートにある`wails.json`ファイルでプロジェクト構成を管理します。 + +フォーマットは若干変更されています。 比較表は次のとおりです: + +

+ +| v1 | v2 | 備考 | +| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| name | name | | +| description | | 消去されました | +| author / name | author / name | | +| author / email | author / email | | +| version | version | | +| binaryname | outputfilename | 変更されました | +| frontend / dir | | 消去されました | +| frontend / install | frontend:install | 変更されました | +| frontend / build | frontend:build | 変更されました | +| frontend / bridge | | 消去されました | +| frontend / serve | | 消去されました | +| tags | | 消去されました | +| | wailsjsdir | wailsjsモジュールを生成するディレクトリ | +| | assetdir | `dev`モードでコンパイルされたフロントエンドアセットのディレクトリ。 通常は自動推定されるため、空のままで構いません。 | +| | reloaddirs | `dev`モードでリロードをトリガーさせたい追加のディレクトリを指定するための、カンマ区切りのリスト。 高度なアセット構成をとる場合にのみ必要です。 | + +

diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..58ee21c687a --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# マウスボタン + +Wailsランタイムでは、マウスクリックを途中で捕捉し、フレームレスウィンドウのサイズ変更が必要かどうかや、ウィンドウの移動が必要かどうかを判断しています。 `window.onclick`はマウスボタンを正しく報告しないため、どのようにマウスクリックが発生したことを検出しているのかを尋ねられました。 以下のコードは、マウスクリックを検出する方法を示しています: + +```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 + } +} +``` + +参考: https://developer.mozilla.org/ja/docs/Web/API/MouseEvent/button diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..9b5bab1fe7f --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# 難読化されたビルド + +Wailsでは、[garble](https://github.com/burrowers/garble)を使用したアプリケーションの難読化をサポートしています。 + +`wails build`コマンドで`-obfuscate`フラグを使用することで、ビルド時に難読化を有効にすることができます: + +```bash +wails build -obfuscated +``` + +また、難読化に関する設定をカスタマイズするために、`-garbleargs`フラグを使用できます: + +```bash +wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed" +``` + +これらの設定は、[プロジェクト構成](../reference/project-config)で記述されている場合もあります。 + +## 動作の仕組み + +標準のビルドでは、バインドされたすべてのメソッドは、フロントエンドの`window.go`変数から利用することができます。 これらのメソッドが呼び出されると、対応するバックエンドメソッドが完全修飾関数名で呼び出されます。 難読化ビルドの場合、メソッドは名前の代わりにIDでバインドされます。 `wailsjs`ディレクトリに生成されたバインディングは、このIDを使用してバックエンドの関数を呼び出します。 + +:::note + +アプリケーションを難読化した状態で動作させるためには、`wailsjs`ディレクトリの配下に生成されたバインディングを使用する必要があります。 + +::: + +## 例 + +Importing the "Greet" method from the bindings like this: + +```js +import { Greet } from "../../wailsjs/go/main/App"; + +// snip +Greet("World"); +``` + +これは、バインディングがIDで再生成され、呼び出しメカニズムが更新されるため、難読化モードでメソッドが正しく動作することを保証します。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..4ee1db0e4ff --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# オーバースクロール + +[オーバースクロール](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior)は、ページコンテンツの境界を越えてスクロールした際に発生する"バウンス効果"です。 この効果はモバイルアプリでよく見かけます。 CSSを使用することでこの効果を無効化できます: + +```css +html { + height: 100%; + overflow: hidden; +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..ba9195d2bb2 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,47 @@ +# ルーティング + +アプリケーションでビューを切り替える一般的な方法は、ルーティングです。 このページでは、ルーティングを実現する方法をいくつか紹介します。 + +## Vue + +Vueにおいてルーティングで推奨されるアプローチは、[ハッシュモード](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 + +Angularにおいてルーティングで推奨されるアプローチは、[HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies#_hashlocationstrategy)となります: + +```ts +RouterModule.forRoot(routes, { useHash: true }); +``` + +## React + +Reactにおいてルーティングで推奨されるアプローチは、[HashRouter](https://reactrouter.com/en/main/router-components/hash-router)となります: + +```jsx +import { HashRouter } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..8b57d7e0fe3 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# コード署名 + +このガイドでは、MacOSおよびWindowsでWailsによって生成されたバイナリに署名するための方法を解説します。 このガイドは、CI環境、とりわけGitHub Actionsを対象としています。 + +## Windows + +まず初めに、コード署名証明書が必要となります。 まだ証明書を持っていない場合は、[こちら](https://docs.microsoft.com/en-us/windows-hardware/drivers/dashboard/get-a-code-signing-certificate)のMicrosoftのページに、いくつかのプロバイダーが紹介されていますので入手してください、 デバイスドライバといったカーネルレベルのソフトウェアを作成する必要がない限り、EV証明書を入手する必要はありません。 Wailsアプリに署名する場合、標準のコード証明書で問題ありません。 + +自動ビルドシステムを対象に作業する前に、ローカルマシン上でバイナリに署名する方法を証明書プロバイダに確認し、特別な要件がないかを確認することを推奨します。 例えば、[こちら](https://www.ssl.com/how-to/using-your-code-signing-certificate/)はSSL.comのWindows向けコード署名ガイドです。 ローカル環境での署名方法が分かっていれば、CI環境で発生するかもしれない問題のトラブルシューティングが容易になることでしょう。 例えば、SSL.comのコード署名証明書は[SignTool.exe](https://docs.microsoft.com/en-us/windows/win32/seccrypto/signtool)において`/tr`フラグを指定する必要がありますが、他の証明書プロバイダでは、タイムスタンプサーバの提供のために、`/t`フラグのみ必要である場合もあります。 [こちら](https://github.com/Dana-Prajea/code-sign-action)のような、Windowsバイナリの署名によく使われるGitHub Actionsのアクションは、SignTool.exeの`/tr`フラグに対応していません。 したがって、このガイドではPowerShellコマンドを使用して手動でアプリケーションに署名する方法に焦点をあてます。ただし、必要であれば[code-sign-action](https://github.com/Dana-Prajea/code-sign-action)アクションといったアクションを使用することも可能です。 + +まずは、GitHub CIでWailsアプリをビルドできるようにしておきましょう。 簡単なワークフローテンプレートは次のとおりです: + +```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 + # 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/* +``` + +次に、GitHubワークフローに署名証明書へのアクセス権を付与する必要があります。 これは、.pfxまたは.p12形式の証明書をbase64文字列にエンコードすることで実現できます。 PowerShellの場合、証明書名が仮に'my-cert.p12'だとすると、次のコマンドが使用できます: + +```PowerShell +certutil -encode .\my-cert.p12 my-cert-base64.txt +``` + +これで、base64でエンコードされた証明書が含まれる.txtファイルが作成されます。 このファイルの中身は、_-----BEGIN CERTIFICATE-----_で始まり、_-----END CERTIFICATE-----_で終わる必要があります。 次に、GitHubで2つのActions secretsを作成します。 _Settings -> Secrets -> Actions_のページに移動し、2つのシークレットを作成してください: + +- **WIN_SIGNING_CERT** には、base64エンコードされた証明書テキストの内容を設定します。 +- **WIN_SIGNING_CERT_PASSWORD** には、証明書のパスワードを設定します。 + +ここまでの作業で、次の2つのいずれかの方法を使用して、ワークフローによる署名処理を実装する準備が整いました。 + +### 方法1: コマンドを使用して署名 + +この方法では、Power Shellコマンドを使用してアプリに署名し、署名プロセス全体をコントロールします。 + +`"Build Wails app"`ステップのあとに、下記のステップをワークフローに追加してください。 + +```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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +このスクリプトでは、証明書ファイル用に新しいディレクトリを作成して、base64シークレットから証明書ファイルを作成します。その証明書を.pfxファイルに変換し、最後にバイナリへ署名します。 下記の変数は、最後の行内で置換してください: + +- **signing algorithm**: 通常は、sha256。 +- **timestamping server**: 証明書で使用するタイムスタンプサーバのURL。 +- **path to binary**: 署名したいバイナリへのパス。 + +Wailsの構成において`outputfilename`に"app.exe"という値が設定されており、SSL.comでの証明書が用意されている場合、次のようなワークフローとなります: + +```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 + # 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/* +``` + +### 方法2: アクションを使用して自動的に署名 + +[こちら](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate)のようなWindowsコード署名のためのアクションを使用することはできますが、証明書用のSHA1ハッシュや証明書名が必要であることに注意してください。 詳しくは、アクションの[マーケットプレイス](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate)で、使用方法を確認してください。 + +--- + +## MacOS + +まずは、Appleのコード署名証明書が必要です。 もし所有していない場合は、Googleで検索すれば取得方法が分るでしょう。 証明書を入手できたら、それをエクスポートし、base64でエンコードする必要があります。 [このチュートリアル](https://localazy.com/blog/how-to-automatically-sign-macos-apps-using-github-actions)をご覧いただければ、簡単にエンコードする方法が分ります。 .p12証明書ファイルをエクスポートした場合、次のコマンドを使用して、チュートリアルで示されているようにbase64にエンコードできます: + +```bash +base64 Certificates.p12 | pbcopy +``` + +これにより、Windowsと同様に、GitHubプロジェクトにいくつかのシークレットを設定する準備が整いました: + +- **APPLE_DEVELOPER_CERTIFICATE_P12_BASE64**には、新しくコピーしたbase64証明書の内容を設定します。 +- **APPLE_DEVELOPER_CERTIFICATE_PASSWORD**には、証明書のパスワードを設定します。 +- **APPLE_PASSWORD**には、[こちら](https://appleid.apple.com/account/manage)で生成できるアプリ固有のパスワードを設定します。 + +GitHub Actionのワークフローで、Wailsアプリをビルドできるようにしましょう。 簡単な例は次のとおりです: + +```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 + # 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/* +``` + +macOSでコード署名をするときは、[gon](https://github.com/mitchellh/gon)という非常に便利なツールを使うことで、コード署名およびAppleサーバとの通信ができます。これはGoで記述されており、このガイドでも使用されています。 + +`Build Wails app`ステップの後に、次のワークフローを追加します: + +```yaml +- name: MacOS download gon for code signing and app notarization + if: matrix.platform == 'macos-latest' + run: | + brew install mitchellh/gon/gon +``` + +ここで、`build/darwin`ディレクトリ内に、gonの構成設定ファイルを用意する必要があります: + +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" + } +} +``` + +`source`にはWailsのバイナリファイルの場所、`bundle_id`にはバンドルID、`apple_id`にはあらかじめ作成したApple IDのユーザ名とアプリ固有のパスワード、`sign.application_identity`には次のコマンドを実行することで分かるIDを指定します: + +```bash +security find-identity -v -p codesigning +``` + +2. entitlements.plist: + +```plist + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +このファイルでは、アプリに必要な権限(たとえば、アプリがカメラを使用する場合、カメラへのアクセス権限)を設定します。 権限について詳しくは[こちら](https://developer.apple.com/documentation/bundleresources/entitlements)をご覧ください。 + +`Info.plist`ファイルのバンドルIDを、`gon-sign.json`に入力したものと同じIDに書き換えてください。 次は、`Info.plist`ファイルの例です: + +```plist + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +これで、Wailsアプリをビルドしたあとに、ワークフローに署名のステップを追加する準備ができました: + +```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 +``` + +Appleでバイナリに署名する場合、数分から数時間程度の所要時間がかかることがありますのでご注意ください。 + +## ワークフローファイルの組み合わせ + +WindowsとmacOSを組み合わせたGitHubワークフローファイルの例は次のとおりです: + +```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 + # 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/* +``` + +# おわりに + +このガイドは、RiftShareプロジェクトとそのワークフローに触発されて作成されたものであり、 [こちら](https://github.com/achhabra2/riftshare/blob/main/.github/workflows/build.yaml)を併せて確認することを強く推奨します。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..4651c422ed1 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +This guide will go into: + +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. Minimal Installation Steps + +##### Install Wails for Svelte. + +- `wails init -n myapp -t svelte` + +##### Delete the svelte frontend. + +- Navigate into your newly created myapp folder. +- Delete the folder named "frontend" + +##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts. + +- `npm create svelte@latest frontend` + +##### Modify 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. + +##### Modify main.go. + +- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build` + +##### Install/remove dependencies using your favorite package manager. + +- Navigate into your "frontend" folder. +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Change adapter in svelte.config.js + +- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Put SvelteKit into SPA mode with prerendering. + +- 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` + +##### Test 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. + +## 2. Install Script + +##### 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. + +- 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` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Important Notes + +##### Server files will cause build failures. + +- \+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. + +##### The Wails runtime unloads with full page navigations! + +- Anything that causes full page navigations: `window.location.href = '//'` 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('//')` 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 `` of myapp/frontend/src/app.html + +``` + +... + + + +... + +``` + +See https://wails.io/docs/guides/frontend for more information. + +##### Inital data can be loaded and refreshed from +page.ts/+page.js to +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. + +##### Error Handling + +- 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. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Using Forms and handling functions + +- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `` +- 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: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..8e1f8304557 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# テンプレート + +Wailsは、事前に作成されたテンプレートからプロジェクトを生成します。 v1では、テンプレートがメンテナンス困難なプロジェクトとなり、時代遅れとなってしまう可能性がありました。 v2では、コミュニティを強化するために、テンプレートにいくつかの新機能が追加されました: + +- [リモート点テンプレート](../reference/cli.mdx#remote-templates)からプロジェクトを生成する機能 +- 独自のテンプレートの作成に役立つツール + +## テンプレートの作成 + +テンプレートを作成するには、`wails generate template`コマンドを使用します。 デフォルトのテンプレートを生成する場合は、次のコマンドを実行してください: + +`wails generate template -name mytemplate` + +これにより、デフォルトのファイルが含まれた"mytemplate"ディレクトリが作成されます: + +```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 +``` + +### テンプレートの概要 + +デフォルトのテンプレートは、次のファイルおよびディレクトリで構成されています: + +| ファイル名 / ディレクトリ名 | 説明 | +| --------------- | ----------------------- | +| NEXTSTEPS.md | テンプレートを完成させる手順を記した説明 | +| README.md | テンプレートとともに公開されるREADME | +| app.tmpl.go | `app.go`のテンプレートファイル | +| frontend/ | フロントエンドアセットを含むディレクトリ | +| go.mod.tmpl | `go.mod`のテンプレートファイル | +| main.tmpl.go | `main.go`のテンプレートファイル | +| template.json | テンプレートのメタデータ | +| wails.tmpl.json | `wails.json`のテンプレートファイル | + +このあとは、`NEXTSTEPS.md`に記述されている手順に従うことを推奨します。 + +## 既存プロジェクトからのテンプレート作成 + +テンプレートの生成時にプロジェクトへのパスを渡すことで、既存のフロントエンドプロジェクトから、テンプレートを作成することができます。 ここでは、Vue3テンプレートの作成方法を説明します: + +- Vue Cliをインストールする: `npm install -g @vue/cli` +- デフォルトのプロジェクトを作成する: `vue create vue3-base` + - その際、`Default (Vue 3) ([Vue 3] babel, eslint)`を選択します +- プロジェクトが作成されたあとに、次のコマンドを実行する: + +```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... +``` + +- `NEXTSTEPS.md`ファイルに記述されているように、テンプレートをカスタマイズする +- ファイルの準備ができたら、次のコマンドを実行してテストする: `wails init -n my-vue3-project -t .\wails-vue3-template\` +- 新しいプロジェクトの動作をテストするために、次のコマンドを実行する: `cd my-vue3-project`および`wails build` +- プロジェクトがコンパイルされたら、実行する: `.\build\bin\my-vue3-project.exe` +- Vue3アプリケーションが完全に動作していることを確認する + +```mdx-code-block +
+ +
+``` + +## テンプレートの公開 + +テンプレートを公開するためにすることは、ファイルをGitHubにプッシュすることだけです。 以下のベストプラクティスを実施することを推奨します: + +- 不要なファイルやディレクトリ(`.git`など)をフロントエンドディレクトリから削除する +- `template.json`がきちんと記述されていること、とくに`helpurl`が記述されていることを確認する +- ファイルをGitHubにプッシュする +- [コミュニティのテンプレート](../community/templates.mdx)ページにプルリクエストを作成する +- [Template Announcement](https://github.com/wailsapp/wails/discussions/825)のディスカッションボードでテンプレートをアナウンスする diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..eb93618657c --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# トラブルシューティング + +このページは、トラブルシューティングを手助けするヒント集です。 + +## `wails`コマンドが見つからないのですが? + +`wails`コマンドが見つからないとシステムに怒られた場合は、Goが、公式のGoインストール手順に従って導入されているかを確認してください。 コマンドが見つからないほとんどの理由は、あなたのホームディレクトリ配下にある`go/bin`ディレクトリのパスが、`PATH`環境変数に含まれていないからです。 また、インストールによって行われた環境変更を反映させるために、もともと開いていたコマンドプロンプト(ターミナル)がある場合はそれらをいったん閉じて、再度開きなおしてください。 + +## アプリケーションがホワイト/ブラックスクリーン表示になってしまいます + +アプリケーション内で、正しいディレクトリでアセットが指定されていることを確認してください。 `main.go`ファイル内には、以下のようなコードが存在します: + +```go +//go:embed all:frontend/dist +var assets embed.FS +``` + +また、`frontend/dist`ディレクトリ内に、アプリケーションアセットがきちんと含まれているか確認してください。 + +### Mac + +この事象がMacで発生した場合は、`Info.plist`に以下の記述を追加してみてください: + +```xml +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +参考: https://github.com/wailsapp/wails/issues/1504#issuecomment-1174317433 + +## Macのアプリケーションが無効になっています + +ビルドしたアプリケーションが次のように表示される場合: + +```mdx-code-block +

+ +

+``` + +アプリケーションの`info.plist`が無効である可能性があります。 `build/.app/Contents/info.plist`ファイルを更新し、データが有効かどうかを確認します。たとえば、バイナリ名が正しいかどうかを確認してください。 変更を反映するには、ファイルを`build/darwin`ディレクトリにコピーします。 + +## Windowsのエクスプローラにアプリケーションアイコンが正しく表示されません + +アプリケーションアイコンが正しく表示されない場合は、`C:\Users\<あなたのユーザ名>\AppData\Local`ディレクトリ内にある、`IconCache.db`という隠しファイルを削除してみてください。 これにより、Windowsのアイコンキャッシュが強制的に再作成されます。 + +出典: https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## 可変長引数を持つバックエンドメソッドをフロントエンドから呼び出せません + +次のように、可変長引数を持つバックエンドメソッドが定義されている場合: + +```go +func (a *App) TestFunc(msg string, args ...interface{}) error { + // Code +} +``` + +このメソッドを、次のようにフロントエンドから呼び出すと失敗します: + +```js +var msg = "Hello: "; +var args = ["Go", "JS"]; +window.go.main.App.TestFunc(msg, ...args) + .then((result) => { + //do things here + }) + .catch((error) => { + //handle error + }); +``` + +回避方法: + +```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 + }); +``` + +出典: https://github.com/wailsapp/wails/issues/1186 + +## Wailsのインストール時にプロキシエラーが発生します + +次のようなエラーが発生する場合: + +``` +"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. +``` + +おそらく、公式のGo Proxyがブロックされています (中国のユーザより報告されています)。 解決するには、次のように、プロキシを手動で設定します: + +``` +go env -w GO111MODULE=on +go env -w GOPROXY=https://goproxy.cn,direct +``` + +出典: https://github.com/wailsapp/wails/issues/1233 + +## 生成されたTypeScriptの型定義が正しくありません + +場合によっては、生成されるTypeScriptの型定義が誤っていることがあります。 この事象を軽減させるために、`ts_type`という構造体のタグを使用して、生成する型を指定することができます。 詳しくは、[こちら](https://github.com/tkrajina/typescriptify-golang-structs#custom-types)をご覧ください。 + +## `index.html`から移動するとフロントエンド上でメソッドを呼び出すことができません + +`index.html`から新しいhtmlファイルへ遷移すると、コンテキスト情報は失われてしまいます。 この事象を修正するには、遷移先の新しいページの``セクションに、次のインポートコードを追加します: + +```html + + + + +``` + +出典: https://github.com/wailsapp/wails/discussions/1512 + +## Macで`wails dev`を実行すると`too many open files`エラーが発生します + +デフォルトでは、macOSは最大で256個のファイルしか開くことができません。 この制限により、`wails dev`コマンド実行時に影響が発生する場合があります。 この制限は、ターミナルで次のようなコマンドを実行することで、緩和することができます: `ulimit -n 1024`。 + +FSNotifyは、Macのために、[Appleのfseventsへの移行を検討しています](https://github.com/fsnotify/fsnotify/issues/11)。 この移行が完了しない間は、[こちら](https://github.com/wailsapp/wails/issues/1733)で言及されているように、独自で実装を行います。 + +## Macアプリで不可解なコンパイルエラーが発生します + +一部のユーザより、次のようなコンパイルエラーが発生することがあるという報告を受けています: + +```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))) +``` + +これは_一般的に_、実行されているOSのバージョンと、インストールされているXCodeコマンドラインツールのバージョンが不一致であることが原因です。 このようなエラーが発生した場合は、XCodeコマンドラインツールを最新バージョンに更新してみてください。 + +XCodeコマンドラインツールの再インストールが引き続き失敗する場合は、次のコマンドを使用して、ツールキットがどこに配置されているかを確認できます: + +`xcode-select -p` + +`/Applications/Xcode.app/Contents/Developer`と表示された場合、`sudo xcode-select --switch /Library/Developer/CommandLineTools`というコマンドを実行してください。 + +出典: https://github.com/wailsapp/wails/issues/1806 および https://github.com/wailsapp/wails/issues/1140#issuecomment-1290446496 + +## My application won't compile on Mac + +次のようなエラーが発生する場合: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## Cannot start service: Host version "x.x.x does not match binary version "x.x.x" + +`frontend/node_modules`と`frontend/package-lock.json`を`.gitignore`に追加することをお勧めします。 そうしないと、異なるバージョンのNodeがインストールされている別のマシンでリポジトリを開いた際に、アプリケーションが実行できなくなる場合があります。 + +この事象が発生した場合は、単純に`frontend/node_modules`と`frontend/package-lock.json`を削除し、`wails build`コマンドおよび`wails dev`コマンドを再実行してください。 + +## ビルドプロセスが"Generating bindings"で停止します + +バインディングの生成プロセスは、アプリケーションを特別なモードで実行します。 アプリケーションに、意図に有無にかかわらず無限ループ(`wails.Run()`のあとに終了されないコード)が含まれている場合、バインディングの生成の段階でビルドプロセスが停止する可能性があります。 コードが正しく終了していることを確認してください。 + +## Mac application flashes white at startup + +This is due to the default background of the webview being white. If you want to use the window background colour instead, you can make the webview background transparent using the following config: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..86b7c16a487 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# Visual Studio Code + +このページでは、Wailsでの開発でVisual Studio Codeを使用する際のさまざまなヒントやコツをご紹介します。 + +## Veturの構成設定 + +このヒントを提供してくれた[@Lyimmi](https://github.com/Lyimmi)に感謝します。 このヒントは[こちら](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349)に投稿されたものです。 + +Veturは、Vueプロジェクトのシンタックスハイライトおよびコード補完を提供してくれる、Visual Studio Codeでのポピュラーな拡張機能です。 VSCodeでWailsのプロジェクトを読み込むと、Veturはルートディレクトリでフロントエンドのプロジェクトを見つけようとするため、エラーが発生します。 これを解消するためには、次の手順を実施します: + +プロジェクトのルートディレクトリに、`vetur.config.js`という名前のファイルを作成します。 + +```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' + ] + } + ] +} +``` + +次に、`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" + ] +} +``` +以上により、Veturを期待どおりに使用できるようになります。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..3e3ae9b5e70 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# NSISインストーラ + +```mdx-code-block +

+ +
+

+``` + +Wailsでは、[NSISインストーラ](https://nsis.sourceforge.io/)を使用したWindowsインストーラの生成をサポートしています。 + +## NSISのインストール + +### Windows + +インストーラは、[NSISダウンロード](https://nsis.sourceforge.io/Download)ページから入手できます。 + +Chocolateyパッケージマネージャを使用している場合は、次のスクリプトを実行することでインストールできます: + +``` +choco install nsis +``` + +NSISを手動でインストールする場合、NSISインストール時に作成される`makensis.exe`ファイルが含まれた_Bin_フォルダを、パスに追加する必要があります。 Windows上でパスを追加する方法については、[こちら](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/)の優れたチュートリアルをご覧ください。 + +### Linux + +`nsis`パッケージは、ディストリビューションのパッケージマネージャから入手できます。 + +### MacOS + +NSISは、homebrew経由でインストールできます: `brew install nsis`。 + +## インストーラの生成 + +新しくプロジェクトが作成されると、Wailsは、`build/windows/installer`内に、NSIS構成ファイルを生成します。 構成データは`installer/info.json`から読み込まれますが、当該データはプロジェクトの`wails.json`のInfo§の情報を使用するように設定されています: + +```json +// ... + "Info": { + "companyName": "My Company Name", + "productName": "Wails Vite", + "productVersion": "1.0.0", + "copyright": "Copyright.........", + "comments": "Built using Wails (https://wails.io)" + }, +``` + +アプリケーションのインストーラを生成するには、`wails build`コマンド実行時に、`-nsis`フラグを使用します: + +``` +wails build -nsis +``` + +これにより、`build/bin`ディレクトリにインストーラが生成されます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..0b47b152967 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# Windows + +このページでは、Windows向けのWailsアプリケーション開発に関する、様々なガイドを掲載しています。 + +## WebView2ランタイム依存関係のハンドリング + +Windows用にビルドされたWailsアプリケーションは、Microsoft [WebView2ランタイム](https://developer.microsoft.com/en-us/microsoft-edge/webview2/)がランタイム要件となっています。 Windows 11ではデフォルトでこのランタイムがインストールされていますが、一部のマシンではインストールされていません。 Wailsでは、この依存関係に対処するための簡単なアプローチを提供しています。 + +ビルド時に`-webview2`フラグを使用することで、アプリ起動時に適切なランタイムが検出されない場合(インストールされているランタイムが古すぎる場合を含む) に、アプリケーションがどのように動作するかを指定できます。 次の4つのオプションがあります: + +1. Download +2. Embed +3. Browser +4. Error + +### Download + +このオプションでは、適切なランタイムが見つからない旨をユーザに知らせ、MicrosoftのWebView2のサイトからダウンロードされる公式のブートストラッパを実行する提案をします。 ユーザが続行を選択した場合、公式のブートストラッパがダウンロードおよび実行されます。 + +### Embed + +このオプションでは、アプリケーション内に公式のブートストラッパの埋め込みます。 適切なランタイムが見つからない場合、アプリケーションはブートストラッパの実行を提案します。 これにより、バイナリサイズが150k程度増えます。 + +### Browser + +このオプションでは、適切なランタイムが見つからない旨をユーザに知らせ、ブートストラッパをダウンロードしてインストールすることのできるWebView2の公式ページをブラウザで開く提案をします。 続行した場合、アプリケーションは終了し、インストールをユーザに委ねます。 + +### Error + +このオプションでは、適切なランタイムが見つからない場合、ユーザにエラーが表示され、それ以上何の処理も実行しません。 + +## フィックスドバージョンランタイム + +WebView2の依存関係に対処するための別手段として、自身でランタイムを運ぶという方法が挙げられます。 [フィックスドバージョンランタイム](https://developer.microsoft.com/microsoft-edge/webview2/#download-section)をダウンロードしてバンドルするか、アプリケーション内でランタイムをダウンロードするようにします。 + +また、Wailsの起動時に`windows.Options`において、フィックスドバージョンWebView2ランタイムのパスを指定する必要があります。 + +```go + wails.Run(&options.App{ + Windows: &windows.Options{ + WebviewBrowserPath: "", + }, + }) +``` + +注意: `WebviewBrowserPath`が指定されている場合、必要な最低バージョンを満たしていなかったり、ランタイムへのパスが無効であったりすると、強制的に`error`オプションの挙動となります。 + +## 他のプログラムの起動 + +スクリプトなどの他のプログラムを起動すると、当該プログラムのウィンドウが画面に表示されます。 このウィンドウを表示させたくない場合は、次のコードを使用してください: + +```go +cmd := exec.Command("your_script.exe") +cmd.SysProcAttr = &syscall.SysProcAttr{ + HideWindow: true, + CreationFlags: 0x08000000, +} +cmd.Start() +``` + +この解決策は、[ディスカッションボード](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172)内で[sithembiso](https://github.com/sithembiso)により示されました。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..00fe1d68b73 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +sidebar_position: 20 +--- + +# どうやって動いているの? + +Wailsは、webkitフロントエンドを備えた、何の変哲もないGoアプリです。 アプリ全体のうちGoの部分は、アプリのコードと、ウィンドウ制御などの便利な機能を提供するランタイムライブラリで構成されています。 フロントエンドはwebkitウィンドウであり、フロンドエンドアセットをウィンドウ上に表示します。 フロントエンドからも、JavaScriptでランタイムライブラリを呼び出すことができます。 そして最終的に、Goのメソッドはフロントエンドにバインドされ、ローカルのJavaScriptメソッドであるかのように、フロントエンドから呼び出すことができます。 + +```mdx-code-block +
+ +
+``` + +## アプリのメインコード + +### 概要 + +アプリは、`wails.Run()`メソッドを1回呼び出すことで、構成することができます。 このメソッドで、アプリのウィンドウサイズやウィンドウタイトル、使用アセットなどを指定することができます。 基本的なアプリを作るコードは次のとおりです: + +```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) +} +``` + +### オプション + +上記のコードでは、次のオプションが指定されています: + +- `Title` - ウィンドウのタイトルバーに表示されるテキスト +- `Width` & `Height` - ウィンドウの大きさ +- `Assets` - アプリのフロントエンドアセット +- `OnStartup` - ウィンドウが作成され、フロントエンドの読み込みを開始しようとする時のコールバック +- `OnShutdown` - アプリを終了しようとするときのコールバック +- `Bind` - フロントエンドにバインドさせたい構造体インスタンスのスライス + +設定可能なすべてのオプションについては、[オプションのリファレンス](reference/options)をご覧ください。 + +#### アセット + +Wailsでフロントエンドアセット無しのアプリを作成することはできないため、`Assets`オプションは必須オプションです。 アセットには、一般的なWebアプリケーションでよく見かけるような、html、js、css、svg、pngなどのファイルを含めることができます。**アセットバンドルを生成する必要は一切なく**、そのままのファイルを使用できます。 アプリが起動すると、アセット内の`index.html`が読み込まれます。この時点で、フロントエンドはブラウザとして動作するようになります。 `embed.FS`を使ってアセットファイルが格納されたディレクトリを指定しますが、ディレクトリの場所はどこでも構いません。 embedで指定するパスは、`frontend/dist`のように、アプリのメインコードから相対的に見たディレクトリパスになります: + +```go title="main.go" +//go:embed all:frontend/dist +var assets embed.FS +``` + +起動時に、Wailsは`index.html`が含まれるディレクトリを再帰的に探します。 他のすべてのアセットは、当該ディレクトリから相対的に読み込まれます。 + +本番用のバイナリファイルには、`embed.FS`で指定されたアセットファイルが含まれるため、アプリ配布時に、バイナリファイルとは別にアセットファイルを付加させる必要はありません。 + +`wails dev`コマンドを使って開発モードでアプリを起動した場合、アセットはディスクから読み込まれ、アセットファイルが更新されると、自動的にアプリがライブリロードされます。 アセットの場所は、`embed.FS`での指定値から推定されます。 + +詳細は、[アプリ開発ガイド](guides/application-development.mdx)をご覧ください。 + +#### アプリのライフサイクル + +フロントエンドが`index.html`を読み込もうとする直前に、[OnStartup](reference/options.mdx#onstartup)で指定されたメソッドがコールバックされます。 Goの標準的なcontextがこのメソッドに渡されます。 このメソッドに引数で渡されるContextは、今後、Wailsのラインタイムを呼び出すときに必要になるため、通常は、このContextへの参照を保持しておいてください。 同様に、アプリがシャットダウンされる直前には、[OnShutdown](reference/options.mdx#onshutdown)で指定されたコールバックが呼び出され、Contextも渡されます。 `index.html`に含まれるすべてのアセットが読み込み終わったときに呼び出される[OnDomReady](reference/options.mdx#ondomready)コールバックもあります。これは、JavaScriptの[`body onload`](https://www.w3schools.com/jsref/event_onload.asp)イベントと同等のものです。 また、[OnBeforeClose](reference/options.mdx#onbeforeclose)を指定すると、ウィンドウを閉じる(またはアプリを終了する)イベントにフックさせることもできます。 + +#### メソッドのバインド + +`Bind`オプションは、Wailsアプリで最も重要なオプションの1つです。 このオプションでは、フロントエンドに公開する、構造体のメソッドを指定することができます。 構造体は、従来のWebアプリにおける"コントローラ"の立ち位置であるとお考えください。 アプリが起動すると、`Bind`オプションで指定されている構造体を対象に、その中にあるパブリックメソッド(大文字で始まるメソッド名)を探します。そして、フロントエンドのコードからそれらのメソッドを呼び出せるJavaScriptが生成されます。 + +:::info 備考 + +Wailsで構造体を正しくバインドするためには、構造体の*インスタンス*をオプションで指定してください。 + +::: + +下記のコードでは、新しく`App`インスタンスを作成し、`wails.Run`関数の`Bind`オプションの中で、そのインスタンスを追加しています: + +```go {17,27} 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) +} +``` + +構造体は、好きな数だけバインドできます。 `Bind`には、構造体のインスタンスを渡すようにしてください: + +```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{}, + }, + }) + +``` + +`wails dev`コマンド(または、`wails generate module`コマンド)を実行すると、以下のものを含むフロントエンドモジュールが生成されます: + +- バインドされたすべてのメソッドのJavaScript +- バインドされたすべてのメソッドのTypeScript宣言 +- バインドされたメソッドの引数または返り値で使用されているGoの構造体のTypeScript宣言 + +これにより、強力な型付けがなされたデータ構造を使用して、フロントエンドから簡単にGoのコードを呼び出すことができます。 + +## フロントエンド + +### 概要 + +フロントエンドは、webkitによってレンダリングされるファイル群です。 ブラウザとWebサーバが一体となったような動きをします。 使用できるフレームワークやライブラリの制限はほぼありません[^1]。 フロントエンドとGoコードとの相互のやり取りについて、主なポイントは次のとおりです: + +- バインドされたGoメソッドの呼び出し +- ランタイムメソッドの呼び出し + +### バインドされたGoメソッドの呼び出し + +`wails dev`コマンドでアプリを起動すると、Go構造体のJavaScriptバインディングが`wailsjs/go`ディレクトリに自動的に生成されます(`wails generate module`コマンドでも生成可能)。 生成されたファイルには、アプリ内のGoパッケージ名が反映されています。 先の例では、`Greet`というパブリックメソッドを持つ`app`をバインドしていました。 この場合、次のようなファイルが生成されることになります: + +```bash +wailsjs + └─go + └─main + ├─App.d.ts + └─App.js +``` + +ご覧のとおり、`main`パッケージ内の`App`構造体JavaScriptバインディングが、それらのメソッドのTypeScript型定義と並んで生成されていることが分かります。 フロントエンドから`Greet`メソッドを呼び出すには、単純にメソッドをインポートし、通常のJavaScript関数と同じように呼び出してください: + +```javascript +// ... +import {Greet} from '../wailsjs/go/main/App' + + function doGreeting(name) { + Greet(name).then((result) => { + // resultを使って何かする + }) + } +``` + +TypeScript型定義ファイルは、バインドされたメソッドの正しい型を提供します: + +```ts +export function Greet(arg1: string): Promise; +``` + +生成されたメソッドはPromiseを返すようになっています。 呼び出しが成功すると、Goからの1番目の返り値が`resolve`ハンドラに渡されます。 呼び出しに失敗したとみなされるのは、Goメソッドの2番目の返り値がerror型で、それがerrorインスタンスを返したときです。 これは、`reject`ハンドラを介して返されます。 先の例では、`Greet`メソッドは`string`型の返り値のみであるため、無効なデータが渡されない限り、JavaScript側でrejectハンドラが呼ばれることはありません。 + +すべてのデータ型は、GoとJavaScriptの間で正しく解釈されます。 もちろん構造体も正しく解釈されます。 Goから構造体が返された場合、フロントエンドにはJavaScriptのクラスとして返されます。 + +:::info 備考 + +TypeScript型定義を正しく自動生成するために、構造体のフィールドには、有効な`json`タグを_必ず_付与するようにしてください。 + +ネストされた匿名構造体(無名構造体) は、現時点ではサポートされていません。 + +::: + +Goに対して引数として構造体を渡すこともできます。 構造体として取り扱ってほしいJavaScriptのマップやクラスを渡すと、構造体に変換されます。 あなたが簡単にこれらのことを把握できるように、`dev`モードでは、バウンドされたGoメソッドで使用されている全構造体の型が定義された、Typescriptモジュールが生成されます。 このモジュールを使用すると、JavaScriptネイティブなオブジェクトを構築し、Goコードへ送信することができます。 + +また、シグネチャに構造体を使用するGoメソッドもサポートされています。 バインドされたメソッドで、引数または返り値として指定されているすべてのGo構造体は、Goのコードラッパーモジュールの一部として生成されたTypeScript定義を持っています。 れらを使用することで、GoとJavaScriptの間で、同じデータモデルを共有できます。 + +例: `Greet`メソッドを更新して、文字列型の代わりに`Person`型を引数で受け付けてみる: + +```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) +} +``` + +`wailsjs/go/main/App.js`ファイルには、次のコードが出力されます: + +```js title="App.js" +export function Greet(arg1) { + return window["go"]["main"]["App"]["Greet"](arg1); +} +``` + +しかし、`wailsjs/go/main/App.d.ts`ファイルは次のコードが出力されます: + +```ts title="App.d.ts" +import { main } from "../models"; + +export function Greet(arg1: main.Person): Promise; +``` + +見ると分かるように、"main"名前空間は、新しく生成された"models.ts"ファイルからインポートされています。 このファイルには、バインドされたメソッドで使用されるすべての構造体の型定義が含まれています。 この例では、`Person`構造体の型定義が含まれています。 `models.ts`を確認すれば、モデルがどのように定義されているかが分かります。 + +```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; + } + } +} +``` + +フロントエンドのビルド構成にTypescriptを使用している限り、これらのモデルを次のように使用できます: + +```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); + }); +} +``` + +生成されたバインディングとTypescriptモデルの組み合わせによって、強力な開発環境を実現させています。 + +バインディングの詳細については、[アプリ開発ガイド](guides/application-development.mdx)の[バインディングメソッド](guides/application-development.mdx#binding-methods)をご覧ください。 + +### ランタイムメソッドの呼び出し + +Javascriptランタイムは`window.runtime`に存在し、イベント発行やロギングなど、さまざまなタスクを実行するためのメソッドが含まれています: + +```js title="mycode.js" +window.runtime.EventsEmit("my-event", 1); +``` + +Javascriptランタイムの詳細については、[ランタイムリファレンス](reference/runtime/intro)をご覧ください。 + +[^1]: まれに、WebViewでサポートされていない機能を使用するライブラリがあります。 ほとんどの場合、それらは代替手段や回避方法がありますので、それらを検討してください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..800ae193f58 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +--- + +# イントロダクション + +Wailsは、Go言語とWeb技術を使用して、デスクトップアプリの構築を可能にするプロジェクトです。 + +"Goの力によって、Electronが軽量かつ高速になったようなもの"、と考えるとよいでしょう。 Goの柔軟性とパワーに、リッチでモダンなフロントエンドを組み合わせたアプリを、簡単に構築することができます。 + +### 特徴 + +- ネイティブなメニュー、ダイアログ、テーマ、透過処理を使用可能です +- Windows、macOS、Linuxをサポートしています +- Svelte、React、Preact、Vue、Lit、バニラJS向けにビルトインテンプレートを用意しています +- GoメソッドをJavaScriptから簡単に呼び出せます +- Go構造体に対応するTypeScript型定義を自動生成します +- WindowsにおいてCGOや外部DLLは必要ありません +- [Vite](https://vitejs.dev/)の力を利用したライブ開発が可能です +- アプリケーションを簡単に作成、ビルド、パッケージングするための強力なCLIを備えています +- 豊富な[ランタイムライブラリ](/docs/reference/runtime/intro)を用意しています +- Wailsで構築されたアプリケーションは、Apple StoreおよびMicrosoft Storeに準拠しています + +例えば varly は、Wailsで構築されたMacOS・Windows向けのデスクトップアプリです。 見栄えが良いだけではなく、ネイティブメニューや半透明効果を使用しています。これらは、モダンなネイティブアプリに期待されるものです。 + +```mdx-code-block +

+ +

+``` + +### クイックスタートテンプレート + +Wailsには、アプリの開発をすばやく始められるように、多数のテンプレートが用意されています。 Svelte、React、Vue、Preact、Lit向け、およびバニラなJavaScript用で、それぞれのテンプレートがあります。 各テンプレートには、Javascript版とTypescript版が用意されています。 + +### ネイティブ要素 + +Wailsは、ウィンドウ、メニュー、ダイアログなどのネイティブ要素を処理する専用ライブラリを使用するため、見栄えが良く、リッチな機能を備えたデスクトップアプリを構築できます。 + +**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. 例えばWindowsの場合、Chromium上でビルトされているMicrosoft Webview2ライブラリを使用します。 + +### GoとJavascriptのやり取り + +Wailsは自動的に、GoのメソッドをJavascriptから利用できるようにするので、フロントエンドからGoのメソッド名を呼び出すことができます。 Goメソッドが使用する構造体を表すTypeScritpt型定義も自動生成されるため、GoとJavaScriptの間で同じデータ構造をやり取りすることができます。 + +### ランタイムライブラリ + +WailsはGoとJavascriptの両方にランタイムライブラリを提供し、イベント、ロギング、ダイアログなど、モダンなアプリに必要な多くの機能を使うことができます。 + +### ライブ開発 + +#### 自動リビルド + +アプリを"dev"モードで起動すると、Wailsはあなたが書いたコードをネイティブデスクトップアプリとしてビルドしますが、プログラムアセットは常にディスクから読み込む状態になります。 その仕組みにより、アプリ起動中にGoコードが書き換えられると、変更を検出して自動的にアプリがリビルドされ、再起動します。 + +#### 自動リロード + +フロントエンドアセットの変更が検出された場合、起動中のアプリは自動的にリロードされ、変更がすぐに反映されます。 + +#### ブラウザを使った開発 + +ブラウザでのデバッグや開発も、Wailsにお任せください。 起動中のアプリはWebサーバを兼ねており、お好きなブラウザから接続してアプリを操作することができます。 プログラムアセットが書き換わった時はすぐに更新されます。 + +### 本番用のネイティブバイナリ + +アプリを本番用にビルドする準備ができたら、CLIが、アプリを単一の実行可能ファイルへコンパイルし、すべてのアセットをバンドルしてくれます。 WindowsおよびMacOSでは、配布用のネイティブパッケージを作成できます。 パッケージ化に必要なアイコン、info.plist、マニフェストファイルなどは、プロジェクトの一部としてカスタマイズできるため、アプリのビルド方法をフルコントロールできます。 + +### ツール + +Wails CLIを使うことで、簡単にアプリを生成、ビルド、バンドルすることができます。 アイコンの作成、最適なコンパイル構成の設定、本番向けのバイナリ配布など、面倒なことをあなたの代わりに引き受けてくれます。 多数のテンプレートの中から、あなたに合ったものを選んで、すぐに開発を始めましょう! diff --git a/website/versioned_docs/version-v2.8.0/reference/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..3a7ff0a1ae5 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,240 @@ +--- +sidebar_position: 2 +--- + +# CLI + +WailsのCLIには、プロジェクトの管理に使用できるコマンドが多数あります。 すべてのコマンドは次の文法で実行できます: + +`wails <コマンド> <フラグ>` + +## init + +`wails init`はプロジェクトの生成に使用します。 + +| フラグ | 説明 | デフォルト | +|:----------------- |:----------------------------------------------------------------------------- |:-------:| +| -n "プロジェクト名" | プロジェクトの名前。 **必須項目**。 | | +| -d "プロジェクトディレクトリ" | 作成するプロジェクトディレクトリ | プロジェクト名 | +| -g | gitリポジトリを初期化する | | +| -l | 利用可能なプロジェクトテンプレート一覧を表示 | | +| -q | コンソールへの出力を抑止 | | +| -t "テンプレート名" | 使用するプロジェクトテンプレート。 ここで指定する値は、デフォルトテンプレート名、または、GitHubでホストされているリモートテンプレートのURLです。 | vanilla | +| -ide | IDEプロジェクトファイルを生成 | | +| -f | アプリケーションを強制的にビルド | false | + +例: `wails init -n test -d mytestproject -g -ide vscode -q` + +この例では、サイレントモードで、"mytestproject"ディレクトリに"test"という名前のプロジェクトが生成されるとともに、gitの初期化、vscodeプロジェクトファイルの生成が行われます。 + +WailsでIDEを使用する場合の詳細については、[こちら](../guides/ides.mdx)をご覧ください。 + +### リモートテンプレート + +WailsではGitHubでホストされているリモートテンプレートをサポートしており、テンプレートのプロジェクトURLを使用してインストールできます。 + +例: `wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]` + +コミュニティがメンテナンスしているテンプレートの一覧は[こちら](../community/templates.mdx)をご覧ください。 + +:::warning 注意 + +**Wailsプロジェクトでは、サードパーティ製テンプレートのメンテナンスは行っておらず、責任も負いません!** + +テンプレートについてよく分からない場合は、`package.json`および`wails.json`を確認し、どのようなスクリプトが実行されるのかや、どのようなパッケージがインストールされるのかを調べてください。 + +::: + +## build + +`wails build`は、プロジェクトを本番配布用のバイナリにコンパイルするときに使用します。 + +| フラグ | 説明 | デフォルト | +|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------- | +| -clean | `build/bin`ディレクトリをクリーンする | | +| -compiler "compiler" | 違うGoコンパイラを使用する。例: go1.15beta1 | go | +| -debug | アプリケーションのデバッグ情報を保持し、デバッグコンソールを表示する。 これにより、アプリケーションウィンドウで開発者ツールを使用することを許可できます。 | | +| -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 | 実際には実行せずにbuildコマンドの結果を表示する | | +| -f | アプリケーションを強制的にビルド | | +| -garbleargs | garbleへ渡す引数 | `-literals -tiny -seed=random` | +| -ldflags "flags" | コンパイラに渡す追加のldflags | | +| -m | コンパイル前のmod tidyの実行をスキップする | | +| -nopackage | アプリケーションをパッケージ化しない | | +| -nocolour | 出力文字に色をつけない | | +| -nosyncgomod | go.modとWailsのバージョンを同期させない | | +| -nsis | Windows向けのNSISインストーラを生成する | | +| -o filename | 出力ファイル名 | | +| -obfuscated | [garble](https://github.com/burrowers/garble)を使用してアプリケーションを難読化する | | +| -platform | 指定された[プラットフォーム](../reference/cli.mdx#platforms)(カンマ区切り) 向けにビルドする。例: `windows/arm64`。 アーキテクチャを指定しない場合は、`runtime.GOARCH`の値が使用されます。 | platform = `GOOS` environment variable if given else `runtime.GOOS`.
arch = `GOARCH` envrionment variable if given else `runtime.GOARCH`. | +| -race | Goのrace detectorを使用してビルドする | | +| -s | フロントエンドのビルドをスキップ | | +| -skipbindings | バインディングの生成をスキップする | | +| -tags "extra tags" | Goコンパイラに渡すビルドタグ。 値は引用符で囲んでください。 また、スペースまたはカンマで区切ってください(両方は使用しないでください)。 | | +| -trimpath | 実行可能ファイルから、すべてのファイルシステムパスを削除する | | +| -u | プロジェクトの`go.mod`を更新し、CLIと同じバージョンのWailsを使用する | | +| -upx | "upx"を使用して最終的にバイナリを圧縮する | | +| -upxflags | upxに渡すフラグ | | +| -v int | 詳細度レベル (0 - サイレント, 1 - デフォルト, 2 - 詳細) | 1 | +| -webview2 | WebView2インストーラーのストラテジ: download,embed,browser,error | download | +| -windowsconsole | Windiws向けビルドでコンソールウィンドウを維持する | | + +`webview2`フラグの詳細については、[Windows](../guides/windows.mdx)ガイドをご覧ください。 + +標準のGoツールを使用してビルドしたい場合は、[手動ビルド](../guides/manual-builds.mdx)ガイドをご覧ください。 + +例: + +`wails build -clean -o myproject.exe` + +:::info + +Macの場合、`Info.dev.plist`ではなく`Info.plist`がアプリケーションにバンドルされます。 + +::: + +:::info AppleシリコンでのUPX + +AppleシリコンにおけるUPXの使用には[既知の問題](https://github.com/upx/upx/issues/446)が確認されています。 + +::: + +:::info WindowsでのUPX + +いくつかのアンチウイルスソフトでは、`upx`で圧縮されたバイナリをウイルスとして検知することが確認されています。詳しくは、[upxのIssue](https://github.com/upx/upx/issues/437)をご覧ください。 + +::: + +### プラットフォーム + +サポートされているプラットフォームは次のとおりです: + +| プラットフォーム | 説明 | +|:---------------- |:-------------------------------- | +| darwin | MacOS + ビルドマシンのアーキテクチャ | +| darwin/amd64 | MacOS 10.13+ AMD64 | +| darwin/arm64 | MacOS 11.0+ ARM64 | +| darwin/universal | MacOS AMD64+ARM64 ユニバーサルアプリケーション | +| windows | Windows 10/11 + ビルドマシンのアーキテクチャ | +| windows/amd64 | Windows 10/11 AMD64 | +| windows/arm64 | Windows 10/11 ARM64 | +| linux | Linux + ビルドマシンのアーキテクチャ | +| linux/amd64 | Linux AMD64 | +| linux/arm64 | Linux ARM64 | + +## doctor + +`wails doctor`は、あなたのコンピュータで開発の準備が整っているかを診断します。 + +例: + +``` +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`は、アプリケーションを"ライブ開発"モードで実行させたいときに使用します。 このコマンドにより、次のことが行われます: + +- アプリケーションの`go.mod`が、CLIと同じバージョンのWailsを使用するように更新されます +- アプリケーションがコンパイルされた後、自動的に実行されます +- ウォッチャーが起動し、Goファイルの変更を検出した際には、アプリがリビルドされます +- `http://localhost:34115`でWebサーバが起動し、HTTP経由でアプリケーション(フロントエンドだけではありません)が提供されます。 これにより、任意のブラウザ拡張機能を使用することができます +- すべてのアプリケーションアセットはディスクから読み込まれます。 アセットが変更された場合、アプリケーションは自動的に、リビルドではなくリロードされます。 接続されているすべてのブラウザもリロードされます +- 以下のものを含むJSモジュールが生成されます: +- GoメソッドのJavaScriptラッパー (コードヒントに有用なJSDocも自動付与されています) +- Goの構造体のTypeScriptバージョン (構造体のインスタンスを生成したり、Goメソッドの引数として渡したりすることができます) +- 別のJSモジュールとして、ランタイムのラッパーおよびTS定義も生成されます +- macOSの場合、アプリケーションは`.app`ファイルにバンドルされて実行されます。 これには、開発用の`build/darwin/Info.dev.plist`を使用します。 + +| フラグ | 説明 | デフォルト | +|:---------------------------- |:----------------------------------------------------------------------------------------------------------------------------- |:--------------------- | +| -appargs "args" | シェル形式でアプリケーションに渡される引数 | | +| -assetdir "./path/to/assets" | 通常のアセットFSを使用する代わりに、指定されたディレクトリからアセットを提供する | `wails.json`で指定されている値 | +| -browser | 起動時にブラウザで`http://localhost:34115`を開く | | +| -compiler "compiler" | 違うGoコンパイラを使用する。例: go1.15beta1 | go | +| -debounce | アセットの変更が検出されたあと、リロードするまでの時間 | 100 (ミリ秒) | +| -devserver "host:port" | Wails開発サーバをバインドするアドレス | "localhost:34115" | +| -extensions | リビルドをトリガーする拡張子 (カンマ区切り) | go | +| -forcebuild | アプリケーションを強制的にビルドする | | +| -frontenddevserverurl "url" | アセットを提供するサードパーティ製の開発サーバ(例: Vite) を使用する | "" | +| -ldflags "flags" | コンパイラに渡す追加のldflags | | +| -loglevel "loglevel" | 使用するログレベル - Trace, Debug, Info, Warning, Error | Debug | +| -nocolour | CLIのカラー出力を無効にする | false | +| -noreload | アセットが変更されたときの自動リロードを無効にする | | +| -nosyncgomod | go.modとWailsのバージョンを同期させない | false | +| -race | Goのrace detectorを使用してビルドする | false | +| -reloaddirs | リロードをトリガーする追加ディレクトリ (カンマ区切り) | `wails.json`で指定されている値 | +| -s | フロントエンドのビルドをスキップ | false | +| -save | 指定された`assetdir`、`reloaddirs`、`wailsjsdir`、`debounce`、`devserver`、`frontenddevserverurl`フラグの値を、`wails.json`へ保存し、次回以降のデフォルト値にする | | +| -skipbindings | バインディングの生成をスキップする | | +| -tags "extra tags" | コンパイラへ渡すビルドタグ (引用符およびスペース区切り) | | +| -v | 詳細度レベル (0 - サイレント, 1 - デフォルト, 2 - 詳細) | 1 | +| -wailsjsdir | 生成されたWailsのJSモジュールを格納するディレクトリ | `wails.json`で指定されている値 | + +例: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +この例では次のことが行われます: + +- アプリケーションをビルドして実行する (詳しくは[こちら](../guides/manual-builds.mdx)をご覧ください) +- WailsのJSモジュールを`./frontend/src`ディレクトリ内に生成する +- `./frontend/dist`ディレクトリ内のファイルの更新を監視し、変更されたときにリロードする +- ブラウザを開き、アプリケーションへ接続する + +既存のフレームワークスクリプトで本機能を使用する方法について詳しくは[こちら](../guides/application-development.mdx#live-reloading)をご覧ください。 + +## generate + +### template + +Wailsは、プロジェクトの生成に必ずテンプレートを使用します。 `wails generate template`コマンドは、プロジェクト生成時に使用できるテンプレートの作成を支援します。 + +| フラグ | 説明 | +|:---------------- |:---------------------------- | +| -name | テンプレート名 (必須項目) | +| -frontend "path" | テンプレートで使用するフロントエンドプロジェクトへのパス | + +テンプレートの作成について詳しくは、[テンプレートガイド](../guides/templates.mdx)をご覧ください。 + +### module + +`wails generate module`コマンドを使用すると、アプリケーションの`wailsjs`ディレクトリを手動で生成できます。 + +## update + +`wails update`コマンドを実行すると、Wails CLIのバージョンをアップデートできます。 + +| フラグ | 説明 | +|:------------------ |:----------------------- | +| -pre | 最新のプレリリースバージョンにアップデートする | +| -version "version" | 特定のバージョンのCLIをインストールする | + +## version + +`wails version`は、現在のCLIバージョンを出力するだけのコマンドです。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..5e1f1e21808 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# メニュー + +Wailsプロジェクトに、アプリケーションメニューを追加することができます。 [Menu](#menu)構造体を定義し、アプリケーション設定の[`Menu`](../reference/options.mdx#menu)オプションへ設定するか、ランタイムの[MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu)メソッドを呼び出すことで、メニューを表示させることができます。 + +メニューを作成する例: + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +Menu構造体を更新し、[MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu)メソッドを呼び出すことで、メニューを動的に更新することも可能です。 + +上記の例では、ヘルパーメソッドを使用していますが、Menu構造体を手動で構築することも可能です。 + +## Menu + +Menuは、MenuItemのコレクションです。 + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +アプリケーションメニューにおいて、各MenuItemは、"編集"などの単一メニューを表します。 + +メニューを構築するするためのシンプルなヘルパーメソッドが提供されています: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +これにより、コードのレイアウトが、実際のメニューと似たレイアウトになるため、メニュー項目を作成した後にそれを手動で追加するといった作業は必要なくなります。 ヘルパーを使用せず、メニュー項目を作成して手動でメニューに追加することもできます。 + +## MenuItem + +MenuItemは、メニュー内の項目を表します。 + +```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 +} +``` + +| フィールド | 型 | 内容 | +| ----------- | ------------------------------------ | -------------------------------------------- | +| Label | string | メニューのテキスト | +| Accelerator | [\*keys.Accelerator](#accelerator) | このメニュー項目のキーバインディング | +| 型 | [型](#type) | メニュー項目の種類 | +| Disabled | bool | メニュー項目を無効化する | +| Hidden | bool | メニュー項目を非表示にする | +| Checked | bool | 項目にチェックを追加する (チェックボックス & ラジオタイプ) | +| SubMenu | [\*Menu](#menu) | サブメニューを設定する | +| Click | [Callback](#callback) | メニューがクリックされたときのコールバック関数 | +| Role | string | メニュー項目に[ロール](#role)を定義する。 現在のところ、Macでのみ有効です。 | + +### Accelerator + +Accelerator(キーボードショートカット) は、キーストロークとメニュー項目とのバインドを定義します。 Wailsでは、Acceleratorを、キー + [Modifier](#modifier)の組み合わせとして定義しています。 これらは`"github.com/wailsapp/wails/v2/pkg/menu/keys"`パッケージから利用可能です。 + +例: + +```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") +``` + +キーは、`+`を除いて、キーボード上の任意の一文字です(`+`は、`plus`で定義されています)。 いくつかのキーは一文字で表現できないため、名前付き文字のセットがあります: + +| | | | | +|:-----------:|:-----:|:-----:|:---------:| +| `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では、Electronと同じ構文のAcceleratorを解析することもできます。 設定ファイルにAcceleratorを保存する際に便利です。 + +例: + +```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 + +ModifierはAcceleratorキーと組み合わせて使用できるキーです: + +```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" +) +``` + +Modifierを使用してAcceleratorを作成するためのヘルパーメソッドがあります: + +```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 +``` + +Modifierは`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) +``` + +### 型 + +各メニュー項目は5種類のうちの1タイプを指定する必要があります: + +```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" +) +``` + +使い勝手の良い、メニュー項目をすばやく作成するためのヘルパーメソッドが提供されています: + +```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 +``` + +"Add"ヘルパーメソッドを使用して、メニューに対して直接メニュー項目を追加することも可能です: + +```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 +``` + +ラジオグループに関する注意事項: ラジオグループは、メニュー内でお互いに隣接しているラジオメニュー項目同士で1つのグループとして定義されます。 つまり、手動でグループ化する必要はありません。 逆に言うと、2つのラジオグループを隣接させることはできません。ラジオグループの間には、ラジオ項目ではないメニューアイテムが必要です。 + +### Callback + +各メニュー項目には、項目がクリックされたときに呼び出されるコールバックがあります: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +このコールバックには、どのメニュー項目がコールバックをトリガーしたのかを識別できる、`CallbackData`構造体が渡されます。 これは、同じコールバックを呼び出すラジオグループを作成する際などに便利です。 + +### Role + +:::info ロール + +現在、ロールはMacでのみサポートされています。 + +::: + +メニュー項目には、もともと事前に定義されたメニュー項目のロールを設定することができます。 現在サポートされているロールは次のとおりです: + +| ロール | 説明 | +| ------------ | -------------------------------------------- | +| AppMenuRole | Macアプリケーションの標準メニュー。 `menu.AppMenu()`で作成できます。 | +| EditMenuRole | Macの標準的な編集メニュー。 `menu.EditMenu()`で作成できます。 | diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..2f53915a0ea --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,853 @@ +--- +sidebar_position: 3 +--- + +# オプション + +## アプリケーションオプション + +`Options.App`構造体には、アプリケーションの構成設定が含まれています。 これを`wails.Run()`メソッドに渡してください: + +```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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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), + }, + // ユーザへのメッセージをカスタマイズします + Messages *windows.Messages + // OnSuspendはWindowsが省電力モードに移行した場合に呼び出されます + OnSuspend func() + // OnResumeはWindowsが省電力モードから復帰した場合に呼び出されます + OnResume func(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### Title + +ウィンドウのタイトルバーに表示されるテキストです。 + +名前: Title
データ型: `string` + +### Width + +ウィンドウの初期幅です。 + +名前: Width
データ型: `int`
デフォルト値: 1024 + +### Height + +ウィンドウの初期の高さです。 + +名前: Height
データ型: `int`
デフォルト値: 768 + +### DisableResize + +デフォルトでは、メインウィンドウのサイズは自在に変更することができます。 この設定を`true`にすると、サイズが固定されます。 + +名前: DisableResize
データ型: `bool` + +### Fullscreen + +非推奨: 代わりに[WindowStartState](#windowstartstate)を使用してください。 + +### WindowStartState + +起動時にウィンドウをどのように表示させるかを定義します。 + +| 値 | Win | Mac | Lin | +| ---------- | --- | --- | --- | +| Fullscreen | ✅ | ✅ | ✅ | +| Maximised | ✅ | ✅ | ✅ | +| Minimised | ✅ | ❌ | ✅ | + +名前: WindowStartState
データ型: `options.WindowStartState` + +### Frameless + +この設定を`true`にすると、ウィンドウに境界線やタイトルバーが表示されなくなります。 詳しくは[フレームレスウィンドウ](../guides/frameless.mdx)をご覧ください。 + +名前: Frameless
データ型: `bool` + +### MinWidth + +ウィンドウの最小幅を設定します。 `Width`の値がこの値より小さい場合、ウィンドウ幅はデフォルトで`MinWidth`の値となります。 + +名前: MinWidth
データ型: `int` + +### MinHeight + +ウィンドウの最小の高さを設定します。 `Height`の値がこの値より小さい場合、ウィンドウの高さはデフォルトで`MinHeight`の値となります。 + +名前: MinHeight
データ型: `int` + +### MaxWidth + +ウィンドウの最大幅を設定します。 `Width`の値がこの値より大きい場合、ウィンドウ幅はデフォルトで`MaxWidth`の値となります。 + +名前: MaxWidth
データ型: `int` + +### MaxHeight + +ウィンドウの最大の高さを設定します。 `Height`の値がこの値より大きい場合、ウィンドウの高さはデフォルトで`MaxHeight`の値となります。 + +名前: MaxHeight
データ型: `int` + +### StartHidden + +`true`に設定すると、アプリケーションは[WindowShow](../reference/runtime/window.mdx#windowshow)が呼び出されるまで非表示となります。 + +名前: StartHidden
データ型: `bool` + +### HideWindowOnClose + +デフォルトでは、ウィンドウを閉じるとアプリケーションが終了します。 この設定を`true`にすると、ウィンドウを閉じる操作をした際に、 + +ウィンドウが非表示の状態になります。 + +名前: HideWindowOnClose
データ型: `bool` + +### BackgroundColour + +ウィンドウのデフォルトの背景色です。 例: options.NewRGBA(255,0,0,128) - 50%透過された赤色 + +名前: BackgroundColour
データ型: `*options.RGBA`
デフォルト値: white + +### AlwaysOnTop + +ウィンドウへのフォーカスが無くなっても、他ウィンドウより手前側にウィンドウを表示させるかを設定します。 + +名前: AlwaysOnTop
データ型: `bool` + +### Assets + +非推奨: 代わりに[AssetServerの固有オプション](#assetserver)であるAssetsオプションを使用してください。 + +### AssetsHandler + +非推奨: 代わりに[AssetServerの固有オプション](#assetserver)であるAssetsHandlerオプションを使用してください。 + +### AssetServer + +AssetServerの固有オプションを定義します。 静的なアセットでAssetServerをカスタマイズしたり、`http.Handler`で動的なアセットを提供したり、`assetserver.Middleware`でリクエストチェーンにフックしたりすることができます。 + +現在のところ、`http.Request`のすべての機能がサポートされているわけではありません。次の機能マトリクスを確認してください: + +| 機能 | Win | Mac | Lin | +| ----------------------- | --- | --- | ------ | +| GET | ✅ | ✅ | ✅ | +| POST | ✅ | ✅ | ✅ [^1] | +| PUT | ✅ | ✅ | ✅ [^1] | +| PATCH | ✅ | ✅ | ✅ [^1] | +| DELETE | ✅ | ✅ | ✅ [^1] | +| Request Headers | ✅ | ✅ | ✅ [^1] | +| Request Body | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +名前: AssetServer
データ型: `*assetserver.Options` + +#### Assets + +アプリケーションのフロントエンドで使用される静的アセットです。 + +GETリクエストが要求された場合、まず初めに、この`fs.FS`からのアセット提供を試みます。 `fs.FS`から、当該ファイルが存在しない旨の`os.ErrNotExist`エラーが返された場合、このリクエストは[Handler](#handler)へフォールバックされ、ハンドラ側でGETリクエストへの応答を試みます。 + +nilがセットされている場合、GETリクエストに常に[Handler](#handler)へ転送されます。 + +名前: Assets
データ型: `fs.FS` + +#### Handler + +アセットハンドラは、アセットが見つからなかった場合のフォールバック処理を担う、ジェネリックな`http.Handler`です。 + +[Assets](#assets)内で`os.ErrNotExist`エラーが発生したことにより、アセットを提供できないと判断されたすべてのGETリクエストによって、このハンドラが呼び出されます。 また、GET以外のすべての種類のリクエストは、常にこのハンドラから応答が返されます。 ハンドラが定義されていない状態で、ハンドラが呼び出された場合、次の応答が返されます: + +- GETリクエスト: `http.StatusNotFound` +- その他のリクエスト: `http.StatusMethodNotAllowed` + +注意: フロントエンド側の開発サーバと組み合わせて使用すると、一部制限がかかる場合があります。 Viteは、拡張子を含まないパスに対して、常にindex.htmlを返します。 + +名前: AssetsHandler
データ型: `http.Handler` + +#### Middleware + +MiddlewareはHTTPミドルウェアで、AssetServerのリクエストチェーンをフックすることができます。 例えば、特殊なルーティングを実装したいときなど、デフォルトのリクエストハンドラを動的にスキップさせることができます。 Middlewareは、AssetSeverが使用する新しい`http.Handler`を生成するために呼び出されます。引数では、AssetServerがデフォルトで使用するハンドラを受け取ります。 + +Middlewareが定義されていない場合、デフォルトのAssetServerのリクエストチェーンが実行されます。 + +名前: Middleware
データ型: `assetserver.Middleware` + +### Menu + +アプリケーションで使用されるメニューです。 メニューについて詳しくは、[メニューのリファレンス](../reference/runtime/menu.mdx)をご覧ください。 + +:::note + +Macでは、メニューが指定されていない場合、デフォルトメニューが作成されます。 + +::: + +名前: Menu
データ型: `*menu.Menu` + +### Logger + +アプリケーションで使用するロガーです。 ロギングについて詳しくは、[ログのリファレンス](../reference/runtime/log.mdx)をご覧ください。 + +名前: Logger
データ型: `logger.Logger`
デフォルト値: 標準出力へのロガー + +### LogLevel + +デフォルトのログレベルです。 ロギングについて詳しくは、[ログのリファレンス](../reference/runtime/log.mdx)をご覧ください。 + +名前: LogLevel
データ型: `logger.LogLevel`
デフォルト値: 開発モードの場合は`Info`、本番モードの場合は`Error` + +### LogLevelProduction + +本番ビルド時のデフォルトのログレベルです。 ロギングについて詳しくは、[ログのリファレンス](../reference/runtime/log.mdx)をご覧ください。 + +名前: LogLevelProduction
データ型: `logger.LogLevel`
デフォルト値: `Error` + +### OnStartup + +フロントエンド作成後、`index.html`が読み込まれる前に呼び出されるコールバックです。 アプリケーションのcontextが渡されます。 + +名前: OnStartup
データ型: `func(ctx context.Context)` + +### OnDomReady + +フロントエンドが`index.html`とそのリソースを読み込んだ後に呼び出されるコールバックです。 アプリケーションのcontextが渡されます。 + +名前: OnDomReady
データ型: `func(ctx context.Context)` + +### OnShutdown + +フロントエンドが破棄され、アプリケーションが終了する直前に呼び出されるコールバックです。 アプリケーションのcontextが渡されます。 + +名前: OnShutdown
データ型: `func(ctx context.Context)` + +### OnBeforeClose + +ウィンドウの閉じるボタンをクリックするか、`runtime.Quit`が呼ばれて、アプリケーションが終了されそうになっているときに呼び出されるコールバックです。 trueを返すとアプリケーションはそのまま維持され、falseを返すと通常どおりシャットダウンされます。 ユーザに対してプログラムの終了を確認したいときは、このコールバックを使うのが良いでしょう。 + +例: + +```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" +} +``` + +名前: OnBeforeClose
データ型: `func(ctx context.Context) bool` + +### CSSDragProperty + +ウィンドウをドラッグできる要素を特定するためのCSSプロパティ名を設定します。 デフォルト値: `--wails-draggable` + +名前: CSSDragProperty
データ型: `string` + +### CSSDragValue + +ウィンドウのドラッグを有効にするために、`CSSDragProperty`スタイルが持つべき値を設定します。 デフォルト値: `drag` + +名前: CSSDragValue
データ型: `string` + +### EnableDefaultContextMenu + +EnableDefaultContextMenuは、本番環境において、ブラウザのデフォルトコンテキストメニューを有効にします。 + +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. + +このオプションを有効にすると、デフォルトでは、テキストに関するコンテキスト(切り取り/コピー/貼り付け) のみがコンテキストメニューに表示されます。この動作をオーバーライドするには、`--default-contextmenu`というCSSプロパティを任意のHTML要素(`body`含む) で以下の値と共に使用してください: + +| CSSスタイル | 動作 | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `--default-contextmenu: auto;` | (**デフォルト**) 次の場合にのみデフォルトのコンテキストメニューを表示します:
contentEditableがtrueである、またはテキストが選択されている、またはinput要素/textarea要素であるとき | +| `--default-contextmenu: show;` | 常にデフォルトのコンテキストメニューを表示します | +| `--default-contextmenu: hide;` | 常にデフォルトのコンテキストメニューを非表示にします | + +このルールは通常のCSSルールと同様に継承されるため、ネストも期待どおりに動作します。 + +:::note +このフィルタリング機能は本番環境でのみ有効であり、開発・デバッグビルドでは、フルコンテキストメニューが常に使用できます。 +::: + +:::warning +このフィルタリング機能はセキュリティ対策として使用することはできません。開発者は、画像のダウンロード、リロード、ウェブページの保存といったコマンドを含むフルコンテキストメニューが常にリークされる可能性を考慮すべきです。この点が気になる場合、開発者はデフォルトのコンテキストメニューを有効にするべきではありません。 +::: + + +名前: EnableDefaultContextMenu
データ型: `bool` + +### EnableFraudulentWebsiteDetection + +EnableFraudulentWebsiteDetectionは、マルウェアやフィッシング詐欺などの不正コンテンツのスキャンサービスを有効にします。 これらのサービスは、ナビゲートされたURLやその他コンテンツ情報を、アプリからAppleおよびMicrosoftのクラウドサービスに送信する可能性があります。 + +名前: EnableFraudulentWebsiteDetection
データ型: `bool` + +### ZoomFactor + +名前: ZoomFactor
データ型: `float64` + +WebView2の拡大率を定義します。 これは、Edgeのユーザによるズームインまたはズームアウトに対応するオプションです。 + +### IsZoomControlEnabled + +名前: IsZoomControlEnabled
データ型: `bool` + +このオプションを有効にすると、拡大率をユーザによって変更することができます。 拡大率の変更がユーザに許可されていない間は、オプションで拡大率を設定することができますのでご注意ください (例: キオスクアプリケーションなど)。 + +### Bind + +フロントエンドにバインドする必要があるメソッドが定義された、構造体インスタンスのスライスです。 + +名前: Bind
データ型: `[]interface{}` + +### ErrorFormatter + +JSからGoへ呼び出されたメソッドがエラーを返す際に、エラーをフォーマットする関数です。 返り値はJSONとして変換されます。 + +名前: ErrorFormatter
データ型: `func (error) any` + +### Windows + +[Windows固有のオプション](#windows)を定義します。 + +名前: Windows
データ型: `*windows.Options` + +#### WebviewIsTransparent + +この値を`true`に設定すると、アルファ値が`0`の際に、WebViewの背景が透明になります。 つまり、CSSで`background-color`に`rgba(0,0,0,0)`を設定すると、ホストウィンドウが透けて見えるようになります。 多くの場合、[WindowIsTranslucent](#WindowIsTranslucent)と組み合わて、霜のように見えるアプリケーションを作成する際に使用します。 + +名前: WebviewIsTransparent
データ型: `bool` + +#### WindowIsTranslucent + +この値を`true`に設定すると、ウィンドウの背景が半透明になります。 多くの場合、[WebviewIsTransparent](#WebviewIsTransparent)と組み合わせて使用されます。 + +ビルド22621より前のWindows 11の場合、半透明を実現させるために[BlurBehind](https://learn.microsoft.com/ja-jp/windows/win32/dwm/blur-ovw)メソッドを使用するため、処理が遅くなる可能性があります。 ビルド22621以降のWindows 11では、より高速な、新しい半透明タイプが有効になります。 デフォルトで使用される半透明タイプは、Windowsにより決定されます。 このタイプを設定するには、[BackdropType](#BackdropType)オプションを使用してください。 + +名前: WindowIsTranslucent
データ型: `bool` + +#### BackdropType + +:::note + +この設定を適用するには、Windows 11 ビルド22621以降が必要です。 + +::: + +ウィンドウの半透明タイプを設定します。 この設定は、[WindowIsTranslucent](#WindowIsTranslucent)が`true`に設定されている場合にのみ適用されます。 + +名前: BackdropType
データ型: `windows.BackdropType` + +値は次のいずれかを指定してください: + +| 値 | 説明 | +| ------- | ----------------------------------------------------------------------------------- | +| Auto | Windowsに背景を決定させる | +| None | 半透明にしない | +| Acrylic | [アクリル](https://learn.microsoft.com/ja-jp/windows/apps/design/style/acrylic)の効果を使用する | +| Mica | [マイカ](https://learn.microsoft.com/ja-jp/windows/apps/design/style/mica)の効果を使用する | +| Tabbed | タブを使用する。 これはマイカに似ている背景です。 | + +#### DisableWindowIcon + +この設定を`true`にすると、タイトルバーの左上隅のアイコンが消去されます。 + +名前: DisableWindowIcon
データ型: `bool` + +#### DisableFramelessWindowDecorations + +この設定を`true`にすると、[フレームレス](#Frameless)モードでのウィンドウデコレーションが消去されます。 つまり、'Aero Shadow'および'Rounded Corners'がウィンドウに適用されなくなります。 なお、'Rounded Corners'はWindows 11でのみサポートされていますのでご注意ください。 + +名前: DisableFramelessWindowDecorations
データ型: `bool` + +#### WebviewUserDataPath + +WebView2が、ユーザデータを格納するパスを設定します。 空の場合は、`%APPDATA%\[BinaryName.exe]`が使用されます。 + +名前: WebviewUserDataPath
データ型: `string` + +#### WebviewBrowserPath + +WebView2の実行ファイルおよびライブラリが存在するディレクトリへのパスを設定します。 空の場合、システムにインストールされているWebView2が使用されます。 + +固定バージョンランタイムディストリビューションに関する重要情報: + +- [ランタイムの取得および展開方法](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#details-about-the-fixed-version-runtime-distribution-mode) +- [固定バージョンに関する既知の問題](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#known-issues-for-fixed-version) +- [WenView2ランタイムの固定バージョンのパスに、\Edge\Application\ を含めてはいけません](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/webview2-idl?view=webview2-1.0.1245.22#createcorewebview2environmentwithoptions) + +名前: WebviewBrowserPath
データ型: `string` + +#### Theme + +サポートされるWindowsの最小バージョン: Windows 10 2004/20H1 + +アプリケーションが使用するテーマを設定します: + +| 値 | 説明 | +| ------------- | ---------------------------------------------------------------------------------------- | +| SystemDefault | _デフォルト値_です。 テーマは、システムのデフォルト設定に基づきます。 ユーザがシステムのテーマ設定を変更した場合、アプリケーションは新しい設定を使用するように更新されます。 | +| Dark | アプリケーションはダークテーマのみを使用します。 | +| Light | アプリケーションはライトテーマのみを使用します。 | + +名前: Theme
データ型: `windows.Theme` + +#### CustomTheme + +:::note + +サポートされるWindowsの最小バージョン: Windows 10/11 2009/21H2 ビルド22000 + +::: + +ウィンドウがアクティブまたは非アクティブのときに、ライトモード・ダークモードのそれぞれにおいて、タイトルバー、タイトルテキスト、ボーダーのカスタムカラーを設定できます。 + +名前: CustomTheme
データ型: `windows.CustomTheme` + +##### CustomTheme 型 + +CustomTheme構造体は、`int32`型で色の値を指定します。 これは`0x00BBGGAA`で表されるWindowsの標準フォーマットで指定します。 RGBの値をこのフォーマットに変換するために、`windows.RGB(r,g,b uint8)`のようなヘルパー関数が用意されています。 + +注意: 指定されていない値はデフォルトで黒色になります。 + +```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 +} +``` + +例: + +```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 + +利用可能なWebView2ランタイムが見つからなかったときに表示する、WebView2インストーラに関するメッセージ文字列を設定します。 + +名前: Messages
データ型: `*windows.Messages` + +プロジェクトがサポートする言語にあわせて、この設定をカスタマイズしてください。 + +#### ResizeDebounceMS + +ResizeDebounceMSは、ウィンドウサイズが変更されたときに、WebView2の再描画を実行するまでの時間です。 デフォルト値(0) は、できるだけ早く再描画を実行します。 + +名前: ResizeDebounceMS
データ型: `uint16` + +#### OnSuspend + +Windowsがローパワーモード(サスペンド/休止状態) に切り替わると呼び出されるコールバックを設定します。 + +名前: OnSuspend
データ型: `func()` + +#### OnResume + +Windowsがローパワーモード(サスペンド/休止状態) から復帰したときに呼び出されるコールバックを設定します。 + +名前: OnResume
データ型: `func()` + +#### WebviewGpuIsDisabled + +`true`に設定すると、webviewのGPUハードウェアアクセラレーションが無効化されます。 + +名前: WebviewGpuIsDisabled
データ型: `bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +[Mac固有のオプション](#mac)を定義します。 + +名前: Mac
データ定義: `*mac.Options` + +#### TitleBar + +TitleBar構造体は、タイトルバーのルック・アンド・フィールを設定する機能を提供します。 + +名前: TitleBar
データ型: [`*mac.TitleBar`](#titlebar-struct) + +##### Titlebar 構造体 + +アプリケーションのタイトルバーは、TitleBarオプションを使用することでカスタマイズできます: + +```go +type TitleBar struct { + TitlebarAppearsTransparent bool + HideTitle bool + HideTitleBar bool + FullSizeContent bool + UseToolbar bool + HideToolbarSeparator bool +} +``` + +| 名前 | 説明 | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| TitlebarAppearsTransparent | タイトルバーを透明にします。 これにより、タイトルバーが非表示になり、コンテンツがウィンドウ全体に表示されます。 [Appleドキュメント](https://developer.apple.com/documentation/appkit/nswindow/1419167-titlebarappearstransparent?language=objc) | +| HideTitle | ウィンドウタイトルを非表示にします。 [Appleドキュメント](https://developer.apple.com/documentation/appkit/nswindowtitlevisibility?language=objc) | +| HideTitleBar | スタイルマスクから[NSWindowStyleMaskTitled](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktitled/)を消去します。 | +| FullSizeContent | WebViewをウィンドウ全体に表示します。 [Appleドキュメント](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemaskfullsizecontentview) | +| UseToolbar | ウィンドウにデフォルトツールバーを追加します。 [Appleドキュメント](https://developer.apple.com/documentation/appkit/nstoolbar?language=objc) | +| HideToolbarSeparator | ツールバーの下側の線を消去します。 [Appleドキュメント](https://developer.apple.com/documentation/appkit/nstoolbar/1516954-showsbaselineseparator?language=objc) | + +事前設定されたタイトルバー構成を利用することも可能です: + +| 設定 | 例 | +| --------------------------- | ---------------------------------------------- | +| `mac.TitleBarDefault()` | ![](/img/reference/titlebar-default.webp) | +| `mac.TitleBarHidden()` | ![](/img/reference/titlebar-hidden.webp) | +| `mac.TitleBarHiddenInset()` | ![](/img/reference/titlebar-hidden-inset.webp) | + +例: + +```go +Mac: &mac.Options{ + TitleBar: mac.TitleBarHiddenInset(), +} +``` + +タイトルバーのカスタマイズに関してインスピレーションを得たい場合は[こちら](https://github.com/lukakerr/NSWindowStyles)をご覧ください。 + +#### Appearance + +Appearanceは、Appleの[NSAppearance](https://developer.apple.com/documentation/appkit/nsappearancename?language=objc)Nameに従って、アプリケーションのスタイルを設定するために使用します。 + +名前: Appearance
データ型: [`mac.AppearanceType`](#appearance-type) + +##### Appearance 型 + +アプリケーションの[外観](https://developer.apple.com/documentation/appkit/nsappearance?language=objc)を指定します。 + +| 値 | 説明 | +| ----------------------------------------------------- | ------------------------------------- | +| DefaultAppearance | DefaultAppearanceは、システムのデフォルト値を使用します。 | +| NSAppearanceNameAqua | システムの標準的なライト外観 | +| NSAppearanceNameDarkAqua | システムの標準的なダーク外観 | +| NSAppearanceNameVibrantLight | より鮮やかなライト外観 | +| NSAppearanceNameAccessibilityHighContrastAqua | システムの標準的なライト外観のハイコントラスト版 | +| NSAppearanceNameAccessibilityHighContrastDarkAqua | システムの標準的なダーク外観のハイコントラスト版 | +| NSAppearanceNameAccessibilityHighContrastVibrantLight | より鮮やかなライト外観のハイコントラスト版 | +| NSAppearanceNameAccessibilityHighContrastVibrantDark | より鮮やかなダーク外観のハイコントラスト版 | + +例: + +```go +Mac: &mac.Options{ + Appearance: mac.NSAppearanceNameDarkAqua, +} +``` + +#### WebviewIsTransparent + +この値を`true`に設定すると、アルファ値が`0`の際に、WebViewの背景が透明になります。 つまり、CSSで`background-color`に`rgba(0,0,0,0)`を設定すると、ホストウィンドウが透けて見えるようになります。 多くの場合、[WindowIsTranslucent](#WindowIsTranslucent)と組み合わて、霜のように見えるアプリケーションを作成する際に使用します。 + +名前: WebviewIsTransparent
データ型: `bool` + +#### WindowIsTranslucent + +この値を`true`に設定すると、ウィンドウの背景が半透明になります。 多くの場合、[WebviewIsTransparent](#WebviewIsTransparent)と組み合わて、霜のように見えるアプリケーションを作成する際に使用します。 + +名前: WindowIsTranslucent
データ型: `bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled u.Bool + FullscreenEnabled u.Bool +} +``` + +| 名前 | 説明 | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 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) | + +例: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### About + +"AppMenu"ロールで作成されたアプリケーションメニューの中にある"About"メニュー項目において、タイトル、メッセージ、アイコンを設定できます。 + +名前: About
データ型: [`*mac.AboutInfo`](#about-struct) + +##### About 構造体 + +```go + +type AboutInfo struct { + Title string + Message string + Icon []byte +} +``` + +これらの設定が定義されている場合、`AppMenu`ロールが使用されていれば、アプリケーションメニュー内に"About"メニューが表示されます。 例えば以下のように設定すると: + +```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, + }, + }, + }) +``` + +アプリケーションメニューに"About"メニュー項目が表示されます: + +```mdx-code-block +
+ +
+
+``` + +クリックすると、アプリケーション概要メッセージボックスが開かれます: + +```mdx-code-block +
+ +
+
+``` + +### Linux + +[Linux固有のオプション](#linux)を定義します。 + +名前: Linux
データ型: `*linux.Options` + +#### Icon + +ウィンドウを示すアイコンを設定します。 このアイコンは、ウィンドウが最小化されたときに使用されます(iconifiedと呼ばれます)。 + +名前: Icon
データ型: `[]byte` + +一部のウィンドウマネージャやデスクトップ環境では、ウィンドウフレームに配置されたり、他のコンテキストで表示される場合もあります。 反対に、環境によっては全くアイコンが使用されないこともありますのでご注意ください。 + +注意: 少なくともWayland上のGnomeでは、このアイコンは表示されません。 アプリケーションアイコンを表示させるには、`.desktop`ファイルを使用する必要があります。 KDEの場合は正常に表示されるはずです。 + +アイコンは、何の加工もされていないサイズで用意してください。つまり、拡大/縮小された画像は使用しないでください。 最高品質を確保するために、拡大/縮小は、最終的な目的サイズがはっきりするまで待ってください。 + +#### WindowIsTranslucent + +この値を`true`に設定すると、ウィンドウの背景が半透明になります。 ウィンドウマネージャによっては、この設定を無視したり、ブラックウィンドウになる場合があります。 + +名前: WindowIsTranslucent
データ型: `bool` + +#### WebviewGpuPolicy + +このオプションでは、webviewのハードウェアアクセラレーションポリシーを指定することができます。 + +名前: WebviewGpuPolicy
データ型: [`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
デフォルト値: `WebviewGpuPolicyAlways` + +##### WebviewGpuPolicy型 + +| 値 | 説明 | +| ------------------------ | --------------------------------------------- | +| WebviewGpuPolicyAlways | ハードウェアアクセラレーションを常に有効にする | +| WebviewGpuPolicyOnDemand | Webコンテンツからの要求に応じて、ハードウェアアクセラレーションの有効/無効を切り替える | +| WebviewGpuPolicyNever | ハードウェアアクセラレーションを常に無効にする | + +#### ProgramName + +このオプションでは、GTKのg_set_prgname() を使用し、ウィンドウマネージャのプログラム名を設定することができます。 ただし、ローカライズされた名前を設定すべきではありません。詳しくは[ドキュメント](https://docs.gtk.org/glib/func.set_prgname.html)をご覧ください。 + +.desktopファイルが作成される際、.desktopファイルの`Name`オプションと実行ファイルのファイル名が異なる場合に、ウィンドウのグループ化およびデスクトップアイコンの表示に、本オプションは役立ちます。 + +名前: ProgramName
データ型: string
+ +### Debug + +デバッグビルド時に適用される[デバッグ固有のオプション](#Debug)を定義します。 + +名前: Debug
データ型: `options.Debug` + +#### OpenInspectorOnStartup + +このオプションを`true`に設定すると、アプリケーション起動時にWeb開発者ツールが表示されます。 + +名前: OpenInspectorOnStartup
データ型: `bool` + +[^1]: この機能の動作には、WebKit2GTK 2.36以上が必要となるため、機能を確実に対応させたい場合は、アプリビルド時にビルドタグ`webkit2_36`を付与してください。 これにより、アプリに必要なWebKit2GTKの最小バージョン要件が2.36に引き上げられます。 +[^2]: この機能の動作には、WebKit2GTK 2.40以上が必要となるため、機能を確実に対応させたい場合は、アプリビルド時にビルドタグ`webkit2_40`を付与してください。 これにより、アプリに必要なWebKit2GTKの最小バージョン要件が2.40に引き上げられます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..514c48c4ca9 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,91 @@ +--- +sidebar_position: 5 +--- + +# プロジェクト構成 + +プロジェクト構成は、プロジェクトディレクトリ内の`wails.json`ファイルで設定します。 ファイルの構造は次のとおりです: + +```json5 +{ + // プロジェクト構成のバージョン。 + "version": "", + // プロジェクト名。 + "name": "", + // コンパイルされたアセットディレクトリへの相対パス。通常は自動的に推測されるため、空で構いません。 + "assetdir": "", + // 再読み込みのトリガーとなる追加のディレクトリ(カンマ区切り)。高度なアセット構成をとる場合にのみ使用します。 + "reloaddirs": "", + // ビルドファイルが存在するディレクトリ。 デフォルトは'build'です。 + "build:dir": "", + // フロントエンドディレクトリの相対パス。 デフォルトは'frontend'です。 + "frontend:dir": "", + // node依存関係をインストールするために、フロントエンドディレクトリで実行するコマンド。一般的には`npm install`です。 + "frontend:install": "", + // アセットをビルドするために、フロントエンドディレクトリで実行するコマンド。一般的には`npm run build`です。 + "frontend:build": "", + // このコマンドはfrontend:dev:buildへ置換されました。 frontend:dev:buildが指定されていない場合は、代わりにこのコマンドが実行されます。 このコマンドも指定されていない場合は、代わりにfrontend:buildが実行されます。 + "frontend:dev": "", + // 開発モードにおけるfrontend:buildと同様のコマンド。 指定されていない場合は、代わりにfrontend:devが実行されます。 + "frontend:dev:build": "", + // 開発モードにおけるfrontend:installと同様のコマンド。 指定されていない場合は、代わりにfrontend:installが実行されます。 + "frontend:dev:install": "", + // `wails dev`実行時に別プロセスで実行するコマンド。 サードパーティ製のウォッチャや開発サーバを起動したい場合に便利です。 + "frontend:dev:watcher": "", + // Viteなど、アセットを提供するサードパーティ製の開発サーバのURL。 'auto'に設定すると、Viteの出力から自動的に開発サーバURLを推測します。 + "frontend:dev:serverUrl": "", + // 自動生成されるJSモジュールを出力するディレクトリへの相対パス。 + "wailsjsdir": "", + // 出力バイナリのファイル名 + "outputfilename": "", + // アセットファイルに変更があった場合に、開発サーバが再読み込みを行うまでのデフォルトの待ち時間。 + "debounceMS": 100, + // Wailsの開発サーバをバインドするアドレス。 デフォルト値: localhost:34115 + "devServer": "", + // 開発モードのときに、アプリケーションに渡されるシェルスタイルの引数。 + "appargs": "", + // ホストOS以外のOS用にビルドフックが定義されている場合、それらを実行するかどうか。 + "runNonNativeBuildHooks": false, + "preBuildHooks": { + // 指定されたGOOS/GOARCHのビルドの前に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換されます。 'GOOS/GOARCH'フックは、'GOOS/*'および'*/*'フックの前に実行されます。 + "GOOS/GOARCH": "", + // 指定されたGOOSのビルド前に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換されます。 'GOOS/*'フックは、'*/*'フックの前に実行されます。 + "GOOS/*": "", + // 毎回のビルドの前に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換されます。 + "*/*": "" + }, + "postBuildHooks": { + // 指定されたGOOS/GOARCHのビルドの後に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換され、${bin}はコンパイル済みバイナリへのパスに置換されます。 'GOOS/GOARCH'フックは、'GOOS/*'および'*/*'フックの前に実行されます。 + "GOOS/GOARCH": "", + // 指定されたGOOSのビルド後に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換され、${bin}はコンパイル済みバイナリへのパスに置換されます。 'GOOS/*'フックは、'*/*'フックの前に実行されます。 + "GOOS/*": "", + // 毎回のビルドの後に実行されるコマンド。${platform}は'GOOS/GOARCH'に置換され、${bin}はコンパイル済みバイナリへのパスに置換されます。 + "*/*": "" + }, + // マニフェストやバージョン情報で使用されるデータ。 + "info": { + // 会社名。 デフォルト値: [プロジェクト名] + "companyName": "", + // 製品名。 デフォルト値: [プロジェクト名] + "productName": "", + // 製品バージョン。 デフォルト値: '1.0.0'] + "productVersion": "", + // 製品の著作権。 デフォルト値: 'Copyright.........' + "copyright": "", + // アプリケーションの説明。 デフォルト値: 'Built using Wails (https://wails.app)' + "comments": "" + }, + // 'multiple': アーキテクチャごとに1つのインストーラ。 'single': ビルドした全アーキテクチャに対応する単一ユニバーサルインストーラ。 デフォルト値: 'multiple' + "nsisType": "", + // アプリ難読化を実行するかどうか。 デフォルト値: false + "obfuscated": "", + // obfuscatedフラグがtrueの際に、garbleコマンドへ渡す引数。 + "garbleargs": "" +} +``` + +このファイルは、Wails CLIで `wails build` コマンドまたは `wails dev` コマンドを実行した際に読み込まれます。 + +`wails build/dev` コマンドを実行時に、`assetdir`、`reloaddirs`、`wailsjsdir`、`debounceMS`、`devserver`、`frontenddevserverurl`フラグを使用すると、プロジェクト構成が更新され、次回以降コマンドを実行する際のデフォルト値となります。 + +このファイルのJSONスキーマは、[こちら](https://wails.io/schemas/config.v2.json)にあります。 diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..9e146a3da00 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +sidebar_position: 7 +--- + +# ブラウザ + +これらは、システムブラウザに関連したメソッドです。 + +### BrowserOpenURL + +指定されたURLをシステムブラウザで開きます。 + +Go: `BrowserOpenURL(ctx context.Context, url string)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..9e632294ba2 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# クリップボード + +ランタイム機能の一部として、オペレーティングシステムのクリップボードへのアクセスを提供します。
現在は、テキストの処理のみに対応しています。 + +### ClipboardGetText + +このメソッドは、クリップボードに現在保存されているテキストを読み込みます。 + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
返り値: 文字列(クリップボードが空の場合は、空文字)またはエラー。 + +JS: `ClipboardGetText(): Promise`
返り値: 文字列を待機するPromise(クリップボードが空の場合は、空文字)。 + +### ClipboardSetText + +このメソッドは、クリップボードにテキストを書き込みます。 + +Go: `ClipboardSetText(ctx context.Context, text string) error`
返り値: anyの場合はエラー。 + +JS: `ClipboardSetText(text: string): Promise`
返り値: クリップボードにテキストが正常に書き込まれた場合はtrue、そうでない場合はfalseを返すようなPromise。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..721ba5f31d4 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +sidebar_position: 5 +--- + +# ダイアログ + +ランタイムでは、ファイルセレクターやメッセージボックスといったネイティブダイアログへのアクセスを提供しています。 + +:::info JavaScript + +現在、Javascriptランタイムではダイアログをサポートしていません。 + +::: + +### OpenDirectoryDialog + +ユーザにディレクトリの選択を求めるダイアログを開きます。 [OpenDialogOptions](#opendialogoptions)を使用してカスタマイズできます。 + +Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +返り値: 選択されたディレクトリ(キャンセルされた場合は空) またはエラー + +### OpenFileDialog + +ユーザにファイルの選択を求めるダイアログを開きます。 [OpenDialogOptions](#opendialogoptions)を使用してカスタマイズできます。 + +Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +返り値: 選択されたファイル(キャンセルされた場合は空) またはエラー + +### OpenMultipleFilesDialog + +ユーザに複数ファイルの選択を求めるダイアログを開きます。 [OpenDialogOptions](#opendialogoptions)を使用してカスタマイズできます。 + +Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)` + +返り値: 選択された複数ファイル(キャンセルされた場合はnil) またはエラー + +### SaveFileDialog + +保存の目的でユーザにファイル名を入力選択させるダイアログを開きます。 [SaveDialogOptions](#savedialogoptions)を使用してカスタマイズできます。 + +Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)` + +返り値: 入力選択されたファイル(キャンセルされた場合は空) またはエラー + +### MessageDialog + +メッセージダイアログを使用してメッセージを表示します。 [MessageDialogOptions](#messagedialogoptions)を使用してカスタマイズできます。 + +Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)` + +返り値: 選択されたボタンのテキストまたはエラー + +## オプション + +### OpenDialogOptions + +```go +type OpenDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + ResolvesAliases bool + TreatPackagesAsDirectories bool +} +``` + +| フィールド | 説明 | Win | Mac | Lin | +| -------------------------- | ------------------------- | --- | --- | --- | +| DefaultDirectory | ダイアログが開かれたときに初期表示するディレクトリ | ✅ | ✅ | ✅ | +| DefaultFilename | デフォルトファイル名 | ✅ | ✅ | ✅ | +| Title | ダイアログのタイトル | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | ファイルフィルタのリスト | ✅ | ✅ | ✅ | +| ShowHiddenFiles | システムの隠しファイルを表示 | | ✅ | ✅ | +| CanCreateDirectories | ユーザによるディレクトリの作成を許可する | | ✅ | | +| ResolvesAliases | エイリアスではなくファイルパスを返す | | ✅ | | +| TreatPackagesAsDirectories | パッケージへのナビゲーションを許可 | | ✅ | | + +### SaveDialogOptions + +```go +type SaveDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + TreatPackagesAsDirectories bool +} +``` + +| フィールド | 説明 | Win | Mac | Lin | +| -------------------------- | ------------------------- | --- | --- | --- | +| DefaultDirectory | ダイアログが開かれたときに初期表示するディレクトリ | ✅ | ✅ | ✅ | +| DefaultFilename | デフォルトファイル名 | ✅ | ✅ | ✅ | +| Title | ダイアログのタイトル | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | ファイルフィルタのリスト | ✅ | ✅ | ✅ | +| ShowHiddenFiles | システムの隠しファイルを表示 | | ✅ | ✅ | +| CanCreateDirectories | ユーザによるディレクトリの作成を許可する | | ✅ | | +| TreatPackagesAsDirectories | パッケージへのナビゲーションを許可 | | ✅ | | + +### MessageDialogOptions + +```go +type MessageDialogOptions struct { + Type DialogType + Title string + Message string + Buttons []string + DefaultButton string + CancelButton string +} +``` + +| フィールド | 説明 | Win | Mac | Lin | +| ------------- | ------------------------------------------------- | -------------- | --- | --- | +| Type | メッセージダイアログの種類 (質問、情報など) | ✅ | ✅ | ✅ | +| Title | ダイアログのタイトル | ✅ | ✅ | ✅ | +| Message | ユーザに表示するメッセージ | ✅ | ✅ | ✅ | +| Buttons | ボタンテキストのリスト | | ✅ | | +| DefaultButton | 指定されたテキストのボタンをデフォルトボタンとして扱う。 `return`キーにバインドされます。 | ✅[*](#windows) | ✅ | | +| CancelButton | 指定されたテキストのボタンをキャンセルボタンとして扱う。 `escape`キーにバインドされます。 | | ✅ | | + +#### Windows + +Windowsでは、ボタンのカスタマイズができない標準ダイアログタイプがあります。 返却される値は次のいずれかとなります: "Ok"、"Cancel"、"Abort"、"Retry"、"Ignore"、"Yes"、"No"、"Try Again"、"Continue"。 + +質問ダイアログの場合、デフォルトボタンは"Yes"、キャンセルボタンは"No"となります。 この設定は、`DefaultButton`の値を`"No"`にすることで、変更できます。 + +例: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linuxでは、ボタンのカスタマイズができない標準ダイアログタイプがあります。 返り値は次のいずれかになります: "Ok"、"Cancel"、"Yes"、"No" + +#### Mac + +Macのメッセージダイアログでは、最大4つまでのボタンを指定できます。 `DefaultButton`や`CancelButton`が指定されていない場合、1番目のボタンがデフォルトボタンとして扱われ、`return`キーにバインドされます。 + +例えば次のようなコードの場合: + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "It's your turn!", + Message: "Select a number", + Buttons: []string{"one", "two", "three", "four"}, +}) +``` + +1番目のボタンがデフォルトになります: + +```mdx-code-block +
+ +
+
+``` + +そして`DefaultButton`を"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", +}) +``` + +2番目のボタンがデフォルトになります。 このとき`return`キーが押されると、返り値として"two"が返却されます: + +```mdx-code-block +
+ +
+
+``` + +また、`CancelButton`を"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", +}) +``` + +ダイアログの下部に"three"ボタンが表示されるようになります。 このとき`escape`キーが押されると、返り値として"three"が返却されます: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### 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では、ダイアログボックスで複数のファイルフィルタを使用できます。 それぞれのFileFiltersは、ダイアログ上で個別のエントリーとして表示されます: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Linux + +Linuxでは、ダイアログボックスで複数のファイルフィルタを使用できます。 それぞれのFileFiltersは、ダイアログ上で個別のエントリーとして表示されます: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Mac + +Macのダイアログでは、ファイルをフィルタするためのパターンセットは1つしか持たせることができません。 もし複数のFileFiltersを定義した場合、Wailsはそれらすべてのパターンを使用します。 + +例: + +```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", + }, + }, + }) +``` + +このとき、ファイル選択ダイアログを開くと、`*.png,*.jpg,*.mov,*.mp4`がフィルタとして使用されます。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..ac4f40eba00 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +sidebar_position: 2 +--- + +# イベント + +Wailsでは、GoまたはJavaScriptによって発行および受信できる、一元化されたイベントシステムが用意されています。 必要に応じて、イベント発行時にデータを渡すことも可能です。 イベントリスナーは、そのデータをローカルデータ型で受け取ります。 + +### EventsOn + +このメソッドは、指定されたイベント名のイベントリスナーを新たに設定します。 `eventName`という名前のイベントが[発行](#EventsEmit)されると、コールバックがトリガーされます。 イベント発行時にデータも付与されていた場合、そのデータはコールバックに渡されます。 このメソッドは、リスナーをキャンセルするための関数を返します。 + +Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOff + +このメソッドは、指定されたイベント名のイベントリスナー設定を解除します。引数の`additionalEventNames`を使用することで、複数のリスナーを一度に解除できます。 + +Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`
JS: `EventsOff(eventName string, ...additionalEventNames)` + +### EventsOnce + +このメソッドは、指定されたイベント名のイベントリスナーを新たに設定し、一度だけトリガーさせます。 このメソッドは、リスナーをキャンセルするための関数を返します。 + +Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOnMultiple + +このメソッドは、指定されたイベント名のイベントリスナーを新たに設定し、最大`counter`回だけトリガーします。 このメソッドは、リスナーをキャンセルするための関数を返します。 + +Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`
JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void` + +### EventsEmit + +このメソッドは、指定されたイベントを発行します。 必要に応じて、イベント発行時にデータを渡すこともできます。 このメソッドによって、任意のイベントリスナーをトリガーさせることができます。 + +Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..01e62ff1af0 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# イントロダクション + +ランタイムは、アプリケーションにユーティリティメソッドを提供するライブラリです。 GoとJavaScriptの両方にランタイムがあり、どちらにもほぼ同じメソッドが提供されています。 + +ユーティリティメソッドには次のようなものがあります: + +- [ウィンドウ](window.mdx) +- [メニュー](menu.mdx) +- [ダイアログ](dialog.mdx) +- [イベント](events.mdx) +- [ブラウザ](browser.mdx) +- [ログ](log.mdx) +- [クリップボード](clipboard.mdx) + +Goのランタイムは、`github.com/wailsapp/wails/v2/pkg/runtime`をインポートすることで利用できます。 このパッケージのすべてのメソッドは、1番目の引数でContextを渡す必要があります。 このContextは、[OnStartup](../options.mdx#onstartup)フック、または[OnDomReady](../options.mdx#ondomready)フックからあらかじめ取得しておいてください。 + +:::info 備考 + +[OnStartup](../options.mdx#onstartup)で提供されるContextは、ウィンドウが別のスレッドで初期化されているため、ランタイムが機能する保証がありません。 起動時にランタイムメソッドを呼び出したい場合は、[OnDomReady](../options.mdx#ondomready)を使用してください。 + +::: + +JavaScriptのランタイムは、`window.runtime`マップを介してフロントエンド上で利用できます。 `dev`モードでは、TypeScript型定義を提供するランタイムパッケージが生成されます。 これらは、フロントエンドディレクトリの`wailsjs`ディレクトリに配置しておく必要があります。 + +### Hide + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +アプリケーションを非表示にします。 + +:::info 備考 + +Macでこのメソッドを使用すると、標準のMacアプリケーションにおけるメニュー項目の`Hide`と同じ方法で、アプリケーションが非表示になります。 これはウィンドウの非表示とは異なりますが、アプリケーションはフォアグラウンドに残ったままになります。 WindowsおよびLinuxでは、`WindowHide`メソッドと同等です。 + +::: + +### Show + +アプリケーションを表示します。 + +:::info 備考 + +Macでこのメソッドを使用すると、アプリケーションがフォアグラウンドに戻ります。 WindowsおよびLinuxでは、`WindowShow`メソッドと同等です。 + +::: + +Go: `Show(ctx context.Context)`
JS: `Show()` + +### Quit + +アプリケーションを終了します。 + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### Environment + +現在の環境の詳細情報を取得します。 + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### EnvironmentInfo + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..924f6257ac1 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# ログ + +Wailsでは、GoまたはJavaScriptから呼び出すことのできるロギングメカニズムを用意しています。 一般的なロガーと同じように、ログにはいくつかのログレベルがあります: + +- Trace +- Debug +- Info +- Warning +- Error +- Fatal + +ロガーは、設定されている出力ログレベル以上のログメッセージを出力します。 例えば、出力ログレベルを`Debug`に設定した場合、`Trace`以外のすべてのレベルのメッセージが出力されます。 + +### LogPrint + +指定されたメッセージをRawメッセージとしてロギングします。 + +Go: `LogPrint(ctx context.Context, message string)`
JS: `LogPrint(message: string)` + +### LogPrintf + +指定されたメッセージをRawメッセージとしてロギングします。 + +Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`
+ +### LogTrace + +指定されたメッセージを`Trace`ログレベルでロギングします。 + +Go: `LogTrace(ctx context.Context, message string)`
JS: `LogTrace(message: string)` + +### LogTracef + +指定されたメッセージを`Trace`ログレベルでロギングします。 + +Go: `LogTracef(ctx context.Context, format string, args ...interface{})`
+ +### LogDebug + +指定されたメッセージを`Debug`ログレベルでロギングします。 + +Go: `LogDebug(ctx context.Context, message string)`
JS: `LogDebug(message: string)` + +### LogDebugf + +指定されたメッセージを`Debug`ログレベルでロギングします。 + +Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`
+ +### LogInfo + +指定されたメッセージを`Info`ログレベルでロギングします。 + +Go: `LogInfo(ctx context.Context, message string)`
JS: `LogInfo(message: string)` + +### LogInfof + +指定されたメッセージを`Info`ログレベルでロギングします。 + +Go: `LogInfof(ctx context.Context, format string, args ...interface{})`
+ +### LogWarning + +指定されたメッセージを`Warning`ログレベルでロギングします。 + +Go: `LogWarning(ctx context.Context, message string)`
JS: `LogWarning(message: string)` + +### LogWarningf + +指定されたメッセージを`Warning`ログレベルでロギングします。 + +Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`
+ +### LogError + +指定されたメッセージを`Error`ログレベルでロギングします。 + +Go: `LogError(ctx context.Context, message string)`
JS: `LogError(message: string)` + +### LogErrorf + +指定されたメッセージを`Error`ログレベルでロギングします。 + +Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`
+ +### LogFatal + +指定されたメッセージを`Fatal`ログレベルでロギングします。 + +Go: `LogFatal(ctx context.Context, message string)`
JS: `LogFatal(message: string)` + +### LogFatalf + +指定されたメッセージを`Fatal`ログレベルでロギングします。 + +Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`
+ +### LogSetLogLevel + +出力ログレベルを設定します。 JavaScriptでは、数値が次のログレベルに対応しています: + +| 値 | ログレベル | +| - | ------- | +| 1 | Trace | +| 2 | Debug | +| 3 | Info | +| 4 | Warning | +| 5 | Error | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
JS: `LogSetLogLevel(level: number)` + +## カスタムロガーの使用 + +カスタムロガーは、アプリケーションオプションの1つである[Logger](../options.mdx#logger)で指定してあげることで、使用することができます。 カスタムロガーを使用する際の唯一の要件は、`github.com/wailsapp/wails/v2/pkg/logger`で定義されている`logger.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) +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..9d38fcd62a7 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +sidebar_position: 6 +--- + +# メニュー + +これらは、アプリケーションメニューに関連したメソッドです。 + +:::info JavaScript + +現在、Javascriptランタイムではメニューをサポートしていません。 + +::: + +### MenuSetApplicationMenu + +指定された[menu](../menus.mdx)をアプリケーションメニューとして設定します。 + +Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)` + +### MenuUpdateApplicationMenu + +`MenuSetApplicationMenu`に渡されたメニューへの変更を検知し、アプリケーションメニューを更新します。 + +Go: `MenuUpdateApplicationMenu(ctx context.Context)` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..954c407d5ca --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# スクリーン + +これらのメソッドは、現在接続されているスクリーンに関する情報を提供します。 + +### ScreenGetAll + +現在接続されているスクリーンのリストを返します。 + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### スクリーン + +Go構造体: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript型定義: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..ea6dd358d5b --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +sidebar_position: 4 +--- + +# ウィンドウ + +アプリケーションウィンドウを制御できるメソッド群です。 + +### WindowSetTitle + +ウィンドウのタイトルバーにテキストを設定します。 + +Go: `WindowSetTitle(ctx context.Context, title string)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen + +ウィンドウをフルスクリーンにします。 + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen + +フルスクリーンにする前のウィンドウサイズおよび位置に戻します。 + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen + +ウィンドウがフルスクリーンの場合は、trueを返します。 + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter + +ウィンドウが現在表示されているモニターの中央に、ウィンドウを配置させます。 + +Go: `WindowCenter(ctx context.Context)`
JS: `WindowCenter()` + +### WindowExecJS + +ウィンドウ内で、任意のJSコードを実行します。 + +このメソッドは、ブラウザ上で非同期にコードを実行し、すぐにリターンされます。 スクリプトでエラーが発生した場合、エラーログはブラウザコンソールでのみ確認できます。 + +Go: `WindowExecJS(ctx context.Context, js string)` + +### WindowReload + +リロードします。(現在表示されているページをリロード) + +Go: `WindowReload(ctx context.Context)`
JS: `WindowReload()` + +### WindowReloadApp + +アプリケーションフロントエンドをリロードします。 + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme + +Windowsのみ使用可能。 + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
JS: `WindowSetSystemDefaultTheme()` + +ウィンドウのテーマをシステムデフォルト(ダーク/ライト) に設定します。 + +### WindowSetLightTheme + +Windowsのみ使用可能。 + +Go: `WindowSetLightTheme(ctx context.Context)`
JS: `WindowSetLightTheme()` + +ウィンドウのテーマをライトに設定します。 + +### WindowSetDarkTheme + +Windowsのみ使用可能。 + +Go: `WindowSetDarkTheme(ctx context.Context)`
JS: `WindowSetDarkTheme()` + +ウィンドウのテーマをダークに設定します。 + +### WindowShow + +ウィンドウが非表示になっている場合は、表示させます。 + +Go: `WindowShow(ctx context.Context)`
JS: `WindowShow()` + +### WindowHide + +現在表示されているウィンドウを非表示にします。 + +Go: `WindowHide(ctx context.Context)`
JS: `WindowHide()` + +### WindowIsNormal + +ウィンドウが最小化、最大化、またはフルスクリーンになっていない場合、trueを返します。 + +Go: `WindowIsNormal(ctx context.Context) bool`
JS: `WindowIsNormal() bool` + +### WindowSetSize + +ウィンドウの幅と高さを設定します。 + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize + +ウィンドウの幅と高さを取得します。 + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
JS: `WindowGetSize() : Size` + +### WindowSetMinSize + +ウィンドウの最小サイズを設定します。 現在のウィンドウサイズが、指定された最小サイズよりも小さい場合、現在のウィンドウサイズは変更されます。 + +サイズを`0,0`に設定すると、サイズの制約が無効化されます。 + +Go: `WindowSetMinSize(ctx context.Context, width int, height int)`
JS: `WindowSetMinSize(width: number, height: number)` + +### WindowSetMaxSize + +ウィンドウの最大サイズを設定します。 現在のウィンドウサイズが、指定された最大サイズよりも大きい場合、現在のウィンドウサイズは変更されます。 + +サイズを`0,0`に設定すると、サイズの制約が無効化されます。 + +Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### WindowSetAlwaysOnTop + +ウィンドウを常に最前面に表示するかを切り替えます。 + +Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
JS: `WindowSetAlwaysOnTop(b: Boolen)` + +### WindowSetPosition + +現在ウィンドウが表示されているモニターに対する、相対的なウィンドウ位置を設定します。 + +Go: `WindowSetPosition(ctx context.Context, x int, y int)`
JS: `WindowSetPosition(x: number, y: number)` + +### WindowGetPosition + +現在ウィンドウが表示されているモニターに対する、相対的なウィンドウ位置を取得します。 + +Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
JS: `WindowGetPosition() : Position` + +### WindowMaximise + +ウィンドウを最大化します。 + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise + +ウィンドウの最大化を解除し、最大化する前のサイズおよび位置に戻します。 + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised + +ウィンドウが最大化している場合はtrueを返します。 + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise + +最大化の状態を切り替えます。 + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise + +ウィンドウを最小化します。 + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise + +ウィンドウの最小化を解除し、最小化する前のサイズおよび位置に戻します。 + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised + +ウィンドウが最小化している場合はtrueを返します。 + +Go: `WindowIsMinimised(ctx context.Context) bool`
JS: `WindowIsMinimised() bool` + +### WindowSetBackgroundColour + +ウィンドウの背景色をRGBAカラー定義で設定します。 この色は、すべての透過ピクセルに対して表示されます。 + +R、G、B、Aの有効な値の範囲は0~255です。 + +:::info Windows + +Windowsの場合、0または255のアルファ値(A) のみがサポートされています。 0以外の値を指定すると、すべて255とみなされます。 + +::: + +Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +ネイティブな印刷ダイアログを開きます。 + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## TypeScript型定義 + +### Position + +```ts +interface Position { + x: number; + y: number; +} +``` + +### Size + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/versioned_docs/version-v2.8.0/tutorials/_category_.json b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json similarity index 100% rename from website/versioned_docs/version-v2.8.0/tutorials/_category_.json rename to website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..8422c83f715 --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# ドッグAPI + +```mdx-code-block +
+ +
+
+``` + +:::note + +このチュートリアルは[@tatadan](https://twitter.com/tatadan)より提供されたもので、[Wails Examples Repository](https://github.com/tataDan/wails-v2-examples)の一部になります。 + +::: + +このチュートリアルでは、Webから犬の写真を取得して表示するためのアプリケーションを開発していきます。 + +### プロジェクトの作成 + +アプリケーションを作成していきましょう。 ターミナルで次のように入力します: `wails init -n dogs-api -t svelte` + +注意: IDEサポートが欲しい場合は、コマンドの末尾に、`-ide vscode`オプションまたは`-ide goland`オプションを付与してください。 + +では、`cd dogs-api`で移動し、プロジェクトファイルの編集を始めましょう。 + +### 未使用コードの削除 + +まず、使用しないと分かっているいくつかの要素を削除していきます: + +- `app.go`を開き、次の行を削除します: + +```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) +} +``` + +- `frontend/src/App.svelte`を開き、すべての行を削除します。 +- `frontend/src/assets/images/logo-universal.png`ファイルを削除します。 + +### アプリケーションの作成 + +では、新しいGoコードを書いていきましょう。 + +関数を定義する前に、`app.go`に下記の構造体の宣言を追加します: + +```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 +} +``` + +下記の関数を`app.go`に追加します(おそらく既存の関数定義の後ろ側に追加することになります): + +```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 +} +``` + +`app.go`の`import`セクションを次のように変更します: + +```go +import ( + "context" + "fmt" + "encoding/json" + "io/ioutil" + "log" + "net/http" + "sort" +) +``` + +`frontend/src/App.svelte`に次の行を追加します: + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### アプリケーションのテスト + +バインディングを生成してアプリケーションをテストするには、`wails dev`コマンドを実行してください。 + +### アプリケーションのコンパイル + +アプリケーションを本番用の単一バイナリにコンパイルするには、`wails build`コマンドを実行してください。 diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..55c52342d7b --- /dev/null +++ b/website/i18n/ja/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +sidebar_position: 10 +--- + +# Hello World + +このチュートリアルの目的は、Wailsを使用して、最も基礎的なアプリケーションを起動および実行することです。 あなたは、次のことができるようになります: + +- 新しいWailsアプリケーションを作成する +- アプリケーションをビルドする +- アプリケーションを実行する + +:::note + +このチュートリアルでは、Windowsをターゲットプラットフォームとして使用します。 出力される内容は、オペレーティングシステムによって多少異なります。 + +::: + +## 新しいWailsアプリケーションを作成する + +デフォルトのバニラJSテンプレートを使用して、新しいWailsアプリケーションを作成するには、次のコマンドを実行します: + +```bash +wails init -n helloworld +``` + +すると、次のように表示されます: + +``` +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. +``` + +これにより、カレントディレクトリに`helloworld`という新しいディレクトリが作成されます。 このディレクトリには、いくつかのファイルがあります: + +``` +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 +``` + +## アプリケーションをビルドする + +アプリケーションをビルドするには、新しくできた`helloworld`プロジェクトディレクトリに移動し、次のコマンドを実行します: + +```bash +wails build +``` + +すると、次のように表示されます: + +``` +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 +Devtools: false +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. +``` + +これにより、アプリケーションがコンパイルされ、`build/bin`ディレクトリに保存されます。 + +## アプリケーションを実行する + +Windowsのエクスプローラで`build/bin`ディレクトリを閲覧すると、プロジェクトのバイナリファイルが存在するはずです: + +```mdx-code-block +
+ +
+
+``` + +`helloworld.exe`ファイルをダブルクリックするだけで起動できます。 + +Macの場合、Wailsは`helloworld.app`ファイルを生成します。このファイルをダブルクリックすることで起動できます。 + +Linuxの場合、`build/bin`ディレクトリ内の`./helloworld`を呼び出すことでアプリケーションを起動できます。 + +アプリケーションが期待したとおりに動作することでしょう: + +```mdx-code-block +
+ +
+
+``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..e36a6edfe8c --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +sidebar_position: 2 +--- + +# Links + +This page serves as a list for community related links. Please submit a PR (click `Edit this page` at the bottom) to submit links. + +## Awesome Wails + +The [definitive list](https://github.com/wailsapp/awesome-wails) of links related to Wails. + +## Support Channels + +- [Wails Discord Server](https://discord.gg/JDdSxwjhGf) +- [Github Issues](https://github.com/wailsapp/wails/issues) +- [v2 Beta Discussion Board](https://github.com/wailsapp/wails/discussions/828) + +## Social Media + +- [Twitter](https://twitter.com/wailsapp) +- [Wails Chinese Community QQ Group](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - Group number: 1067173054 + +## Other Tutorials and Articles + +- [Building of Bulletin Board](https://blog.customct.com/building-bulletin-board) diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/bulletinboard.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/bulletinboard.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..9d2a86918ba --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,39 @@ +# CFN Tracker + +```mdx-code-block +

+ +
+

+``` + +[CFN 추적기](https://github.com/williamsjokvist/cfn-tracker) - Street Fighter 6 +또는 V CFN 프로필의 실시간 경기를 추적하세요. 시작하려면 +[웹사이트](https://cfn.williamsjokvist.se/)를 확인하세요. + +## 특징 + +- 실시간 경기 추적 +- 경기 로그 및 통계 저장 +- 브라우저 소스를 통해 OBS에 실시간 통계 표시 지원 +- SF6 및 SFV 모두 지원 +- 사용자가 CSS를 사용하여 자신만의 OBS 브라우저 테마를 만들 수 있는 기능 + +### 웨일스와 함께 사용되는 주요 기술 + +- [작업](https://github.com/go-task/task) - 일반적인 명령을 쉽게 사용할 수 있도 + 록 Wails CLI를 래핑합니다. +- [React](https://github.com/facebook/react) - 풍부한 생태계(radix, 프레이머-모 + 션)로 인해 선택됨 +- [Bun](https://github.com/oven-sh/bun) - 빠른 종속성 해결 및 빌드 시간에 사용됩 + 니다. +- [Rod](https://github.com/go-rod/rod) - 인증 및 폴링 변경을 위한 헤드리스 브라 + 우저 자동화 +- [SQLite](https://github.com/mattn/go-sqlite3) - 경기, 세션 및 프로필을 저장하 + 는 데 사용됩니다. +- [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - + OBS 브라우저 소스에 추적 업데이트를 보내는 http 스트림 +- [i18next](https://github.com/i18next/) - Go 레이어에서 현지화 개체를 제공하기 + 위한 백엔드 커넥터 포함 +- [xstate](https://github.com/statelyai/xstate) - 인증 프로세스 및 추적을 위한 + 상태 머신 diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/emailit.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/emailit.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..4c8cac235a3 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[EncryptEasy](https://www.encrypteasy.app)는 간단하고 사용하기 쉬운 PGP 암호화 도구로 모든 키들을 관리합니다. 암호화는 간단해야 합니다. 그리고 Wails로 개발되었습니다.** + +PGP를 사용한 메시지 암호화는 업계 표준입니다. 모두 개인 키와 공개 키를 가지고 있습니다. 귀하의 개인 키는 귀하만 메시지를 읽을 수 있도록 비공개로 유지되어야 합니다. 귀하의 공개 키는 귀하에게 암호화된 비밀 메시지를 보내려는 모든 사람에게 배포됩니다. 키 관리, 메시지 암호화 및 메시지 해독은 매끄러운 경험이어야 합니다. EncryptEasy는 모든 것을 쉽게 만드는 것입니다. EncryptEasy는 모든 것을 쉽게 만듭니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..73f93417cf0 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[ESP Studio](https://github.com/torabian/esp-studio) - 크로스 플랫폼, 데스크탑, 클라우드 및 임베디드 소프트웨어 +ESP/Arduino 장치 제어, 복잡한 IOT 워크플로 및 제어 시스템 구축용 \ No newline at end of file diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..0881bfe9e1e --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# FileHound Export Utility + +```mdx-code-block +

+ +
+

+``` + +[FileHound Export Utility](https://www.filehound.co.uk/) FileHound는 안전한 파일 보존, 비즈니스 프로세스 자동화 및 SmartCapture 기능을 위해 만들어진 클라우드 문서 관리 플랫폼입니다. + +FileHound Export Utility를 사용하면 FileHound 관리자가 대체 백업 및 복구 목적으로 보안 문서 및 데이터 추출 작업을 실행할 수 있습니다. 이 응용 프로그램은 선택한 필터를 기반으로 FileHound에 저장된 모든 문서 및/또는 메타 데이터를 다운로드합니다. 메타데이터는 JSON 및 XML 형식으로 내보낼 수 있습니다. + +백엔드의 구성은 다음과 같습니다: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2 + +사용된 프론트엔드: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..87e5837d32f --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter) is a simple and efficient http API testing client tool. Based on Wails, Go and sveltejs. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..d31eac0d5f8 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Minecraft Updater + +```mdx-code-block +

+ +
+

+``` + +[Minecraft Updater](https://github.com/Gurkengewuerz/MinecraftModUpdater)는 사용자 기반의 Minecraft 모드를 업데이트하고 동기화하는 유틸리티 도구입니다. Wails2와 [antd](https://ant.design/)를 프런트엔드 프레임워크로 사용한 React를 사용하여 구축되었습니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..9c98dc86473 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Modal File Manager + +```mdx-code-block +

+ +
+

+``` + +[Modal File Manager](https://github.com/raguay/ModalFileManager) 는 웹 기술을 사용하는 이중 창 모양의 파일 관리자입니다. 나의 원래 디자인은 NW.js를 기반으로 했으며 [여기](https://github.com/raguay/ModalFileManager-NWjs)에서 찾을 수 있습니다. 이 버전은 동일한 Svelte 기반 프론트엔드 코드를 사용하지만(그러나 NW.js에서 출발한 이후 크게 수정됨) 백엔드는 [Wails 2](https://wails.io/) 구현입니다. By using this implementation, I no longer use command line `rm`, `cp`, etc. commands, but a git install has to be on the system to download themes and extensions. Go를 사용하여 코딩되었으며, 이전 버전보다 훨씬 빠르게 실행됩니다. + +이 파일 관리자는 Vim과 동일한 원칙, 즉 상태 제어 키보드 동작을 기반으로 설계되었습니다. 상태의 수는 고정이 안되어 있지만, 그러나 매우 프로그래머블합니다. 그러므로, 키보드 설정들의 무한한 수는 생성 될 수 있고 사용될 수 있습니다. 이것은 다른 파일 매니저들과 다른 주요점입니다. There are themes and extensions available to download from GitHub. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..57eda38f981 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[Molly Wallet](https://github.com/grvlle/constellation_wallet/) 은 Constellation Network의 공식 $DAG 지갑입니다. 이를 통해 사용자는 $DAG 트랜잭션 생성에 국한되지 않고 다양한 방식으로 Hypergraph Network와 상호 작용할 수 있습니다. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/october.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/october.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..6bc28218bc5 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# 옵티머스(Optimus) + +```mdx-code-block +

+ +
+

+``` + +[Optimus](https://github.com/splode/optimus) 데스크탑 이미지 최적화 애플리케이션입니다. WebP, JPEG, PNG 이미지 포맷 형식간의 변환 및 압축을 지원합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..f174364c13d --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# 포트폴(Portfall) + +```mdx-code-block +

+ +
+

+``` + +[Portfall](https://github.com/rekon-oss/portfall) - 모든 클러스터 UI에 쉽게 액세스할 수 있는 데스크탑 k8s 포트 포워딩 포털입니다. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/restic-browser.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/restic-browser.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/riftshare.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/riftshare.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/scriptbar.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/scriptbar.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/surge.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/surge.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/wally.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/wally.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..950dc3f3db1 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# Minecraft launcher for WarMine + +```mdx-code-block +

+ + +
+

+``` + +[Minecraft launcher for WarMine](https://warmine.ru/) is a Wails application, that allows you to easily join modded game servers and manage your game accounts. + +The Launcher downloads the game files, checks their integrity and launches the game with a wide range of customization options for the launch arguments from the backend. + +Frontend is written in Svelte, whole launcher fits in 9MB and supports Windows 7-11. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..b2dc9302a9c --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# 웜뱃(Wombat) + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat) 은 크로스 플랫폼인 gRPC 클라이언트 입니다. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/ytd.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/ytd.mdx rename to website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..6ecbac37ee8 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +--- + +# Templates + +This page serves as a list for community supported templates. Please submit a PR (click `Edit this page` at the bottom) to include your templates. To build your own template, please see the [Templates](../guides/templates.mdx) guide. + +To use these templates, run `wails init -n "Your Project Name" -t [the link below[@version]]` + +If there is no version suffix, the main branch code template is used by default. If there is a version suffix, the code template corresponding to the tag of this version is used. + +Example: `wails init -n "Your Project Name" -t https://github.com/misitebao/wails-template-vue` + +:::warning Attention + +**The Wails project does not maintain, is not responsible nor liable for 3rd party templates!** + +If you are unsure about a template, inspect `package.json` and `wails.json` for what scripts are run and what packages are installed. + +::: + +## Vue + +- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - Wails template based on Vue ecology (Integrated TypeScript, Dark theme, Internationalization, Single page routing, TailwindCSS) +- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Vue 3 TypeScript with Vite (and instructions to add features) +- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vue 3 TypeScript with Vite, Vuex, Vue Router, Sass, and ESLint + Prettier +- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - A template using JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier) +- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - A template using TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, Composition API with <script setup>) +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Wails template based on Naive UI (A Vue 3 Component Library) + +## Angular + +- [wails-template-angular](https://github.com/mateothegreat/wails-template-angular) - Angular 15+ action packed & ready to roll to production. +- [wails-angular-template](https://github.com/TAINCER/wails-angular-template) - Angular with TypeScript, Sass, Hot-Reload, Code-Splitting and i18n + +## React + +- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - A template using reactjs +- [wails-react-template](https://github.com/flin7/wails-react-template) - A minimal template for React that supports live development +- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - A template using Next.js and TypeScript +- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - A template for React + TypeScript + Vite + TailwindCSS +- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - A template with Vite, React, TypeScript, TailwindCSS, and shadcn/ui + +## Svelte + +- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - A template using Svelte +- [wails-vite-svelte-template](https://github.com/BillBuilt/wails-vite-svelte-template) - A template using Svelte and Vite +- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - A template using Svelte and Vite with TailwindCSS v3 +- [wails-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - An updated template using Svelte v4.2.0 and Vite with TailwindCSS v3.3.3 +- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - A template using SvelteKit + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - A template using Solid + Ts + Vite +- [wails-template-vite-solid-js](https://github.com/xijaja/wails-template-solid-js) - A template using Solid + Js + Vite + +## Elm + +- [wails-elm-template](https://github.com/benjamin-thomas/wails-elm-template) - Develop your GUI app with functional programming and a **snappy** hot-reload setup :tada: :rocket: +- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - Combine the powers :muscle: of Elm + Tailwind CSS + Wails! Hot reloading supported. + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - Use a unique combination of pure htmx for interactivity plus templ for creating components and forms + +## Pure JavaScript (Vanilla) + +- [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - A template with nothing but just basic JavaScript, HTML, and CSS diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..57d509dfef7 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +sidebar_position: 6 +--- + +# 프로젝트 컴파일 + +프로젝트 디렉토리에서 `wails build` 명령을 실행합니다. 이것은 프로젝트를 컴파일하고 `build/bin` 디렉토리에 프로덕션-준비(production-ready) 바이너리를 저장합니다. + +바이너리를 실행하면 기본 애플리케이션이 표시되어야 합니다: + +```mdx-code-block +
+ +
+
+``` + +컴파일 옵션에 대한 자세한 내용은 [CLI Reference](../reference/cli.mdx#build)를 참조하세요. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..5d0d9185cf4 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 5 +--- + +# 애플리케이션 개발하기 + +프로젝트 디렉토리에서 `wails dev` 명령을 실행하여 개발 모드에서 애플리케이션을 실행할 수 있습니다. 이렇게 하면 다음 작업이 수행됩니다. + +- 애플리케이션 빌드 및 실행 +- JavaScript에서 호출할 수 있도록 Go 코드를 프론트엔드에 바인딩 +- [Vite](https://vitejs.dev/)의 기능을 사용하여 Go 파일의 수정 사항을 감시하고 변경 시 다시 빌드/재실행 합니다. +- 브라우저를 통해 애플리케이션을 제공할 [Webserver](http://localhost:34115) 를 설정합니다. 이렇게 하면 브라우저 확장을 사용할 수 있습니다. 콘솔에서 Go 코드를 호출할 수도 있습니다. + +시작하려면, 프로젝트 디렉토리 내에서 `wails dev` 명령을 실행하세요. 더많은 정보는 [here](../reference/cli.mdx#dev) 에서 찾을 수 있습니다. + +출시 예정: 튜토리얼 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..45f2aa8a57e --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 2 +--- + +# 프로젝트 생성하기 + +## 프로젝트 생성 + +이제 CLI가 설치되었습니다, `wails init` 명령을 사용하여 새로운 프로젝트를 생성할 수 있습니다. + +원하는 프레임워크를 선택하세요: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Generate a Svelte project using JavaScript with:

+ + wails init -n myproject -t svelte + +If you would rather use TypeScript:
+ + wails init -n myproject -t svelte-ts + +
+ + Generate a React project using JavaScript with:

+ + wails init -n myproject -t react + +If you would rather use TypeScript:
+ + wails init -n myproject -t react-ts + +
+ + Generate a Vue project using JavaScript with:

+ + wails init -n myproject -t vue + +If you would rather use TypeScript:
+ + wails init -n myproject -t vue-ts + +
+ + Generate a Preact project using JavaScript with:

+ + wails init -n myproject -t preact + +If you would rather use TypeScript:
+ + wails init -n myproject -t preact-ts + +
+ + Generate a Lit project using JavaScript with:

+ + wails init -n myproject -t lit + +If you would rather use TypeScript:
+ + wails init -n myproject -t lit-ts + +
+ + Generate a Vanilla project using JavaScript with:

+ + wails init -n myproject -t vanilla + +If you would rather use TypeScript:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +다양한 기능과 프레임워크를 제공하는 [커뮤니티 템플릿](../community/templates.mdx)도 있습니다. + +사용 가능한 다른 옵션을 보려면 `wails init -help` 명령을 실행할 수 있습니다. 자세한 내용은 [CLI Reference](../reference/cli.mdx#init)에서 찾을 수 있습니다. + +## 프로젝트 레이아웃 + +Wails 프로젝트는 다음 레이아웃을 따릅니다: + +``` +. +├── build/ +│ ├── appicon.png +│ ├── darwin/ +│ └── windows/ +├── frontend/ +├── go.mod +├── go.sum +├── main.go +└── wails.json +``` + +### 프로젝트 구조 개요 + +- `/main.go` - 메인 애플리케이션 +- `/frontend/` - Frontend 프로젝트 파일들 +- `/build/` - 프로젝트 빌드 디렉토리 +- `/build/appicon.png` - 애플리케이션 아이콘 +- `/build/darwin/` - Mac 특정 프로젝트 파일 +- `/build/windows/` - Windows 특정 프로젝트 파일 +- `/wails.json` - 프로젝트 구성 파일 +- `/go.mod` - Go 모듈 파일 +- `/go.sum` - Go 모듈 체크섬 파일 + +`frontend` 프론트엔드 디렉토리에는 Wails와 관련된 것이 없으며 선택한 모든 프론트엔드 프로젝트가 될 수 있습니다. + +`build` 디렉토리는 빌드가 진행되는 동안 사용됩니다. 이 파일들을 업데이트 하여 빌드를 커스텀마이징할 수 있습니다. 만약 빌드 디렉토리에서 파일이 제거되면 기본 버전이 재생성됩니다. + +`go.mod`의 기본 모듈 이름은 "changeme" 입니다. 이것을 더 적절한 것으로 변경해야 합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..1d911d11802 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +--- + +# 설치하기 + +## 지원되는 플랫폼 + +- Windows 10/11 AMD64/ARM64 +- MacOS 10.13+ AMD64 +- MacOS 11.0+ ARM64 +- Linux AMD64/ARM64 + +## 의존성 + +Wails는 설치 전에 아래와 같은 몇 가지 공통적인 의존성이 필요합니다. + +- Go 1.18+ +- NPM (Node 15+) + +### Go + +[Go 다운로드 페이지](https://go.dev/dl/)에서 Go를 다운로드 합니다. + +공식 [Go 설치 지침](https://go.dev/doc/install)에 따라 진행하세요. 또한 `PATH` 환경 변수에 `~/go/bin` 디렉토리에 대한 경로도 포함되어 있는지 확인해야 합니다. 터미널을 다시 시작하고 아래 내용을 확인하세요. + +- Go가 정상적으로 설치되었는지 확인: `go version` +- PATH 변수에 "~/go/bin" 확인: `echo $PATH | grep go/bin` + +### NPM + +[Node 다운로드 페이지](https://nodejs.org/en/download/)에서 NPM을 다운로드 합니다. 우리는 일반적으로 최신 버전에서 테스트를 진행하기 때문에 최신 버전 사용을 권장합니다. + +정상적으로 설치된 것을 확인하기 위해 `npm --version`을 실행합니다. + +## 플랫폼에 따른 의존성 + +플랫폼별 의존 항목도 설치해야 합니다: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Wails 는 xcode line tools 설치를 필요로 합니다. xcode-select --install. 를 실행하여 수행할 수 있습니다. + + + Wails 는 WebView2 런타임 설치를 필요로 합니다. 몇몇 Windows는 이미 설치되어 있습니다. wails doctor 명령을 사용하여 확인할 수 있습니다. + + + Linux requires the standard gcc build tools plus libgtk3 and libwebkit. 다양한 배포판에 대한 수 많은 명령을 나열하는 대신 Wail는 특정 배포판에 대한 설치 명령이 무엇인지 결정할 수 있습니다. wails doctor 명령을 실행하면 설치 후 종속성을 설치하는 방법을 보여줍니다. 만약 배포판/패키지 매니저가 지원하지 않는다면, 를 통해 문의하세요. 리눅스 배포판 추가 가이드 + + +``` + +## 선택 설치 + +- [UPX](https://upx.github.io/) 는 애플리케이션 압축을 위함. +- [NSIS](https://wails.io/docs/guides/windows-installer/) 는 윈도우 인스톨러를 생성하기 위함. + +## Wails 설치 + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` 명령을 실행하여 Wails CLI를 설치합니다. + +참고: 다음과 비슷한 오류가 발생하는 경우: + +```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 +``` +Go 1.18 이상의 버전이 설치되어 있는지 확인하세요: +```shell +go version +``` + +## 시스템 점검 + +`wails doctor`를 실행하면 의존성이 올바르게 설치되어 있는지 점검할 수 있습니다. 문제가 있는 의존성에 대해서는 문제 해결을 위한 도움을 줄 수 있습니다. + +## `wails` 명령이 사라졌다고 나오나요? + +시스템에서 `wails` 명령이 누락되었다고 뜨는 경우 Go 설치 가이드를 바르게 따랐는지 확인하세요. 일반적으로, 사용자의 홈 디렉토리에 있는 `go/bin` 디렉토리가 `PATH` 환경 변수에 없음을 의미합니다. 또한, 설치 프로그램이 수행한 환경 변경 사항이 명령 프롬프트에 반영되도록 일반적으로 열려 있는 모든 명령 프롬프트를 닫았다가 다시 열어야합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..1b21f9daa7a --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# Angular + +Wails에는 Angular 템플릿이 없지만 Wails와 함께 Angular를 사용할 수 있습니다. + +## 개발자 모드 + +Angular에서 작동하는 개발 모드를 사용하려면 `wails.json`에 다음을 추가해야 합니다. + +```json + "frontend:build": "npx ng build", + "frontend:install": "npm install", + "frontend:dev:watcher": "npx ng serve", + "frontend:dev:serverUrl": "http://localhost:4200", +``` \ No newline at end of file diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..e4251eba409 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# 애플리케이션 개발 + +Wails로 애플리케이션을 개발하기 위한 엄격한 규칙은 없으나 몇 가지의 기본 가이드가 있습니다. + +## 애플리케이션 셋업 + +기본 템플릿에서 사용되는 패턴은 `main.go`가 애플리케이션 구성 및 실행에 사용되는 반면 `app.go`는 애플리케이션 로직 정의에 사용된다는 것입니다. + +`app.go` 파일은 기본 애플리케이션에 hook 역할을 하는 2개의 메소드가 있는 구조체를 정의합니다. + +```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) { +} +``` + +- 시작 메서드는 Wails가 필요한 리소스를 할당하는 즉시 호출되며 리소스 생성, 이벤트 리스너 설정 및 시작 시 응용 프로그램에 필요한 모든 것을 설정하기에 좋은 위치입니다. 일반적으로 구조체 필드에 저장되는 `context.Context`가 제공됩니다. 이 컨텍스트는 [런타임](../reference/runtime/intro.mdx)을 호출하는 데 필요합니다. 이 메서드가 오류를 반환하면 응용 프로그램이 종료됩니다. 개발 모드에서는 오류가 콘솔에 출력됩니다. + +- Shutdown 메소드는 shutdown 프로세스가 끝날 때 바로 Wails에 의해 호출됩니다. 이것은 메모리 할당을 해제하고 모든 shutodown 작업을 수행하기에 좋은 위치입니다. + +`main.go` 파일은 일반적으로 애플리케이션 구성을 허용하는 `wails.Run()`에 대한 단일 호출로 구성됩니다. 템플릿에서 사용하는 패턴은 `wails.Run()`을 호출하기 전에 `app.go`에서 정의한 구조체의 인스턴스가 생성되어 변수에 저장된다는 것입니다. 이것은 `app`이라고 합니다. 이 configuration 은 콜백을 추가하는 위치입니다: + +```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) + } +} + +``` + +애플리케이션 lifecycle hook에 대한 자세한 내용은 [여기](../howdoesitwork.mdx#application-lifecycle-callbacks)에서 확인할 수 있습니다. + +## 바인딩 메소드 + +프론트엔드에서 Go 메서드를 호출할 가능성이 높습니다. 이는 일반적으로 `app.go`에서 이미 정의된 구조체에 public method를 추가하여 수행됩니다. + +```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) +} +``` + +메인 어플리케이션 구성에서, `Bind` 키는 Wails에 무엇을 바인딩할지 알릴 수 있는 부분입니다. + +```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) + } +} + +``` + +이렇게 하면 `App` 구조체의 모든 공개 메서드가 바인딩됩니다(시작 및 종료 메서드는 바인딩되지 않음). + +### 여러 구조체를 바인딩할 때의 컨텍스트 처리 + +여러 구조체에 대한 메서드를 바인딩하고 싶지만 런타임을 사용할 수 있도록 각 구조체가 컨텍스트에 대한 참조를 유지하기를 원하는 경우, 함수에서 좋은 패턴은 `OnStartup` 메서드에서 구조체 인스턴스로 컨텍스트를 전달하는 것입니다. + +```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) + } +} +``` + +바인딩에 대한 더 많은 정보는 [여기](../howdoesitwork.mdx#method-binding)에서 확인할 수 있습니다. + +## Application Menu + +Wails는 당신의 애플리케이션에 메뉴 추가를 지원합니다. 이것은 [Menu](../reference/menus.mdx#menu) 구조체를 애플리케이션 구성에 전달하여 수행됩니다. Menu를 반환하는 메서드를 사용하는 것이 일반적이며 lifecycle hooks에 사용되는 `App` 구조체의 메서드인 경우에는 훨씬 더 일반적입니다. + +```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 + +Wails v2가 assets을 처리하는 방식의 장점은 그렇지 않다는 것입니다! Wails에 제공해야 하는 유일한 것은 `embed.FS`입니다. 당신이 어떻게 얻어내는가는 전적으로 당신에게 달렸습니다. 바닐라 템플릿과 같은 바닐라 html/css/js를 사용할 수 있습니다. 복잡한 빌드 시스템을 가질 수 있으나, 중요하지 않습니다. + +`wails build`가 실행되면 프로젝트 최상위에서 `wails.json` 프로젝트 파일을 확인합니다. 프로젝트 파일에는 2개의 키가 있습니다. + +- "frontend:install" +- "frontend:build" + +첫 번째는 노드 모듈을 설치하기 위해 `frontend` 디렉토리에서 실행됩니다. 두 번째는 프런트엔드 프로젝트를 빌드하기 위해 `frontend` 디렉토리에서 실행됩니다. + +이 2개의 키가 주어지지 않으면 Wails는 프런트엔드에서 아무 작업도 수행하지 않습니다. 그것은 `embed.FS`에서만 기대합니다. + +### AssetsHandler + +Wails v2 앱은 선택적으로 `options.App`에서 `http.Handler`를 정의할 수 있습니다. 즉석에서 파일을 생성하거나 POST/PUT 요청을 처리합니다. GET 요청은 항상 `assets` FS에서 먼저 처리됩니다. FS가 요청된 파일을 찾지 못하면 요청은 제공을 위해 `http.Handler`로 전달됩니다. GET 이외의 모든 요청은 지정된 경우 `AssetsHandler`에서 직접 처리됩니다. `Assets` 옵션으로 `nil`을 지정하여 `AssetsHandler`만 사용할 수도 있습니다. + +## Built in Dev Server + +`wails dev`를 실행하면 내장된 dev 서버가 시작되어 프로젝트 디렉토리에서 file watcher를 시작합니다. 기본적으로 파일이 변경되면 wails는 응용 프로그램 파일인지 확인합니다(기본값: `.go`, `-e` 플래그로 구성 가능). 그렇다면 응용 프로그램을 다시 빌드하고 다시 시작합니다. 변경된 파일이 assets에 있는 경우 짧은 시간 후에 다시 로드를 발행합니다. + +개발 서버는 "debouncing"이라는 기술을 사용합니다. 즉, 짧은 시간에 여러 파일이 변경될 수 있으므로 바로 다시 로드되지 않습니다. 트리거가 발생하면 다시 로드하기 전에 설정된 시간 동안 기다립니다. 다른 트리거가 발생하면 다시 대기 시간으로 재설정됩니다. 기본 값은 `100ms` 입니다. 이 값이 프로젝트에서 작동하지 않는 경우 `-debounce` 플래그를 사용하여 구성할 수 있습니다. 사용하는 경우 이 값은 프로젝트 구성에 저장되고 기본값이 됩니다. + +## External Dev Server + +일부 프레임워크는 자체 라이브 리로딩 서버와 함께 제공되지만 Wails Go 바인딩을 활용할 수 없습니다. 이 시나리오에서는 Wails가 감시할 빌드 디렉토리에 프로젝트를 다시 빌드하는 watcher script를 실행하는 것이 가장 좋습니다. 예를 보려면 [rollup](https://rollupjs.org/guide/en/)을 사용하는 기본 svelte 템플릿을 참조하세요. + +### Create React App + +The process for a Create-React-App project is slightly more complicated. In order to support live frontend reloading the following configuration needs to be added to your `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +The `frontend:dev:watcher` command will start the Create-React-App development server (hosted on port `3000` typically). The `frontend:dev:serverUrl` command then instructs Wails to serve assets from the development server when loading the frontend rather than from the build folder. In addition to the above, the `index.html` needs to be updated with the following: + +```html + + + + + +``` + +This is required as the watcher command that rebuilds the frontend prevents Wails from injecting the required scripts. This circumvents that issue by ensuring the scripts are always injected. With this configuration, `wails dev` can be run which will appropriately build the frontend and backend with hot-reloading enabled. Additionally, when accessing the application from a browser the React developer tools can now be used on a non-minified version of the application for straightforward debugging. Finally, for faster builds, `wails dev -s` can be run to skip the default building of the frontend by Wails as this is an unnecessary step. + +## Go Module + +기본 Wails 템플릿은 "changeme"라는 모듈 이름이 포함된 `go.mod` 파일을 생성합니다. 프로젝트 생성 후에 이 파일의 이름을 변경해야 합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..989202e27a6 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# 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 {17-36,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 +

+ +

+``` + +However, if we request `go.mod`, we will see the following output: + +```mdx-code-block +

+ +

+``` + +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 + +``` + +with: + +```html + +``` + +Then we would see the following: + +```mdx-code-block +

+ +

+``` + +:::warning + +Exposing your filesystem in this way is a security risk. It is recommended that you properly manage access to your filesystem. + +::: diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..3845736f427 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# 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 + + + + + + + +
+ + +
+
+ + + + +``` + +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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info Fullscreen + +If you allow your application to go fullscreen, this drag functionality will be disabled. + +::: diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..ac087ee4514 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# Frontend + +## Script Injection + +When Wails serves your `index.html`, by default, it will inject 2 script entries into the `` 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 + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### Overriding Default Script Injection + +To provide more flexibility to developers, there is a meta tag that may be used to customise this behaviour: + +```html + +``` + +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 + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..f742822832a --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# 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 +

+ +

+``` + +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. + +::: diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..8b25c15754a --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# 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 `.go`, where `` 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! + +::: diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..229c282bf55 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# 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) diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..4ba1f34c37d --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# 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 => ` + +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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..961595711c7 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# 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 + +#### 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. + +## 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. You will need to replace the Team ID and Application Name with the ones you registered above. + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +**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. + +#### 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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..dcf192d337f --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# 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/.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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..7123cbe6b60 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,191 @@ +# 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: + +

+ +| 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. | + +

diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..4a3de2a61b5 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# 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 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..21f7875e389 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# 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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..e94cfbb7e77 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# 오버스크롤(Overscroll) + +[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) 은 페이지의 콘텐츠 경계를 넘어 스크롤할 때 가끔 발생하는 "바운스 효과"입니다. 이것은 모바일 앱에서도 동일합니다. CSS를 사용하여 비활성 할 수 있습니다. + +```css +html { + height: 100%; + overflow: hidden; +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..ce176943ea5 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,47 @@ +# 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/en/main/router-components/hash-router): + +```jsx +import { HashRouter } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..4c7cf45ba99 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# 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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +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 + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +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 + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +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). diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..4651c422ed1 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +This guide will go into: + +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. Minimal Installation Steps + +##### Install Wails for Svelte. + +- `wails init -n myapp -t svelte` + +##### Delete the svelte frontend. + +- Navigate into your newly created myapp folder. +- Delete the folder named "frontend" + +##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts. + +- `npm create svelte@latest frontend` + +##### Modify 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. + +##### Modify main.go. + +- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build` + +##### Install/remove dependencies using your favorite package manager. + +- Navigate into your "frontend" folder. +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Change adapter in svelte.config.js + +- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Put SvelteKit into SPA mode with prerendering. + +- 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` + +##### Test 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. + +## 2. Install Script + +##### 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. + +- 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` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Important Notes + +##### Server files will cause build failures. + +- \+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. + +##### The Wails runtime unloads with full page navigations! + +- Anything that causes full page navigations: `window.location.href = '//'` 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('//')` 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 `` of myapp/frontend/src/app.html + +``` + +... + + + +... + +``` + +See https://wails.io/docs/guides/frontend for more information. + +##### Inital data can be loaded and refreshed from +page.ts/+page.js to +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. + +##### Error Handling + +- 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. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Using Forms and handling functions + +- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `` +- 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: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..790e3107f04 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# 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 +
+ +
+``` + +## 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 diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..2b5b7a25840 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# Troubleshooting + +An assortment of troubleshooting tips. + +## `wails` 명령어를 찾을 수 없나요? + +시스템에서 `wails` 명령어를 찾을 수 없는 경우 Go 설치 지침을 잘 따라했는지 확인해보세요. 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 +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +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 +

+ +

+``` + +it's likely that your application's `info.plist` is invalid. Update the file in `build/.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. + +## My application is not displaying the correct icon in Windows Explorer + +If your application is not displaying the correct icon, try deleting the hidden `IconCache.db` file located in the `C:\Users\<your username>\AppData\Local` directory. This will force Windows to rebuild the icon cache. + +Source: https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## 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 `` section of any new page you navigate to: + +```html + + + + +``` + +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 + +## My application won't compile on Mac + +If you are getting errors like this: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## 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. + +## Build process stuck on "Generating bindings" + +Bindings generation process runs your application in a special mode. If application, intentionally or unintentionally, contains an endless loop (i.e. not exiting after `wails.Run()` finished), this can lead to build process stuck on the stage of bindings generation. Please make sure your code exits properly. + +## Mac application flashes white at startup + +This is due to the default background of the webview being white. If you want to use the window background colour instead, you can make the webview background transparent using the following config: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..ed258656d63 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# 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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..22d3aec7078 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# NSIS installer + +```mdx-code-block +

+ +
+

+``` + +Wails는 [NSIS installer](https://nsis.sourceforge.io/)를 사용하여 Windows 인스톨러 생성을 지원합니다. + +## NSIS 설치하기 + +### Windows + +인스톨러는 [NSIS Download](https://nsis.sourceforge.io/Download) 페이지에서 사용이 가능합니다. + +만약 chocolatey 패키지 매니저를 사용한다면, 다음 스크립트를 실행하세요: + +``` +choco install nsis +``` + +만약 NSIS를 수동으로 설치하기 원한다면, NSIS가 설치된 경로에서 `makensis.exe`가 포함된 _Bin_ 폴더를 추가 해야합니다. [여기](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) Windows에서 어떻게 경로를 추가하는지에 대한 튜토리얼이 있습니다. + +### Linux + +`nsis` 패키지는 사용자의 배포판 패키지 매니저를 통해 이용이 가능합니다. + +### MacOS + +NSIS는 homebrew를 통해 설치가 가능합니다: `brew install nsis`. + +## 인스톨러 생성하기 + +새로운 프로젝트가 생성되었을때, Wails는 NSIS 설정 파일을 `build/windows/installer`에 생성합니다. 설정 데이터는 `installer/info.json`로 부터 읽어오며 이 데이터는 이 프로젝트의 `wails.json` Info 섹션에서 설정되어 사용됩니다: + +```json +// ... + "Info": { + "companyName": "My Company Name", + "productName": "Wails Vite", + "productVersion": "1.0.0", + "copyright": "Copyright.........", + "comments": "Built using Wails (https://wails.io)" + }, +``` + +애플리케이션을 위한 인스톨러를 생성하기 위해 `-nsis` 플래그를 `wails build`와 함께 사용하세요: + +``` +wails build -nsis +``` + +이제 인스톨러는 `build/bin` 디렉토리에서 이용이 가능합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..821808c0b8d --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# 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. Browser +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. + +### Browser + +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). diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..44fa130cc74 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +sidebar_position: 20 +--- + +# How does it work? + +A Wails application is a standard Go application, with a webkit frontend. The Go part of the application consists of the application code and a runtime library that provides a number of useful operations, like controlling the application window. The frontend is a webkit window that will display the frontend assets. Also available to the frontend is a JavaScript version of the runtime library. Finally, it is possible to bind Go methods to the frontend, and these will appear as JavaScript methods that can be called, just as if they were local JavaScript methods. + +```mdx-code-block +
+ +
+``` + +## The Main Application + +### Overview + +The main application consists of a single call to `wails.Run()`. It accepts the application configuration which describes the size of the application window, the window title, what assets to use, etc. A basic application might look like this: + +```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) +} +``` + +### Options rundown + +This example has the following options set: + +- `Title` - The text that should appear in the window's title bar +- `Width` & `Height` - The dimensions of the window +- `Assets` - The application's frontend assets +- `OnStartup` - A callback for when the window is created and is about to start loading the frontend assets +- `OnShutdown` - A callback for when the application is about to quit +- `Bind` - A slice of struct instances that we wish to expose to the frontend + +A full list of application options can be found in the [Options Reference](reference/options). + +#### Assets + +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 {17,27} 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 {10-12} + //... + 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. + +## The Frontend + +### Overview + +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; +``` + +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; +``` + +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). + +### Calling runtime methods + +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. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..e3118cba38a --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +--- + +# 소개 + +Wails is a project that enables you to write desktop apps using Go and web technologies. + +Consider it a lightweight and fast Electron alternative for Go. You can easily build applications with the flexibility and power of Go, combined with a rich, modern frontend. + +### Features + +- Native Menus, Dialogs, Theming and Translucency +- Windows, macOS and linux support +- Built in templates for Svelte, React, Preact, Vue, Lit and Vanilla JS +- Easily call Go methods from JavaScript +- Automatic Go struct to TypeScript model generation +- No CGO or external DLLs required on Windows +- Live development mode using the power of [Vite](https://vitejs.dev/) +- Powerful CLI to easily Create, Build and Package applications +- A rich [runtime library](/docs/reference/runtime/intro) +- Applications built with Wails are Apple & Microsoft Store compliant + +This is varly - a desktop application for MacOS & Windows written using Wails. Not only does it look great, it uses native menus and translucency - everything you'd expect from a modern native app. + +```mdx-code-block +

+ +

+``` + +### Quick Start Templates + +Wails comes with a number of pre-configured templates that allow you to get your application up and running quickly. There are templates for the following frameworks: Svelte, React, Vue, Preact, Lit and Vanilla. There are both JavaScript and TypeScript versions for each template. + +### Native Elements + +Wails uses a purpose built library for handling native elements such as Window, Menus, Dialogs, etc, so you can build good-looking, feature rich desktop applications. + +**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. On Windows, this is the new Microsoft Webview2 library, built on Chromium. + +### Go & JavaScript Interoperability + +Wails automatically makes your Go methods available to JavaScript, so you can call them by name from your frontend! It even generates TypeScript models for the structs used by your Go methods, so you can pass the same data structures between Go and JavaScript. + +### Runtime Library + +Wails provides a runtime library, for both Go and JavaScript, that handles a lot of the things modern applications need, like Eventing, Logging, Dialogs, etc. + +### Live Development Experience + +#### Automatic Rebuilds + +When you run your application in "dev" mode, Wails will build your application as a native desktop application, but will read your assets from disk. It will detect any changes to your Go code and automatically rebuild and relaunch your application. + +#### Automatic Reloads + +When changes to your application assets are detected, your running application will "reload", reflecting your changes almost immediately. + +#### Develop your application in a Browser + +If you prefer to debug and develop in a browser then Wails has you covered. The running application also has a webserver that will run your application in any browser that connects to it. It will even refresh when your assets change on disk. + +### Production-ready Native Binaries + +When you're ready to do the final build of your application, the CLI will compile it down to a single executable, with all the assets bundled into it. On Windows and MacOS, it is possible to create a native package for distribution. The assets used in packaging (icon, info.plist, manifest file, etc) are part of your project and may be customised, giving you total control over how your applications are built. + +### Tooling + +The Wails CLI provides a hassle-free way to generate, build and bundle your applications. It will do the heavy lifting of creating icons, compiling your application with optimal settings and delivering a distributable, production ready binary. Choose from a number of starter templates to get up and running quickly! diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..c7aea10a64d --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,240 @@ +--- +sidebar_position: 2 +--- + +# CLI + +The Wails CLI has a number of commands that are used for managing your projects. All commands are run in the following way: + +`wails ` + +## init + +`wails init` is used for generating projects. + +| Flag | Description | Default | +|:------------------ |:----------------------------------------------------------------------------------------------------------------------- |:-------------------:| +| -n "project name" | Name of the project. **Mandatory**. | | +| -d "project dir" | Project directory to create | Name of the project | +| -g | Initialise git repository | | +| -l | List available project templates | | +| -q | Suppress output to console | | +| -t "template name" | The project template to use. This can be the name of a default template or a URL to a remote template hosted on github. | vanilla | +| -ide | Generate IDE project files | | +| -f | Force build application | false | + +Example: `wails init -n test -d mytestproject -g -ide vscode -q` + +This will generate a a project called "test" in the "mytestproject" directory, initialise git, generate vscode project files and do so silently. + +More information on using IDEs with Wails can be found [here](../guides/ides.mdx). + +### Remote Templates + +Remote templates (hosted on GitHub) are supported and can be installed by using the template's project URL. + +Example: `wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]` + +A list of community maintained templates can be found [here](../community/templates.mdx) + +:::warning Attention + +**The Wails project does not maintain, is not responsible nor liable for 3rd party templates!** + +If you are unsure about a template, inspect `package.json` and `wails.json` for what scripts are run and what packages are installed. + +::: + +## build + +`wails build` is used for compiling your project to a production-ready binary. + +| Flag | Description | Default | +|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------- | +| -clean | Cleans the `build/bin` directory | | +| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go | +| -debug | Retains debug information in the application and shows the debug console. Allows the use of the devtools in the application window | | +| -devtools | Allows the use of the devtools in the application window in production (when -debug is not used). Ctrl/Cmd+Shift+F12 may be used to open the devtools window. *NOTE*: This option will make your application FAIL Mac appstore guidelines. Use for debugging only. | | +| -dryrun | Prints the build command without executing it | | +| -f | Force build application | | +| -garbleargs | Arguments to pass to garble | `-literals -tiny -seed=random` | +| -ldflags "flags" | Additional ldflags to pass to the compiler | | +| -m | Skip mod tidy before compile | | +| -nopackage | Do not package application | | +| -nocolour | Disable colour in output | | +| -nosyncgomod | Do not sync go.mod with the Wails version | | +| -nsis | Generate NSIS installer for Windows | | +| -o filename | Output filename | | +| -obfuscated | Obfuscate the application using [garble](https://github.com/burrowers/garble) | | +| -platform | Build for the given (comma delimited) [platforms](../reference/cli.mdx#platforms) eg. `windows/arm64`. Note, if you do not give the architecture, `runtime.GOARCH` is used. | platform = `GOOS` environment variable if given else `runtime.GOOS`.
arch = `GOARCH` envrionment variable if given else `runtime.GOARCH`. | +| -race | Build with Go's race detector | | +| -s | Skip building the frontend | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Build tags to pass to Go compiler. Must be quoted. Space or comma (but not both) separated | | +| -trimpath | Remove all file system paths from the resulting executable. | | +| -u | Updates your project's `go.mod` to use the same version of Wails as the CLI | | +| -upx | Compress final binary using "upx" | | +| -upxflags | Flags to pass to upx | | +| -v int | Verbosity level (0 - silent, 1 - default, 2 - verbose) | 1 | +| -webview2 | WebView2 installer strategy: download,embed,browser,error | download | +| -windowsconsole | Keep the console window for Windows builds | | + +For a detailed description of the `webview2` flag, please refer to the [Windows](../guides/windows.mdx) Guide. + +If you prefer to build using standard Go tooling, please consult the [Manual Builds](../guides/manual-builds.mdx) guide. + +Example: + +`wails build -clean -o myproject.exe` + +:::info + +On Mac, the application will be bundled with `Info.plist`, not `Info.dev.plist`. + +::: + +:::info UPX on Apple Silicon + +There are [issues](https://github.com/upx/upx/issues/446) with using UPX with Apple Silicon. + +::: + +:::info UPX on Windows + +Some Antivirus vendors false positively mark `upx` compressed binaries as virus, see [issue](https://github.com/upx/upx/issues/437). + +::: + +### Platforms + +Supported platforms are: + +| Platform | Description | +|:---------------- |:--------------------------------------------- | +| darwin | MacOS + architecture of build machine | +| darwin/amd64 | MacOS 10.13+ AMD64 | +| darwin/arm64 | MacOS 11.0+ ARM64 | +| darwin/universal | MacOS AMD64+ARM64 universal application | +| windows | Windows 10/11 + architecture of build machine | +| windows/amd64 | Windows 10/11 AMD64 | +| windows/arm64 | Windows 10/11 ARM64 | +| linux | Linux + architecture of build machine | +| linux/amd64 | Linux AMD64 | +| linux/arm64 | Linux ARM64 | + +## doctor + +`wails doctor` will run diagnostics to ensure that your system is ready for development. + +Example: + +``` +Wails CLI v2.0.0-beta + +Scanning system - Please wait (this may take a long time)...Done. + +System +------ +OS: Windows 10 Pro +Version: 2009 (Build: 19043) +ID: 21H1 +Go Version: go1.18 +Platform: windows +Architecture: amd64 + +Dependency Package Name Status Version +---------- ------------ ------ ------- +WebView2 N/A Installed 93.0.961.52 +npm N/A Installed 6.14.15 +*upx N/A Installed upx 3.96 + +* - Optional Dependency + +Diagnosis +--------- +Your system is ready for Wails development! + +``` + +## dev + +`wails dev` is used to run your application in a "live development" mode. This means: + +- The application's `go.mod` will be updated to use the same version of Wails as the CLI +- The application is compiled and run automatically +- A watcher is started and will trigger a rebuild of your dev app if it detects changes to your go files +- A webserver is started on `http://localhost:34115` which serves your application (not just frontend) over http. This allows you to use your favourite browser development extensions +- All application assets are loaded from disk. If they are changed, the application will automatically reload (not rebuild). All connected browsers will also reload +- A JS module is generated that provides the following: +- JavaScript wrappers of your Go methods with autogenerated JSDoc, providing code hinting +- TypeScript versions of your Go structs, that can be constructed and passed to your go methods +- A second JS module is generated that provides a wrapper + TS declaration for the runtime +- On macOS, it will bundle the application into a `.app` file and run it. It will use a `build/darwin/Info.dev.plist` for development. + +| Flag | Description | Default | +|:---------------------------- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:--------------------- | +| -appargs "args" | Arguments passed to the application in shell style | | +| -assetdir "./path/to/assets" | Serve assets from the given directory instead of using the provided asset FS | Value in `wails.json` | +| -browser | Opens a browser to `http://localhost:34115` on startup | | +| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go | +| -debounce | The time to wait for reload after an asset change is detected | 100 (milliseconds) | +| -devserver "host:port" | The address to bind the wails dev server to | "localhost:34115" | +| -extensions | Extensions to trigger rebuilds (comma separated) | go | +| -forcebuild | Force build of application | | +| -frontenddevserverurl "url" | Use 3rd party dev server url to serve assets, EG Vite | "" | +| -ldflags "flags" | Additional ldflags to pass to the compiler | | +| -loglevel "loglevel" | Loglevel to use - Trace, Debug, Info, Warning, Error | Debug | +| -nocolour | Turn off colour cli output | false | +| -noreload | Disable automatic reload when assets change | | +| -nosyncgomod | Do not sync go.mod with the Wails version | false | +| -race | Build with Go's race detector | false | +| -reloaddirs | Additional directories to trigger reloads (comma separated) | Value in `wails.json` | +| -s | Skip building the frontend | false | +| -save | Saves the given `assetdir`, `reloaddirs`, `wailsjsdir`, `debounce`, `devserver` and `frontenddevserverurl` flags in `wails.json` to become the defaults for subsequent invocations. | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Build tags to pass to compiler (quoted and space separated) | | +| -v | Verbosity level (0 - silent, 1 - standard, 2 - verbose) | 1 | +| -wailsjsdir | The directory to generate the generated Wails JS modules | Value in `wails.json` | + +Example: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +This command will do the following: + +- Build the application and run it (more details [here](../guides/manual-builds.mdx) +- Generate the Wails JS modules in `./frontend/src` +- Watch for updates to files in `./frontend/dist` and reload on any change +- Open a browser and connect to the application + +There is more information on using this feature with existing framework scripts [here](../guides/application-development.mdx#live-reloading). + +## generate + +### template + +Wails uses templates for project generation. The `wails generate template` command helps scaffold a template so that it may be used for generating projects. + +| Flag | Description | +|:---------------- |:------------------------------------------- | +| -name | The template name (Mandatory) | +| -frontend "path" | Path to frontend project to use in template | + +For more details on creating templates, consult the [Templates guide](../guides/templates.mdx). + +### module + +The `wails generate module` command allows you to manually generate the `wailsjs` directory for your application. + +## update + +`wails update` will update the version of the Wails CLI. + +| Flag | Description | +|:------------------ |:------------------------------------- | +| -pre | Update to latest pre-release version | +| -version "version" | Install a specific version of the CLI | + +## version + +`wails version` will simply output the current CLI version. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..ff9a2442281 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# Menus + +It is possible to add an application menu to Wails projects. This is achieved by defining a [Menu](#menu) struct and setting it in the [`Menu`](../reference/options.mdx#menu) application config, or by calling the runtime method [MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu). + +An example of how to create a menu: + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +It is also possible to dynamically update the menu, by updating the menu struct and calling [MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu). + +The example above uses helper methods, however it's possible to build the menu structs manually. + +## Menu + +A Menu is a collection of MenuItems: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +For the Application menu, each MenuItem represents a single menu such as "Edit". + +A simple helper method is provided for building menus: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +This makes the layout of the code more like that of a menu without the need to add the menu items manually after creating them. Alternatively, you can just create the menu items and add them to the menu manually. + +## MenuItem + +A MenuItem represents an item within a Menu. + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +// MenuItem represents a menu item contained in a menu +type MenuItem struct { + Label string + Role Role + Accelerator *keys.Accelerator + Type Type + Disabled bool + Hidden bool + Checked bool + SubMenu *Menu + Click Callback +} +``` + +| Field | Type | Notes | +| ----------- | ------------------------------------ | ------------------------------------------------------------- | +| Label | string | The menu text | +| Accelerator | [\*keys.Accelerator](#accelerator) | Key binding for this menu item | +| Type | [Type](#type) | Type of MenuItem | +| Disabled | bool | Disables the menu item | +| Hidden | bool | Hides this menu item | +| Checked | bool | Adds check to item (Checkbox & Radio types) | +| SubMenu | [\*Menu](#menu) | Sets the submenu | +| Click | [Callback](#callback) | Callback function when menu clicked | +| Role | string | Defines a [role](#role) for this menu item. Mac only for now. | + +### Accelerator + +Accelerators (sometimes called keyboard shortcuts) define a binding between a keystroke and a menu item. Wails defines an Accelerator as a combination or key + [Modifier](#modifier). They are available in the `"github.com/wailsapp/wails/v2/pkg/menu/keys"` package. + +Example: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines cmd+o on Mac and ctrl-o on Window/Linux + myShortcut := keys.CmdOrCtrl("o") +``` + +Keys are any single character on a keyboard with the exception of `+`, which is defined as `plus`. Some keys cannot be represented as characters so there are a set of named characters that may be used: + +| | | | | +|:-----------:|:-----:|:-----:|:---------:| +| `backspace` | `f1` | `f16` | `f31` | +| `tab` | `f2` | `f17` | `f32` | +| `return` | `f3` | `f18` | `f33` | +| `enter` | `f4` | `f19` | `f34` | +| `escape` | `f5` | `f20` | `f35` | +| `left` | `f6` | `f21` | `numlock` | +| `right` | `f7` | `f22` | | +| `up` | `f8` | `f23` | | +| `down` | `f9` | `f24` | | +| `space` | `f10` | `f25` | | +| `delete` | `f11` | `f36` | | +| `home` | `f12` | `f37` | | +| `end` | `f13` | `f38` | | +| `page up` | `f14` | `f39` | | +| `page down` | `f15` | `f30` | | + +Wails also supports parsing accelerators using the same syntax as Electron. This is useful for storing accelerators in config files. + +Example: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines cmd+o on Mac and ctrl-o on Window/Linux + myShortcut, err := keys.Parse("Ctrl+Option+A") +``` + +#### Modifier + +The following modifiers are keys that may be used in combination with the accelerator key: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" +const ( + // CmdOrCtrlKey represents Command on Mac and Control on other platforms + CmdOrCtrlKey Modifier = "cmdorctrl" + // OptionOrAltKey represents Option on Mac and Alt on other platforms + OptionOrAltKey Modifier = "optionoralt" + // ShiftKey represents the shift key on all systems + ShiftKey Modifier = "shift" + // ControlKey represents the control key on all systems + ControlKey Modifier = "ctrl" +) +``` + +A number of helper methods are available to create Accelerators using modifiers: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" +func CmdOrCtrl(key string) *Accelerator +func OptionOrAlt(key string) *Accelerator +func Shift(key string) *Accelerator +func Control(key string) *Accelerator +``` + +Modifiers can be combined using `keys.Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)`: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines "Ctrl+Option+A" on Mac and "Ctrl+Alt+A" on Window/Linux + myShortcut := keys.Combo("a", ControlKey, OptionOrAltKey) +``` + +### Type + +Each menu item must have a type and there are 5 types available: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +const ( + TextType Type = "Text" + SeparatorType Type = "Separator" + SubmenuType Type = "Submenu" + CheckboxType Type = "Checkbox" + RadioType Type = "Radio" +) +``` + +For convenience, helper methods are provided to quickly create a menu item: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func Text(label string, accelerator *keys.Accelerator, click Callback) *MenuItem +func Separator() *MenuItem +func Radio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func Checkbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func SubMenu(label string, menu *Menu) *Menu +``` + +You can also create menu items directly on a menu by using the "Add" helpers: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func (m *Menu) AddText(label string, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddSeparator() *MenuItem +func (m *Menu) AddRadio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddCheckbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddSubMenu(label string, menu *Menu) *MenuI +``` + +A note on radio groups: A radio group is defined as a number of radio menu items that are next to each other in the menu. This means that you do not need to group items together as it is automatic. However, that also means you cannot have 2 radio groups next to each other - there must be a non-radio item between them. + +### Callback + +Each menu item may have a callback that is executed when the item is clicked: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +The function is given a `CallbackData` struct which indicates which menu item triggered the callback. This is useful when using radio groups that may share a callback. + +### Role + +:::info Roles + +Roles are currently supported on Mac only. + +::: + +A menu item may have a role, which is essentially a pre-defined menu item. We currently support the following roles: + +| Role | Description | +| ------------ | ------------------------------------------------------------------------ | +| AppMenuRole | The standard Mac application menu. Can be created using `menu.AppMenu()` | +| EditMenuRole | The standard Mac edit menu. Can be created using `menu.EditMenu()` | diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..46d1c071b60 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,853 @@ +--- +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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### Title + +The text shown in the window's title bar. + +Name: Title
Type: `string` + +### Width + +The initial width of the window. + +Name: Width
Type: `int`
Default: 1024. + +### Height + +The initial height of the window. + +Name: Height
Type: `int`
Default: 768 + +### DisableResize + +By default, the main window is resizable. Setting this to `true` will keep it a fixed size. + +Name: DisableResize
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
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
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
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
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
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
Type: `int` + +### StartHidden + +When set to `true`, the application will be hidden until [WindowShow](../reference/runtime/window.mdx#windowshow) is called. + +Name: StartHidden
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
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
Type: `*options.RGBA`
Default: white + +### AlwaysOnTop + +Indicates that the window should stay above other windows when losing focus. + +Name: AlwaysOnTop
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 | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +Name: AssetServer
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
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
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
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
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
Type: `logger.Logger`
Default: Logs to Stdout + +### LogLevel + +The default log level. More details about logging in the [Log Reference](../reference/runtime/log.mdx). + +Name: LogLevel
Type: `logger.LogLevel`
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
Type: `logger.LogLevel`
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
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
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
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
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
Type: `string` + +### CSSDragValue + +Indicates what value the `CSSDragProperty` style should have to drag the window. Default: `drag`. + +Name: CSSDragValue
Type: `string` + +### EnableDefaultContextMenu + +EnableDefaultContextMenu enables the browser's default context-menu in 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. + +When this option is enabled, by default the context-menu will only be shown for text contexts (where Cut/Copy/Paste is needed), to override this behavior, you can use the CSS property `--default-contextmenu` on any HTML element (including the `body`) with the following values : + +| CSS Style | Behavior | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--default-contextmenu: auto;` | (**default**) will show the default context menu only if :
contentEditable is true OR text has been selected OR element is input or textarea | +| `--default-contextmenu: show;` | will always show the default context menu | +| `--default-contextmenu: hide;` | will always hide the default context menu | + +This rule is inherited like any normal CSS rule, so nesting works as expected. + +:::note +This filtering functionality is only enabled in production, so in development and in debug build, the full context-menu is always available everywhere. +::: + +:::warning +This filtering functionality is NOT a security measure, the developer should expect that the full context-menu could be leaked anytime which could contain commands like (Download image, Reload, Save webpage), if this is a concern, the developer SHOULD NOT enable the default context-menu. +::: + + +Name: EnableDefaultContextMenu
Type: `bool` + +### EnableFraudulentWebsiteDetection + +EnableFraudulentWebsiteDetection enables scan services for fraudulent content, such as malware or phishing attempts. These services might send information from your app like URLs navigated to and possibly other content to cloud services of Apple and Microsoft. + +Name: EnableFraudulentWebsiteDetection
Type: `bool` + +### ZoomFactor + +Name: ZoomFactor
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
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
Type: `[]interface{}` + +### ErrorFormatter + +A function that determines how errors are formatted when returned by a JS-to-Go method call. The returned value will be marshalled as JSON. + +Name: ErrorFormatter
Type: `func (error) any` + +### Windows + +This defines [Windows specific options](#windows). + +Name: Windows
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
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
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
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
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
Type: `bool` + +#### WebviewUserDataPath + +This defines the path where the WebView2 stores the user data. If empty `%APPDATA%\[BinaryName.exe]` will be used. + +Name: WebviewUserDataPath
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
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
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
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
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
Type: `uint16` + +#### OnSuspend + +If set, this function will be called when Windows initiates a switch to low power mode (suspend/hibernate) + +Name: OnSuspend
Type: `func()` + +#### OnResume + +If set, this function will be called when Windows resumes from low power mode (suspend/hibernate) + +Name: OnResume
Type: `func()` + +#### WebviewGpuIsDisabled + +Setting this to `true` will disable GPU hardware acceleration for the webview. + +Name: WebviewGpuIsDisabled
Type: `bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +This defines [Mac specific options](#mac). + +Name: Mac
Type: `*mac.Options` + +#### TitleBar + +The TitleBar struct provides the ability to configure the look and feel of the title bar. + +Name: TitleBar
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
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
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
Type: `bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled u.Bool + FullscreenEnabled u.Bool +} +``` + +| Name | 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) | + +Example: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### 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
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 +
+ +
+
+``` + +When clicked, that will open an about message box: + +```mdx-code-block +
+ +
+
+``` + +### Linux + +This defines [Linux specific options](#linux). + +Name: Linux
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
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, don’t 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
Type: `bool` + +#### WebviewGpuPolicy + +This option is used for determining the webview's hardware acceleration policy. + +Name: WebviewGpuPolicy
Type: [`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
Default: `WebviewGpuPolicyAlways` + +##### WebviewGpuPolicy type + +| Value | Description | +| ------------------------ | -------------------------------------------------------------------- | +| WebviewGpuPolicyAlways | Hardware acceleration is always enabled | +| WebviewGpuPolicyOnDemand | Hardware acceleration is enabled/disabled as request by web contents | +| WebviewGpuPolicyNever | Hardware acceleration is always disabled | + +#### 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). + +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. + +Name: ProgramName
Type: string
+ +### Debug + +This defines [Debug specific options](#Debug) that apply to debug builds. + +Name: Debug
Type: `options.Debug` + +#### OpenInspectorOnStartup + +Setting this to `true` will open the WebInspector on startup of the application. + +Name: OpenInspectorOnStartup
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. +[^2]: This requires WebKit2GTK 2.40+ support and your app needs to be build with the build tag `webkit2_40` to activate support for this feature. This also bumps the minimum requirement of WebKit2GTK to 2.40 for your app. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..8e763502bcc --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,92 @@ +--- +sidebar_position: 5 +--- + +# Project Config + +The project config resides in the `wails.json` file in the project directory. The structure of the config is: + +```json5 +{ + // Project config version + "version": "", + // The project name + "name": "", + // Relative path to the directory containing the compiled assets, this is normally inferred and could be left empty + "assetdir": "", + // Additional directories to trigger reloads (comma separated), this is only used for some advanced asset configurations + "reloaddirs": "", + // The directory where the build files reside. Defaults to 'build' + "build:dir": "", + // Relative path to the frontend directory. Defaults to 'frontend' + "frontend:dir": "", + // The command to install node dependencies, run in the frontend directory - often `npm install` + "frontend:install": "", + // The command to build the assets, run in the frontend directory - often `npm run build` + "frontend:build": "", + // This command has been replaced by frontend:dev:build. If frontend:dev:build is not specified will falls back to this command. \nIf this command is also not specified will falls back to frontend:build + "frontend:dev": "", + // This command is the dev equivalent of frontend:build. If not specified falls back to frontend:dev + "frontend:dev:build": "", + // This command is the dev equivalent of frontend:install. If not specified falls back to frontend:install + "frontend:dev:install": "", + // This command is run in a separate process on `wails dev`. Useful for 3rd party watchers or starting 3d party dev servers + "frontend:dev:watcher": "", + // URL to a 3rd party dev server to be used to serve assets, EG Vite. \nIf this is set to 'auto' then the devServerUrl will be inferred from the Vite output + "frontend:dev:serverUrl": "", + // Relative path to the directory that the auto-generated JS modules will be created + "wailsjsdir": "", + // The name of the binary + "outputfilename": "", + // The default time the dev server waits to reload when it detects a change in assets + "debounceMS": 100, + // Address to bind the wails dev sever to. Default: localhost:34115 + "devServer": "", + // Arguments passed to the application in shell style when in dev mode + "appargs": "", + // Defines if build hooks should be run though they are defined for an OS other than the host OS. + "runNonNativeBuildHooks": false, + "preBuildHooks": { + // The command that will be executed before a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH". + "*/*": "" + }, + "postBuildHooks": { + // The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. + "*/*": "" + }, + // Data used to populate manifests and version info. + "info": { + // The company name. Default: [The project name] + "companyName": "", + // The product name. Default: [The project name] + "productName": "", + // The version of the product. Default: '1.0.0' + "productVersion": "", + // The copyright of the product. Default: 'Copyright.........' + "copyright": "", + // A short comment of the app. Default: 'Built using Wails (https://wails.app)' + "comments": "" + }, + // '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": "" +} +``` + +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). diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..b8eef677b92 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +sidebar_position: 7 +--- + +# 브라우저 + +이 메소드들은 시스템 브라우저와 관련 있습니다. + +### BrowserOpenURL + +시스템 브라우저에서 URL을 엽니다. + +Go: `BrowserOpenURL(ctx context.Context, url string)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..805f68ed917 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# Clipboard + +This part of the runtime provides access to the operating system's clipboard.
The current implementation only handles text. + +### ClipboardGetText + +This method reads the currently stored text from the clipboard. + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
Returns: a string (if the clipboard is empty an empty string will be returned) or an error. + +JS: `ClipboardGetText(): Promise`
Returns: a promise with a string result (if the clipboard is empty an empty string will be returned). + +### ClipboardSetText + +This method writes a text to the clipboard. + +Go: `ClipboardSetText(ctx context.Context, text string) error`
Returns: an error if there is any. + +JS: `ClipboardSetText(text: string): Promise`
Returns: a promise with true result if the text was successfully set on the clipboard, false otherwise. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..9b3e6cf145c --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +sidebar_position: 5 +--- + +# Dialog + +This part of the runtime provides access to native dialogs, such as File Selectors and Message boxes. + +:::info JavaScript + +Dialog is currently unsupported in the JS runtime. + +::: + +### OpenDirectoryDialog + +Opens a dialog that prompts the user to select a directory. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Returns: Selected directory (blank if the user cancelled) or an error + +### OpenFileDialog + +Opens a dialog that prompts the user to select a file. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Returns: Selected file (blank if the user cancelled) or an error + +### OpenMultipleFilesDialog + +Opens a dialog that prompts the user to select multiple files. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)` + +Returns: Selected files (nil if the user cancelled) or an error + +### SaveFileDialog + +Opens a dialog that prompts the user to select a filename for the purposes of saving. Can be customised using [SaveDialogOptions](#savedialogoptions). + +Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)` + +Returns: The selected file (blank if the user cancelled) or an error + +### MessageDialog + +Displays a message using a message dialog. Can be customised using [MessageDialogOptions](#messagedialogoptions). + +Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)` + +Returns: The text of the selected button or an error + +## Options + +### OpenDialogOptions + +```go +type OpenDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + ResolvesAliases bool + TreatPackagesAsDirectories bool +} +``` + +| Field | Description | Win | Mac | Lin | +| -------------------------- | ---------------------------------------------- | --- | --- | --- | +| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ | +| DefaultFilename | The default filename | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ | +| CanCreateDirectories | Allow user to create directories | | ✅ | | +| ResolvesAliases | If true, returns the file not the alias | | ✅ | | +| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | | + +### SaveDialogOptions + +```go +type SaveDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + TreatPackagesAsDirectories bool +} +``` + +| Field | Description | Win | Mac | Lin | +| -------------------------- | ---------------------------------------------- | --- | --- | --- | +| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ | +| DefaultFilename | The default filename | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ | +| CanCreateDirectories | Allow user to create directories | | ✅ | | +| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | | + +### MessageDialogOptions + +```go +type MessageDialogOptions struct { + Type DialogType + Title string + Message string + Buttons []string + DefaultButton string + CancelButton string +} +``` + +| Field | Description | Win | Mac | Lin | +| ------------- | -------------------------------------------------------------------------- | -------------- | --- | --- | +| Type | The type of message dialog, eg question, info... | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| Message | The message to show the user | ✅ | ✅ | ✅ | +| Buttons | A list of button titles | | ✅ | | +| DefaultButton | The button with this text should be treated as default. Bound to `return`. | ✅[*](#windows) | ✅ | | +| CancelButton | The button with this text should be treated as cancel. Bound to `escape` | | ✅ | | + +#### Windows + +Windows has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" or "Continue". + +For Question dialogs, the default button is "Yes" and the cancel button is "No". This can be changed by setting the `DefaultButton` value to `"No"`. + +Example: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linux has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Yes", "No" + +#### Mac + +A message dialog on Mac may specify up to 4 buttons. If no `DefaultButton` or `CancelButton` is given, the first button is considered default and is bound to the `return` key. + +For the following code: + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "It's your turn!", + Message: "Select a number", + Buttons: []string{"one", "two", "three", "four"}, +}) +``` + +the first button is shown as default: + +```mdx-code-block +
+ +
+
+``` + +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 +
+ +
+
+``` + +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 +
+ +
+
+
+
+``` + +#### 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 +
+ +
+
+
+
+``` + +#### 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 +
+ +
+
+
+
+``` + +#### Mac + +Mac dialogs only have the concept of a single set of patterns to filter files. If multiple FileFilters are provided, Wails will use all the Patterns defined. + +Example: + +```go + selection, err := runtime.OpenFileDialog(b.ctx, runtime.OpenDialogOptions{ + Title: "Select File", + Filters: []runtime.FileFilter{ + { + DisplayName: "Images (*.png;*.jpg)", + Pattern: "*.png;*.jpg", + }, { + DisplayName: "Videos (*.mov;*.mp4)", + Pattern: "*.mov;*.mp4", + }, + }, + }) +``` + +This will result in the Open File dialog using `*.png,*.jpg,*.mov,*.mp4` as a filter. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..856ba6f0c26 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +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()`
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)`
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()`
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()`
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{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..3cacb6ba9a7 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# 소개 + +런타임은 애플리케이션에 유틸리티 메서드를 제공하는 라이브러리입니다. There is both a Go and JavaScript runtime and the aim is to try and keep them at parity where possible. + +다음에 대한 유틸리티 메서드가 있습니다: + +- [Window](window.mdx) +- [Menu](menu.mdx) +- [Dialog](dialog.mdx) +- [Events](events.mdx) +- [Browser](browser.mdx) +- [Log](log.mdx) +- [Clipboard](clipboard.mdx) + +Go 런타임은 `github.com/wailsapp/wails/v2/pkg/runtime` 가져오기를 통해 사용할 수 있습니다. 이 패키지의 모든 메소드는 컨텍스트를 첫 번째 매개변수로 사용합니다. 이 컨텍스트는 [OnStartup](../options.mdx#onstartup) 또는 [OnDomReady](../options.mdx#ondomready) 후크에서 가져와야 합니다. + +:::참고 + +컨텍스트는 [OnStartup](../options.mdx#onstartup) 메서드를 사용할 경우 런타임이 이 메서드에서 다음과 같이 작동할 것이라는 보장은 없습니다. 창이 다른 스레드에서 초기화되고 있습니다. 시작 시 런타임 메서드를 호출하려면 [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. 이것은 프론트엔드 디렉토리의 `wailsjs` 디렉토리에 있어야 합니다. + +### Hide + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +애플리케이션을 숨깁니다. + +:::참고 + +On Mac, this will hide the application in the same way as the `Hide` menu item in standard Mac applications. This is different to hiding the window, but the application still being in the foreground. For Windows and Linux, this is currently the same as `WindowHide`. + +::: + +### Show + +Shows the application. + +:::참고 + +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)`
JS: `Show()` + +### Quit + +Quits the application. + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### Environment + +Returns details of the current environment. + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### EnvironmentInfo + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..2112e1c9e4f --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# Log + +The Wails runtime provides a logging mechanism that may be called from Go or JavaScript. 대부분처럼 loggers 에는 다양한 로그 수준이 있습니다: + +- Trace +- Debug +- Info +- Warning +- Error +- Fatal + +Logger는 현재 이상의 로그 수준에서 모든 로그 메시지를 출력합니다. Example: `Debug` 로그 level은 `Trace` 메시지를 제외한 모든 메시지를 출력합니다. + +### LogPrint + +주어진 메시지를 원본 메시지로 기록합니다. + +Go: `LogPrint(ctx context.Context, message string)`
JS: `LogPrint(message: string)` + +### LogPrintf + +주어진 메시지를 원본 메시지로 기록합니다. + +Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`
+ +### LogTrace + +`Trace` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogTrace(ctx context.Context, message string)`
JS: `LogTrace(message: string)` + +### LogTracef + +`Trace` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogTracef(ctx context.Context, format string, args ...interface{})`
+ +### LogDebug + +`Debug` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogDebug(ctx context.Context, message string)`
JS: `LogDebug(message: string)` + +### LogDebugf + +`Debug` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`
+ +### LogInfo + +`Info` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogInfo(ctx context.Context, message string)`
JS: `LogInfo(message: string)` + +### LogInfof + +`Info` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogInfof(ctx context.Context, format string, args ...interface{})`
+ +### LogWarning + +`Warning` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogWarning(ctx context.Context, message string)`
JS: `LogWarning(message: string)` + +### LogWarningf + +`Warning` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`
+ +### LogError + +`Error` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogError(ctx context.Context, message string)`
JS: `LogError(message: string)` + +### LogErrorf + +`Error` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`
+ +### LogFatal + +`Fatal` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogFatal(ctx context.Context, message string)`
JS: `LogFatal(message: string)` + +### LogFatalf + +`Fatal` 로그 수준에서 지정된 메시지를 기록합니다. + +Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`
+ +### LogSetLogLevel + +로그 레벨을 설정합니다. In JavaScript, the number relates to the following log levels: + +| 값 | 로그 레벨 | +| - | ------- | +| 1 | Trace | +| 2 | Debug | +| 3 | Info | +| 4 | Warning | +| 5 | Error | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
JS: `LogSetLogLevel(level: number)` + +## 커스텀 Logger 사용하기 + +사용자 커스텀 logger는 [Logger](../options.mdx#logger)를 사용하여 제공하여 사용할 수 있습니다. 응용 프로그램 옵션. 유일한 요구 사항은 logger가 `logger.Logger` 인터페이스를 구현한다는 것입니다. 이는 `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) +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..0eab71c0162 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +sidebar_position: 6 +--- + +# 메뉴 + +애플리케이션 메뉴는 이 메소드들과 관련 있습니다. + +:::info JavaScript + +현재 메뉴는 JS runtime을 지원하지 않습니다. + +::: + +### MenuSetApplicationMenu + +애플리케이션 메뉴는 [menu](../menus.mdx)를 통해 설정하세요. + +Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)` + +### MenuUpdateApplicationMenu + +애플리케이션 메뉴를 업데이트하여 `MenuSetApplicationMenu`에 전달된 메뉴에 대한 모든 변경 사항을 선택합니다. + +Go: `MenuUpdateApplicationMenu(ctx context.Context)` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..457c92ebff9 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# Screen + +These methods provide information about the currently connected screens. + +### ScreenGetAll + +Returns a list of currently connected screens. + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### Screen + +Go struct: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript interface: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..8e1052289b9 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +sidebar_position: 4 +--- + +# Window + +이러한 메서드는 응용 프로그램 창을 제어합니다. + +### WindowSetTitle + +창 제목 표시줄의 텍스트를 설정합니다. + +Go: `WindowSetTitle(ctx context.Context, title string)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen + +창을 전체화면으로 만듭니다. + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen + +전체 화면 이전의 이전 창 크기와 위치를 복원합니다. + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen + +창이 전체 화면이면 true를 반환합니다. + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter + +창이 현재 켜져 있는 모니터의 중앙에 창을 맞춥니다. + +Go: `WindowCenter(ctx context.Context)`
JS: `WindowCenter()` + +### WindowExecJS + +창에서 임의의 JS 코드를 실행합니다. + +이 메서드는 브라우저에서 코드를 비동기적으로 실행하고 즉시 반환합니다. 만약 스크립트에서 오류가 발생하면 브라우저 콘솔에서만 사용할 수 있습니다. + +Go: `WindowExecJS(ctx context.Context, js string)` + +### WindowReload + +"새로고침"을 수행합니다(현재 페이지 새로고침). + +Go: `WindowReload(ctx context.Context)`
JS: `WindowReload()` + +### WindowReloadApp + +프론트엔드 애플리케이션을 새로고침합니다. + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme + +윈도우 전용. + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
JS: `WindowSetSystemDefaultTheme()` + +창의 테마를 시스템 기본값으로 설정합니다(다크/라이트). + +### WindowSetLightTheme + +윈도우 전용. + +Go: `WindowSetLightTheme(ctx context.Context)`
JS: `WindowSetLightTheme()` + +창 테마를 라이트 모드로 설정합니다. + +### WindowSetDarkTheme + +윈도우 전용. + +Go: `WindowSetDarkTheme(ctx context.Context)`
JS: `WindowSetDarkTheme()` + +윈도우 테마를 다크로 설정합니다. + +### WindowShow + +만약 현재 창의 상태가 숨기기로 되어 있다면, 창을 보여줍니다. + +Go: `WindowShow(ctx context.Context)`
JS: `WindowShow()` + +### WindowHide + +현재 창이 표시되어 있는 경우 창을 숨깁니다. + +Go: `WindowHide(ctx context.Context)`
JS: `WindowHide()` + +### WindowIsNormal + +창이 최소화, 최대화 또는 전체 화면이 아닌 경우 true를 반환합니다. + +Go: `WindowIsNormal(ctx context.Context) bool`
JS: `WindowIsNormal() bool` + +### WindowSetSize + +창의 너비와 높이를 설정합니다. + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize + +창의 너비와 높이를 가져옵니다. + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
JS: `WindowGetSize() : Size` + +### WindowSetMinSize + +최소 창 크기를 설정합니다. 창이 현재 지정된 크기보다 작은 경우 창 크기를 조정합니다. + +`0,0`의 크기를 설정하면 이 제약 조건이 비활성화됩니다. + +Go: `WindowSetMinSize(ctx context.Context, width int, height int)`
JS: `WindowSetMinSize(width: number, height: number)` + +### WindowSetMaxSize + +최대 창 크기를 설정합니다. 창이 현재 지정된 크기보다 큰 경우 창 크기를 조정합니다. + +`0,0`의 크기를 설정하면 이 제약 조건이 비활성화됩니다. + +Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### WindowSetAlwaysOnTop + +창을 항상위 또는 맨 위에 놓지 않도록 설정합니다. + +Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
JS: `WindowSetAlwaysOnTop(b: Boolen)` + +### WindowSetPosition + +창이 현재 켜져 있는 모니터를 기준으로 창 위치를 설정합니다. + +Go: `WindowSetPosition(ctx context.Context, x int, y int)`
JS: `WindowSetPosition(x: number, y: number)` + +### WindowGetPosition + +창이 현재 있는 모니터에 상대적인 창 위치를 가져옵니다. + +Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
JS: `WindowGetPosition() : Position` + +### WindowMaximise + +창을 최대화하여 화면을 채웁니다. + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise + +창을 최대화하기 전의 크기와 위치로 복원합니다. + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised + +창이 최대화되면 true를 반환합니다. + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise + +최대화와 최대화 해제 사이를 전환합니다. + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise + +창을 최소화합니다. + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise + +최소화하기 전의 크기와 위치로 창을 복원합니다. + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised + +창이 최소화된 경우 true를 반환합니다. + +Go: `WindowIsMinimised(ctx context.Context) bool`
JS: `WindowIsMinimised() bool` + +### WindowSetBackgroundColour + +창의 배경색을 지정된 RGBA 색상 정의로 설정합니다. 이 색상은 모든 투명 픽셀에 대해 표시됩니다. + +R, G, B 및 A의 유효한 값은 0-255입니다. + +:::info Windows + +Windows에서는 0 또는 255의 알파 값만 지원됩니다. 0이 아닌 모든 값은 255로 간주됩니다. + +::: + +Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +Opens tha native print dialog. + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## TypeScript Object Definitions + +### 위치 + +```ts +interface Position { + x: number; + y: number; +} +``` + +### 크기 + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..98129e5b753 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# Dogs API + +```mdx-code-block +
+ +
+
+``` + +:::note + +이 튜토리얼은 [@tatadan](https://twitter.com/tatadan)에 의해 제공되었습니다. 그리고 [ Wails 예시 리포지토리](https://github.com/tataDan/wails-v2-examples)에서 예시를 확인할 수 있습니다. + +::: + +이 튜토리얼에서는 웹에서 개 사진을 검색한 다음 표시하는 애플리케이션을 개발할 것입니다. + +### 프로젝트 생성 + +애플리케이션을 생성합니다. 터미널에 다음과 같이 입력합니다: `wails init -n dogs-api -t svelte` + +참고: 원하는 경우 선택적으로 이 명령의 끝에 `-ide vscode` 또는 `-ide goland`를 추가할 수 있습니다. IDE 지원을 추가합니다. + +이제 `cd dogs-api`를 만들고 프로젝트 파일 편집을 시작합니다. + +### 사용하지 않는 코드 제거 + +사용하지 않는 몇가지 요소를 제거합니다. + +- `app.go`를 열고 다음 줄을 제거합니다. + +```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) +} +``` + +- `frontend/src/App.svelte`를 열고 모든 줄을 삭제합니다. +- `frontend/src/assets/images/logo-universal.png` 파일을 삭제합니다. + +### 우리만의 애플리케이션 생성하기 + +이제 새로운 Go 코드를 추가합니다. + +함수 정의 앞에 다음 구조체 선언을 `app.go`에 추가합니다. + +```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 +} +``` + +`app.go`에 다음 함수를 추가합니다(함수 정의 뒤쪽에 존재): + +```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 +} +``` + +`app.go`의 `import` 섹션을 다음과 같이 수정합니다. + +```go +import ( + "context" + "fmt" + "encoding/json" + "io/ioutil" + "log" + "net/http" + "sort" +) +``` + +`frontend/src/App.svelte`에 다음 줄을 추가합니다. + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### 애플리케이션 테스트하기 + +바인딩을 생성하고 애플리케이션을 테스트하려면 `wails dev`를 실행합니다. + +### 애플리케이션 컴파일하기 + +응용 프로그램을 단일 바이너리로 컴파일하려면 `wails build`를 실행합니다. diff --git a/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..4bc3bcaafc2 --- /dev/null +++ b/website/i18n/ko/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +sidebar_position: 10 +--- + +# Hello World + +이 튜토리얼의 목표는 Wails를 사용하여 가장 기본적인 애플리케이션을 시작하고 실행하는 것입니다. 튜토리얼을 통해 다음과 같은 것들을 할 수있습니다. + +- 새로운 Wails 애플리케이션 생성 +- 애플리케이션 빌드 +- 애플리케이션 실행 + +:::note + +이 튜토리얼에서는 Windows를 대상 플랫폼으로 사용합니다. 출력이 약간 다를 수 있습니다. 운영체제에 따라 다릅니다. + +::: + +## 새로운 Wails 애플리케이션 생성 + +기본 바닐라 JS 템플릿을 사용하여 새 Wails 애플리케이션을 만들려면, 다음 명령을 실행해야 합니다: + +```bash +wails init -n helloworld +``` + +실행 결과로 다음과 유사한 결과가 반환됩니다. + +``` +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. +``` + +이렇게 하면 현재 디렉터리에 `helloworld`라는 새 디렉터리가 생성됩니다. 이 디렉토리에는 여러 파일이 있습니다: + +``` +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 +``` + +## 애플리케이션 빌드 + +애플리케이션을 빌드하려면 새 `helloworld` 프로젝트 디렉토리로 변경하고 다음 명령을 실행하십시오. + +```bash +wails build +``` + +다음과 같은 내용이 표시되어야 합니다: + +``` +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 +Devtools: false +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. +``` + +이것은 애플리케이션을 컴파일하고 `build/bin` 디렉토리에 결과 실행파일을 저장합니다. + +## 애플리케이션 실행 + +Windows 탐색기에서 `build/bin` 디렉토리를 보면 프로젝트 바이너리가 표시되어야 합니다. + +```mdx-code-block +
+ +
+
+``` + +`helloworld.exe` 파일을 두 번 클릭하면 실행됩니다. + +Mac에서 Wails는 두 번 클릭하여 실행할 수 있는 `helloworld.app` 파일을 생성합니다. + +Linux에서는 `build/bin` 디렉토리에서 `./helloworld`를 사용하여 애플리케이션을 실행할 수 있습니다. + +애플리케이션이 예상대로 동작하는지 확인해야 합니다. + +```mdx-code-block +
+ +
+
+``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..006ff61ed06 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +sidebar_position: 2 +--- + +# Links + +Esta página serve como uma lista para links da comunidade relacionados. Envie um PR (clique `Editar esta página` na parte inferior) para enviar links. + +## Awesome Wails + +A [lista definitiva](https://github.com/wailsapp/awesome-wails) dos links relacionados à Wails. + +## Canais de Suporte + +- [Servidor do Discord Wails](https://discord.gg/JDdSxwjhGf) +- [Github Issues](https://github.com/wailsapp/wails/issues) +- [v2 Beta Discussion Board](https://github.com/wailsapp/wails/discussions/828) + +## Redes Sociais + +- [Twitter](https://twitter.com/wailsapp) +- [Wails Chinese Community QQ Group](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - Group number: 1067173054 + +## Outros tutoriais e Artigos + +- [Building of Bulletin Board](https://blog.customct.com/building-bulletin-board) diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..6373a7ff16e --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +O aplicativo [BulletinBoard](https://github.com/raguay/BulletinBoard) é um quadro de mensagens versitais para mensagens estáticas ou diálogos para obter informações do usuário para um script. Ele tem uma TUI para criar novas caixas de diálogo que podem ser usadas por último para obter informações do usuário. É um design que fica em execução no seu sistema e mostra as informações conforme necessário e depois se esconde. Tenho um processo para assistir um arquivo no meu sistema e enviar o conteúdo para o BulletinBoard quando alterado. Funciona bem com meus fluxos de trabalho. Há também um [fluxo de trabalho Alfred](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow) para enviar informações ao programa. O fluxo de trabalho também é para trabalhar com [EmailIt](https://github.com/raguay/EmailIt). diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..642dd1ba1d5 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,41 @@ +# CFN Tracker + +```mdx-code-block +

+ +
+

+``` + +[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) - Acompanhe +qualquer partida ao vivo do perfil Street Fighter 6 ou V CFN. Verifique +[o site](https://cfn.williamsjokvist.se/) para começar. + +## Características + +- Acompanhamento de partidas em tempo real +- Armazenamento de registros e estatísticas de partidas +- Suporte para exibição de estatísticas ao vivo no OBS via fonte do navegador +- Suporte para SF6 e SFV +- Capacidade para os usuários criarem seus próprios temas do navegador OBS com + CSS + +### Principais tecnologias usadas junto com Wails + +- [Tarefa](https://github.com/go-task/task) - agrupando a CLI do Wails para + facilitar o uso de comandos comuns +- [React](https://github.com/facebook/react) - escolhido por seu rico + ecossistema (radix, framer-motion) +- [Bun](https://github.com/oven-sh/bun) - usado por sua rápida resolução de + dependências e tempo de construção +- [Rod](https://github.com/go-rod/rod) - automação de navegador headless para + autenticação e alterações de pesquisa +- [SQLite](https://github.com/mattn/go-sqlite3) - usado para armazenar + correspondências, sessões e perfis +- [Eventos enviados pelo servidor](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - + um fluxo http para enviar atualizações de rastreamento para fontes do + navegador OBS +- [i18next](https://github.com/i18next/) - com conector de back-end para servir + objetos de localização da camada Go +- [xstate](https://github.com/statelyai/xstate) - máquinas de estado para + processo de autenticação e rastreamento diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..862c304e973 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[EmailIt](https://github.com/raguay/EmailIt/) é um programa Wails 2 que é um remetente de e-mail baseado em markdown com apenas nove notepads, scripts para manipular o texto e templates. Ele também tem um terminal para rodar scripts em EmailIt em arquivos do seu sistema. Os scripts e modelos podem ser usados na própria linha de comando ou com as extensões Alfred, Keyboard Maestro, Dropzone ou PopClip. Ele também suporta scripts e temas baixados no formulário GitHub. A documentação não está completa, mas os programas funcionam. É construído usando Wails2 e Svelte, e o download é um aplicativo macOS universal. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..a5692d35388 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[EncryptEasy](https://www.encrypteasy.app) é uma ferramenta simples e fácil de usar de criptografia PGP, gerenciando todas as suas chaves de contato e suas chaves. A criptografia deve ser simples. Desenvolvido com Wails.** + +Criptografar mensagens usando PGP é o padrão da indústria. Todos têm uma chave privada e pública. A sua chave privada precisa ser privada para que apenas você possa ler as mensagens. Sua chave pública é distribuída para qualquer pessoa que queira lhe enviar o segredo, mensagens criptografadas. Gerenciar chaves, criptografar mensagens e descriptografar mensagens devem ser uma experiência suave. EncryptEasy é sobre facilitar o processo. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..78c79769f7e --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[ESP Studio](https://github.com/torabian/esp-studio) - Software multiplataforma, desktop, nuvem e incorporado +para controlar dispositivos ESP/Arduino e construir fluxos de trabalho e sistemas de controle IOT complexos \ No newline at end of file diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..0b5d7fc36ba --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# Utilitário de Exportação FileHound + +```mdx-code-block +

+ +
+

+``` + +[Utilitário de exportação de FileHound](https://www.filehound.co.uk/) FileHound é uma plataforma de gerenciamento de documentos em nuvem feita para retenção segura de arquivos, automação de processos de negócio e recursos de SmartCaptura. + +O Utilitário de Exportação FileHound permite os admnistradores FileHound a capacidade de executar um documento seguro e extração de tarefas para um backup alternativo. Esta aplicação irá baixar todos os documentos e/ou meta dados salvos no FileHound com base nos filtros que você escolher. Os metadados serão exportados em ambos os formatos JSON e XML. + +Backend construído com: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2 + +Frontend com: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6 diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..13ed9dc7c53 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter) é uma ferramenta simples e eficiente de teste de cliente http API. Baseado em Wails, Go and sveltejs. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..d606f87f961 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Atualizador do Minecraft + +```mdx-code-block +

+ +
+

+``` + +[O atualziador do Minecraft](https://github.com/Gurkengewuerz/MinecraftModUpdater) é uma ferramenta utilitária para atualizar e sincronizar mods do Minecraft para sua base de usuários. Ele é construído usando Wails2 e React com [antd](https://ant.design/) como framework frontend. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..9633a7d4a84 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Gerenciador de arquivos Modal + +```mdx-code-block +

+ +
+

+``` + +[Gerenciador de Arquivos Modal](https://github.com/raguay/ModalFileManager) é um gerenciador de arquivos dual pane usando tecnologias da web. Meu design original foi baseado em NW.js e pode ser encontrado [aqui](https://github.com/raguay/ModalFileManager-NWjs). Esta versão usa o mesmo código de frontend baseado em Svelte (mas foi muito modificado desde a partida do NW.), mas o backend implementado com [Wails 2](https://wails.io/). Ao usar esta implementação, não uso mais comandos de linha de comando `rm`, `cp`, etc., mas um git install deve estar no sistema para baixar temas e extensões. Está totalmente codificado usando Go e roda muito mais rápido do que as versões anteriores. + +Este gerenciador de arquivos é projetado em torno do mesmo princípio do Vim: uma ação controlada pelo teclado. O número de estados não é fixo, mas muito programável. Portanto, um número infinito de configurações de teclado pode ser criado e usado. Esta é a principal diferença em relação a outros gerenciadores de arquivos. Existem temas e extensões disponíveis para download do GitHub. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..a0570d03546 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[Molley Wallet](https://github.com/grvlle/constellation_wallet/) a carteira oficial $DAG da rede Constellation. Ele permitirá que os usuários interajam com a Rede Hypergraph de várias maneiras, não limitado à produção de $DAG transações. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..0069bae7230 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[Constellation ](https://october.utf9k.net) é uma pequena aplicação de Wails que facilita muito a extração de destaques de [Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader) e então os encaminha para [Readwise](https://readwise.io). + +Tem um escopo relativamente pequeno com todas as versões de plataforma pesando abaixo de 10MB, e isso é sem habilitar [a compressão UPX](https://upx.github.io/)! + +Em contraste, as tentativas anteriores do autor com o Electron rapidamente incharam várias centenas de megabytes. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..606d5c4a87f --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# Optimus + +```mdx-code-block +

+ +
+

+``` + +[Optimus](https://github.com/splode/optimus) é uma aplicação de otimização de imagem para área de trabalho. Ele suporta conversão e compressão entre formatos de imagem WebP, JPEG e PNG. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..4db08021efe --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# Portfall + +```mdx-code-block +

+ +
+

+``` + +[Portfall](https://github.com/rekon-oss/portfall) - Um portal de encaminhamento de porta para desktop para fácil acesso a todas as suas interfaces diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..fbe86fd6db5 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[Restic-Browser](https://github.com/emuell/restic-browser) - Uma GUI de backup simples e multiplataforma [restica](https://github.com/restic/restic) para navegação e restauração de repositórios resóticos. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..961debade5f --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +Compartilhamento de arquivos fácil, seguro e gratuito para todos. Saiba mais em [Riftshare.app](https://riftshare.app) + +## Funcionalidades + +- Compartilhamento fácil e seguro de arquivos entre computadores tanto na rede local quanto através da internet +- Suporta o envio de arquivos ou diretórios de forma segura através do [magic wormhole protocol](https://magic-wormhole.readthedocs.io/en/latest/) +- Compatível com todos os outros aplicativos que usam magic wormhole (magic-wormhole ou wormhole-william CLI, wormhole-gui, etc.) +- Compactação automática de vários arquivos selecionados para enviar de uma vez +- Animações completas, barra de progresso e cancelamento do suporte para envio e recebimento +- Seleção de arquivo Native OS +- Abrir arquivos em um clique uma vez recebido +- Atualização Automática - não se preocupe em ter a versão mais recente! diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..335e360e37a --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp) é um programa que mostra a saída dos scripts ou o servidor [Node-Red](https://nodered.org). Ele executa scripts definidos no programa EmailIt e mostra a saída. Scripts de xBar ou TextBar podem ser usados, mas atualmente em scripts da TextBar funcionam bem. Também exibe a saída de scripts no seu sistema. ScriptBar não os coloca na barra de menus, mas os tenha todos em uma janela convidada para fácil visualização. Você pode ter várias abas para ter muitas coisas diferentes mostradas. Você também pode manter os links para os sites mais visitados. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..78db0e7b460 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[Surge](https://getsurge.io/) é um aplicativo de compartilhamento de arquivos p2p projetado para utilizar tecnologias blockchain para habilitar transferências de arquivos 100% anônimas. O Surgeé criptografado, descentralizado e de código aberto. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..8b2f2c6c4fb --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[Wally](https://ergodox-ez.com/pages/wally) é o flasher oficial para os teclados [Ergodox](https://ergodox-ez.com/). Parece excelente e é um exemplo fantástico do que você pode conseguir com o Wails: a capacidade de combinar o poder do Go e as ricas ferramentas gráficas do mundo de desenvolvimento web. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..c56880f0e19 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# Launcher Minecraft para WarMine + +```mdx-code-block +

+ + +
+

+``` + +[Minecraft Launcher para WarMine](https://warmine.ru/) é uma aplicação Wails que permite que você entre nos servidores de jogos modificados facilmente e gerencie suas contas de jogo. + +O Launcher baixa os arquivos do jogo, verifica sua integridade e lança o jogo com uma grande variedade de opções de personalização para os argumentos de lançamento pelo backend. + +Frontend está escrito em Svelte, todo o launcher se enquadra em 9MB e suporta Windows 7-11. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..d2e5eaf3ee6 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# Wombat + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat) é um cliente gRPC multiplataforma. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..01a56449817 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails) é um aplicativo para baixar faixas do youtube, criar listas de reprodução offline e compartilhar com seus amigos, seus amigos poderão reproduzir suas playlists ou baixá-las para escuta offline, tem um player embutido. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..5fab64fd42a --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +--- + +# Templates + +Esta página serve como uma lista para modelos suportados pela comunidade. Por favor, envie um PR (clique `Editar esta página` na parte inferior) para incluir seus modelos. Para construir seu próprio modelo, consulte o guia de [Modelos](../guides/templates.mdx). + +Para usar estes templates, execute `wails init -n "Seu Nome do Projeto" -t [o link abaixo[@version]]` + +Se não houver nenhum sufixo de versão, o modelo de código principal da branch é usado por padrão. Se houver um sufixo de versão, o template de código correspondente à tag desta versão é usado. + +Exemplo: `wails init -n "Seu Nome do Projeto" -t https://github.com/misitebao/wails-template-vue` + +:::warning Atenção + +**O projeto Wails não é mantido, não é responsável nem responsável por modelos de terceiros!** + +Se você não tiver certeza sobre um template, inspecione `package.json` e `wails.json` para quais scripts são executados e quais pacotes estão instalados. + +::: + +## Vue + +- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - Wails template based on Vue ecology (Integrated TypeScript, Dark theme, Internationalization, Single page routing, TailwindCSS) +- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Vue 3 TypeScript with Vite (and instructions to add features) +- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vue 3 TypeScript with Vite, Vuex, Vue Router, Sass, and ESLint + Prettier +- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - Um template usando JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier) +- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - Um modelo usando TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, API de composição com <configuração de script>) +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Modelo de ervas baseado em Naive UI (biblioteca de componentes Vue 3) + +## Angular + +- [A-modelo de wails-angular](https://github.com/mateothegreat/wails-template-angular) - ação Angular 15 + compactada & pronta para ser rolada para produção. +- [wails-angular-template](https://github.com/TAINCER/wails-angular-template) - Angular with TypeScript, Sass, Hot-Reload, Code-Splitting and i18n + +## React + +- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - A template using reactjs +- [wails-react-template](https://github.com/flin7/wails-react-template) - A minimal template for React that supports live development +- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - A template using Next.js and TypeScript +- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - A template for React + TypeScript + Vite + TailwindCSS +- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - Um modelo com Vite, React, TypeScript, TailwindCSS, e shadcn/ui + +## Svelte + +- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - A template using Svelte +- [wails-vite-svelte-template](https://github.com/BillBuilt/wails-vite-svelte-template) - A template using Svelte and Vite +- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - A template using Svelte and Vite with TailwindCSS v3 +- [wails-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - Um modelo atualizado usando Svelte v4.2.0 e Vite com TailwindCSS v3.3.3 +- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - A template using SvelteKit + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - Um modelo usando Sólido + Ts + Vite +- [wails-template-vite-solid-js](https://github.com/xijaja/wails-template-solid-js) - Um modelo usando Sólid + Js + Vite + +## Elm + +- [wails-elm-template](https://github.com/benjamin-thomas/wails-elm-template) - Develop your GUI app with functional programming and a **snappy** hot-reload setup :tada: :rocket: +- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - Combine the powers :muscle: of Elm + Tailwind CSS + Wails! Hot reloading supported. + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - Use a unique combination of pure htmx for interactivity plus templ for creating components and forms + +## Pure JavaScript (Vanilla) + +- [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - A template with nothing but just basic JavaScript, HTML, and CSS diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..d06faa9eab2 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +sidebar_position: 6 +--- + +# Compilando seu projeto + +No diretório do projeto, execute `wails builds`. Isso compilará seu projeto e salvará o binário pronto para produção no diretório `build/bin`. + +Se você executar o binário, você verá a aplicação padrão: + +```mdx-code-block +
+ +
+
+``` + +Para mais detalhes sobre as opções de compilação, consulte a [Referência do CLI](../reference/cli.mdx#build). diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..be641d3b98d --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 5 +--- + +# Desenvolvendo sua aplicação + +Você pode executar sua aplicação no modo de desenvolvimento executando `wails dev` no diretório do seu projeto. Isso fará o seguinte: + +- Construa seu aplicativo e o execute +- Vincule seu código Go para o frontend para que ele possa ser chamado a partir de JavaScript +- Usando o poder do [Vite](https://vitejs.dev/), observará modificações em seus arquivos Go e reconstruir/re-executar na alteração +- Configure um [servidor web](http://localhost:34115) que irá servir seu aplicativo em um navegador. Isso permite usar suas extensões de navegador favoritas. Você pode até mesmo chamar seu código Go do console + +Para começar, execute `wails dev` no diretório do projeto. Mais informações sobre isso podem ser encontradas [aqui](../reference/cli.mdx#dev). + +Em breve: Tutorial diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..f98b71ee493 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 2 +--- + +# Criando um projeto + +## Geração de Projeto + +Agora que o CLI está instalado, você pode gerar um novo projeto usando o comando `wails init`. + +Escolha seu framework favorito: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Generate a Svelte project using JavaScript with:

+ + wails init -n myproject -t svelte + +If you would rather use TypeScript:
+ + wails init -n myproject -t svelte-ts + +
+ + Generate a React project using JavaScript with:

+ + wails init -n myproject -t react + +If you would rather use TypeScript:
+ + wails init -n myproject -t react-ts + +
+ + Generate a Vue project using JavaScript with:

+ + wails init -n myproject -t vue + +If you would rather use TypeScript:
+ + wails init -n myproject -t vue-ts + +
+ + Generate a Preact project using JavaScript with:

+ + wails init -n myproject -t preact + +If you would rather use TypeScript:
+ + wails init -n myproject -t preact-ts + +
+ + Generate a Lit project using JavaScript with:

+ + wails init -n myproject -t lit + +If you would rather use TypeScript:
+ + wails init -n myproject -t lit-ts + +
+ + Generate a Vanilla project using JavaScript with:

+ + wails init -n myproject -t vanilla + +If you would rather use TypeScript:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +Há também [templates da comunidade](../community/templates.mdx) disponíveis que oferecem diferentes recursos e frameworks. + +Para ver as outras opções disponíveis, você pode executar `wails init -help`. Mais detalhes podem ser encontrados na [Referência da CLI](../reference/cli.mdx#init). + +## Layout do Projeto + +Os projetos Wails possuem o seguinte layout: + +``` +. +├── build/ +│ ├── appicon.png +│ ├── darwin/ +│ └── windows/ +├── frontend/ +├── go.mod +├── go.sum +├── main.go +└── wails.json +``` + +### Estrutura do projeto em execução + +- `/main.go` - A aplicação principal +- `/frontend/` - Arquivos do Frontend do projeto +- `/build/` - Diretório de compilação do projeto +- `/build/appicon.png` - O ícone da aplicação +- `/build/darwin/` - Arquivos do projeto específicos do Mac +- `/build/windows/` - Arquivos de projeto específicos do Windows +- `/wails.json` - A configuração do projeto +- `/go.mod` - O arquivo de módulos do Go +- `/go.sum` - O arquivo de checagem dos módulos do Go + +O diretório `frontend` não tem nada específico para o Wails e pode ser qualquer projeto frontend de sua escolha. + +O diretório `build` é usado durante o processo de compilação. Esses arquivos podem ser atualizados para personalizar suas compilações. Se arquivos forem removidos do diretório de compilação, as versões padrão serão restauradas. + +O nome do módulo padrão em `go.mod` é "changeme". Você deveria mudar isso para algo mais apropriado. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..33400cdfdbf --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +--- + +# Instalação + +## Plataformas Suportadas + +- Windows 10/11 AMD64/ARM64 +- MacOS 10.13+ AMD64 +- MacOS 11.0+ ARM64 +- Linux AMD64/ARM64 + +## Dependências + +O Wails tem várias dependências comuns que são necessárias antes da instalação: + +- Go 1.18+ +- NPM (Node 15+) + +### Go + +Baixe o Go direto da [página de download do Go](https://go.dev/dl/). + +Certifique-se de seguir as [instruções oficiais de instalação do Go](https://go.dev/doc/install). Você também precisará garantir que sua `variável de ambiente PATH` também inclua o caminho para o seu diretório `~/go/bin`. Reinicie seu terminal e faça as seguintes verificações: + +- Verificar se o Go está instalado corretamente: `go version` +- Cheque se `~/go/bin` está nas suas variáveis de ambiente `echo $PATH | grep go/bin` + +### NPM + +Baixe o NPM da [Página de downloads do Node](https://nodejs.org/en/download/). É melhor usar o último lançamento, pois é isso que costumamos testar. + +Execute `npm --version` para verificar. + +## Dependências específicas da plataforma + +Você também precisará instalar as dependências específicas da plataforma: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Wails requires that the xcode command line tools are installed. This can be + done by running xcode-select --install. + + + Wails requires that the WebView2 runtime is installed. Algumas instalações do Windows já terão isto instalado. Você pode conferir usando o comando do wails doctor. + + + Linux requires the standard gcc build tools plus libgtk3 and libwebkit. Ao invés de listar uma tonelada de comandos para diferentes distros, os Wails podem tentar determinar quais são os comandos de instalação para sua distribuição específica. Execute o wails doctor após a instalação para ser mostrado como instalar as dependencias. Se o seu gerenciador de destro/pacote não for suportado, por favor, consulte o guia Adicionar Distro do Linux. + + +``` + +## Dependências opcionais + +- [UPX](https://upx.github.io/) para comprimir suas aplicações. +- [NSIS](https://wails.io/docs/guides/windows-installer/) for generating Windows installers. + +## Instalando Wails + +Execute `instale github.com/wailsapp/wails/v2/cmd/wails@latest` para instalar a CLI do Wails. + +Note: If you get an error similar to this: + +```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 +``` +please check you have Go 1.18+ installed: +```shell +go version +``` + +## Verificação do sistema + +Ao executar `wails doctor ` verificará quais dependências estão instaladas corretamente. Caso contrário, aconselhará sobre o que está em falta e ajudará a corrigir quaisquer problemas. + +## O comando `wail` parece estar faltando? + +Se o sistema está relatando que o comando `wail` está faltando, certifique-se de ter seguido o guia de instalação corretamente. Normalmente, isso significa que o diretório `go/bin` no diretório do seu usuário não está na variável do ambiente `PATH`. Você normalmente também precisará fechar e reabrir qualquer prompt de comando aberto para que as alterações no ambiente feitas pelo instalador sejam refletidas no prompt de comando. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..cae0d7f95a5 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# Angular + +Embora as Wails não tenham um modelo angular, é possível usar Angular com Wails. + +## Modo Desenvolvedor + +Para que o modo de desenvolvimento funcione com Angular, você precisa adicionar o seguinte ao seu `wails.json`: + +```json + "frontend:build": "npx ng build", + "frontend:install": "npm install", + "frontend:dev:watcher": "npx ng serve", + "frontend:dev:serverUrl": "http://localhost:4200", +``` \ No newline at end of file diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..f81eae7fa8d --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# Desenvolvimento de Aplicações + +Não existem regras rígidas e rápidas para o desenvolvimento das aplicações com o "Wails”, mas existem algumas orientações básicas. + +## Configurar Aplicação + +O padrão usado pelos templates padrão é que `main.go` é usado para configurar e executar a aplicação, enquanto `app.go` é usado para definir a lógica da aplicação. + +O arquivo `app.go` definirá uma struct que tem 2 métodos que funcionam como hooks na aplicação principal: + +```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) { +} +``` + +- O método `startup` é chamado assim que as Wails alocam os recursos de que precisa e é um bom lugar para a criação de recursos configurando ouvintes de eventos e qualquer outra coisa que o aplicativo precise na inicialização. É dado a ele um `context.Context` que é geralmente salvo em um campo struct. Este contexto é necessário para chamar o [runtime](../reference/runtime/intro.mdx). Se este método retornar um erro, o aplicativo será encerrado. No modo de desenvolvimento, o erro será exibido no console. + +- O método de `shutdown` será chamado pelo Wails logo no final do processo de encerramento. Este é um bom lugar para limpar memória e executar qualquer tarefa encerrada. + +O arquivo `main.go` geralmente consiste de uma única chamada para `wails.Run()`, que aceita a configuração da aplicação. O padrão usado pelos templates é o antes da chamada para `wails.Run()`, uma instância do struct definido no aplicativo `app. o` é criado e salvo em uma variável chamada `app`. Essa configuração é onde adicionamos os nossos 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) + } +} + +``` + +Mais informações sobre os hooks do ciclo de vida da aplicação podem ser encontradas [aqui](../howdoesitwork.mdx#application-lifecycle-callbacks). + +## Métodos de vínculo + +É provável que você queira chamar métodos Go do frontend. Isso normalmente é feito adicionando métodos públicos ao a struct já definida no `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) +} +``` + +Na configuração principal do aplicativo, a tecla `Bind` é onde podemos dizer aos Wails o que queremos vincular: + +```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) + } +} + +``` + +Isso vinculará todos os métodos públicos em nosso `App` de construção (isso nunca vinculará os métodos de inicialização e desligação). + +### Lidando com contexto quando vincular várias structs + +Se você quiser vincular métodos para várias structs , mas deseja que cada structs mantenha uma referência ao contexto para que você possa usar as funções de tempo de execução, um bom padrão é passar o contexto do método `OnStartup` para suas instâncias de construção : + +```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) + } +} +``` + +Mais informações sobre isso podem ser encontradas [aqui](../howdoesitwork.mdx#method-binding). + +## Menu da aplicação + +O Wails suporta adicionar um menu à sua aplicação. Isso é feito passando uma [struct](../reference/menus.mdx#menu) de menu para a configuração da aplicação. É comum o uso de um método que retorna um Menu, e ainda mais comum que seja um método na struct `App` usada para hooks de ciclo de vida. + +```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 + +A grande coisa do jeito que o Wails v2 lida com assets é que não o faz! A única coisa que você precisa fazer no Wails é um `embed.FS`. A forma como se chega a isso depende inteiramente de você. Você pode usar arquivos html/css/js como o modelo vanilla. Você pode ter um sistema de compilação complicado, isso não importa. + +Quando `wails build` é executado, ele vai verificar o arquivo do projeto `wails.json` na raiz do projeto. Há duas chaves no arquivo do projeto que são lidas: + +- "frontend:install" +- "frontend:build" + +O primeiro, se dado, será executado no diretório `frontend` para instalar os módulos do Node. O segundo, se dado, será executado no diretório `frontend` para realizar o build do projeto frontend. + +Se essas duas chaves não são dadas, então as Wails não faz absolutamente nada com a frontend. É apenas esperando o `embed.FS`. + +### AssetsHandler + +Um aplicativo Wails v2 pode opcionalmente definir um `http.Handler` nas opções `options.App`, que permite o gancho do AssetServer criar arquivos em tempo real ou processe solicitações POST/PUT. Solicitações GET sempre são tratadas primeiramente pelos `assets` FS. Se o FS não encontrar o arquivo solicitado, a solicitação será encaminhada para `http.Handler` para servir. Qualquer requisição que não seja o GET será diretamente processada pelo `AssetsHandler` se especificado. Também é usar apenas o `AssetsHandler` por especificação é `nil` como a opção `Assets`. + +## Servidor de Desenvolvedor nativo + +Executar `wails dev` iniciará o servidor de desenvolvimento que também iniciará um observador de arquivos no seu diretório de projeto. Por padrão, se qualquer arquivo for alterado, verifica-se se era um arquivo da aplicação (padrão: `.go`, configurável com `-e` flag). Se foi, então ele irá reconstruir sua aplicação e reiniciá-la. Se o arquivo alterado estiver nos assets, emitirá uma recarga após um curto período de tempo. + +O servidor de desenvolvimento utiliza uma técnica chamada "debwaring" que significa que não recarrega imediatamente, como pode haver vários arquivos alterados em um curto período de tempo. Quando um gatilho ocorre, ele espera por uma quantidade de tempo definida antes de emitir um recarregamento. Se outro gatilho acontecer, ele será redefinido para esperar novamente. Por padrão, esse valor é de `100ms`. Se este valor não funcionar para o seu projeto, ele pode ser configurado usando a flag `-debounce`. Se usado, este valor será salvo na configuração do seu projeto e se tornará o padrão. + +## Servidor de Desenvolvedor Externo + +Alguns frameworks vêm com seu próprio servidor ao vivo, no entanto, eles não serão capazes de tirar proveito das ligações Go/Wails. Neste cenário, é melhor executar um script de observador que reconstrui o projeto no diretório build, que Wails estará assistindo. Por exemplo, veja o modelo padrão do svelte que usa [rollup](https://rollupjs.org/guide/en/). + +### Criar Aplicativo React + +O processo para um projeto Create-React-App é um pouco mais complicado. Para ajudar o frontend a recarregar ao vivo a seguinte configuração precisa ser adicionado ao seu `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +O comando `frontend: dev:watcher` iniciará o servidor de desenvolvimento Create-React-App (hospedado na porta `3000` normalmente). O comando `frontend: dev:serverUrl` e instrui a Wails a servir assets do servidor de desenvolvimento ao carregar o frontend em vez de a partir da pasta de compilação. Além do acima acima o `index.html` precisa ser atualizado com o seguinte: + +```html + + + + + +``` + +Isso é necessário pois o comando do observador que reconstrui o frontend impede que o Wails injete os scripts necessários. Isso contorna esse problema garantindo os scripts são sempre injetados. Com esta configuração, `ondas de desenvolvimento` pode ser executado, o que irá construir adequadamente o frontend e o backend com o carregamento de quente ativado. Além disso, ao acessar o aplicativo a partir de um navegador, as ferramentas de desenvolvedor do React agora podem ser usadas em uma versão não minificada do aplicativo para simplificar depuração. Finalmente, para compilações mais rápidas, `wail dev -s` pode ser executado para ignorar o edifício padrão do frontend pelas Wails, pois este é um passo desnecessário. + +## Go Module + +Os modelos padrão do Wails geram um arquivo `go.mod` que contém o nome do módulo "changeme". Você deve alterar isto para algo mais apropriado após a geração do projeto. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..627bbeb5e36 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# Recursos Dinâmicos + +Se você deseja carregar ou gerar assets para seu frontend de forma dinâmica, você pode conseguir isso usando a opção [AssetsHandler](../reference/options#assetshandler). O AssetsHandler é um `http.Handler` genérico que irá ser chamado para qualquer solicitação não GET no servidor de ativos e para solicitações GET que não podem ser atendidas pelo ativos agrupados porque o arquivo não foi encontrado. + +Ao instalar um AssetsHandler personalizado, você pode servir seus próprios assets usando um servidor de arquivos personalizado. + +## Exemplo + +Em nosso projeto de exemplo, vamos criar um gerenciador de arquivos simples que irá carregar arquivos fora do disco: + +```go title=main.go {17-36,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) + } +} +``` + +Quando executarmos o aplicativo no modo de desenvolvimento usando `wail dev`, veremos a seguinte saída: + +``` +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler +Requesting file: favicon.ico +``` + +Como você pode ver, o manipulador de assets é chamado quando o servidor de assets padrão não consegue servir o arquivo `favicon.ico`. + +Se você clicar com o botão direito no aplicativo principal e selecionar "inspeção" para abrir as devtools, você pode testar esta função digitando o seguinte no console: + +``` +let response = await fetch('does-not-exist.txt'); +``` + +Isto irá gerar um erro no devtools. Podemos ver que o erro é o que esperamos, retornado por nosso manipulador de ativos personalizados: + +```mdx-code-block +

+ +

+``` + +No entanto, se requisitarmos `go.mod`, veremos a seguinte saída: + +```mdx-code-block +

+ +

+``` + +Esta técnica pode ser usada para carregar imagens diretamente para a página. Se atualizarmos nosso modelo padrão do vanilla e substituirmos a imagem do logotipo: + +```html + +``` + +com: + +```html + +``` + +Veremos então o seguinte: + +```mdx-code-block +

+ +

+``` + +:::warning + +Expor seu sistema de arquivos desta forma é um risco à segurança. É recomendável que você gerencie corretamente o acesso ao seu sistema de arquivos. + +::: diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..430f53a6afc --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# Aplicações sem frames + +O Wails suporta aplicativos que não possuem frames. Isso pode ser conseguido usando o campo [sem frameless](../reference/options.mdx#frameless) no [Application Options](../reference/options.mdx#application-options). + +Wails oferece uma solução simples para arrastar a janela: qualquer elemento HTML que tenha o estilo CSS `--wails-draggable:drag` irá atuar como uma "alça de arrastar". Esta propriedade se aplica a todos os elementos filhos. Se você precisar indicar que um elemento aninhado não deve arrastar, então use o atributo '--wails-draggable:no-drag' nesse elemento. + +```html + + + + + + + +
+ + +
+
+ + + + +``` + +Para alguns projetos, usar uma variável CSS pode não ser possível devido a um estilo dinâmico. Neste caso, você pode usar o aplicativo `CSSDragProperty` e `CSSDragValue` opções para definir uma propriedade e valor que serão usados para indicar regiões arrastáveis: + +```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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info Tela Cheia + +Se você permitir que seu aplicativo vá para tela cheia, esta funcionalidade de arrastar será desativada. + +::: diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..aade2b7f4cc --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# Frontend + +## Injeção de script + +Quando Wails serve a página `index.html`, por padrão injetará duas entradas de escript na ``tag para carregar `/wails/ipc.js` e `/wails/runtime.js`. Esses arquivos instalam o bindings e o tempo de execução, respectivamente. + +O código abaixo mostra onde estas são injetadas por padrão: + +```html + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### Sobrescrevendo a injeção de script padrão + +Para oferecer mais flexibilidade aos desenvolvedores, há uma meta tag que pode ser usada para personalizar este comportamento: + +```html + +``` + +As configurações são as seguintes: + +| Valor | Descrição | +| ------------------- | ---------------------------------------------- | +| noautoinjectruntime | Desativa a auto-injeção no `/wails/runtime.js` | +| noautoinjectipc | Desativa a autoinjeção no `/wails/ipc.js` | +| noautoinject | Desativa todas as autoinjeções de scripts | + +Várias opções podem ser usadas, desde que sejam separadas por vírgulas. + +Este código é perfeitamente válido e opera o mesmo que a versão da auto-injeção: + +```html + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..fdb83a6adf3 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# IDEs + +O Wails pretende proporcionar uma grande experiência de desenvolvimento. Para atingir isso, agora suportamos a geração de configuração específica de IDE para fornecer uma configuração de projeto mais suave. + +Atualmente, nós suportamos o [Visual Studio Code](https://code.visualstudio.com/) mas buscamos oferecer suporte a outros IDEs, como o Goland. + +## Visual Studio Code + +```mdx-code-block +

+ +

+``` + +Ao gerar um projeto usando a `-ide vscode` flag, arquivos IDE serão criados juntamente com os outros arquivos do projeto. Estes arquivos são colocados no diretório `.vscode` e fornecem a configuração correta para depurar seu aplicativo. + +Os 2 arquivos gerados são `tasks.json` e `launch.json`. Abaixo estão os arquivos gerados para o projeto vanilla padrão: + +```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": {} + } + ] +} +``` + +### Configurando os passos de instalação e compilação + +O arquivo `tasks.json` é simples para o projeto padrão, já que não há nenhuma etapa de instalação em que `npm` ou `npm run build` seja necessário. Para projetos que tenham uma etapa de build de front-end, como o modelo do Svelte, precisaríamos editar `tasks.json` e adicionar os passos de instalação e compilação: + +```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 Melhoria Futura + +No futuro, esperamos gerar um `tasks.json` que inclui os passos de instalação e compilação automaticamente. + +::: diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..0241bdb5a65 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# Suporte a Distros Linux + +## Visão geral + +O Wails oferece suporte Linux, mas fornecer instruções de instalação para todas as distribuições disponíveis é uma tarefa impossível. Em vez disso, a Wails tenta determinar se os pacotes que você precisa para desenvolver aplicações estão disponíveis através do gerenciador de pacote do seu sistema. Atualmente, suportamos os seguintes gestores de pacotes: + +- apt +- dnf +- emerge +- eopkg +- nixpkgs +- pacman +- zypper + +## Adicionando nomes de pacotes + +Pode haver circunstâncias em que sua distro use um dos gerentes de pacote suportados, mas o nome do pacote é diferente. Por exemplo, você pode usar um derivado de Ubuntu, mas o nome do pacote para gtk pode ser diferente. Wails tenta encontrar o pacote correto iterando por meio de uma lista de nomes de pacotes. A lista de pacotes é armazenada no arquivo específico do gerenciador de pacotes no diretório `v2/internal/system/packagemanager`. No nosso exemplo, isso seria `v2/internal/system/packagemanager/apt.go`. + +Neste arquivo, a lista de pacotes são definidos pelo método `Packages()`: + +```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}, + }, + } +} +``` + +Vamos supor que na nossa distração em linux, a `libgtk-3` é empacotada com o nome `lib-gtk3-dev`. Podemos adicionar suporte para isso adicionando a seguinte linha: + +```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}, + }, + } +} +``` + +## Adicionando novos gerenciadores de pacotes + +Para adicionar um novo gerenciador de pacotes, execute os seguintes passos: + +- Crie um novo arquivo em `v2/internal/system/packagemanager` chamado `.go`, onde `` é o nome do gerenciador de pacote. +- Defina uma struct que esteja em conformidade com a interface de gerenciador de pacotes definida em `pm.go`: + +```go +type PackageManager interface { + Name() string + Packages() packagemap + PackageInstalled(*Package) (bool, error) + PackageAvailable(*Package) (bool, error) + InstallCommand(*Package) string +} +``` + +- `Name()` deve retornar o nome do gerenciador de pacotes +- `Packages()` deve retornar um `packagemap`, que fornece nomes de arquivo de candidatos para dependências +- `PackageInstalled()` deve retornar `true` se o pacote for instalado +- `PackageAvailable()` deve retornar `true` se o pacote fornecido não estiver instalado, mas disponível para instalação +- `InstallCommand()` deve retornar o comando exato para instalar o nome do pacote dado + +Dê uma olhada no código de outros gerenciadores de pacotes para ter uma ideia de como isto funciona. + +:::info Lembre-se + +Se você adicionar suporte para um novo gerenciador de pacotes, não se esqueça de também atualizar esta página! + +::: diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..a975968f316 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# Linux + +Esta página possui vários guias relacionados ao desenvolvimento de aplicativos Wails para Linux. + +## A tag de vídeo não ativa o evento "ended" + +Ao usar uma tag de vídeo, o evento "ended" não é acionado quando o vídeo terminar de ser reproduzido. Este é um erro no WebkitGTK, no entanto, você pode usar a seguinte solução alternativa para corrigi-lo: + +```js +videoTag.addEventListener("timeupdate", (event) => { + if (event.target.duration - event.target.currentTime < 0.2) { + let ended = new Event("ended"); + event.target.dispatchEvent(ended); + } +}); +``` + +Fonte: [Lyimmi](https://github.com/Lyimmi) no [fórum de discussões](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275) diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..4ba06231463 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# Desenvolvimento Local + +## Visão geral + +Os dispositivos estão em constante desenvolvimento e novos lançamentos são regularmente "marcados". Isso geralmente acontece quando todo o código no `master` foi testado e confirmado funcionando. Se você precisar de uma correção de bug ou recurso que ainda não foi lançado, é possível usar a versão mais recente "bleeding edge" seguindo as seguintes etapas: + +- `git clone https://github.com/wailsapp/wails` +- `cd wails/v2/cmd/wails` +- `go install` + +NOTA: O diretório para o qual você clonou o projeto será agora chamado de "clonedir". + +A CLI do Wails estará na versão mais recente. + +### Atualizando seu projeto + +Para atualizar projetos para usar a versão mais recente da biblioteca Wails, atualize o `do projeto. od` e certifique-se que a seguinte linha está no final do arquivo: + +`replace github.com/wailsapp/wails/v2 => ` + +Exemplo: + +Windows: `substitua github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2` + +Em 'nix: `substitui github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2` + +Para reverter para uma versão estável, execute: + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` + +## Testando uma Branch + +Se você deseja testar um branch, siga as instruções acima, mas certifique-se de alternar o branch que você deseja testar antes de instalar: + +- `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` + +Certifique-se de [atualizar seu projeto](#updating-your-project) conforme descrito acima. + +## Testando uma PR + +Se você deseja testar um branch, siga as instruções acima, mas certifique-se de alternar o branch que você deseja testar antes de instalar. Por favor, substitua `[IDofThePR]` pelo ID do PR mostrado no 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` + +Certifique-se de [atualizar seu projeto](#updating-your-project) conforme descrito acima. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..4b7b589c1a4 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# Guia para Mac App Store + +Esta página dá uma breve visão geral de como enviar seu App Wails para a Mac App Store. + +## Pré-requisitos + +- Você precisará ter uma conta para o Apple Develop. Encontre mais informações no site [do Programa de Desenvolvedor Apple](https://developer.apple.com/support/compare-memberships/) +- Você precisará ter seus Certificados, Identificadores e App criados no portal de desenvolvimento. Mais sobre isto abaixo +- Ferramentas de linha de comando Xcode precisarão ser instaladas na sua máquina local + +#### Criar certificados e identificadores + +1. Vá para sua [Conta de desenvolvedor Apple](https://developer.apple.com/account/) +2. Sob `Certificados, Identificadores & Perfis`, clique em `Identificadores` e Registrar um Novo App ID. Use o formato (com.exemplo.app) +3. Sob a mesma página, clique `Certificados` e gere novos Certificados para a Distribuição da Loja de Aplicativos Mac. Baixe-os e importe os certificados para o Keychain em sua máquina local. + +#### Criar Envio de App + +1. Ir para [App Store Connect Site](https://appstoreconnect.apple.com/apps) +2. Registre um novo aplicativo e vincule o ID do pacote que você criou no passo anterior +3. Preencher seu aplicativo com as capturas de tela corretas, descrições, etc. conforme exigido pela Apple +4. Criar uma nova versão do seu aplicativo + +#### Criar perfil de provisionamento +1. Vá para a página [Apple Developer Profiles](https://developer.apple.com/account/resources/profiles/list) +2. Adicionar um novo perfil de provisionamento para Mac App Store de distribuição +3. Defina o tipo de perfil como Mac e selecione o ID do aplicativo criado acima +4. Selecione o certificado de Distribuição de Aplicativos Mac +5. Nomeie o Perfil de Provisão incorporado e baixe o perfil criado. + +## Guia para Mac App Store + +#### Ativar a App Sandbox da Apple + +Os aplicativos enviados para Mac App Store devem ser executados na [App Sandbox](https://developer.apple.com/app-sandboxing/) da Apple. Você deve criar um arquivo `entitlements.plist` para que isso funcione. A recomendação é criar este arquivo sob este caminho `{PROJECT_DIR}/build/darwin/entitlements.plist`. + +**Exemplo de arquivo de direitos** + +Este é um exemplo de titularidade de arquivo do aplicativo [RiftShare](https://github.com/achhabra2/riftshare). Para referência, por favor coloque os direitos que seu aplicativo exigir. Consulte [este site](https://developer.apple.com/documentation/bundleresources/entitlements) para obter mais informações. Você precisará substituir a ID da Equipe e o Nome da Aplicação pelos que você se registrou acima. + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +**Adicionar Perfil de Provisão Embutido** O Perfil de Provisionamento criado acima precisa ser adicionado à raiz da aplicação. Precisa ser nomeado como embedded.provisionprofile. + +#### Construa e assine o Pacote de Aplicativos + +O seguinte é um exemplo de script para construir e assinar seu aplicativo para o envio da Mac App Store. Ele presume que você está executando o script do diretório do seu projeto raiz. + +Observe que os certificados para a assinatura do aplicativo e a assinatura do instalador são diferentes. Certifique-se de que ambos são importados para o Keychain. Encontre as sequências de caracteres no Keychain e insira-as abaixo. Preencha os nomes do seu certificado e o nome do app abaixo. Executar o seguinte script irá gerar um arquivo `assinado app.pkg` no diretório raiz do seu aplicativo. + +```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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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 +``` + +#### Enviar pacote de aplicativos + +Você precisará enviar o arquivo do pacote gerado e associá-lo à sua Aplicação antes de poder enviá-lo para revisão. + +1. Baixe o [aplicativo Transporter](https://apps.apple.com/us/app/transporter/id1450874784) na Mac App Store +2. Abra e inicie sessão com a sua Apple ID +3. Clique no sinal + e selecione o arquivo `APP_NAME.pkg` que você gerou na etapa anterior. Carregar isto +4. Volte para [Loja de Apps Conectar](https://appstoreconnect.apple.com/apps) e navegue de volta para a submissão de seu aplicativo. Selecione a versão que você está pronto para disponibilizar na App Store. Em `Build` selecione o pacote que você enviou via Transporter. + +É isso! Agora você pode usar o site para enviar seu Aplicativo para análise. Após alguns dias úteis, se tudo correr bem, você verá seu App ao vivo na Mac App Store. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..f3142438d76 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# Compilações manuais + +O CLI Wails faz um trabalho pesado pelo projeto, mas às vezes é desejável construir o seu projeto manualmente. Este documento discutirá as diferentes operações da CLI e a forma como isso pode ser conseguido de diferentes maneiras. + +## Processo de compilação + +Quando `wails build` ou `wails dev` são usados, o Wails CLI executa um processo de compilação comum: + + - Instalar dependências frontend + - Construir projeto frontend + - Gerar mídias de construção + - Compilar aplicação + - [optional] Comprimir o aplicativo + +### Instalar dependências frontend + +#### Passos CLI + +- Se a flag `-s` for dada, esta etapa é ignorada +- Verifica `wails.json` para ver se há um comando de instalação na chave `frontend:install` +- Se não houver, ela pula esta etapa +- Se houver, ele verifica se `package.json` existe no diretório do frontend. Se não existir, pula esta etapa +- Uma soma MD5 é gerada a partir do conteúdo do arquivo `package.json` +- Verifica a existência de `package.json.md5` e, se existir, irá comparar o conteúdo dele (uma soma MD5) com o gerado para ver se o conteúdo mudou. Se eles forem iguais, este passo é ignorado +- Se `package.json.md5` não existir, será criado usando a soma MD5 gerada +- Se uma compilação é necessária agora, ou a `node_modules` não existe, ou a flag `-f` é dada, o comando de instalação é executado no diretório frontend + +#### Passos manuais + +Esta etapa pode ser feita na linha de comando ou um script com o `npm install`. + +### Construir projeto frontend + +#### Wails CLI + +- Se a flag `-s` for dada, esta etapa é ignorada +- Verifica `wails.json` para ver se há um comando de compilação na chave `frontend:build` +- Se não houver, ela pula esta etapa +- Se houver, ele é executado no diretório frontend + +#### Passos manuais + +Esta etapa poderia ser feita a partir da linha de comando ou um script com `npm run build` ou qualquer que seja o script de compilação do frontend. + +### Gerar mídias + +#### Wails CLI + +- Se a flag `-nopackage` estiver definida, este estágio será ignorado +- Se o arquivo `build/appicon.png` não existir, um arquivo padrão será criado +- Para Windows, consulte [Conjuntos para Windows](#windows) +- Se `build/windows/icon.ico` não existir, ele será criado a partir da imagem `build/appicon.png`. + +##### Windows + +- Se `build/windows/icon.ico` não existir, irá criá-lo a partir de `build/appicon. ng` usando tamanhos de ícones de 256, 128, 64, 48, 32 e 16. Isso é feito usando o [winicon](https://github.com/leaanthony/winicon). +- Se o arquivo `build/windows/.manifest` não existir, será criado a partir de uma versão padrão. +- Compila a aplicação como uma compilação de produção (acima) +- Usa [winres](https://github.com/tc-hib/winres) para empacotar o ícone e manifestar em um arquivo `.syso` pronto para vincular. + +#### Passos manuais + +- Crie `icon.ico` usando o [winicon](https://github.com/leaanthony/winicon) Ferramenta de CLI (ou qualquer outra ferramenta). +- Criar / Atualizar o arquivo de `.manifest` para sua aplicação +- Use o [winres CLI](https://github.com/tc-hib/go-winres) para gerar um arquivo `.syso`. + +### Compilar aplicação + +#### Wails CLI + +- Se o sinalizador `-clean` for fornecido, o diretório `build` é excluído e recriado +- Para `wails dev`, as seguintes bandeiras Go padrão são usadas: `-tags dev -gcflags "all=-N -l"` +- Para `wails build`, as seguintes flags padrão do Go são usadas: `-tags desktop,production -ldflags "-w -s"` + - No Windows, `-ldflags "-w -h -H windowsgui"` +- Tags adicionais passadas para o CLI usando `-tags` são adicionadas aos padrões +- Ldflags adicionais passadas para a CLI usando `-ldflags` são adicionados aos padrões +- A bandeira `-o` é passada +- O compilador Go especificado por `-compiler` será usado para compilação + +#### Passos manuais + +- Para compilação de desenvolvedores, o comando mínimo seria: `go build -tags dev -gcflags "all=-N -l"` +- Para a compilação de produção, o comando mínimo seria: `go build -tags desktop,production -ldflags "-w -s -H windowsgui"` +- Certifique-se de compilar no mesmo diretório que o arquivo `.syso` + +### Comprimir aplicativo + +#### Wails CLI + +- Se a flag `-upx` tiver sido dada, o programa `upx` será executado para comprimir o aplicativo com as configurações padrão +- Se `-upxflags` também for colado, essas flags são usadas em vez das padrão + +#### Passos manuais + +- Execute `upx [flags]` manualmente para comprimir o aplicativo. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..a874b03f4f5 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,191 @@ +# Migrando da v1 + +## Visão geral + +Wails v2 é uma mudança significativa em relação à v1. Este documento visa destacar as mudanças e as etapas na migração de um projeto existente. + +### Criando uma aplicação Cli + +Na v1, o aplicativo principal é criado usando `wails.CreateApp`, as ligações são adicionadas com `app.Bind` e, em seguida, o o aplicativo é executado usando `app.Run()`. + +Exemplo: + +```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() +``` + +Na v2, há apenas um único método, `wails.Run()`, que aceita as opções de aplicação [](../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, + }, + }) +``` + +### Mapeamento + +Na v1, foi possível vincular funções e estruturas arbitrárias. Em v2, foi simplificado apenas para estruturas vinculativas. As instâncias de construção que foram passadas anteriormente para o método `Bind()` na v1, estão agora especificados no campo `Vincular` do as opções de aplicação [](../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, + }, + }) +``` + +Na v1, métodos vinculados estavam disponíveis para o frontend em `window.backend`. Isto mudou para `window.go` + +### Ciclo de vida da Aplicação + +Na v1, havia 2 métodos especiais em uma estrutura vinculada: `WailsInit()` e `WailsShutdown()`. Foi substituído por três ganchos de ciclo de vida como parte das [opções do aplicativo](../reference/options.mdx#application-options): + +- [OnStartup](../reference/options.mdx#onstartup) +- [OnShutdown](../reference/options.mdx#onshutdown) +- [OnDomReady](../reference/options.mdx#ondomready) + +Nota: [OnDomReady](../reference/options.mdx#ondomready) substitui o evento do sistema `wails:ready` na v1. + +Estes métodos podem ser funções padrão, mas uma prática comum é tê-los incluído numa estrutura: + +```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 +} +... +``` + +### Tempo de execução + +O tempo de execução na v2 é muito mais rico que a v1 com suporte para menus, manipulação de janelas e melhores diálogos. A assinatura dos métodos mudou ligeiramente - consulte a [Referência de tempo de execução](../reference/runtime/intro.mdx). + +Na v1, o [runtime](../reference/runtime/intro.mdx) estava disponível através de uma struct passada para `WailsInit()`. Em v2, o tempo de execução foi movido para o seu próprio pacote. Cada método no tempo de execução leva o `context.Context` que é passado para o método [OnStartup](../reference/options.mdx#onstartup). + +```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 + +A _maior mudança_ na v2 é como os ativos são geridos. + +Na v1, os ativos foram passados via 2 opções de aplicativo: + +- `JS` - O JavaScript do aplicativo +- `CSS` - O CSS da aplicação + +Isso significava que a responsabilidade de gerar um único arquivo JS e CSS era do desenvolvedor. Isto exigia essencialmente a utilização de embalagens complicadas como o webpack. + +Na v2, Wails não faz suposições sobre seus ativos no frontend, como um servidor web. Todos os seus ativos de aplicação são passados para as opções de aplicação como um `embed.FS`. + +**Isso significa que não há necessidade de agrupar seus ativos, codificar imagens como Base64 ou experimente a arte obscura da configuração do bundler para usar fontes personalizadas**. + +Na inicialização, Wails verificará o `embed.FS` fornecido em busca de `index.html` e usará sua localização como caminho raiz para todos os outros ativos do aplicativo - assim como faria um servidor web. + +Exemplo: Uma aplicação tem o seguinte layout do projeto. Todos os arquivos finais são colocados no diretório `frontend/dist`: + +```shell +. +├── build/ +├── frontend/ +│ └── dist/ +│ ├── index.html +│ ├── main.js +│ ├── main.css +│ └── logo.svg +├── main.go +└── wails.json +``` + +Esses ativos podem ser usados pelo aplicativo simplesmente criando um `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, + }, + }) +} +``` + +Claro, empacotadores podem ser usados se você quiser. O único requisito é passar o diretório final de ativos do aplicativo para Wails usando um `embed.FS` no `Assets` chave das [opções do aplicativo](../reference/options.mdx#application-options). + +### Configuração do Projeto + +Na v1, a configuração do projeto foi armazenada no arquivo `project.json` na raiz do projeto. Na v2, a configuração do projeto é armazenada no arquivo `wails.json` na raiz do projeto. + +O formato do arquivo é ligeiramente diferente. Aqui está uma comparação: + +

+ +| 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. Normalmente, isto é inferido e pode ser deixado vazio. | +| | reloaddirs | Lista separada por vírgulas de diretórios adicionais para observar alterações e acionar recarregamentos no modo `dev`. Isso só é necessário para algumas configurações de ativos mais avançadas. | + +

diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..054ac263bd1 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# Botões do Mouse + +As Wails runtime interceptam cliques do mouse para determinar se uma janela precisa ser redimensionada ou uma janela precisa ser movida. Foi perguntado como detectar quando um clique do mouse ocorreu, porque `window.onclick` não relata os botões do mouse corretamente. O código a seguir mostra como detectar cliques do mouse: + +```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 diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..d921a6a5fc2 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# Builds ofuscadas + +Wails inclui suporte para ofuscar a sua aplicação usando [garble](https://github.com/burrowers/garble). + +Para produzir uma compilação ofuscada, você pode usar o sinalizador `-obfuscate` com o comando `wails build`: + +```bash +wails build -obfuscated +``` + +Para personalizar a configuração de ofuscação, pode-se utilizar a flag: `-garbleargs`: + +```bash +wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed" +``` + +Essas configurações podem estar persistentes na configuração do seu [projeto](../reference/project-config). + +## Como funciona + +Em uma compilação padrão, todos os métodos vinculados estão disponíveis no frontend sob a variável `window.go`. Quando esses métodos são chamados, o método backend correspondente é chamado usando o nome da função totalmente qualificada. Quando usando uma compilação ofuscada, os métodos são vinculados usando um ID em vez de um nome. Os bindings gerados no diretório `wailsjs` usam esses IDs para chamar as funções de backend. + +:::note + +Para garantir que o seu aplicativo irá funcionar no modo ofuscado, você deve usar os bindings geradas sob o diretório `wailsjs` no seu aplicativo. + +::: + +## Exemplo + +Importing the "Greet" method from the bindings like this: + +```js +import { Greet } from "../../wailsjs/go/main/App"; + +// snip +Greet("World"); +``` + +irá garantir que o método funcionará corretamente no modo ofuscado, como os bindings serão regenerados com IDs e o mecanismo de chamada atualizado. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..dcd13f147c3 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# Rolar demais + +[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) é o "efeito de salto" que você às vezes obtém quando você rola além dos limites de conteúdo de uma página. This is common in mobile apps. Isso pode ser desativado usando CSS: + +```css +html { + height: 100%; + overflow: hidden; +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..550e73a57f4 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,47 @@ +# Roteamento + +O roteamento é uma maneira popular de alternar as telas de um aplicativo. Esta página oferece algumas orientações sobre como fazer isso. + +## Vue + +A abordagem recomendada para roteamento em Vue é o [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 + +A abordagem recomendada para roteamento em Angular é [HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies#_hashlocationstrategy): + +```ts +RouterModule.forRoot(routes, { useHash: true }); +``` + +## React + +A abordagem recomendada para roteamento em React é [HashRouter](https://reactrouter.com/en/main/router-components/hash-router): + +```jsx +import { HashRouter } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..c3e0c269658 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# Assinatura de Código + +Este é um guia sobre como você pode assinar seus binários gerados com Wails no MacOS e Windows. O guia visará ambientes de CI, mais especificamente as GitHub Actions. + +## Windows + +Primeiro você precisa de um certificado de assinatura de código. Se você ainda não tiver uma, a página de informações da Microsoft lista alguns provedores [aqui](https://docs.microsoft.com/en-us/windows-hardware/drivers/dashboard/get-a-code-signing-certificate). Observe que um certificado EV não é necessário a menos que você precise escrever um software no nível kernel como drivers de dispositivos. Para assinar o seu aplicativo Wails, um certificado de assinatura de código padrão vai dar certo. + +Pode ser uma boa ideia verificar com seu provedor de certificados como assinar seus binários na sua máquina local antes de direcionar sistemas de compilação automatizada. só para que você saiba se há exigências especiais. Por exemplo, [aqui](https://www.ssl.com/how-to/using-your-code-signing-certificate/) é o guia de assinatura de código de SSL.com para Windows. Se você sabe como assinar localmente, será mais fácil solucionar quaisquer possíveis problemas em um ambiente de CI. Por exemplo, os certificados de assinatura de código SSL.com exigem a flag `/tr` para [SignTool.exe](https://docs.microsoft.com/en-us/windows/win32/seccrypto/signtool) enquanto outros provedores só precisam da flag `/t` para fornecer o servidor de marcação de tempo. GitHub Actions populares para assinar binários Windows como [este](https://github.com/Dana-Prajea/code-sign-action) não suporta a flag `/tr` no SignTool.exe. Portanto, este guia focará em assinar nosso aplicativo manualmente com comandos do PowerShell, mas você pode usar ações como a ação de [de co-sign-action](https://github.com/Dana-Prajea/code-sign-action) se preferir. + +Em primeiro lugar, vamos nos certificar de que somos capazes de construir nosso aplicativo Wails no nosso GitHub CI. Aqui está um pequeno modelo de fluxo de trabalho: + +```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/* +``` + +Em seguida, precisamos dar ao fluxo de trabalho do GitHub acesso ao nosso certificado de assinatura. Isso é feito codificando seu certificado .pfx ou .p12 em uma string base64. Para fazer isso em PowerShell, use o seguinte comando assumindo que seu certificado se chama 'my-cert.p12': + +```PowerShell +certutil -encode .\my-cert.p12 my-cert-base64.txt +``` + +Você deve ter seu arquivo .txt com o certificado codificado em base64. Deve começar com _-----BEGIN CERTIFICATE-----_ e terminar com _-----END CERTIFICATE-----_. Agora você precisa criar duas ações secretas no GitHub. Navegue até _Configurações -> Segredos -> Ações_ e crie os dois seguintes segredos: + +- **WIN_SIGNING_CERT** com o conteúdo de seu texto codificado no certificado base64. +- **WIN_SIGNING_CERT_PASSWORD** com o conteúdo da sua senha do certificado. + +Agora estamos prontos para implementar a assinatura em nosso fluxo de trabalho usando um dos dois métodos: + +### Método 1: Assinar com comandos + +Esse método usa comandos PowerShell para assinar nosso aplicativo, e deixa o controle de todo o processo de assinatura. + +Após o passo `Build Wails app`, podemos adicionar o seguinte passo ao nosso fluxo de trabalho: + +```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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +Este script cria um novo diretório para o seu arquivo de certificado, cria o arquivo de certificado do nosso segredo base64, converte-o em um arquivo .pfx, e finalmente assina o binário. As seguintes variáveis precisam ser substituídas na última linha: + +- **signing algorithm**: geralmente sha256. +- **timestamping server**: URL para o servidor de timestamping a ser usado com seu certificado. +- **path to binary**: caminho para o binário que você deseja assinar. + +Dado que nossa configuração Wails tem `outputfilename` definido para "app.exe" e que temos um certificado de SSL.com, este é o nosso fluxo de trabalho: + +```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/* +``` + +### Método 2: assinar automaticamente com Action + +É possível usar um código Windows assinando uma ação como [este](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate) um, mas nota que requer um hash SHA1 para o certificado e um nome de certificado. Veja um exemplo de como configurá-lo na [loja da ações](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate). + +--- + +## MacOS + +Primeiro você precisa do seu certificado de assinatura de código da Apple. Se você não tem uma, uma pesquisa simples do Google irá ajudá-lo a adquirir uma. Depois de ter o certificado, você precisa exportá-lo e codificá-lo para base64. [Este tutorial](https://localazy.com/blog/how-to-automatically-sign-macos-apps-using-github-actions) te mostra como fazer isso de uma maneira fácil. Depois de ter exportado seu arquivo de certificado .p12, você pode codificá-lo para base64, como visto no tutorial com o seguinte comando: + +```bash +base64 Certificates.p12 | pbcopy +``` + +Agora você está pronto para criar alguns segredos de projeto do GitHub, assim como no Windows: + +- **APPLE_DEVELOPER_CERTIFICATE_P12_BASE64** com o conteúdo de seu certificado base64 recém-copiado. +- **APPLE_DEVELOPER_CERTIFICATE_PASSWORD** com o conteúdo da senha do seu certificado. +- **APPLE_PASSWORD** com o conteúdo de uma senha específica para sua conta Apple-ID que pode gerar [aqui](https://appleid.apple.com/account/manage). + +Vamos nos certificar de que somos capazes de construir nosso aplicativo Wails em nosso fluxo de trabalho do GitHub. Aqui está um pequeno modelo: + +```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/* +``` + +Para assinar o código no macOS, [gon](https://github.com/mitchellh/gon) é uma ferramenta muito útil para a assinatura do código e a comunicação com os servidores Apple, também escrito em Go, e será usado neste guia. + +Após o passo `Build Wails app`, adicione o seguinte ao fluxo de trabalho: + +```yaml +- name: MacOS download gon for code signing and app notarization + if: matrix.platform == 'macos-latest' + run: | + brew install mitchellh/gon/gon +``` + +Agora precisamos configurar alguns arquivos de configuração do gon no nosso diretório `build/darwin`: + +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" + } +} +``` + +Onde o `source` é o binário do seu Wails, `bundle_id` é o seu ID do pacote, `apple_id` contém o seu nome de usuário do ID Apple e a senha do aplicativo que você criou antes, e `sign.application_identity` é sua identidade que você pode encontrar executando o seguinte comando: + +```bash +security find-identity -v -p codesigning +``` + +2. entitlements.plist: + +```plist + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +Neste arquivo, você configura os direitos que você precisa para seu aplicativo, por exemplo, permissões de câmera se seu app usa a câmera. Leia mais sobre entitlements [aqui](https://developer.apple.com/documentation/bundleresources/entitlements). + +Verifique se você atualizou seu arquivo `Info.plist` com o mesmo pacote de ID que você digitou em `gon-sign.json`. Aqui está um arquivo `Info.plis` de exemplo: + +```plist + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +Agora estamos prontos para adicionar a etapa de assinatura em nosso fluxo de trabalho após a construção do aplicativo Wails: + +```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 +``` + +Por favor, note que a assinatura de binários com Apple pode levar a de minutos a horas. + +## Arquivo de fluxo combinado: + +Aqui está nosso arquivo de fluxo de trabalho do GitHub com Windows + macOS combinados: + +```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/* +``` + +# Notas finais + +Este guia inspirado no projeto RiftShare e seu fluxo de trabalho, o que é altamente recomendado para verificar [aqui](https://github.com/achhabra2/riftshare/blob/main/.github/workflows/build.yaml). diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..8281281f325 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +Este guia será para: + +1. Passos de instalação do Miminal - Os passos necessários para obter uma instalação mínima de Wails funcionando para o SvelteKit. +2. Script de Instalação - Bash script para cumprir os passos de Instalação Mínima com a marca opcional de Wails. +3. Notas importantes - Problemas que podem ser encontrados ao usar o SvelteKit + Wails e correções. + +## 1. Passos mínimos de instalação + +##### Instalar Wails para Svelte. + +- `wails init -n myapp -t svelte` + +##### Exclua o front-end do Svelte. + +- Navegue até a pasta myapp recém-criada. +- Excluir a pasta chamada "frontend" + +##### Enquanto estiver na raiz do projeto Wails. Use o seu gerenciador de pacotes favorito e instale o SvelteKit como o novo frontend. Siga as instruções. + +- `npm create svelte@latest frontend` + +##### Modificar o wails.json. + +- Add `"wailsjsdir": "./frontend/src/lib",` Observe que é aqui que suas funções Go e runtime aparecerão. +- Mude o frontend do seu gerenciador de pacotes se não estiver usando npm. + +##### Modificar o main.go. + +- O primeiro comentário `//go:embed all:frontend/dist` precisa ser alterado para `//go:embed all:frontend/build` + +##### Instalar/remover dependências usando seu gerenciador de pacote favorito. + +- Entre na sua pasta "frontend". +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Alterar adaptador em svelte.config.js + +- A primeira linha de arquivo altera `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Coloque o SvelteKit no modo SPA com pré-renderização. + +- Crie um arquivo sob myapp/frontend/src/routes/ chamado +layout.ts/+layout.js. +- Adicione duas linhas ao recém-criado arquivo `export const prerender = true` e `export const ssr = false` + +##### Testar instalação. + +- Navegue de volta à raiz do projeto Wails (um diretório para cima). +- execute `wails dev` +- Se a aplicação não executar, por favor verifique os passos anteriores. + +## 2. Script de Instalação + +##### Este Script do Bash faz as etapas listadas acima. Certifique-se de ler o script e de entender o que o script está fazendo no seu computador. + +- Criar um arquivo sveltekit-wails.sh +- Copie o código abaixo para o novo arquivo e o salve. +- Torná-lo executável com `chmod +x sveltekit-wails.sh` +- A marca é um parâmetro opcional abaixo que adiciona de volta na marca de fregueses. Deixe o terceiro parâmetro em branco para não inserir a marca das Wails. +- Exemplo de uso: `./sveltekit-wails.sh pnpm newapp brand` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Notas importantes + +##### Os arquivos do servidor causarão falhas de construção. + +- \+layout.server.ts, +page.server.ts, +server.ts ou qualquer arquivo com "server" em nome falhará na construção enquanto todas as rotas forem pré-renderizadas. + +##### O tempo de execução do Wails descarrega com navegações de página inteira! + +- Tudo que causa navegações de página completa: `window.location.href = '//'` ou recarga do menu de contexto ao usar wails dev. Isso significa que você pode acabar perdendo a capacidade de chamar qualquer falha no aplicativo em tempo de execução. Há duas formas de trabalhar em torno desta questão. +- Use `import { goto } from '$app/navigation'` e então chame `goto('//')` em sua + page.svelte. Isso impedirá uma navegação de página completa. +- Se a navegação por página inteira não puder ser impedido que o tempo de execução do Wails seja adicionado a todas as páginas, adicionando o abaixo ao `` de myapp/frontend/src/app. Mt + +``` + +... + + + +... + +``` + +Veja https://wails.io/docs/guides/frontend para mais informações. + +##### Os dados de e-mail podem ser carregados e atualizados a partir de +page.ts/+page.js para +page.svelte. + +- \+page.ts/+page.js funciona bem com o load() https://kit.svelte.dev/docs/load#page-data +- invalidateAll() em +page.svelte irá chamar load() de +page.ts/+page.js https://kit.svelte.dev/docs/load#rerunning-load-functions-manual-invalidation. + +##### Tratamento de erros + +- Erros esperados usando o erro Throw funcionam em +page.ts/+page.js com uma página +error.svelte. https://kit.svelte.dev/docs/errors#expected-errors +- Erros inesperados farão com que o aplicativo se torne inutilizável. Somente a opção de recuperação (conhecida até agora) de erros inesperados é recarregar o aplicativo. Para fazer isso, crie um arquivo myapp/frontend/src/hooks.client.ts e adicione o código abaixo ao arquivo. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Usando formas e funções de manipulação + +- A maneira mais simples é chamar uma função do formulário é o padrão, vincular:valor suas variáveis e evitar submissão `` +- A maneira mais avançada é use:enhance (aprimoramento progressivo) que permitirá acesso conveniente a formData, formElemento, emissor. A nota importante é sempre cancel() o formulário que impede o comportamento do lado do servidor. https://kit.svelte.dev/docs/form-actions#progressive-enhancement Exemplo: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..2ae61796b73 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# Templates + +Wails gera projetos a partir de modelos pré-criados. Na v1, este era um conjunto de projetos que estavam sujeitos a sair de moda. No v2, para capacitar a comunidade, alguns novos recursos foram adicionados para os templates: + +- Capacidade de gerar projetos a partir de [Modelos Remotos](../reference/cli.mdx#remote-templates) +- Ferramentas para ajudar a criar seus próprios modelos + +## Criando Templates + +Para criar um template, você pode usar o comando `wails generate template`. Para gerar um modelo padrão, execute: + +`wails generate template -name mytemplate` + +Isso cria o diretório "mytemplate" com os arquivos padrão: + +```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 +``` + +### Visão Geral do Modelo + +O modelo padrão consiste nos seguintes arquivos e diretórios: + +| Nome do arquivo / diretório | Descrição | +| --------------------------- | -------------------------------------------- | +| NEXTSTEPS.md | Instruções sobre como completar o modelo | +| README.md | O README publicado com o modelo | +| app.tmpl.go | Arquivo de modelo `app.go` | +| frontend/ | O diretório que contém os assets do frontend | +| go.mod.tmpl | Arquivo de modelo `go.mod` | +| main.tmpl.go | Arquivo de modelo `main.go` | +| template.json | Os metadados do modelo | +| wails.tmpl.json | Arquivo de modelo `wails.json` | + +Neste ponto é aconselhável seguir os passos em `NEXTSTEPS.md`. + +## Criando um Template de um Projeto Existente + +É possível criar um modelo a partir de um projeto de frontend existente, passando o caminho para o projeto ao gerar o template. Vamos agora andar sobre como criar um modelo do Vue 3: + +- Instale o vue cli: `npm install -g @vue/cli` +- Crie o projeto padrão: `vue create vue3-base` + - Selecione `Padrão (Vue 3) ([Vue 3] babel, eslint)` +- Depois que o projeto for gerado, execute: + +```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... +``` + +- O template agora pode ser personalizado conforme especificado no arquivo `NEXTSTEPS.md` +- Uma vez que os arquivos estão prontos, eles podem ser testados executando: `wails init -n my-vue3-project -t .\wails-vue3-template\` +- Para testar o novo projeto, execute: `cd meu-vue3-projeto` e `wails constroem` +- Uma vez que o projeto tenha compilado, execute-o: `.\build\bin\my-vue3-project.exe` +- Você deve ter um aplicativo Vue3 que funcione plenamente: + +```mdx-code-block +
+ +
+``` + +## Publicando Templates + +A publicação de um template está simplesmente enviando os arquivos para o GitHub. São encorajadas as seguintes melhores práticas: + +- Remova todos os arquivos e diretórios indesejados (como `.git`) do seu diretório no frontend +- Certifique-se de que `template.json` esteja completo, especialmente `helpurl` +- Faça push dos arquivos para o GitHub +- Crie um PR na página [Templates de Comunidade](../community/templates.mdx) +- Anuncie o modelo no fórum de discussão [de Anúncio de Modelo](https://github.com/wailsapp/wails/discussions/825) diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..b4980716836 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# Resolução de Problemas + +Uma variedade de dicas de solução de problemas. + +## O comando `wail` parece estar faltando? + +Se o sistema está relatando que o comando `wails` está faltando, verifique se você seguiu o guia de instalação do Go corretamente. Normalmente, isso significa que o diretório `go/bin` no diretório inicial do seu usuário não está na variável `PATH` ambiente. Você normalmente também precisará fechar e reabrir qualquer prompt de comando aberto para que as alterações no ambiente feitas pelo instalador sejam refletidas no prompt de comando. + +## Meu aplicativo está exibindo uma tela branca/em branco + +Verifique se sua aplicação inclui os conteúdos do diretório correto. No seu arquivo `main.go`, você terá algo semelhante ao seguinte código: + +```go +//go:embed all:frontend/dist +var assets embed.FS +``` + +Verifique que `frontend/dist` contém os ativos da aplicação. + +### Mac + +Se isso acontecer no Mac, tente adicionar o seguinte ao seu `Info.plist`: + +```xml +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +Reference: https://github.com/wailsapp/wails/issues/1504#issuecomment-1174317433 + +## Aplicativo Mac inválido + +Se a sua aplicação construída se parece com isso no buscador: + +```mdx-code-block +

+ +

+``` + +é provável que o `info.plist` do seu aplicativo seja inválido. Atualize o arquivo em `build/.app/Contents/info.plist` e verifique se os dados são válidos, verifique se o nome binário está correto. Para persistir nas alterações, copie o arquivo de volta para o diretório `build/darwin`. + +## Meu aplicativo não está exibindo o ícone correto no Windows Explorer + +Se seu aplicativo não estiver exibindo o ícone correto, tente excluir o arquivo `IconCache.db` oculto localizado na pasta Diretório `C:\Users\<seu nome de usuário>\AppData\Local`. Isto irá forçar o Windows a reconstruir o cache de ícones. + +Reference: https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## Não é possível chamar o método backend no frontend com argumentos variados + +Se você tem um método de backend definido com parâmetros variadicos, por exemplo: + +```go +func (a *App) TestFunc(msg string, args ...interface{}) error { + // Code +} +``` + +chamar esse método a partir do frontend como isso irá falhar: + +```js +var msg = "Hello: "; +var args = ["Go", "JS"]; +window.go.main.App.TestFunc(msg, ...args) + .then((result) => { + //do things here + }) + .catch((error) => { + //handle error + }); +``` + +Gambiarra: + +```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 + +## Estou recebendo erros de proxy ao tentar instalar o Wails + +Se você estiver recebendo erros como este: + +``` +"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. +``` + +é provavelmente porque o Proxy oficial Go está sendo bloqueado (usuários na China relataram isto). A solução é configurar o proxy manualmente, por exemplo: + +``` +go env -w GO111MODULE=on +go env -w GOPROXY=https://goproxy.cn,direct +``` + +Reference: https://github.com/wailsapp/wails/issues/1233 + +## O TypeScript gerado não tem os tipos corretos + +Às vezes, o TypeScript gerado não tem os tipos corretos. Para mitigar isso, é possível especificar quais tipos devem ser gerados usando a tag de struct `ts_type`. Para mais detalhes do, leia [isto](https://github.com/tkrajina/typescriptify-golang-structs#custom-types). + +## Quando navego longe do `index.html`, não consigo chamar métodos no frontend + +Se você navegar do `index.html` para um novo arquivo html, o contexto será perdido. Isso pode ser corrigido adicionando as seguintes importações para a seção `` de qualquer nova página que você navegar: + +```html + + + + +``` + +Reference: https://github.com/wailsapp/wails/discussions/1512 + +## Eu recebo `muitos arquivos abertos` erros no meu Mac quando eu rodo `wails` + +Por padrão, o macOS só permitirá que você abra um máximo de 256 arquivos. Isso pode afetar o comando `wails dev`. Este limite pode ser aumentado em execução: `ulimit -n 1024` no terminal. + +FSNotify é [procurando mudar para os fsevents](https://github.com/fsnotify/fsnotify/issues/11) da Apple para Mac. Se isso não estiver concluído em breve, criaremos nossa própria implementação, monitorada [aqui](https://github.com/wailsapp/wails/issues/1733). + +## Meu aplicativo para Mac me dá erros estranhos de compilação + +Alguns usuários relataram ver erros de compilação como os seguintes: + +```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))) +``` + +Isto é _normalmente_ devido a uma incompatibilidade com a versão do sistema operacional que você está executando e a versão das Ferramentas de Comando XCode instalada. Se você vir um erro como este, tente atualizar suas Ferramentas de Linha de Comando XCode para a versão mais recente. + +Se reinstalar as Ferramentas de Comando Xcode ainda falhar, você pode verificar o caminho onde o kit de ferramentas está usando: + +`xcode-select -p` + +Se `/Applications/Xcode.app/Contents/Developer` for exibido, rode `sudo xcode-select --switch /Library/Developer/CommandLineTools` + +Fontes: https://github.com/wailsapp/wails/issues/1806 and https://github.com/wailsapp/wails/issues/1140#issuecomment-1290446496 + +## My application won't compile on Mac + +Se você estiver recebendo erros como este: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## Não foi possível iniciar o serviço: A versão do host "x.x.x não coincide com a versão binária "x.x.x" + +É preferível adicionar `frontend/node_modules` e `frontend/package-lock.json` ao seu `.gitignore`. Caso contrário, ao abrir o repositório em outra máquina que pode ter diferentes versões do Node instaladas, talvez você não seja capaz de executar seu aplicativo. + +Se isso acontecer, simplesmente exclua `frontend/node_modules` e `frontend/pacote-lock. soa` e corra os seus wails `constroem` ou `wails dev` comando. + +## Processo de compilação travado em "Gerando vinculações" + +Processo de geração de Bindings executa sua aplicação em um modo especial. Se o aplicativo, intencionalmente ou não intencionalmente, contém um laço infinito (ou seja, não sair após `wails.Run()` terminado), isto pode levar a construção do processo travado na geração do palco de amarras. Por favor, certifique-se de que seu código sai corretamente. + +## Aplicação Mac pisca branco na inicialização + +Isto é devido ao plano de fundo padrão do webview ser branco. Se você quiser usar a cor de fundo da janela, você pode tornar o plano de fundo do webview transparente usando a seguinte configuração: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..03962a2184c --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# Visual Studio Code + +Esta página é para dicas e truques diversos ao usar o Visual Studio Code com Wails. + +## Configuração do Vetur + +Muito obrigado [@Lyimmi](https://github.com/Lyimmi) por esta dica. Originalmente publicada [aqui](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349). + +Vetur é um popular plugin para o Visual Studio Code que fornece realce de sintaxe e conclusão de código para projetos Vue. Ao carregar um projeto Wails no VSCode, Vetur lançará um erro já que está esperando para encontrar o projeto frontend no diretório raiz. Para consertar isso, você pode fazer o seguinte: + +Crie um arquivo chamado `vetur.config.js` na raiz do projeto. + +```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' + ] + } + ] +} +``` + +Agora, 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" + ] +} +``` +Isso deve permitir que você use Vetur como esperado. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..40a4256d3f9 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# Instalador NSIS + +```mdx-code-block +

+ +
+

+``` + +O Wails suporta a geração de instaladores do Windows usando o [instalador do NSIS](https://nsis.sourceforge.io/). + +## Installing NSIS + +### Windows + +O instalador está disponível na página de [Download do NSIS](https://nsis.sourceforge.io/Download). + +Se você usar o gerenciador de pacotes de chocolatey, execute o seguinte script: + +``` +choco install nsis +``` + +Se você instalar o NSIS manualmente, você precisará adicionar a pasta _Bin_, que contém `makensis.exe`, e sua instalação NSIS ao seu PATH. [Aqui](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) está um bom tutorial sobre como adicionar ao PATH no Windows. + +### Linux + +O pacote `nsis` deve estar disponível através do gerenciador de pacotes da sua distribuição. + +### MacOS + +O NSIS está disponível para instalação através de homebrew: `brew install nsis`. + +## Gerando o instalador + +Quando um novo projeto é criado, o Wails gera os arquivos de configuração do NSIS em `build/windows/installer`. Os dados de configuração são lidos do `installer/info.json` e estão configurados para usar a seção de informação do projeto `wails.json`: + +```json +// ... + "Info": { + "companyName": "My Company Name", + "productName": "Wails Vite", + "productVersion": "1.0.0", + "copyright": "Copyright.........", + "comments": "Built using Wails (https://wails.io)" + }, +``` + +Para gerar um instalador para o seu aplicativo, use a flag `-nsis` com o comando `wails build`: + +``` +wails build -nsis +``` + +O instalador agora estará disponível no diretório `build/bin`. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..dd76db15adb --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# Windows + +Esta página tem guias diversos relacionados ao desenvolvimento de aplicativos Wails para Windows. + +## Manipulando a dependência de runtime WebView2, + +Aplicativos de Wails feitos para Windows possuem uma exigência de tempo de execução na Microsoft [Runtime WebView2](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). Windows 11 terá isto instalado por padrão, mas algumas máquinas não. O Wails oferece uma abordagem fácil para lidar com esta dependência. + +Usando a flag `-webview2` ao realizar o build, você pode decidir o que sua aplicação fará quando não for detectado um tempo de execução adequado (incluindo se o tempo de execução instalado for muito antigo). As quatro opções são: + +1. Baixar +2. Incorporar +3. Navegador +4. Erro + +### Baixar + +Esta opção irá solicitar ao usuário que nenhum tempo de execução adequado foi encontrado e, em seguida, oferecer para baixar e executar o bootstrapper oficial no site WebView2 da Microsoft. Se o usuário continuar, o bootstrapper oficial será baixado e executado. + +### Incorporar + +Esta opção incorpora o bootstrapper oficial dentro do aplicativo. Se nenhum tempo de execução adequado for encontrado, o aplicativo oferecerá para executar o bootstrapper. Isto adiciona ~150k ao tamanho do binário. + +### Navegador + +Esta opção pedirá ao usuário que nenhum tempo de execução adequado foi encontrado e, em seguida, oferecerá para abrir um navegador na página oficial WebView2, onde o bootstrapper pode ser baixado e instalado. O aplicativo irá então sair, deixando a instalação para o usuário. + +### Erro + +Se não for encontrado um tempo de execução adequado, um erro é dado ao usuário e nenhuma ação foi feita. + +## Execução da versão fixa + +Outra forma de lidar com a dependência webview2 é enviando-a você mesmo. Você pode baixar [versão fixa em tempo de execução](https://developer.microsoft.com/microsoft-edge/webview2/#download-section) e empacotar ou baixá-lo com seu aplicativo. + +Além disso, você deve especificar o caminho para a versão fixa do tempo de execução webview2 nas `windows.Options` structure ao iniciar wails. + +```go + wails.Run(&options.App{ + Windows: &windows.Options{ + WebviewBrowserPath: "", + }, + }) +``` + +Observação: Quando `WebviewBrowserPath` é especificado a estratégia `error` seráforçada em caso de exigência de versão mínima ou erros na busca do runtime. + +## Gerando outros programas + +Ao gerar outros programas, tais como scripts, você verá a janela aparecer na tela. Para ocultar a janela, você pode usar o seguinte código: + +```go +cmd := exec.Command("your_script.exe") +cmd.SysProcAttr = &syscall.SysProcAttr{ + HideWindow: true, + CreationFlags: 0x08000000, +} +cmd.Start() +``` + +Solução fornecida pelo [sithembiso](https://github.com/sithembiso) no [quadro de discussões](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172). diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..44fa130cc74 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +sidebar_position: 20 +--- + +# How does it work? + +A Wails application is a standard Go application, with a webkit frontend. The Go part of the application consists of the application code and a runtime library that provides a number of useful operations, like controlling the application window. The frontend is a webkit window that will display the frontend assets. Also available to the frontend is a JavaScript version of the runtime library. Finally, it is possible to bind Go methods to the frontend, and these will appear as JavaScript methods that can be called, just as if they were local JavaScript methods. + +```mdx-code-block +
+ +
+``` + +## The Main Application + +### Overview + +The main application consists of a single call to `wails.Run()`. It accepts the application configuration which describes the size of the application window, the window title, what assets to use, etc. A basic application might look like this: + +```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) +} +``` + +### Options rundown + +This example has the following options set: + +- `Title` - The text that should appear in the window's title bar +- `Width` & `Height` - The dimensions of the window +- `Assets` - The application's frontend assets +- `OnStartup` - A callback for when the window is created and is about to start loading the frontend assets +- `OnShutdown` - A callback for when the application is about to quit +- `Bind` - A slice of struct instances that we wish to expose to the frontend + +A full list of application options can be found in the [Options Reference](reference/options). + +#### Assets + +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 {17,27} 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 {10-12} + //... + 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. + +## The Frontend + +### Overview + +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; +``` + +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; +``` + +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). + +### Calling runtime methods + +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. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..2a870d43220 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +--- + +# Introdução + +Wails é um projeto que permite a você escrever aplicativos de desktop usando Go e web. + +Considere uma alternativa leve e rápida do Electron para o Go. Você pode facilmente construir aplicativos com a flexibilidade e o poder do Go, combinados com um frontend rico e moderno. + +### Funcionalidades + +- Menus Nativos, Dialogs, Temas e Transparência +- Suporte a Windows, macOS e Linux +- Modelos embutidos para Svelte, React, Preact, Vue, Lit e Vanilla JS +- Easily call Go methods from JavaScript +- Automatic Go struct to TypeScript model generation +- Não são necessárias DLLs externas ou CGO no Windows +- Modo de desenvolvimento ao vivo usando o poder do [Vite](https://vitejs.dev/) +- Poderoso CLI para criar, Construir e Empacotar facilmente +- Uma rica [biblioteca de tempo de execução](/docs/reference/runtime/intro) +- Aplicativos construídos com Wails são compatíveis com Apple & Microsoft Store + +Este é [vago](https://varly.app) - um aplicativo para desktop para MacOS & Windows escrito usando Wails. Não só parece ótimo, como também usa menus nativos e translucidez - tudo o que você esperaria de um aplicativo nativo moderno. + +```mdx-code-block +

+ +

+``` + +### Criação Rápida de Template + +Há uma série de modelos pré-configurados que permitem que o aplicativo entre em funcionamento rapidamente. Há modelos para os seguintes frameworks: Svelte, React, Vue, Preact, Lit e Vanilla. There are both JavaScript and TypeScript versions for each template. + +### Elementos Nativos + +Wails uses a purpose built library for handling native elements such as Window, Menus, Dialogs, etc, so you can build good-looking, feature rich desktop applications. + +**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. No Windows, esta é a nova biblioteca da Microsoft Webview2, construída no Chromium. + +### Go & JavaScript Interoperability + +Wails automatically makes your Go methods available to JavaScript, so you can call them by name from your frontend! It even generates TypeScript models for the structs used by your Go methods, so you can pass the same data structures between Go and JavaScript. + +### Biblioteca de tempo de execução + +Wails provides a runtime library, for both Go and JavaScript, that handles a lot of the things modern applications need, like Eventing, Logging, Dialogs, etc. + +### Experiência de Desenvolvimento Ao Vivo + +#### Reconstruções automáticas + +Quando você executar seu aplicativo no modo "dev", o Wails construirá seu aplicativo como uma aplicação de desktop nativa, e lerá seus ativos a partir do disco. Ele detectará quaisquer alterações no seu Código Go e reconstruirá automaticamente e reiniciará seu aplicativo. + +#### Recarregamentos automáticos + +Quando alterações nos assets de seu aplicativo forem detectadas, seu aplicativo em execução irá "recarregar", reflectindo suas alterações quase imediatamente. + +#### Desenvolva sua aplicação com um navegador + +If you prefer to debug and develop in a browser then Wails has you covered. The running application also has a webserver that will run your application in any browser that connects to it. It will even refresh when your assets change on disk. + +### Production-ready Native Binaries + +When you're ready to do the final build of your application, the CLI will compile it down to a single executable, with all the assets bundled into it. On Windows and MacOS, it is possible to create a native package for distribution. The assets used in packaging (icon, info.plist, manifest file, etc) are part of your project and may be customised, giving you total control over how your applications are built. + +### Tooling + +The Wails CLI provides a hassle-free way to generate, build and bundle your applications. It will do the heavy lifting of creating icons, compiling your application with optimal settings and delivering a distributable, production ready binary. Choose from a number of starter templates to get up and running quickly! diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..c2a5d706bac --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,240 @@ +--- +sidebar_position: 2 +--- + +# Linha de comandos + +A CLI do Wails tem vários comandos que são usados para gerenciar seus projetos. Todos os comandos são executados da seguinte maneira: + +`wails ` + +## init + +`wails init` é usado para gerar projetos. + +| Flag | Descrição | Padrão | +|:------------------------- |:---------------------------------------------------------------------------------------------------------------------------------- |:---------------:| +| -n "nome do projeto" | Nome do projeto. **Obrigatório**. | | +| -d "diretório do projeto" | Diretório de projeto a criar | Nome do projeto | +| -g | Inicializar o repositório git | | +| -l | Listar modelos de projetos disponíveis | | +| -q | Suprimir saída no console | | +| -t "nome do template" | O modelo do projeto a ser usado. Este pode ser o nome de um template padrão ou um URL para um template remoto hospedado no github. | vanilla | +| -ide | Gerar arquivos de projeto IDE | | +| -f | Forçar compilação de aplicação | false | + +Exemplo: `wails init -n test -d mytestproject -g -ide vscode -q` + +Isso irá gerar um projeto chamado "test" no diretório "mytestproject", inicializar o git, gerar arquivos de projeto vscode e fazê-lo silenciosamente. + +Mais informações sobre isso podem ser encontradas [aqui](../guides/ides.mdx). + +### Modelos Remotos + +Modelos remotos (hospedados no GitHub) são suportados e podem ser instalados usando a URL do projeto do template. + +Exemplo: `wails init -n teste -t https://github.com/leaanthony/testtemplate[@v1.0.0]` + +Uma lista de modelos mantidos pela comunidade pode ser encontrada [aqui](../community/templates.mdx) + +:::warning Attention + +**The Wails project does not maintain, is not responsible nor liable for 3rd party templates!** + +If you are unsure about a template, inspect `package.json` and `wails.json` for what scripts are run and what packages are installed. + +::: + +## build + +`wails build` é usado para compilar seu projeto para um binário pronto para produção. + +| Flag | Descrição | Padrão | +|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:----------------------------------------------------------------------------------------------------------------------------------------------------- | +| -clean | Limpa o diretório `compilação/bin` | | +| -compiler "compiler" | Use um compilador de ida diferente para realizar build, por exemplo, go1.15beta1 | go | +| -debug | Retains debug information in the application and shows the debug console. Permite o uso das ferramentas devtools na janela do aplicativo | | +| -devtools | Allows the use of the devtools in the application window in production (when -debug is not used). Ctrl/Cmd+Shift+F12 may be used to open the devtools window. *NOTE*: This option will make your application FAIL Mac appstore guidelines. Use for debugging only. | | +| -dryrun | Prints the build command without executing it | | +| -f | Forçar compilação de aplicação | | +| -garbleargs | Argumentos para passar para o garble | `-literals -tiny -seed=random` | +| -ldflags "flags" | Ldflags adicionais para passar para o compilador | | +| -m | Skip mod tidy before compile | | +| -nopackage | Não empacotar aplicação | | +| -nocolour | Disable colour in output | | +| -nosyncgomod | Do not sync go.mod with the Wails version | | +| -nsis | Generate NSIS installer for Windows | | +| -o nome de arquivo | Nome do Arquivo de Saída | | +| -obfuscated | Ofuscar a aplicação usando [garble](https://github.com/burrowers/garble) | | +| -platform | Compila para as plataformas [(delimitadas por vírgula)](../reference/cli.mdx#platforms) por exemplo. `windows/arm64`. Note, se você não der arquitetura, `runtime.GOARCH` é usado. | platform = `variável de ambiente GOOS` se determinado `runtime.GOOS`.
arch = `GOARCH` variável de envrionment se for dado `runtime.GOARCH`. | +| -race | Realiza build com o Go race detector | | +| -s | Pular build do frontend | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Compilar tags para passar para o compilador Go. Deve ser citado. Separados por espaço ou vírgula (mas não ambos) | | +| -trimpath | Remove todos os caminhos do sistema de arquivo do executável resultante. | | +| -u | Atualiza o `go.mod` do seu projeto para usar a mesma versão de Wails que o CLI | | +| -upx | Comprimir binário final usando "upx" | | +| -upxflags | Flags para passar para o upx | | +| -v int | Nível de verbosidade(0 - silencioso, 1 - padrão, 2 - verbose) | 1 | +| -webview2 | Estratégia de instalação WebView2: download,embed,browser,error | baixar | +| -windowsconsole | Manter a janela de console para builds do Windows | | + +Para uma descrição detalhada do sinalizador `webview2`, consulte o guia [Windows](../guides/windows.mdx). + +Se você preferir construir usando a ferramenta Go padrão, consulte o guia de [Builds Manuais](../guides/manual-builds.mdx). + +Exemplo: + +`wails build -clean -o myproject.exe` + +:::info + +On Mac, the application will be bundled with `Info.plist`, not `Info.dev.plist`. + +::: + +:::info UPX no Apple Silicon + +Há alguns [problemas](https://github.com/upx/upx/issues/446) com o uso de UPX com o Apple Silicon. + +::: + +:::info UPX no Windows + +Alguns fornecedores de antivírus marcam como falsos positivos os binários `upx` comprimidos como vírus, veja [problema](https://github.com/upx/upx/issues/437). + +::: + +### Plataformas + +Plataformas Suportadas: + +| Plataforma | Descrição | +|:---------------- |:--------------------------------------------- | +| darwin | MacOS + architecture of build machine | +| darwin/amd64 | MacOS 10.13+ AMD64 | +| darwin/arm64 | MacOS 11.0+ ARM64 | +| darwin/universal | MacOS AMD64+ARM64 universal application | +| windows | Windows 10/11 + architecture of build machine | +| windows/amd64 | Windows 10/11 AMD64 | +| windows/arm64 | Windows 10/11 ARM64 | +| linux | Linux + architecture of build machine | +| linux/amd64 | Linux AMD64 | +| linux/arm64 | Linux ARM64 | + +## doctor + +`wails doctor` executará o diagnóstico para garantir que seu sistema esteja pronto para desenvolvimento. + +Exemplo: + +``` +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` é usado para executar sua aplicação em um modo de "desenvolvimento ao vivo". Isso significa que: + +- O aplicativo `go.mod` será atualizado para usar a mesma versão do Wails como a CLI +- A aplicação é compilada e executada automaticamente +- Um observador é iniciado e acionará uma reconstrução do seu aplicativo de desenvolvimento se ele detectar alterações em seus arquivos go +- Um servidor web foi iniciado em `http://localhost:34115` que serve sua aplicação (não apenas frontend) sobre http. Isso permite que você use suas extensões de desenvolvimento de navegador favoritas +- Todos os conteúdos do aplicativo são carregados do disco. Se forem alterados, o aplicativo irá recarregar automaticamente (não reconstruir). Todos os navegadores conectados também recarregarão +- A JS module is generated that provides the following: +- JavaScript wrappers of your Go methods with autogenerated JSDoc, providing code hinting +- TypeScript versions of your Go structs, that can be constructed and passed to your go methods +- A second JS module is generated that provides a wrapper + TS declaration for the runtime +- On macOS, it will bundle the application into a `.app` file and run it. It will use a `build/darwin/Info.dev.plist` for development. + +| Flag | Descrição | Padrão | +|:--------------------------------- |:---------------------------------------------------------------------------------------------------------------------------------------------------------------- |:--------------------- | +| -appargs "args" | Argumentos passados para o aplicativo no estilo shell | | +| -assetdir "./caminho/para/midias" | Serve os arquivos a partir do diretório fornecido em vez de usar os arquivos FS fornecidos | Valor em `wails.json` | +| -browser | Abre um navegador para `http://localhost:34115` na inicialização | | +| -compiler "compiler" | Use um compilador de ida diferente para realizar build, por exemplo, go1.15beta1 | go | +| -debounce | O tempo de esperar por recarregar depois que uma alteração de ativo for detectada | 100 (milliseconds) | +| -devserver "host:port" | O endereço para vincular o servidor de desenvolvimento de wails a | "localhost:34115" | +| -extensions | Extensões para acionar reconstruções (separadas por vírgula) | go | +| -forcebuild | Force build of application | | +| -frontenddevserverurl "url" | Usar URL do servidor de desenvolvimento de terceiros para servir midias, Vite EG | "" | +| -ldflags "flags" | Ldflags adicionais para passar para o compilador | | +| -loglevel "loglevel" | Nível de log a ser usado - Trace, Debug, Info, Warning, Error | Debug | +| -nocolour | Desativar saída da colorida da cli | false | +| -noreload | Desativar a recarga automática quando os arquivos forem alterados | | +| -nosyncgomod | Do not sync go.mod with the Wails version | false | +| -race | Realiza build com o Go race detector | false | +| -reloaddirs | Diretórios adicionais para acionar recarregamentos (separados por vírgula) | Valor em `wails.json` | +| -s | Pular build do frontend | false | +| -save | Salva o `assetdir`, `reloaddirs`,`wailsjsdir`,`debounce`,`devserver` e `frontenddevserverurl` passado, flag em `wails.json` para realizar chamadas subsequentes. | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Compilar tags para passar para o compilador (citado e espaço separado) | | +| -v | Nível de verbosidade(0 - silencioso, 1 - padrão, 2 - verbose) | 1 | +| -wailsjsdir | O diretório para gerar os módulos gerados do Wails JS | Valor em `wails.json` | + +Exemplo: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +Este comando fará o seguinte: + +- Compilação do aplicativo e execução (mais detalhes [aqui](../guides/manual-builds.mdx) +- Gerar os módulos JS de Wails em `./frontend/src` +- Assistir por atualizações em arquivos em `./frontend/dist` e recarregar em qualquer alteração +- Abrir um navegador e conectar-se ao aplicativo + +Há mais informações sobre como usar este recurso com scripts de framework existentes [aqui](../guides/application-development.mdx#live-reloading). + +## generate + +### template + +A Wails usa modelos para a geração de projeto. O comando `wails generate template` ajuda a fazer um template para que ele possa ser usado para gerar projetos. + +| Flag | Descrição | +|:---------------- |:----------------------------------------------------- | +| -name | O nome do template (Obrigatório) | +| -frontend "path" | Caminho para o projeto frontend para usar no template | + +Para mais detalhes sobre a criação de modelos, consulte o [guia de Modelos](../guides/templates.mdx). + +### module + +O comando `wails generate template` permite que você gere manualmente o diretório `wailsjs` para o seu aplicativo. + +## update + +`wails update` irá atualizar a versão da CLI do Wails. + +| Flag | Descrição | +|:------------------ |:------------------------------------- | +| -pre | Atualizar para a versão mais recente | +| -version "version" | Instalar uma versão específica do CLI | + +## version + +`wails version` simplesmente irá retornar a versão CLI atual. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..a60919a04b3 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# Menus + +É possível adicionar um menu de aplicação aos projetos do Wails. Isso é conseguido definindo uma struct [Menu](#menu) e configurando-a no configuração do aplicativo [`Menu`](../reference/options.mdx#menu) ou chamando o método [MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu). + +Um exemplo de como criar um menu: + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +Também é possível atualizar dinamicamente o menu, atualizando o menu struct e chamando [MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu). + +O exemplo acima usa métodos de ajuda, no entanto, é possível construir as construções do menu manualmente. + +## Menu + +Um Menu é uma coleção de MenuItems: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +Para o menu de Aplicação, cada MenuItem representa um único menu como "Editar". + +Um método simples de ajuda é fornecido para menus de construção: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +Isto torna o layout do código mais parecido com o de um menu sem a necessidade de adicionar os itens de menu manualmente depois de criá-los. Como alternativa, você pode apenas criar os itens de menu e adicioná-los ao menu manualmente. + +## MenuItem + +Um MenuItem representa um item dentro de um 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 +} +``` + +| Campo | Tipo | Notas | +| ----------- | ------------------------------------ | -------------------------------------------------------------------------- | +| Label | string | O texto do menu | +| Accelerator | [\*keys.Accelerator](#accelerator) | Vinculação de teclas para este item de menu | +| Tipo | [Tipo](#type) | Tipo de MenuItem | +| Disabled | bool | Desativa o item de menu | +| Hidden | bool | Oculta este item de menu | +| Checked | bool | Adiciona uma seleção para o item ( & Tipos de Rádio) | +| SubMenu | [\*Menu](#menu) | Define o submenu | +| Click | [Callback](#callback) | Função Callback quando clicado no menu | +| Role | string | Define um papel [](#role) para este item de menu. Mac apenas por enquanto. | + +### Accelerator + +Os aceleradores (às vezes chamados atalhos de teclado) definem uma ligação entre um toque de tecla e um item de menu. Lamentos define um Acelerador como uma combinação ou tecla + [Modificador](#modifier). Eles estão disponíveis no pacote `"github.com/wailsapp/wails/v2/pkg/menu/keys"`. + +Exemplo: + +```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") +``` + +Teclas são qualquer caractere único em um teclado com exceção de `+`, que é definido como `plus`. Algumas chaves não podem ser representadas como caracteres, portanto há um conjunto de caracteres nomeados que podem ser usados: + +| | | | | +|:-----------:|:-----:|:-----:|:---------:| +| `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 também suportam a análise de aceleradores usando a mesma sintaxe que o Electron. Isso é útil para armazenar aceleradores em arquivos de configuração. + +Exemplo: + +```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") +``` + +#### Modificador + +Os seguintes modificadores são chaves que podem ser usadas em combinação com a tecla de aceleração: + +```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" +) +``` + +Vários métodos de ajuda estão disponíveis para criar aceleradores usando modificadores: + +```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 +``` + +Modificadores podem ser combinados usando `keys.Combo(string de chaves, modificador 1 modificador, modificador modificador, rest ...Modificador)`: + +```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) +``` + +### Tipo + +Cada item de menu deve ter um tipo e existem 5 tipos disponíveis: + +```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" +) +``` + +Para conveniência, métodos auxiliares são fornecidos para criar rapidamente um item de menu: + +```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 +``` + +Você também pode criar itens de menu diretamente em um menu, usando os ajudantes "Adicionar": + +```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 +``` + +Uma nota nos grupos de rádio: Um grupo de rádio é definido como um número de itens do menu de rádio que estão próximos um ao outro no menu. Isso significa que não é necessário agrupar os itens porque é automático. No entanto, isso também significa que você não pode ter 2 grupos lado a lado - deve haver um item que não seja de rádio entre eles. + +### Callback + +Cada item de menu pode ter um callback que é executado quando o item é clicado: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +A função recebe uma instrução `CallbackData` que indica qual item de menu acionou a callback. Isso é útil quando usar grupos de rádio que podem compartilhar um callback. + +### Role + +:::info Regras + +As regras que são atualmente suportados apenas no Mac. + +::: + +Um item de menu pode ter uma função, que é essencialmente um item de menu pré-definido. Atualmente, apoiamos as seguintes funções: + +| Role | Descrição | +| ------------ | --------------------------------------------------------------------------- | +| AppMenuRole | Menu padrão do aplicativo para Mac. Pode ser criado usando `menu.AppMenu()` | +| EditMenuRole | O menu de edição padrão para Mac. Pode ser criado usando `menu.EditMenu()` | diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..46d1c071b60 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,853 @@ +--- +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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### Title + +The text shown in the window's title bar. + +Name: Title
Type: `string` + +### Width + +The initial width of the window. + +Name: Width
Type: `int`
Default: 1024. + +### Height + +The initial height of the window. + +Name: Height
Type: `int`
Default: 768 + +### DisableResize + +By default, the main window is resizable. Setting this to `true` will keep it a fixed size. + +Name: DisableResize
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
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
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
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
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
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
Type: `int` + +### StartHidden + +When set to `true`, the application will be hidden until [WindowShow](../reference/runtime/window.mdx#windowshow) is called. + +Name: StartHidden
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
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
Type: `*options.RGBA`
Default: white + +### AlwaysOnTop + +Indicates that the window should stay above other windows when losing focus. + +Name: AlwaysOnTop
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 | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +Name: AssetServer
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
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
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
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
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
Type: `logger.Logger`
Default: Logs to Stdout + +### LogLevel + +The default log level. More details about logging in the [Log Reference](../reference/runtime/log.mdx). + +Name: LogLevel
Type: `logger.LogLevel`
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
Type: `logger.LogLevel`
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
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
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
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
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
Type: `string` + +### CSSDragValue + +Indicates what value the `CSSDragProperty` style should have to drag the window. Default: `drag`. + +Name: CSSDragValue
Type: `string` + +### EnableDefaultContextMenu + +EnableDefaultContextMenu enables the browser's default context-menu in 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. + +When this option is enabled, by default the context-menu will only be shown for text contexts (where Cut/Copy/Paste is needed), to override this behavior, you can use the CSS property `--default-contextmenu` on any HTML element (including the `body`) with the following values : + +| CSS Style | Behavior | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--default-contextmenu: auto;` | (**default**) will show the default context menu only if :
contentEditable is true OR text has been selected OR element is input or textarea | +| `--default-contextmenu: show;` | will always show the default context menu | +| `--default-contextmenu: hide;` | will always hide the default context menu | + +This rule is inherited like any normal CSS rule, so nesting works as expected. + +:::note +This filtering functionality is only enabled in production, so in development and in debug build, the full context-menu is always available everywhere. +::: + +:::warning +This filtering functionality is NOT a security measure, the developer should expect that the full context-menu could be leaked anytime which could contain commands like (Download image, Reload, Save webpage), if this is a concern, the developer SHOULD NOT enable the default context-menu. +::: + + +Name: EnableDefaultContextMenu
Type: `bool` + +### EnableFraudulentWebsiteDetection + +EnableFraudulentWebsiteDetection enables scan services for fraudulent content, such as malware or phishing attempts. These services might send information from your app like URLs navigated to and possibly other content to cloud services of Apple and Microsoft. + +Name: EnableFraudulentWebsiteDetection
Type: `bool` + +### ZoomFactor + +Name: ZoomFactor
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
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
Type: `[]interface{}` + +### ErrorFormatter + +A function that determines how errors are formatted when returned by a JS-to-Go method call. The returned value will be marshalled as JSON. + +Name: ErrorFormatter
Type: `func (error) any` + +### Windows + +This defines [Windows specific options](#windows). + +Name: Windows
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
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
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
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
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
Type: `bool` + +#### WebviewUserDataPath + +This defines the path where the WebView2 stores the user data. If empty `%APPDATA%\[BinaryName.exe]` will be used. + +Name: WebviewUserDataPath
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
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
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
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
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
Type: `uint16` + +#### OnSuspend + +If set, this function will be called when Windows initiates a switch to low power mode (suspend/hibernate) + +Name: OnSuspend
Type: `func()` + +#### OnResume + +If set, this function will be called when Windows resumes from low power mode (suspend/hibernate) + +Name: OnResume
Type: `func()` + +#### WebviewGpuIsDisabled + +Setting this to `true` will disable GPU hardware acceleration for the webview. + +Name: WebviewGpuIsDisabled
Type: `bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +This defines [Mac specific options](#mac). + +Name: Mac
Type: `*mac.Options` + +#### TitleBar + +The TitleBar struct provides the ability to configure the look and feel of the title bar. + +Name: TitleBar
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
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
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
Type: `bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled u.Bool + FullscreenEnabled u.Bool +} +``` + +| Name | 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) | + +Example: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### 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
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 +
+ +
+
+``` + +When clicked, that will open an about message box: + +```mdx-code-block +
+ +
+
+``` + +### Linux + +This defines [Linux specific options](#linux). + +Name: Linux
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
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, don’t 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
Type: `bool` + +#### WebviewGpuPolicy + +This option is used for determining the webview's hardware acceleration policy. + +Name: WebviewGpuPolicy
Type: [`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
Default: `WebviewGpuPolicyAlways` + +##### WebviewGpuPolicy type + +| Value | Description | +| ------------------------ | -------------------------------------------------------------------- | +| WebviewGpuPolicyAlways | Hardware acceleration is always enabled | +| WebviewGpuPolicyOnDemand | Hardware acceleration is enabled/disabled as request by web contents | +| WebviewGpuPolicyNever | Hardware acceleration is always disabled | + +#### 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). + +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. + +Name: ProgramName
Type: string
+ +### Debug + +This defines [Debug specific options](#Debug) that apply to debug builds. + +Name: Debug
Type: `options.Debug` + +#### OpenInspectorOnStartup + +Setting this to `true` will open the WebInspector on startup of the application. + +Name: OpenInspectorOnStartup
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. +[^2]: This requires WebKit2GTK 2.40+ support and your app needs to be build with the build tag `webkit2_40` to activate support for this feature. This also bumps the minimum requirement of WebKit2GTK to 2.40 for your app. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..8e763502bcc --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,92 @@ +--- +sidebar_position: 5 +--- + +# Project Config + +The project config resides in the `wails.json` file in the project directory. The structure of the config is: + +```json5 +{ + // Project config version + "version": "", + // The project name + "name": "", + // Relative path to the directory containing the compiled assets, this is normally inferred and could be left empty + "assetdir": "", + // Additional directories to trigger reloads (comma separated), this is only used for some advanced asset configurations + "reloaddirs": "", + // The directory where the build files reside. Defaults to 'build' + "build:dir": "", + // Relative path to the frontend directory. Defaults to 'frontend' + "frontend:dir": "", + // The command to install node dependencies, run in the frontend directory - often `npm install` + "frontend:install": "", + // The command to build the assets, run in the frontend directory - often `npm run build` + "frontend:build": "", + // This command has been replaced by frontend:dev:build. If frontend:dev:build is not specified will falls back to this command. \nIf this command is also not specified will falls back to frontend:build + "frontend:dev": "", + // This command is the dev equivalent of frontend:build. If not specified falls back to frontend:dev + "frontend:dev:build": "", + // This command is the dev equivalent of frontend:install. If not specified falls back to frontend:install + "frontend:dev:install": "", + // This command is run in a separate process on `wails dev`. Useful for 3rd party watchers or starting 3d party dev servers + "frontend:dev:watcher": "", + // URL to a 3rd party dev server to be used to serve assets, EG Vite. \nIf this is set to 'auto' then the devServerUrl will be inferred from the Vite output + "frontend:dev:serverUrl": "", + // Relative path to the directory that the auto-generated JS modules will be created + "wailsjsdir": "", + // The name of the binary + "outputfilename": "", + // The default time the dev server waits to reload when it detects a change in assets + "debounceMS": 100, + // Address to bind the wails dev sever to. Default: localhost:34115 + "devServer": "", + // Arguments passed to the application in shell style when in dev mode + "appargs": "", + // Defines if build hooks should be run though they are defined for an OS other than the host OS. + "runNonNativeBuildHooks": false, + "preBuildHooks": { + // The command that will be executed before a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH". + "*/*": "" + }, + "postBuildHooks": { + // The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. + "*/*": "" + }, + // Data used to populate manifests and version info. + "info": { + // The company name. Default: [The project name] + "companyName": "", + // The product name. Default: [The project name] + "productName": "", + // The version of the product. Default: '1.0.0' + "productVersion": "", + // The copyright of the product. Default: 'Copyright.........' + "copyright": "", + // A short comment of the app. Default: 'Built using Wails (https://wails.app)' + "comments": "" + }, + // '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": "" +} +``` + +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). diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..2765c844d53 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +sidebar_position: 7 +--- + +# Browser + +Esses métodos estão relacionados com o navegador do sistema. + +### BrowserOpenURL + +Abre a URL fornecida no navegador do sistema. + +Go: `BrowserOpenURL(ctx context.Context, url string)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..805f68ed917 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# Clipboard + +This part of the runtime provides access to the operating system's clipboard.
The current implementation only handles text. + +### ClipboardGetText + +This method reads the currently stored text from the clipboard. + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
Returns: a string (if the clipboard is empty an empty string will be returned) or an error. + +JS: `ClipboardGetText(): Promise`
Returns: a promise with a string result (if the clipboard is empty an empty string will be returned). + +### ClipboardSetText + +This method writes a text to the clipboard. + +Go: `ClipboardSetText(ctx context.Context, text string) error`
Returns: an error if there is any. + +JS: `ClipboardSetText(text: string): Promise`
Returns: a promise with true result if the text was successfully set on the clipboard, false otherwise. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..6a12ce1350a --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +sidebar_position: 5 +--- + +# Diálogo + +Esta parte do tempo de execução fornece acesso a dialogos nativos, como os Seletores de Arquivo e caixas de mensagem. + +:::info JavaScript + +O dialog não é suportado pelo runtime do JS. + +::: + +### OpenDirectoryDialog + +Abre um diálogo que solicita o usuário para selecionar um diretório. Pode ser personalizado usando o [OpenDialogOptions](#opendialogoptions). + +Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Retorna: Diretório selecionado (nulo se o usuário cancelar) ou um erro + +### OpenFileDialog + +Abre um diálogo que solicita o usuário para selecionar um arquivo. Pode ser personalizado usando o [OpenDialogOptions](#opendialogoptions). + +Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Retorna: Arquivo selecionado (nulo se o usuário cancelar) ou um erro + +### OpenMultipleFilesDialog + +Abre um diálogo que pede o usuário para selecionar vários arquivos. Pode ser personalizado usando o [OpenDialogOptions](#opendialogoptions). + +Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)` + +Retorna: Arquivos selecionados (nulo se o usuário cancelar) ou um erro + +### SaveFileDialog + +Abre um diálogo que solicita o usuário selecionar um nome de arquivo para salvar. Pode ser personalizado usando [SaveDialogOptions](#savedialogoptions). + +Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)` + +Retorna: O arquivo selecionado (nulo se o usuário cancelar) ou um erro + +### MessageDialog + +Exibe uma mensagem usando a caixa de diálogo da mensagem. Pode ser personalizado usando o [MessageDialogOptions](#messagedialogoptions). + +Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)` + +Retorna: O texto do botão selecionado ou um erro + +## Opções + +### OpenDialogOptions + +```go +type OpenDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + ResolvesAliases bool + TreatPackagesAsDirectories bool +} +``` + +| Atributo | Descrição | Win | Mac | Lin | +| -------------------------- | ------------------------------------------------------------- | --- | --- | --- | +| DefaultDirectory | O diretório que a caixa de diálogo será exibida quando aberta | ✅ | ✅ | ✅ | +| DefaultFilename | O nome do arquivo padrão | ✅ | ✅ | ✅ | +| Title | Título para a caixa de diálogo | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | Uma lista de filtros de arquivos | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Exibir arquivos ocultos pelo sistema | | ✅ | ✅ | +| CanCreateDirectories | Permitir que o usuário crie diretórios | | ✅ | | +| ResolvesAliases | Se verdadeiro, retorna o arquivo não o alias | | ✅ | | +| TreatPackagesAsDirectories | Permitir a navegação em pacotes | | ✅ | | + +### SaveDialogOptions + +```go +type SaveDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + TreatPackagesAsDirectories bool +} +``` + +| Atributo | Descrição | Win | Mac | Lin | +| -------------------------- | ------------------------------------------------------------- | --- | --- | --- | +| DefaultDirectory | O diretório que a caixa de diálogo será exibida quando aberta | ✅ | ✅ | ✅ | +| DefaultFilename | O nome do arquivo padrão | ✅ | ✅ | ✅ | +| Title | Título para a caixa de diálogo | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | Uma lista de filtros de arquivos | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Exibir arquivos ocultos pelo sistema | | ✅ | ✅ | +| CanCreateDirectories | Permitir que o usuário crie diretórios | | ✅ | | +| TreatPackagesAsDirectories | Permitir a navegação em pacotes | | ✅ | | + +### MessageDialogOptions + +```go +type MessageDialogOptions struct { + Type DialogType + Title string + Message string + Buttons []string + DefaultButton string + CancelButton string +} +``` + +| Atributo | Descrição | Win | Mac | Lin | +| ------------- | ------------------------------------------------------------------------ | -------------- | --- | --- | +| Tipo | O tipo de diálogo de mensagem, por exemplo, pergunta, informações... | ✅ | ✅ | ✅ | +| Title | Título para a caixa de diálogo | ✅ | ✅ | ✅ | +| Message | A mensagem para mostrar o usuário | ✅ | ✅ | ✅ | +| Buttons | Uma lista de títulos de botões | | ✅ | | +| DefaultButton | O botão com este texto deve ser tratado como padrão. Vincule a `return`. | ✅[*](#windows) | ✅ | | +| CancelButton | O botão com este texto deve ser tratado como padrão. Vincule a `return` | | ✅ | | + +#### Windows + +Windows tem tipos de diálogo padrão em que os botões não são personalizáveis. O valor retornado será um dos: "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" or "Continue". + +Para diálogos de Perguntas, o botão padrão é "Sim" e o botão cancelar é "Não". Isso pode ser alterado definindo o valor do `DefaultButton` para `"No"`. + +Exemplo: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linux tem tipos de diálogo padrão em que os botões não são personalizáveis. O valor retornado será um de: "Ok", "Cancel", "Yes", "No" + +#### Mac + +Uma caixa de diálogo de mensagem no Mac pode especificar até 4 botões. Se nenhum `DefaultButton` ou `CancelButton` for dado, o primeiro botão é considerado padrão e está ligado à chave `return`. + +Para o código a seguir: + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "It's your turn!", + Message: "Select a number", + Buttons: []string{"one", "two", "three", "four"}, +}) +``` + +o primeiro botão é mostrado como padrão: + +```mdx-code-block +
+ +
+
+``` + +E se especificarmos o `DefaultButton` como "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", +}) +``` + +o segundo botão será mostrado como padrão. Quando `return` é pressionado, o valor "dois" é retornado. + +```mdx-code-block +
+ +
+
+``` + +Se especificarmos agora o `CancelButton` como "três: + +```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", +}) +``` + +o botão com "três" é mostrado na parte inferior do diálogo. Quando `escape` é pressionado, o valor "três" é retornado: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### 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 + +O Windows permite que você use vários filtros de arquivos em caixas de diálogo. Cada FileFilter aparecerá como uma entrada separada na caixa de diálogo: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Linux + +Linux permite que você use vários filtros de arquivo em caixas de diálogo. Cada FileFilter aparecerá como uma entrada separada na caixa de diálogo: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Mac + +As caixas de diálogo Mac possuem apenas o conceito de um único conjunto de padrões para filtrar arquivos. Se vários Filtros forem fornecidos, o Wails usará todos os padrões definidos. + +Exemplo: + +```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", + }, + }, + }) +``` + +Isso resultará na caixa de diálogo Abrir Arquivo usando `*.png,*.jpg,*.mov,*.mp4` como filtro. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..ec0eb61e4e7 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +sidebar_position: 2 +--- + +# Events + +The Wails runtime provides a unified events system, where events can be emitted or received by either Go or JavaScript. Opcionalmente, dados podem ser passados com os eventos. Os ouvintes receberão os dados nos tipos de dados locais. + +### EventsOn + +Este método configura um ouvinte para o nome do evento. Quando um evento do tipo `eventName` é [emitted](#EventsEmit), a callback é acionada. Quaisquer dados adicionais enviados com o evento emitido serão passados para o retorno de chamada. Retorna uma função para cancelar o ouvinte. + +Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOff + +Este método desregistra o listener para o nome do evento, opcionalmente várias listagens podem ser desregistradas via `adicionalEventNames`. + +Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`
JS: `EventsOff(eventName string, ...additionalEventNames)` + +### EventsOnce + +Esse método configura um listener para o nome do evento, mas só será acionado uma vez. Retorna uma função para cancelar o ouvinte. + +Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOnMultiple + +Este método configura um listener para o nome do evento, mas acionará apenas um máximo de `counter` vezes. Retorna uma função para cancelar o ouvinte. + +Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`
JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void` + +### EventsEmit + +Este método emite o evento fornecido. Os dados opcionais podem ser passados com o evento. Isto irá acionar quaisquer ouvintes de eventos. + +Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..b6f4e8a787c --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# Introduction + +O runtime é uma biblioteca que fornece métodos utilitários para sua aplicação. There is both a Go and JavaScript runtime and the aim is to try and keep them at parity where possible. + +Ele tem métodos de utilitário para: + +- [Janelas](window.mdx) +- [Menus](menu.mdx) +- [Caixa de diálogo](dialog.mdx) +- [Eventos](events.mdx) +- [Browser](browser.mdx) +- [Registro](log.mdx) +- [Clipboard](clipboard.mdx) + +O runtime do Go está disponível através da importação de `github.com/wailsapp/wails/v2/pkg/runtime`. Todos os métodos neste pacote assumem um contexto como o primeiro parâmetro. Este contexto deve ser obtido a partir dos ganchos [OnStartup](../options.mdx#onstartup) ou [OnDomReady](../options.mdx#ondomready). + +:::info Nota + +Embora o contexto seja fornecido para o método [Inicialização](../options.mdx#onstartup), não há garantia de que o runtime funcionará neste método, pois a janela está inicializando em um tópico diferente. Se você deseja chamar métodos de tempo de execução na inicialização, 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. Isso deve ser localizado no diretório `wailsjs` em seu diretório frontend. + +### Hide + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +Oculta a aplicação. + +:::info Nota + +No Mac, isto irá ocultar o aplicativo da mesma forma que o `Ocultar` item de menu nos aplicativos padrão Mac. Isso é diferente de esconder a janela, mas a aplicação ainda está em primeiro plano. Para Windows e Linux, atualmente isso é o mesmo que `WindowHide`. + +::: + +### Show + +Mostra a aplicação. + +:::info Nota + +No Mac, a aplicação voltará a ser apresentada em primeiro plano. Para Windows e Linux, atualmente isso é o mesmo que `WindowShow`. + +::: + +Go: `Show(ctx context.Context)`
JS: `Show()` + +### Quit + +Encerra a aplicação. + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### Environment + +Retorna detalhes do ambiente atual. + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### EnvironmentInfo + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..0513b9431fd --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# Registro + +The Wails runtime provides a logging mechanism that may be called from Go or JavaScript. Como a maioria dos registros de, há um número de níveis de log: + +- Trace +- Debug +- Info +- Warning +- Error +- Fatal + +O logger irá gerar qualquer mensagem de log no nível atual, ou superior, de log. Exemplo: O `Debug` log level irá retornar todas as mensagens exceto `Trace` mensagens. + +### LogPrint + +Registra a mensagem dada como uma mensagem "bruta". + +Go: `LogPrint(ctx context.Context, message string)`
JS: `LogPrint(message: string)` + +### LogPrintf + +Registra a mensagem dada como uma mensagem "bruta". + +Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`
+ +### LogTrace + +Registra a mensagem dada no `nível de log`. + +Go: `LogTrace(ctx context.Context, message string)`
JS: `LogTrace(message: string)` + +### LogTracef + +Registra a mensagem dada no `nível de log`. + +Go: `LogTracef(ctx context.Context, format string, args ...interface{})`
+ +### LogDebug + +Registra a mensagem dada no nível de log `Debug`. + +Go: `LogDebug(ctx context.Context, message string)`
JS: `LogDebug(message: string)` + +### LogDebugf + +Registra a mensagem dada no nível de log `Debug`. + +Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`
+ +### LogInfo + +Registra a mensagem dada no nível de log de `Info`. + +Go: `LogInfo(ctx context.Context, message string)`
JS: `LogInfo(message: string)` + +### LogInfof + +Registra a mensagem dada no nível de log de `Info`. + +Go: `LogInfof(ctx context.Context, format string, args ...interface{})`
+ +### LogWarning + +Registra a mensagem dada no nível de log de `Warning`. + +Go: `LogWarning(ctx context.Context, message string)`
JS: `LogWarning(message: string)` + +### LogWarningf + +Registra a mensagem dada no nível de log de `Warning`. + +Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`
+ +### LogError + +Registra a mensagem dada no nível de log de `Error`. + +Go: `LogError(ctx context.Context, message string)`
JS: `LogError(message: string)` + +### LogErrorf + +Registra a mensagem dada no nível de log de `Error`. + +Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`
+ +### LogFatal + +Registra a mensagem dada no nível de log `Fatal`. + +Go: `LogFatal(ctx context.Context, message string)`
JS: `LogFatal(message: string)` + +### LogFatalf + +Registra a mensagem dada no nível de log `Fatal`. + +Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`
+ +### LogSetLogLevel + +Define o nível de log. In JavaScript, the number relates to the following log levels: + +| Valor | Nível de Log | +| ----- | ------------ | +| 1 | Trace | +| 2 | Debug | +| 3 | Info | +| 4 | Warning | +| 5 | Erro | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
JS: `LogSetLogLevel(level: number)` + +## Usando um Logger personalizado + +Um logger personalizado pode ser usado fornecendo usando a opção de aplicativo [Logger](../options.mdx#logger). O único requisito é que o logger implemente a interface de `logger.Logger` definida em `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) +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..ae07d327c93 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +sidebar_position: 6 +--- + +# Menus + +Estes métodos estão relacionados ao menu da aplicação. + +:::info JavaScript + +O menu não é suportado atualmente no runtime do JS. + +::: + +### MenuSetApplicationMenu + +Define o menu do aplicativo para o [menu](../menus.mdx) fornecido. + +Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)` + +### MenuUpdateApplicationMenu + +Atualiza o menu do aplicativo, pegando qualquer alteração no menu passado para `MenuSetApplicationMenu`. + +Go: `MenuUpdateApplicationMenu(ctx context.Context)` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..457c92ebff9 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# Screen + +These methods provide information about the currently connected screens. + +### ScreenGetAll + +Returns a list of currently connected screens. + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### Screen + +Go struct: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript interface: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..04cc08ea679 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +sidebar_position: 4 +--- + +# Janela + +Esses métodos dão controle da janela do aplicativo. + +### WindowSetTitle + +Define o texto na barra de título da janela. + +Go: `WindowSetTitle(ctx context.Context, title string)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen + +Faz a janela estar em tela cheia. + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen + +Restaura as dimensões e a posição anteriores da janela antes da tela cheia. + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen + +Retorna verdadeiro se a janela estiver em tela cheia. + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter + +Centraliza a janela no monitor que a janela está ativada. + +Go: `WindowCenter(ctx context.Context)`
JS: `WindowCenter()` + +### WindowExecJS + +Executa código JS arbitrário na janela. + +Este método executa o código no navegador de forma assíncrona e retorna imediatamente. Se o script causar quaisquer erros, eles só estarão disponíveis no console do navegador. + +Go: `WindowExecJS(ctx context.Context, js string)` + +### WindowReload + +Executa um "recarregar" (Recarrega a página atual). + +Go: `WindowReload(ctx context.Context)`
JS: `WindowReload()` + +### WindowReloadApp + +Recarrega o front-end do aplicativo. + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme + +Somente para Windows. + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
JS: `WindowSetSystemDefaultTheme()` + +Define o tema da janela para padrão do sistema (escuro/claro). + +### WindowSetLightTheme + +Somente para Windows. + +Go: `WindowSetLightTheme(ctx context.Context)`
JS: `WindowSetLightTheme()` + +Define o tema da janela como claro. + +### WindowSetDarkTheme + +Somente para Windows. + +Go: `WindowSetDarkTheme(ctx context.Context)`
JS: `WindowSetDarkTheme()` + +Define o tema da janela como escuro. + +### WindowShow + +Mostra a janela, se ela estiver oculta no momento. + +Go: `WindowShow(ctx context.Context)`
JS: `WindowShow()` + +### WindowHide + +Oculta a janela, se ela estiver visível no momento. + +Go: `WindowHide(ctx context.Context)`
JS: `WindowHide()` + +### WindowIsNormal + +Retorna verdadeiro se a janela não for minimizada, maximizada ou tela inteira. + +Go: `WindowIsNormal(ctx context.Context) bool`
JS: `WindowIsNormal() bool` + +### WindowSetSize + +Define a largura e a altura da janela. + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize + +Obtém a largura e a altura da janela. + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
JS: `WindowGetSize() : Size` + +### WindowSetMinSize + +Define o tamanho mínimo da janela. Será redimensionada a janela se a janela for atualmente menor do que as dimensões fornecidas. + +Definir um tamanho de `0,0` irá desativar esta restrição. + +Go: `WindowSetMinSize(ctx context.Context, width int, height int)`
JS: `WindowSetMinSize(width: number, height: number)` + +### WindowSetMaxSize + +Define o tamanho máximo da janela. Será redimensionada a janela se a janela for atualmente maior do que as dimensões fornecidas. + +Definir um tamanho de `0,0` irá desativar esta restrição. + +Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### WindowSetAlwaysOnTop + +Define a janela sempreOnTop ou não no topo. + +Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
JS: `WindowSetAlwaysOnTop(b: Boolen)` + +### WindowSetPosition + +Define a posição da janela em relação ao monitor da janela ativada. + +Go: `WindowSetPosition(ctx context.Context, x int, y int)`
JS: `WindowSetPosition(x: number, y: number)` + +### WindowGetPosition + +Obtém a posição da janela em relação ao monitor que a janela está ativada. + +Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
JS: `WindowGetPosition() : Position` + +### WindowMaximise + +Maximiza a janela para preencher a tela. + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise + +Restaurar a janela para as dimensões e a posição antes de maximizar. + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised + +Retorna verdadeiro se a janela for maximizada. + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise + +Alterna entre Maximizado e Não Maximizado. + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise + +Minimiza a janela. + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise + +Restaura a janela para as dimensões e a posição antes de minimizar. + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised + +Retorna verdadeiro se a janela estiver minimizada. + +Go: `WindowIsMinimised(ctx context.Context) bool`
JS: `WindowIsMinimised() bool` + +### WindowSetBackgroundColour + +Define a cor de fundo da janela para a definição de cores RGBA fornecida. Esta cor será exibida para todos os pixels transparentes. + +Valores válidos para R, G, B e A são 0-255. + +:::info Windows + +No Windows, apenas valores alfa de 0 ou 255 são suportados. Qualquer valor que não for 0 será considerado 255. + +::: + +Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +Opens tha native print dialog. + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## TypeScript Object Definitions + +### Position + +```ts +interface Position { + x: number; + y: number; +} +``` + +### Size + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..1af16f7745a --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# Dogs API + +```mdx-code-block +
+ +
+
+``` + +:::note + +This tutorial has been kindly provided by [@tatadan](https://twitter.com/tatadan) and forms part of their [Wails Examples Repository](https://github.com/tataDan/wails-v2-examples). + +::: + +In this tutorial we are going to develop an application that retrieves photos of dogs from the web and then displays them. + +### Create the project + +Let's create the application. From a terminal enter: `wails init -n dogs-api -t svelte` + +Note: We could optionally add `-ide vscode` or `-ide goland` to the end of this command if you wanted to add IDE support. + +Now let's `cd dogs-api` and start editing the project files. + +### Remove unused code + +We will start by removing some elements that we know we will not use: + +- Open `app.go` and remove the following lines: + +```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) +} +``` + +- Open `frontend/src/App.svelte` and delete all lines. +- Delete the `frontend/src/assets/images/logo-universal.png` file + +### Creating our application + +Now let's add our new Go code. + +Add the following struct declarations to `app.go` before the function definitions: + +```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 +} +``` + +Add the following functions to `app.go` (perhaps after the existing function definitions): + +```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 +} +``` + +Modify the `import` section of `app.go` to look like this: + +```go +import ( + "context" + "fmt" + "encoding/json" + "io/ioutil" + "log" + "net/http" + "sort" +) +``` + +Add the following lines to `frontend/src/App.svelte`: + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### Testing the application + +To generate the bindings and test the application, run `wails dev`. + +### Compiling the application + +To compile the application to a single, production grade binary, run `wails build`. diff --git a/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..ea350890049 --- /dev/null +++ b/website/i18n/pt/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +sidebar_position: 10 +--- + +# Hello World + +The aim of this tutorial is to get you up and running with the most basic application using Wails. You will be able to: + +- Create a new Wails application +- Build the application +- Run the application + +:::note + +This tutorial uses Windows as the target platform. Output will vary slightly depending on your operating system. + +::: + +## Create a new Wails application + +To create a new Wails application using the default vanilla JS template, you need to run the following command: + +```bash +wails init -n helloworld +``` + +You should see something similar to the following: + +``` +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. +``` + +This will create a new directory called `helloworld` in the current directory. In this directory, you will find a number of files: + +``` +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 +``` + +## Build the application + +To build the application, change to the new `helloworld` project directory and run the following command: + +```bash +wails build +``` + +You should see something like the following: + +``` +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 +Devtools: false +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. +``` + +This has compiled the application and saved it in the `build/bin` directory. + +## Run the application + +If we view the `build/bin` directory in Windows Explorer, we should see our project binary: + +```mdx-code-block +
+ +
+
+``` + +We can run it by simply double-clicking the `helloworld.exe` file. + +On Mac, Wails generates a `helloworld.app` file which can be run by double-clicking it. + +On Linux, you can run the application using `./helloworld` from the `build/bin` directory. + +You should see the application working as expected: + +```mdx-code-block +
+ +
+
+``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..64c3f23b5ca --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +sidebar_position: 2 +--- + +# Ссылки + +Эта страница служит списком ссылок на сообщество. Пожалуйста, отправьте PR (нажмите `Редактировать эту страницу` внизу) для отправки ссылок. + +## Awesome Wails + +[Полный список](https://github.com/wailsapp/awesome-wails) ссылок, связанных с Wails. + +## Каналы поддержки + +- [Wails Discord Server](https://discord.gg/JDdSxwjhGf) +- [Github Issues](https://github.com/wailsapp/wails/issues) +- [v2 Beta Discussion Board](https://github.com/wailsapp/wails/discussions/828) + +## Социальные сети + +- [Twitter](https://twitter.com/wailsapp) +- [Wails группа в QQ китайского сообщества](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - Номер группы: 1067173054 + +## Другие руководства и статьи + +- [Создание доски объявлений](https://blog.customct.com/building-bulletin-board) diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..37be75135ed --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +The [BulletinBoard](https://github.com/raguay/BulletinBoard) application is a versital message board for static messages or dialogs to get information from the user for a script. It has a TUI for creating new dialogs that can latter be used to get information from the user. It's design is to stay running on your system and show the information as needed and then hide away. I have a process for watching a file on my system and sending the contents to BulletinBoard when changed. It works great with my workflows. There is also an [Alfred workflow](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow) for sending information to the program. The workflow is also for working with [EmailIt](https://github.com/raguay/EmailIt). diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..430f02c8327 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,41 @@ +# CFN Tracker + +```mdx-code-block +

+ +
+

+``` + +[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) — отслеживайте +живые матчи любого профиля Street Fighter 6 или V CFN. Чтобы начать, посетите +[веб-сайт](https://cfn.williamsjokvist.se/). + +## Функции + +- Отслеживание матчей в режиме реального времени +- Хранение журналов матчей и статистики +- Поддержка отображения статистики в реальном времени в OBS через источник + браузера. +- Поддержка как SF6, так и SFV. +- Возможность для пользователей создавать свои собственные темы браузера OBS с + помощью CSS. + +### Основные технологии, используемые вместе с Wails + +- [Задача](https://github.com/go-task/task) - перенос Wails CLI для упрощения + использования общих команд. +- [React](https://github.com/facebook/react) — выбран из-за богатой экосистемы + (radix,framer-motion) +- [Bun](https://github.com/oven-sh/bun) – используется для быстрого разрешения + зависимостей и времени сборки. +- [Rod](https://github.com/go-rod/rod) – автономная автоматизация браузера для + аутентификации и опроса изменений. +- [SQLite](https://github.com/mattn/go-sqlite3) - используется для хранения + совпадений, сессий и профилей. +- [Server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) + – http-поток для отправки обновлений отслеживания в источники браузера OBS. +- [i18next](https://github.com/i18next/) - с бэкэнд-коннектором для обслуживания + объектов локализации из слоя Go. +- [xstate](https://github.com/statelyai/xstate) — конечные автоматы для процесса + аутентификации и отслеживания. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..c1817b70fff --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[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 scripts terminal to run scripts in EmailIt on files in your system. The scripts and templates can be used from the commandline itself or with the Alfred, Keyboard Maestro, Dropzone, or PopClip extensions. It also supports scripts and themes downloaded form GitHub. Documentation is not complete, but the programs works. It’s built using Wails2 and Svelte, and the download is a universal macOS application. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..a03cc9bedc6 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[EncryptEasy](https://www.encrypteasy.app) - это простой и простой в использовании PGP инструмент шифрования, управления вашими ключами и ключами ваших контактов. Шифрование не должно быть сложным процессом для пользователя. Разработано на Wails.** + +Шифрование сообщений с помощью PGP является стандартом отрасли. У каждого есть приватный и публичный ключ. Ваш приватный ключ должен оставаться в секрете, для того, чтобы только вы могли читать сообщения. Ваш публичный ключ передается всем, кто хочет отправлять вам секретные и зашифрованные сообщения. Управление ключами, шифрованием сообщений и расшифровкой сообщений должно бесперебойно работать. EncryptEasy - это то, что позволяет сделать это с лёгкостью. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..0fc168d6300 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[ESP Studio](https://github.com/torabian/esp-studio) - Кроссплатформенное, настольное, облачное и встроенное программное обеспечение +для управления устройствами ESP/Arduino и построения сложных рабочих процессов и систем управления IOT. \ No newline at end of file diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..22b6d90816e --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# FileHound утилита для экспорта данных + +```mdx-code-block +

+ +
+

+``` + +[FileHound утилита для экспорта данных](https://www.filehound.co.uk/) FileHound это облачная платформа управления документами для безопасного сохранения файлов, автоматизации бизнес-процессов и SmartCapture возможностей. + +Утилита экспорта данных из FileHound позволяет администраторам запустить безопасное извлечение документов и данных для альтернативного варианта создания бэкапов и восстановления данных. Это приложение загруит все документы и/или метаданные, сохраненные в FileHound основываясь на выбранных фильтрах. Метадата будет извлечена в форматах XML и JSON. + +Бэкенд: Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2 + +Frontend with: Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6 diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..87e5837d32f --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter) is a simple and efficient http API testing client tool. Based on Wails, Go and sveltejs. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..b79e123cab4 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Minecraft Updater + +```mdx-code-block +

+ +
+

+``` + +[Minecraft Updater](https://github.com/Gurkengewuerz/MinecraftModUpdater) — утилита для обновления и синхронизации Minecraft модов для вашей пользовательской базы. Она построена с помощью Wails2 и React с [antd](https://ant.design/) в качестве фронтенд фреймворка. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..ed470b8bd55 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Modal File Manager + +```mdx-code-block +

+ +
+

+``` + +[Modal File Manager](https://github.com/raguay/ModalFileManager) — это двухпанельный файловый менеджер с использованием веб-технологий. Мой оригинальный дизайн был основан на NW.js, и его можно найти [здесь](https://github.com/raguay/ModalFileManager-NWjs). В этой версии используется тот же код интерфейса Svelte (но с момента выхода из NW.), но бэкенд - это реализация [Wails 2](https://wails.io/). By using this implementation, I no longer use command line `rm`, `cp`, etc. commands, but a git install has to be on the system to download themes and extensions. Он полностью закодирован с помощью Go и работает гораздо быстрее, чем предыдущие версии. + +Этот файловый менеджер построен вокруг того же принципа, что и Vim: управление состоянием клавиатурных действий. Количество состояний не фиксировано, но очень программируется. Поэтому может быть создано и использовано бесконечное количество конфигураций клавиатуры. Это главное отличие от других файловых менеджеров. There are themes and extensions available to download from GitHub. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..2795fc6241c --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[Molly Wallet](https://github.com/grvlle/constellation_wallet/) официальный кошелек $DAG сети Constellation. Это позволит пользователям взаимодействовать с Hypergraph Network различными способами, не ограничиваясь $DAG транзакциями. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..b9dbea1f888 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[October](https://october.utf9k.net) - это небольшая программа Wails, которая позволяет извлечь выделения из [Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader) и затем переслать их в [Readwise](https://readwise.io). + +Он обладает относительно небольшим охватом со всеми версиями платформы, весом менее 10 МБ, и это без включения [UPX сжатия](https://upx.github.io/)! + +В отличие от этого, предыдущие попытки автора с Electron быстро вылились в несколько сот мегабайт. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..24a41cbd6cd --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# Optimus + +```mdx-code-block +

+ +
+

+``` + +[Optimus](https://github.com/splode/optimus) - приложение для оптимизации изображений. Он поддерживает конвертацию и сжатие изображений между форматами WebP, JPEG и PNG. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..1a9fa1eb7d5 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# Portfall + +```mdx-code-block +

+ +
+

+``` + +[Portfall](https://github.com/rekon-oss/portfall) - Портпад k8s портал для перенаправления портов для легкого доступа ко всем интерфейсам кластера diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..5461ccf1af5 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[Restic-Browser](https://github.com/emuell/restic-browser) - Простой кросс-платформенный интерфейс для [restic](https://github.com/restic/restic) для просмотра и восстановления оставшихся репозиториев. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..1b234072e13 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +Простой, безопасный и бесплатный обмен файлами для всех. Узнайте больше на [Riftshare.app](https://riftshare.app) + +## Возможности + +- Легкий обмен файлами между компьютерами как в локальной сети, так и через Интернет +- Поддерживает безопасную отправку файлов или директорий через [magic wormhole протокол](https://magic-wormhole.readthedocs.io/en/latest/) +- Совместимо со всеми приложениями, использующими magic wormhole (magic-wormhole или wormhole-william CLI, wormhole-gui и т. д.) +- Автоматическое сжатие нескольких выбранных файлов для одновременной отправки +- Полная анимация, индикатор прогресса и поддержка отмены для отправки и получения +- Нативное окно выбора файла +- Открытие файлов в один клик после получения +- Автоматическое обновление - не беспокойтесь о получении последней версии! diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..a512448fe40 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp) is a program to show the output of scripts or [Node-Red](https://nodered.org) server. It runs scripts defined in EmailIt program and shows the output. Scripts from xBar or TextBar can be used, but currently on the TextBar scripts work well. Он также отображает вывод скриптов в вашей системе. ScriptBar не помещает их в меню, но все они в удобном окне для удобного просмотра. Вы можете открыть несколько вкладок, чтобы показать множество различных вещей. Вы также можете держать ссылки на наиболее посещаемые вами веб-сайты. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..8f77bfb8a14 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[Surge](https://getsurge.io/) это p2p приложение для обмена файлов, разработанное для использования блокчейн технологий для 100% анонимной передачи файлов. Surge зашифрован сквозным шифрованием, децентрализован и с открытым исходным кодом. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..1d112481d06 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[Wally](https://ergodox-ez.com/pages/wally) это официальное приложение для прошивки [Ergodox](https://ergodox-ez.com/) клавиатур. Это великолепный и фантастический пример того, чего вы можете достичь с помощью Wails: возможности сочетать мощь Go и богатые графические инструменты мира веб-разработки. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..950dc3f3db1 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# Minecraft launcher for WarMine + +```mdx-code-block +

+ + +
+

+``` + +[Minecraft launcher for WarMine](https://warmine.ru/) is a Wails application, that allows you to easily join modded game servers and manage your game accounts. + +The Launcher downloads the game files, checks their integrity and launches the game with a wide range of customization options for the launch arguments from the backend. + +Frontend is written in Svelte, whole launcher fits in 9MB and supports Windows 7-11. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..f526142ec28 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# Wombat + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat) - это кроссплатформенный клиент gRPC. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..15be62e01e2 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails) это приложение для скачивания треков с youtube, создания оффлайн плейлистов и обмена ими с друзьями, ваши друзья смогут воспроизвести ваши плейлисты или загрузить их для оффлайн прослушивания, имеет встроенный плеер. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..0b86bb8d9bd --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +--- + +# Шаблоны + +Эта страница служит списком шаблонов, поддерживаемых сообществом. Пожалуйста, отправьте PR (нажмите `Изменить эту страницу` внизу) чтобы включить ваши шаблоны. Чтобы создать свой собственный шаблон, см. [руководство по шаблонам](../guides/templates.mdx). + +Чтобы использовать эти шаблоны, запустите `wails init -n "Название вашего проекта" -t [ссылка ниже[@version]]` + +Если нет суффикса версии, по умолчанию используется основной шаблон кода ветки. При наличии суффикса версии используется кодовый шаблон, соответствующий тегу этой версии. + +Пример: `wails init -n "Project Name" -t https://github.com/misitebao/wails-template-vue` + +::warning Внимание + +**Проект Wails не поддерживает и не несет ответственности за сторонние шаблоны!** + +Если вы не уверены в шаблоне, проверьте `package.json` и `wails.json` на какие скрипты запускаются и какие пакеты установлены. + +::: + +## Vue + +- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - шаблон, основанный на Vue ecology (ИнтегрированTypeScript, Темная тема, интернационализация, маршрутизация для одной страницы, TailwindCSS) +- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Vue 3 TypeScript с Vite (и инструкции для добавления функций) +- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vue 3 TypeScript с Vite, Vuex, Vue Router, Sass, и ESLint + Prettier +- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - A template using JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier) +- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - A template using TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, Composition API with <script setup>) +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Wails template based on Naive UI (A Vue 3 Component Library) + +## Angular + +- [wails-template-angular](https://github.com/mateothegreat/wails-template-angular) - Angular 15+ action packed & ready to roll to production. +- [wails-угловый-template](https://github.com/TAINCER/wails-angular-template) - Angular с TypeScript, Sass, Hot-Reload, Code-Splitting и i18n + +## React + +- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - Шаблон с использованием reactjs +- [wails-react-template](https://github.com/flin7/wails-react-template) - минимальный шаблон для React, который поддерживает живую разработку +- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - шаблон с использованием Next.js и TypeScript +- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - шаблон для React + TypeScript + Vite + TailwindCSS +- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - A template with Vite, React, TypeScript, TailwindCSS, and shadcn/ui + +## Svelte + +- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - шаблон с использованием Svelte +- [wails-vite-template](https://github.com/BillBuilt/wails-vite-svelte-template) - шаблон с использованием Svelte и Vite +- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - шаблон с использованием Svelte и Vite с TailwindCSS v3 +- [wails-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - An updated template using Svelte v4.2.0 and Vite with TailwindCSS v3.3.3 +- [wails-sveltekit-template](https://github.com/h8gi/wails-sveltekit-template) - шаблон с использованием SvelteKit + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - A template using Solid + Ts + Vite +- [wails-template-vite-solid-js](https://github.com/xijaja/wails-template-solid-js) - A template using Solid + Js + Vite + +## Elm + +- [wails-elm-шаблон](https://github.com/benjamin-thomas/wails-elm-template) - Разработайте ваше GUI приложение с функциональным программированием и **snappy** настройками горячей перезагрузки :tada: :rocket: +- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - Объединение возможностей :muscle: Elm + Tailwind CSS + Wails! Поддерживается горячая перезагрузка. + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - Use a unique combination of pure htmx for interactivity plus templ for creating components and forms + +## Чистый JavaScript (Vanilla) + +- [wails-pure-js-шаблон](https://github.com/KiddoV/wails-pure-js-template) - шаблон, содержащий только базовый JavaScript, HTML и CSS diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..11122314cdc --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +sidebar_position: 6 +--- + +# Компиляция проекта + +Из каталога проекта запустите `wails build`. Это позволит скомпилировать ваш проект и сохранить готовый к выпуску бинарный файл в директории `build/bin`. + +Если вы запустите исполняемый файл, вы увидите приложение по умолчанию: + +```mdx-code-block +
+ +
+
+``` + +Для получения более подробной информации о параметрах компиляции обратитесь к [CLI Reference](../reference/cli.mdx#build). diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..e7c6351e782 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 5 +--- + +# Разработка вашего приложения + +Вы можете запустить ваше приложение в режиме разработки, выполнив `wails dev` в вашем каталоге проекта. Это сделает следующие вещи: + +- Соберет ваше приложение и запустит +- Bind your Go code to the frontend so it can be called from JavaScript +- С помощью [Vite](https://vitejs.dev/), будет наблюдать за изменениями в ваших Go файлах и пересобирать/перезапускать при изменении +- Устанавливает [веб-сервер](http://localhost:34115), который будет обслуживать ваше приложение через браузер. Это позволит вам использовать ваши любимые расширения браузера. Вы даже можете вызвать ваш Go-код из консоли + +Для начала запустите `wails dev` в каталоге проекта. Более подробную информацию об этом можно найти [здесь](../reference/cli.mdx#dev). + +Скоро: Инструкция diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..52b58fa7757 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 2 +--- + +# Создание проекта + +## Генерация проекта + +Теперь, когда CLI установлен, вы можете создать новый проект, используя команду `wails init`. + +Выберите Ваш любимый фреймворк: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Generate a Svelte project using JavaScript with:

+ + wails init -n myproject -t svelte + +If you would rather use TypeScript:
+ + wails init -n myproject -t svelte-ts + +
+ + Generate a React project using JavaScript with:

+ + wails init -n myproject -t react + +If you would rather use TypeScript:
+ + wails init -n myproject -t react-ts + +
+ + Generate a Vue project using JavaScript with:

+ + wails init -n myproject -t vue + +If you would rather use TypeScript:
+ + wails init -n myproject -t vue-ts + +
+ + Generate a Preact project using JavaScript with:

+ + wails init -n myproject -t preact + +If you would rather use TypeScript:
+ + wails init -n myproject -t preact-ts + +
+ + Generate a Lit project using JavaScript with:

+ + wails init -n myproject -t lit + +If you would rather use TypeScript:
+ + wails init -n myproject -t lit-ts + +
+ + Generate a Vanilla project using JavaScript with:

+ + wails init -n myproject -t vanilla + +If you would rather use TypeScript:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +Доступны также [шаблоны сообщества](../community/templates.mdx), которые предлагают различные возможности и фреймворки. + +Чтобы увидеть другие доступные опции, вы можете запустить `wails init -help`. Более подробную информацию можно найти в [CLI Reference](../reference/cli.mdx#init). + +## Структура проекта + +Проекты Wails имеют следующую структуру: + +``` +. +├── build/ +│ ├── appicon.png +│ ├── darwin/ +│ └── windows/ +├── frontend/ +├── go.mod +├── go.sum +├── main.go +└── wails.json +``` + +### Краткое описание структуры проекта + +- `/main.go` - основное приложение +- `/frontend/` - фронтенд файлы проекта +- `/build/` - директория сборки проекта +- `/build/appicon.png` - значок приложения +- `/build/darwin/` - файлы проекта для Mac +- `/build/windows/` - файлы проектов, специфичных для Windows +- `/wails.json` - Конфигурация проекта +- `/go.mod` - Go module файл +- `/go.sum` - Go module проверочная сумма + +Каталог `frontend` ничего не имеет специфического для Wails и может быть любым пользовательским проектом по вашему выбору. + +Каталог `build` используется в процессе сборки. Эти файлы можно обновить, чтобы настроить ваши сборки. Если удалить файлы из директории, они будут заново сгенерированы с версией по-умолчанию. + +Название модуля по умолчанию в `go.mod` - это "changeme". Вы должны изменить это на нечто более подходящее. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..b69ab2d4c76 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,90 @@ +--- +sidebar_position: 1 +--- + +# Инструкция по установке + +## Поддерживаемые платформы + +- Windows 10/11 AMD64/ARM64 +- MacOS 10.13+ AMD64 +- MacOS 11.0+ ARM64 +- Linux AMD64/ARM64 + +## Зависимости + +Wails имеет ряд общих зависимостей, которые необходимы перед установкой: + +- Go 1.18+ +- NPM (Node 15+) + +### Go + +Скачайте Go с [Go Downloads Page](https://go.dev/dl/). + +Убедитесь, что вы следуете официальным [Инструкциям по установке](https://go.dev/doc/install). Вам также нужно убедиться, что ваша переменная окружения `PATH` также включает путь к вашему каталогу `~/go/bin`. Перезапустите терминал и выполните следующие шаги: + +- Проверьте то, что Go установлен правильно: `go version` +- Проверьте "~/go/bin" в переменной PATH: `echo $PATH | grep go/bin` + +### NPM + +Загрузите NPM отсюда: [Node Downloads Page](https://nodejs.org/en/download/). Лучше использовать последнюю версию, так как это то, что мы её обычно тестируем. + +Запустите `npm --version` для проверки. + +## Зависимости платформы + +Вам также нужно установить специфичные для платформы зависимости: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Wails требует установки инструментов xcode command line tools. Их можно установить, + запустив xcode-select --install. + + + Wails требует установки WebView2. В некоторых установках Windows это уже установлено. Вы можете проверить используя команду wails doctor. + + + Linux requires the standard gcc build tools plus libgtk3 and libwebkit. Вместо того чтобы перечислять огромное количество команд для разных дистрибутивов, Wails может попробовать определить команды установки, специфичные для вашего дистрибутива. Запустите wails doctor после установки, чтобы узнать, как установить зависимости. Если ваш дистрибутив или менеджер пакетов не поддерживается, пожалуйста, обратитесь к руководству {" "} Добавление дистрибутива Linux. + + +``` + +## Необязательные зависимости + +- [UPX](https://upx.github.io/) для сжатия приложений. +- [NSIS](https://wails.io/docs/guides/windows-installer/) for generating Windows installers. + +## Установка Wails + +Выполните `go install github.com/wailsapp/wails/v2/cmd/wails@latest` для установки Wails CLI. + +Примечание: Если вы получите ошибку, похожую на эту: + +```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 +``` +пожалуйста, убедитесь, что у вас установлен Go 1.18+: +```shell +go version +``` + +## Проверка системы + +Запуск `wails doctor` проверит установлены ли у вас правильные зависимости. Если нет, то он покажет что не хватает, и покажет как исправить какие-либо проблемы. + +## Отсутствует команда `wails`? + +Если ваша система пишет, что команда `wails` отсутствует, удостоверьтесь, что вы корректно следовали инструкции по установке Go. Обычно это значит, что папка `go/bin`, находящаяся в домашней папке пользователя не добавлена в переменную окружения `PATH`. Обычно после изменения переменных окружения нужно переоткрыть командную строку, чтобы изменения применились в ней. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..4d56b65bba1 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# Angular + +Хотя у Wails нет шаблона с Angular, тем не менее Angular использовать возможно. + +## Режим разработчика + +Чтобы получить режим dev работы с Angular, вам нужно добавить следующие значения к `wails.json`: + +```json + "frontend:build": "npx ng build", + "frontend:install": "npm install", + "frontend:dev:watcher": "npx ng serve", + "frontend:dev:serverUrl": "http://localhost:4200", +``` \ No newline at end of file diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..f9e723fee41 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# Разработка приложения + +Нет жестких и быстрых правил для разработки приложений с помощью Wails, но есть некоторые основные принципы. + +## Application Setup + +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/). + +### Create React App + +The process for a Create-React-App project is slightly more complicated. In order to support live frontend reloading the following configuration needs to be added to your `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +The `frontend:dev:watcher` command will start the Create-React-App development server (hosted on port `3000` typically). The `frontend:dev:serverUrl` command then instructs Wails to serve assets from the development server when loading the frontend rather than from the build folder. In addition to the above, the `index.html` needs to be updated with the following: + +```html + + + + + +``` + +This is required as the watcher command that rebuilds the frontend prevents Wails from injecting the required scripts. This circumvents that issue by ensuring the scripts are always injected. With this configuration, `wails dev` can be run which will appropriately build the frontend and backend with hot-reloading enabled. Additionally, when accessing the application from a browser the React developer tools can now be used on a non-minified version of the application for straightforward debugging. Finally, for faster builds, `wails dev -s` can be run to skip the default building of the frontend by Wails as this is an unnecessary step. + +## 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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..975916524b4 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# Динамические ресурсы + +Если вы хотите загрузить или генерировать ресурсы для вашего фронтенда динамически, вы можете это сделать, используя опцию [AssetsHandler](../reference/options#assetshandler). AssetsHandler это общий `http.Handler`, который будет вызываться для любого запроса, не являющегося GET, на сервере ресурсов и для запросов GET, которые не могут быть обработаны из бандла ресурсов, поскольку файл не найден. + +Установив пользовательские AssetsHandler, вы можете предоставлять свои собственные ресурсы с помощью пользовательского ресурсного сервера. + +## Пример + +В нашем примере мы создадим простой обработчик ресурсов, который загрузит файлы с диска: + +```go title=main.go {17-36,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) + } +} +``` + +Когда мы запустим приложение в dev режиме, с помощью команды `wails dev`, мы увидим следующий вывод: + +``` +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler +Requesting file: favicon.ico +``` + +Как видите, обработчик ресурсов вызывается, когда стандартный сервер ресурсов не может предоставить файл `favicon.ico`. + +Если вы щелкните правой кнопкой мыши по окну приложения и выберите "Исследовать элемент" для вызова devtools, вы сможете протестировать эту функцию, введя в консоль следующую строку: + +``` +let response = await fetch('does-not-exist.txt'); +``` + +Это сгенерирует ошибку в devtools. Мы видим ошибку обработчика пользовательских ресурсов, которую мы ожидали увидеть: + +```mdx-code-block +

+ +

+``` + +Однако, если мы вызовем `go.mod`, мы увидим следующий вывод: + +```mdx-code-block +

+ +

+``` + +А так мы можем разместить изображение прямо на страницу. Если мы обновим шаблон по умолчанию и заменим изображение логотипа: + +```html + +``` + +на: + +```html + +``` + +Тогда мы увидим следующее: + +```mdx-code-block +

+ +

+``` + +:::warning + +Раскрытие структуры файловой системы таким образом сопряжено с рисками безопасности. Рекомендуется правильно управлять доступом к файловой системе. + +::: diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..1c7a661e794 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# Безрамочные приложения + +Wails поддерживает приложения, не имеющие рамок. Этого можно добиться, используя поле [frameless](../reference/options.mdx#frameless) в [опциях приложения](../reference/options.mdx#application-options). + +Wails предоставляет легкое решение для перемещения окна: любой HTML элемент имеющий стиль `--wails-draggable:drag` будет работать как "ручка для перетаскивания". Это свойство применяется для всех дочерних элементов. Если вам необходимо указать, что вложенный элемент не должен перестаскивать окно, то используйте атрибут '--wails-draggable:no-drag' на этом элементе. + +```html + + + + + + + +
+ + +
+
+ + + + +``` + +Для некоторых проектов использование CSS переменной может оказаться невозможным из-за динамических стилей. В этом случае вы можете использовать параметры `CSSDragProperty` и `CSSDragValue` в опциях приожения для определения свойства и значения, которые будут использоваться для указания перетаскиваемых областей: + +```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() { + // Создаем экземляр структуры приложения + app := NewApp() + + // Создаем приложение с опциями + 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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info Fullscreen + +Если вы разрешите приложению перейти в полноэкранный режим, функция перетаскивания будет отключена. + +::: diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..ac087ee4514 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# Frontend + +## Script Injection + +When Wails serves your `index.html`, by default, it will inject 2 script entries into the `` 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 + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### Overriding Default Script Injection + +To provide more flexibility to developers, there is a meta tag that may be used to customise this behaviour: + +```html + +``` + +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 + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..9319fbb2371 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# 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 +

+ +

+``` + +When generating a project using the `-ide vscode` flags, IDE files will be created alongside the other project files. Эти файлы помещаются в директорию `.vscode` и предоставляют правильную конфигурацию для отладки вашего приложения. + +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. + +::: diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..10750baaf09 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# Поддержка Linux + +## Обзор + +Wails предлагает поддержку Linux, но составить инструкции по установке для всех доступных дистрибутивов - это невыполнимая задача. Вместо этого Wails пытается определить, доступны ли пакеты для разработки через системный менеджер пакетов. В настоящее время мы поддерживаем следующие менеджеры пакетов: + +- apt +- dnf +- emerge +- eopkg +- nixpkgs +- pacman +- zypper + +## Добавление имен пакетов + +Может возникнуть ситуация, когда ваш дистрибутив использует один из поддерживаемых менеджеров пакетов, но имя пакета отличается от названия. Например, вы можете использовать производную от Ubuntu систему, но имя пакета для gtk может быть другим. Wails пытается найти правильный пакет, ища по списку имен пакетов. Список пакетов хранится в файле (packagemanager) в каталоге `v2/internal/system/packagemanager`. В нашем примере это `v2/internal/system/packagemanager/apt.go`. + +В этом файле список пакетов определяется методом `Packages()`: + +```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}, + }, + } +} +``` + +Предположим, что в нашем Linux-дистрибутиве `libgtk-3` упакован под именем `lib-gtk3-dev`. Мы могли бы добавить поддержку для этого, добавив следующую строку: + +```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}, + }, + } +} +``` + +## Добавление новых менеджеров пакетов + +Чтобы добавить новый менеджер пакетов, выполните следующие действия: + +- Создайте новый файл в `v2/internal/system/packagemanager` под названием `.go`, где `` это имя менеджера пакетов. +- Определите структуру, которая соответствует интерфейсу менеджера пакетов, определенному в `pm.go`: + +```go +type PackageManager interface { + Name() string + Packages() packagemap + PackageInstalled(*Package) (bool, error) + PackageAvailable(*Package) (bool, error) + InstallCommand(*Package) string +} +``` + +- `Name()` должен возвращать имя менеджера пакетов +- `Packages()` должен возвращать `packagemap`, который предоставляет имена файлов для зависимостей +- `PackageInstalled()` должен возвращать `true`, если данный пакет установлен +- `PackageAvailable()` должен возвращать `true`, если данный пакет не установлен, но доступен для установки +- `InstallCommand()` должен возвращать точную команду для установки данного пакета + +Взгляните на другие коды менеджеров пакетов, чтобы получить представление о том, как это работает. + +::info Помните + +Если вы добавите поддержку для нового менеджера пакетов, не забудьте также обновить эту страницу! + +::: diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..229c282bf55 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# 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) diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..4ba1f34c37d --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# 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 => ` + +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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..961595711c7 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# 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 + +#### 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. + +## 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. You will need to replace the Team ID and Application Name with the ones you registered above. + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +**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. + +#### 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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..dcf192d337f --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# 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/.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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..7123cbe6b60 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,191 @@ +# 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: + +

+ +| 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. | + +

diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..1655b380018 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# Клавиши мыши + +Время выполнения кода Wails перехватывает щелчки мыши для определения необходимости изменения размера окна или перемещения окна. Был задан вопрос о том, как определить, когда произошел клик мышки, потому что `window.onclick` не сообщит о кнопках мыши. Следующий код показывает, как обнаружить клики мышкой: + +```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 + } +} +``` + +Источник: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..8094a0324f1 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# Обфускация кода + +Wails поддерживает обфускацию вашего приложения с помощью [grable](https://github.com/burrowers/garble). + +Чтобы обфусцировать ваше приложение, вы можете добавить флаг `obfuscate` к команде `wails build`: + +```bash +wails build -obfuscated +``` + +Для изменения настроек обфускации, вы можете использовать флаг `garbleargs`: + +```bash +wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed" +``` + +These settings may be persisted in your [project config](../reference/project-config). + +## Как это работает + +При стандартной сборке, все привязанные методы доступны в фронтенде через переменную `window.go`. При вызове этих методов происходит вызов соответствущих методов в бекенде, для этого используется имя функции. При использовании обфускации, методы привязываются по ID, а не по имени. Привязки, сгенерированные в папке `wailsjs` используют эти ID для вызова метода в бекенде. + +:::note + +Чтобы убедиться, что ваше приложение будет работать в режиме обфускации, используйте сгенерированные в папке `wailsjs` привязки. + +::: + +## Example + +Импортирование метода "Greet" из биндинга: + +```js +import { Greet } from "../../wailsjs/go/main/App"; + +// snip +Greet("World"); +``` + +обеспечит корректную работу с включенным режимом обфускации, так как привязки будут сгенерированы заново, используя новый механизм вызова метода по ID. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..915633d0cea --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# Overscroll + +[Overscroll](https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior) - это "эффект отскоков", который иногда получается, когда вы прокручиваете за границы содержимого страницы. Это часто используется в мобильных приложениях. Это можно отключить с помощью CSS: + +```css +html { + height: 100%; + overflow: hidden; +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..acb1eb656d6 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,47 @@ +# Маршрутизация + +Маршрутизация - это популярный способ переключения шаблонов в приложении. Эта страница предлагает некоторые рекомендации о том, как это сделать. + +## Vue + +Рекомендуемый подход к маршрутизации в Vue — [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 + +Рекомендуемый подход к маршрутизации в Angular - [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/en/main/router-components/hash-router): + +```jsx +import { HashRouter } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..4c7cf45ba99 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# 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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +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 + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +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 + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +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). diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..4651c422ed1 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +This guide will go into: + +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. Minimal Installation Steps + +##### Install Wails for Svelte. + +- `wails init -n myapp -t svelte` + +##### Delete the svelte frontend. + +- Navigate into your newly created myapp folder. +- Delete the folder named "frontend" + +##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts. + +- `npm create svelte@latest frontend` + +##### Modify 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. + +##### Modify main.go. + +- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build` + +##### Install/remove dependencies using your favorite package manager. + +- Navigate into your "frontend" folder. +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Change adapter in svelte.config.js + +- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Put SvelteKit into SPA mode with prerendering. + +- 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` + +##### Test 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. + +## 2. Install Script + +##### 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. + +- 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` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Important Notes + +##### Server files will cause build failures. + +- \+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. + +##### The Wails runtime unloads with full page navigations! + +- Anything that causes full page navigations: `window.location.href = '//'` 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('//')` 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 `` of myapp/frontend/src/app.html + +``` + +... + + + +... + +``` + +See https://wails.io/docs/guides/frontend for more information. + +##### Inital data can be loaded and refreshed from +page.ts/+page.js to +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. + +##### Error Handling + +- 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. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Using Forms and handling functions + +- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `` +- 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: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..23e24c4c8dc --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# Templates + +Wails генерирует проекты из заранее созданных шаблонов. В v1 это было трудно поддерживать набор проектов, которые были подвержены устареванию. В v2 для расширения прав и возможностей сообщества добавлено несколько новых возможностей для шаблонов: + +- Возможность создания проектов из [удаленных шаблонов](../reference/cli.mdx#remote-templates) +- Инструменты, которые помогут создать собственные шаблоны + +## Создание шаблонов + +Для создания шаблона вы можете использовать команду `wails generate template`. Для создания шаблона по умолчанию запустите: + +`wails generate template -name mytemplate` + +Это создает каталог "mytemplate" с файлами по умолчанию: + +```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 +``` + +### Обзор шаблона + +Шаблон по умолчанию состоит из следующих файлов и директорий: + +| Имя файла / Каталог | Описание | +| ------------------- | ------------------------------------ | +| NEXTSTEPS.md | Инструкции по заполнению шаблона | +| README.md | README публикуемый с шаблоном | +| app.tmpl.go | `app.go` файл шаблона | +| frontend/ | Каталог, содержащий файлы интерфейса | +| go.mod.tmpl | `go.mod` файл шаблона | +| main.tmpl.go | `main.go` файл шаблона | +| template.json | Метаданные шаблона | +| wails.tmpl.json | `wails.json` файл шаблона | + +На данный момент желательно выполнить шаги в `NEXTSTEPS.md`. + +## Создать шаблон из существующего проекта + +Можно создать шаблон из существующего проекта фронтенда, передав путь к проекту при генерации шаблона. Теперь мы рассмотрим как создать шаблон Vue 3: + +- Установите vue cli: `npm install -g @vue/cli` +- Создайте проект по умолчанию: `vue create vue3-base` + - Выберите `Default (Vue 3) ([Vue 3] babel, eslint)` +- После создания проекта, выполните: + +```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... +``` + +- Шаблон теперь может быть настроен как указано в файле `NEXTSTEPS.md` +- Как только файлы будут готовы, их можно протестировать, запустив: `wails init -n my-vue3-project -t .\wails-vue3-template\` +- Для тестирования нового проекта выполните: `cd my-vue3-project` затем `wails build` +- Как только проект будет скомпилирован, запустите его: `.\build\bin\my-vue3-project.exe` +- У вас должно получиться полностью работающее приложение Vue3: + +```mdx-code-block +
+ +
+``` + +## Публикация шаблона + +Для публикации шаблона просто загрузите файлы на GitHub. Поощряется следующая лучшая практика: + +- Удалите любые нежелательные файлы и каталоги (например, `.git`) из вашей frontend директории +- Убедитесь, что `template.json` завершен, особенно `helpurl` +- Отправить файлы на GitHub +- Создайте PR на странице [Шаблоны сообщества](../community/templates.mdx) +- Расскажите о своем шаблоне на [Template Announcement](https://github.com/wailsapp/wails/discussions/825) форуме diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..1c3b6a9cc52 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# 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 +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +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 +

+ +

+``` + +it's likely that your application's `info.plist` is invalid. Update the file in `build/.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. + +## My application is not displaying the correct icon in Windows Explorer + +If your application is not displaying the correct icon, try deleting the hidden `IconCache.db` file located in the `C:\Users\<your username>\AppData\Local` directory. This will force Windows to rebuild the icon cache. + +Source: https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## 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 `` section of any new page you navigate to: + +```html + + + + +``` + +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 + +## My application won't compile on Mac + +If you are getting errors like this: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## 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. + +## Build process stuck on "Generating bindings" + +Bindings generation process runs your application in a special mode. If application, intentionally or unintentionally, contains an endless loop (i.e. not exiting after `wails.Run()` finished), this can lead to build process stuck on the stage of bindings generation. Please make sure your code exits properly. + +## Mac application flashes white at startup + +This is due to the default background of the webview being white. If you want to use the window background colour instead, you can make the webview background transparent using the following config: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..539c52ba582 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# Visual Studio Code + +Эта страница предназначена для разных советов и трюков при использовании Visual Studio Code с Wails. + +## Конфигурация Vetur + +Большое спасибо [@Lyimmi](https://github.com/Lyimmi) за этот совет. Изначально оставил сообщение [здесь](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349). + +Vetur - это популярный плагин для кода Visual Studio, который предоставляет подсветку синтаксиса и завершение кода для Vue проектов. При загрузке проекта Wails в VSCode, Ветур выбросит ошибку, ожидая найти проект фронтенда в корневом каталоге. Чтобы исправить это, можно сделать следующее: + +Создайте файл `vetur.config.js` в корне проекта. + +```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' + ] + } + ] +} +``` + +Затем настройте `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" + ] +} +``` +Это должно позволить теперь использовать Vetur как ожидалось. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..b332c5f1dc0 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# NSIS installer + +```mdx-code-block +

+ +
+

+``` + +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 + +Пакет `nsis` должен быть доступен через менеджер пакетов вашего дистрибутива. + +### 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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..821808c0b8d --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# 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. Browser +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. + +### Browser + +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). diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..44fa130cc74 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +sidebar_position: 20 +--- + +# How does it work? + +A Wails application is a standard Go application, with a webkit frontend. The Go part of the application consists of the application code and a runtime library that provides a number of useful operations, like controlling the application window. The frontend is a webkit window that will display the frontend assets. Also available to the frontend is a JavaScript version of the runtime library. Finally, it is possible to bind Go methods to the frontend, and these will appear as JavaScript methods that can be called, just as if they were local JavaScript methods. + +```mdx-code-block +
+ +
+``` + +## The Main Application + +### Overview + +The main application consists of a single call to `wails.Run()`. It accepts the application configuration which describes the size of the application window, the window title, what assets to use, etc. A basic application might look like this: + +```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) +} +``` + +### Options rundown + +This example has the following options set: + +- `Title` - The text that should appear in the window's title bar +- `Width` & `Height` - The dimensions of the window +- `Assets` - The application's frontend assets +- `OnStartup` - A callback for when the window is created and is about to start loading the frontend assets +- `OnShutdown` - A callback for when the application is about to quit +- `Bind` - A slice of struct instances that we wish to expose to the frontend + +A full list of application options can be found in the [Options Reference](reference/options). + +#### Assets + +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 {17,27} 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 {10-12} + //... + 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. + +## The Frontend + +### Overview + +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; +``` + +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; +``` + +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). + +### Calling runtime methods + +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. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..2900528aa8d --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +--- + +# Введение + +Wails - это проект, позволяющий писать настольные приложения с использованием Go и web технологий. + +Считайте, что это легкая и быстрая альтернатива Electron для Go. Вы можете легко создавать приложения с гибкостью и мощностью Go, в сочетании с богатым современным фронтендом. + +### Возможности + +- Нативные меню, диалоги, темы и прозрачность +- Поддержка Windows, macOS и linux +- Встроенные шаблоны для Svelte, React, Preact, Vue, Lit и Vanilla JS +- Easily call Go methods from JavaScript +- Automatic Go struct to TypeScript model generation +- Для Windows не требуется CGO или внешние DLL +- Горячая перезагрузка, используя мощь [Vite](https://vitejs.dev/) +- Мощный CLI для простого создания, сборки и упаковки приложений +- Богатая [runtime библиотека](/docs/reference/runtime/intro) +- Приложения, созданные с помощью Wails совместимы с Apple и Microsoft Store + +Например, varly - настольное приложение для MacOS и Windows, написанное с помощью Wails. Оно не только великолепно выглядит, но и использует системные меню и полупрозрачность - все, что можно ожидать от современного нативного приложения. + +```mdx-code-block +

+ +

+``` + +### Шаблоны для быстрого начала + +Wails поставляется с рядом предварительно настроенных шаблонов, которые позволяют вам быстро создать и запустить ваше приложение. Есть шаблоны для следующих фреймворков: Svelte, React, Vue, Preact, Lit и Vanilla. There are both JavaScript and TypeScript versions for each template. + +### Системные элементы + +Wails использует специально созданную библиотеку для обработки системных элементов, таких как окна, меню, диалоги и так далее, чтобы вы могли создавать хорошо выглядящие, богатые функционалом приложения. + +**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. На Windows это новая библиотека Microsoft Webview2, основанная на Chromium. + +### Go & JavaScript Interoperability + +Wails automatically makes your Go methods available to JavaScript, so you can call them by name from your frontend! It even generates TypeScript models for the structs used by your Go methods, so you can pass the same data structures between Go and JavaScript. + +### Библиотека среды выполнения + +Wails provides a runtime library, for both Go and JavaScript, that handles a lot of the things modern applications need, like Eventing, Logging, Dialogs, etc. + +### Опыт разработки в реальном времени + +#### Автоматическая пересборка + +Когда вы запускаете ваше приложение в режиме разработки, Wails будет собирать его, но читать ресурсы с диска. Он будет отслеживать любые изменения в вашем коде на Go и автоматически пересобирать и перезапускать приложение. + +#### Автоматическая перезагрузка + +Когда будут обнаружены изменения ресурсов вашего приложения, ваше запущенное приложение перезагрузится, почти сразу, отражая ваши изменения. + +#### Разрабатывайте приложение в браузере + +Если вы предпочитаете отладку и разработку в браузере, то Wails это умеет. Запущенное приложение также имеет веб-сервер, который запустит ваше приложение в любом, подключенном к нему, браузере. Он будет перезапускаться когда ресурсы на вашем диске изменятся. + +### Бинарные файлы, готовые к выпуску + +Когда вы готовы сделать финальную сборку вашего приложения, CLI соберет всё в один исполняемый файл со всеми ресурсами внутри. На Windows и MacOS есть возможность создать нативный установочный пакет для распространения. Ресурсы, используемые при упаковке (иконка, info.plist, файл manifest'а, и т.д.) являются частью вашего проекта и могут быть изменены, что даёт вам полный контроль над тем, как вы создаете приложение. + +### Инструментарий + +Wails CLI предоставляет легкий способ генерировать, собирать и упаковывать ваши приложения. Оно создаст иконки, соберет ваше приложение с оптимальными параметрами и создаст готовый для распространения исполняемый файл. Выберите из нескольких стартовых шаблонов для быстрого старта! diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..c7aea10a64d --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,240 @@ +--- +sidebar_position: 2 +--- + +# CLI + +The Wails CLI has a number of commands that are used for managing your projects. All commands are run in the following way: + +`wails ` + +## init + +`wails init` is used for generating projects. + +| Flag | Description | Default | +|:------------------ |:----------------------------------------------------------------------------------------------------------------------- |:-------------------:| +| -n "project name" | Name of the project. **Mandatory**. | | +| -d "project dir" | Project directory to create | Name of the project | +| -g | Initialise git repository | | +| -l | List available project templates | | +| -q | Suppress output to console | | +| -t "template name" | The project template to use. This can be the name of a default template or a URL to a remote template hosted on github. | vanilla | +| -ide | Generate IDE project files | | +| -f | Force build application | false | + +Example: `wails init -n test -d mytestproject -g -ide vscode -q` + +This will generate a a project called "test" in the "mytestproject" directory, initialise git, generate vscode project files and do so silently. + +More information on using IDEs with Wails can be found [here](../guides/ides.mdx). + +### Remote Templates + +Remote templates (hosted on GitHub) are supported and can be installed by using the template's project URL. + +Example: `wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]` + +A list of community maintained templates can be found [here](../community/templates.mdx) + +:::warning Attention + +**The Wails project does not maintain, is not responsible nor liable for 3rd party templates!** + +If you are unsure about a template, inspect `package.json` and `wails.json` for what scripts are run and what packages are installed. + +::: + +## build + +`wails build` is used for compiling your project to a production-ready binary. + +| Flag | Description | Default | +|:-------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:--------------------------------------------------------------------------------------------------------------------------------------------------- | +| -clean | Cleans the `build/bin` directory | | +| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go | +| -debug | Retains debug information in the application and shows the debug console. Allows the use of the devtools in the application window | | +| -devtools | Allows the use of the devtools in the application window in production (when -debug is not used). Ctrl/Cmd+Shift+F12 may be used to open the devtools window. *NOTE*: This option will make your application FAIL Mac appstore guidelines. Use for debugging only. | | +| -dryrun | Prints the build command without executing it | | +| -f | Force build application | | +| -garbleargs | Arguments to pass to garble | `-literals -tiny -seed=random` | +| -ldflags "flags" | Additional ldflags to pass to the compiler | | +| -m | Skip mod tidy before compile | | +| -nopackage | Do not package application | | +| -nocolour | Disable colour in output | | +| -nosyncgomod | Do not sync go.mod with the Wails version | | +| -nsis | Generate NSIS installer for Windows | | +| -o filename | Output filename | | +| -obfuscated | Obfuscate the application using [garble](https://github.com/burrowers/garble) | | +| -platform | Build for the given (comma delimited) [platforms](../reference/cli.mdx#platforms) eg. `windows/arm64`. Note, if you do not give the architecture, `runtime.GOARCH` is used. | platform = `GOOS` environment variable if given else `runtime.GOOS`.
arch = `GOARCH` envrionment variable if given else `runtime.GOARCH`. | +| -race | Build with Go's race detector | | +| -s | Skip building the frontend | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Build tags to pass to Go compiler. Must be quoted. Space or comma (but not both) separated | | +| -trimpath | Remove all file system paths from the resulting executable. | | +| -u | Updates your project's `go.mod` to use the same version of Wails as the CLI | | +| -upx | Compress final binary using "upx" | | +| -upxflags | Flags to pass to upx | | +| -v int | Verbosity level (0 - silent, 1 - default, 2 - verbose) | 1 | +| -webview2 | WebView2 installer strategy: download,embed,browser,error | download | +| -windowsconsole | Keep the console window for Windows builds | | + +For a detailed description of the `webview2` flag, please refer to the [Windows](../guides/windows.mdx) Guide. + +If you prefer to build using standard Go tooling, please consult the [Manual Builds](../guides/manual-builds.mdx) guide. + +Example: + +`wails build -clean -o myproject.exe` + +:::info + +On Mac, the application will be bundled with `Info.plist`, not `Info.dev.plist`. + +::: + +:::info UPX on Apple Silicon + +There are [issues](https://github.com/upx/upx/issues/446) with using UPX with Apple Silicon. + +::: + +:::info UPX on Windows + +Some Antivirus vendors false positively mark `upx` compressed binaries as virus, see [issue](https://github.com/upx/upx/issues/437). + +::: + +### Platforms + +Supported platforms are: + +| Platform | Description | +|:---------------- |:--------------------------------------------- | +| darwin | MacOS + architecture of build machine | +| darwin/amd64 | MacOS 10.13+ AMD64 | +| darwin/arm64 | MacOS 11.0+ ARM64 | +| darwin/universal | MacOS AMD64+ARM64 universal application | +| windows | Windows 10/11 + architecture of build machine | +| windows/amd64 | Windows 10/11 AMD64 | +| windows/arm64 | Windows 10/11 ARM64 | +| linux | Linux + architecture of build machine | +| linux/amd64 | Linux AMD64 | +| linux/arm64 | Linux ARM64 | + +## doctor + +`wails doctor` will run diagnostics to ensure that your system is ready for development. + +Example: + +``` +Wails CLI v2.0.0-beta + +Scanning system - Please wait (this may take a long time)...Done. + +System +------ +OS: Windows 10 Pro +Version: 2009 (Build: 19043) +ID: 21H1 +Go Version: go1.18 +Platform: windows +Architecture: amd64 + +Dependency Package Name Status Version +---------- ------------ ------ ------- +WebView2 N/A Installed 93.0.961.52 +npm N/A Installed 6.14.15 +*upx N/A Installed upx 3.96 + +* - Optional Dependency + +Diagnosis +--------- +Your system is ready for Wails development! + +``` + +## dev + +`wails dev` is used to run your application in a "live development" mode. This means: + +- The application's `go.mod` will be updated to use the same version of Wails as the CLI +- The application is compiled and run automatically +- A watcher is started and will trigger a rebuild of your dev app if it detects changes to your go files +- A webserver is started on `http://localhost:34115` which serves your application (not just frontend) over http. This allows you to use your favourite browser development extensions +- All application assets are loaded from disk. If they are changed, the application will automatically reload (not rebuild). All connected browsers will also reload +- A JS module is generated that provides the following: +- JavaScript wrappers of your Go methods with autogenerated JSDoc, providing code hinting +- TypeScript versions of your Go structs, that can be constructed and passed to your go methods +- A second JS module is generated that provides a wrapper + TS declaration for the runtime +- On macOS, it will bundle the application into a `.app` file and run it. It will use a `build/darwin/Info.dev.plist` for development. + +| Flag | Description | Default | +|:---------------------------- |:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:--------------------- | +| -appargs "args" | Arguments passed to the application in shell style | | +| -assetdir "./path/to/assets" | Serve assets from the given directory instead of using the provided asset FS | Value in `wails.json` | +| -browser | Opens a browser to `http://localhost:34115` on startup | | +| -compiler "compiler" | Use a different go compiler to build, eg go1.15beta1 | go | +| -debounce | The time to wait for reload after an asset change is detected | 100 (milliseconds) | +| -devserver "host:port" | The address to bind the wails dev server to | "localhost:34115" | +| -extensions | Extensions to trigger rebuilds (comma separated) | go | +| -forcebuild | Force build of application | | +| -frontenddevserverurl "url" | Use 3rd party dev server url to serve assets, EG Vite | "" | +| -ldflags "flags" | Additional ldflags to pass to the compiler | | +| -loglevel "loglevel" | Loglevel to use - Trace, Debug, Info, Warning, Error | Debug | +| -nocolour | Turn off colour cli output | false | +| -noreload | Disable automatic reload when assets change | | +| -nosyncgomod | Do not sync go.mod with the Wails version | false | +| -race | Build with Go's race detector | false | +| -reloaddirs | Additional directories to trigger reloads (comma separated) | Value in `wails.json` | +| -s | Skip building the frontend | false | +| -save | Saves the given `assetdir`, `reloaddirs`, `wailsjsdir`, `debounce`, `devserver` and `frontenddevserverurl` flags in `wails.json` to become the defaults for subsequent invocations. | | +| -skipbindings | Skip bindings generation | | +| -tags "extra tags" | Build tags to pass to compiler (quoted and space separated) | | +| -v | Verbosity level (0 - silent, 1 - standard, 2 - verbose) | 1 | +| -wailsjsdir | The directory to generate the generated Wails JS modules | Value in `wails.json` | + +Example: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +This command will do the following: + +- Build the application and run it (more details [here](../guides/manual-builds.mdx) +- Generate the Wails JS modules in `./frontend/src` +- Watch for updates to files in `./frontend/dist` and reload on any change +- Open a browser and connect to the application + +There is more information on using this feature with existing framework scripts [here](../guides/application-development.mdx#live-reloading). + +## generate + +### template + +Wails uses templates for project generation. The `wails generate template` command helps scaffold a template so that it may be used for generating projects. + +| Flag | Description | +|:---------------- |:------------------------------------------- | +| -name | The template name (Mandatory) | +| -frontend "path" | Path to frontend project to use in template | + +For more details on creating templates, consult the [Templates guide](../guides/templates.mdx). + +### module + +The `wails generate module` command allows you to manually generate the `wailsjs` directory for your application. + +## update + +`wails update` will update the version of the Wails CLI. + +| Flag | Description | +|:------------------ |:------------------------------------- | +| -pre | Update to latest pre-release version | +| -version "version" | Install a specific version of the CLI | + +## version + +`wails version` will simply output the current CLI version. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..ff9a2442281 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# Menus + +It is possible to add an application menu to Wails projects. This is achieved by defining a [Menu](#menu) struct and setting it in the [`Menu`](../reference/options.mdx#menu) application config, or by calling the runtime method [MenuSetApplicationMenu](../reference/runtime/menu.mdx#menusetapplicationmenu). + +An example of how to create a menu: + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +It is also possible to dynamically update the menu, by updating the menu struct and calling [MenuUpdateApplicationMenu](../reference/runtime/menu.mdx#menuupdateapplicationmenu). + +The example above uses helper methods, however it's possible to build the menu structs manually. + +## Menu + +A Menu is a collection of MenuItems: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +For the Application menu, each MenuItem represents a single menu such as "Edit". + +A simple helper method is provided for building menus: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +This makes the layout of the code more like that of a menu without the need to add the menu items manually after creating them. Alternatively, you can just create the menu items and add them to the menu manually. + +## MenuItem + +A MenuItem represents an item within a Menu. + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +// MenuItem represents a menu item contained in a menu +type MenuItem struct { + Label string + Role Role + Accelerator *keys.Accelerator + Type Type + Disabled bool + Hidden bool + Checked bool + SubMenu *Menu + Click Callback +} +``` + +| Field | Type | Notes | +| ----------- | ------------------------------------ | ------------------------------------------------------------- | +| Label | string | The menu text | +| Accelerator | [\*keys.Accelerator](#accelerator) | Key binding for this menu item | +| Type | [Type](#type) | Type of MenuItem | +| Disabled | bool | Disables the menu item | +| Hidden | bool | Hides this menu item | +| Checked | bool | Adds check to item (Checkbox & Radio types) | +| SubMenu | [\*Menu](#menu) | Sets the submenu | +| Click | [Callback](#callback) | Callback function when menu clicked | +| Role | string | Defines a [role](#role) for this menu item. Mac only for now. | + +### Accelerator + +Accelerators (sometimes called keyboard shortcuts) define a binding between a keystroke and a menu item. Wails defines an Accelerator as a combination or key + [Modifier](#modifier). They are available in the `"github.com/wailsapp/wails/v2/pkg/menu/keys"` package. + +Example: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines cmd+o on Mac and ctrl-o on Window/Linux + myShortcut := keys.CmdOrCtrl("o") +``` + +Keys are any single character on a keyboard with the exception of `+`, which is defined as `plus`. Some keys cannot be represented as characters so there are a set of named characters that may be used: + +| | | | | +|:-----------:|:-----:|:-----:|:---------:| +| `backspace` | `f1` | `f16` | `f31` | +| `tab` | `f2` | `f17` | `f32` | +| `return` | `f3` | `f18` | `f33` | +| `enter` | `f4` | `f19` | `f34` | +| `escape` | `f5` | `f20` | `f35` | +| `left` | `f6` | `f21` | `numlock` | +| `right` | `f7` | `f22` | | +| `up` | `f8` | `f23` | | +| `down` | `f9` | `f24` | | +| `space` | `f10` | `f25` | | +| `delete` | `f11` | `f36` | | +| `home` | `f12` | `f37` | | +| `end` | `f13` | `f38` | | +| `page up` | `f14` | `f39` | | +| `page down` | `f15` | `f30` | | + +Wails also supports parsing accelerators using the same syntax as Electron. This is useful for storing accelerators in config files. + +Example: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines cmd+o on Mac and ctrl-o on Window/Linux + myShortcut, err := keys.Parse("Ctrl+Option+A") +``` + +#### Modifier + +The following modifiers are keys that may be used in combination with the accelerator key: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" +const ( + // CmdOrCtrlKey represents Command on Mac and Control on other platforms + CmdOrCtrlKey Modifier = "cmdorctrl" + // OptionOrAltKey represents Option on Mac and Alt on other platforms + OptionOrAltKey Modifier = "optionoralt" + // ShiftKey represents the shift key on all systems + ShiftKey Modifier = "shift" + // ControlKey represents the control key on all systems + ControlKey Modifier = "ctrl" +) +``` + +A number of helper methods are available to create Accelerators using modifiers: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" +func CmdOrCtrl(key string) *Accelerator +func OptionOrAlt(key string) *Accelerator +func Shift(key string) *Accelerator +func Control(key string) *Accelerator +``` + +Modifiers can be combined using `keys.Combo(key string, modifier1 Modifier, modifier2 Modifier, rest ...Modifier)`: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu/keys" + // Defines "Ctrl+Option+A" on Mac and "Ctrl+Alt+A" on Window/Linux + myShortcut := keys.Combo("a", ControlKey, OptionOrAltKey) +``` + +### Type + +Each menu item must have a type and there are 5 types available: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +const ( + TextType Type = "Text" + SeparatorType Type = "Separator" + SubmenuType Type = "Submenu" + CheckboxType Type = "Checkbox" + RadioType Type = "Radio" +) +``` + +For convenience, helper methods are provided to quickly create a menu item: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func Text(label string, accelerator *keys.Accelerator, click Callback) *MenuItem +func Separator() *MenuItem +func Radio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func Checkbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func SubMenu(label string, menu *Menu) *Menu +``` + +You can also create menu items directly on a menu by using the "Add" helpers: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func (m *Menu) AddText(label string, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddSeparator() *MenuItem +func (m *Menu) AddRadio(label string, selected bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddCheckbox(label string, checked bool, accelerator *keys.Accelerator, click Callback) *MenuItem +func (m *Menu) AddSubMenu(label string, menu *Menu) *MenuI +``` + +A note on radio groups: A radio group is defined as a number of radio menu items that are next to each other in the menu. This means that you do not need to group items together as it is automatic. However, that also means you cannot have 2 radio groups next to each other - there must be a non-radio item between them. + +### Callback + +Each menu item may have a callback that is executed when the item is clicked: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +The function is given a `CallbackData` struct which indicates which menu item triggered the callback. This is useful when using radio groups that may share a callback. + +### Role + +:::info Roles + +Roles are currently supported on Mac only. + +::: + +A menu item may have a role, which is essentially a pre-defined menu item. We currently support the following roles: + +| Role | Description | +| ------------ | ------------------------------------------------------------------------ | +| AppMenuRole | The standard Mac application menu. Can be created using `menu.AppMenu()` | +| EditMenuRole | The standard Mac edit menu. Can be created using `menu.EditMenu()` | diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..46d1c071b60 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,853 @@ +--- +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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### Title + +The text shown in the window's title bar. + +Name: Title
Type: `string` + +### Width + +The initial width of the window. + +Name: Width
Type: `int`
Default: 1024. + +### Height + +The initial height of the window. + +Name: Height
Type: `int`
Default: 768 + +### DisableResize + +By default, the main window is resizable. Setting this to `true` will keep it a fixed size. + +Name: DisableResize
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
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
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
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
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
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
Type: `int` + +### StartHidden + +When set to `true`, the application will be hidden until [WindowShow](../reference/runtime/window.mdx#windowshow) is called. + +Name: StartHidden
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
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
Type: `*options.RGBA`
Default: white + +### AlwaysOnTop + +Indicates that the window should stay above other windows when losing focus. + +Name: AlwaysOnTop
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 | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +Name: AssetServer
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
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
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
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
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
Type: `logger.Logger`
Default: Logs to Stdout + +### LogLevel + +The default log level. More details about logging in the [Log Reference](../reference/runtime/log.mdx). + +Name: LogLevel
Type: `logger.LogLevel`
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
Type: `logger.LogLevel`
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
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
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
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
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
Type: `string` + +### CSSDragValue + +Indicates what value the `CSSDragProperty` style should have to drag the window. Default: `drag`. + +Name: CSSDragValue
Type: `string` + +### EnableDefaultContextMenu + +EnableDefaultContextMenu enables the browser's default context-menu in 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. + +When this option is enabled, by default the context-menu will only be shown for text contexts (where Cut/Copy/Paste is needed), to override this behavior, you can use the CSS property `--default-contextmenu` on any HTML element (including the `body`) with the following values : + +| CSS Style | Behavior | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--default-contextmenu: auto;` | (**default**) will show the default context menu only if :
contentEditable is true OR text has been selected OR element is input or textarea | +| `--default-contextmenu: show;` | will always show the default context menu | +| `--default-contextmenu: hide;` | will always hide the default context menu | + +This rule is inherited like any normal CSS rule, so nesting works as expected. + +:::note +This filtering functionality is only enabled in production, so in development and in debug build, the full context-menu is always available everywhere. +::: + +:::warning +This filtering functionality is NOT a security measure, the developer should expect that the full context-menu could be leaked anytime which could contain commands like (Download image, Reload, Save webpage), if this is a concern, the developer SHOULD NOT enable the default context-menu. +::: + + +Name: EnableDefaultContextMenu
Type: `bool` + +### EnableFraudulentWebsiteDetection + +EnableFraudulentWebsiteDetection enables scan services for fraudulent content, such as malware or phishing attempts. These services might send information from your app like URLs navigated to and possibly other content to cloud services of Apple and Microsoft. + +Name: EnableFraudulentWebsiteDetection
Type: `bool` + +### ZoomFactor + +Name: ZoomFactor
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
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
Type: `[]interface{}` + +### ErrorFormatter + +A function that determines how errors are formatted when returned by a JS-to-Go method call. The returned value will be marshalled as JSON. + +Name: ErrorFormatter
Type: `func (error) any` + +### Windows + +This defines [Windows specific options](#windows). + +Name: Windows
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
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
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
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
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
Type: `bool` + +#### WebviewUserDataPath + +This defines the path where the WebView2 stores the user data. If empty `%APPDATA%\[BinaryName.exe]` will be used. + +Name: WebviewUserDataPath
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
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
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
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
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
Type: `uint16` + +#### OnSuspend + +If set, this function will be called when Windows initiates a switch to low power mode (suspend/hibernate) + +Name: OnSuspend
Type: `func()` + +#### OnResume + +If set, this function will be called when Windows resumes from low power mode (suspend/hibernate) + +Name: OnResume
Type: `func()` + +#### WebviewGpuIsDisabled + +Setting this to `true` will disable GPU hardware acceleration for the webview. + +Name: WebviewGpuIsDisabled
Type: `bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +This defines [Mac specific options](#mac). + +Name: Mac
Type: `*mac.Options` + +#### TitleBar + +The TitleBar struct provides the ability to configure the look and feel of the title bar. + +Name: TitleBar
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
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
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
Type: `bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled u.Bool + FullscreenEnabled u.Bool +} +``` + +| Name | 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) | + +Example: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### 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
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 +
+ +
+
+``` + +When clicked, that will open an about message box: + +```mdx-code-block +
+ +
+
+``` + +### Linux + +This defines [Linux specific options](#linux). + +Name: Linux
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
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, don’t 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
Type: `bool` + +#### WebviewGpuPolicy + +This option is used for determining the webview's hardware acceleration policy. + +Name: WebviewGpuPolicy
Type: [`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
Default: `WebviewGpuPolicyAlways` + +##### WebviewGpuPolicy type + +| Value | Description | +| ------------------------ | -------------------------------------------------------------------- | +| WebviewGpuPolicyAlways | Hardware acceleration is always enabled | +| WebviewGpuPolicyOnDemand | Hardware acceleration is enabled/disabled as request by web contents | +| WebviewGpuPolicyNever | Hardware acceleration is always disabled | + +#### 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). + +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. + +Name: ProgramName
Type: string
+ +### Debug + +This defines [Debug specific options](#Debug) that apply to debug builds. + +Name: Debug
Type: `options.Debug` + +#### OpenInspectorOnStartup + +Setting this to `true` will open the WebInspector on startup of the application. + +Name: OpenInspectorOnStartup
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. +[^2]: This requires WebKit2GTK 2.40+ support and your app needs to be build with the build tag `webkit2_40` to activate support for this feature. This also bumps the minimum requirement of WebKit2GTK to 2.40 for your app. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..8e763502bcc --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,92 @@ +--- +sidebar_position: 5 +--- + +# Project Config + +The project config resides in the `wails.json` file in the project directory. The structure of the config is: + +```json5 +{ + // Project config version + "version": "", + // The project name + "name": "", + // Relative path to the directory containing the compiled assets, this is normally inferred and could be left empty + "assetdir": "", + // Additional directories to trigger reloads (comma separated), this is only used for some advanced asset configurations + "reloaddirs": "", + // The directory where the build files reside. Defaults to 'build' + "build:dir": "", + // Relative path to the frontend directory. Defaults to 'frontend' + "frontend:dir": "", + // The command to install node dependencies, run in the frontend directory - often `npm install` + "frontend:install": "", + // The command to build the assets, run in the frontend directory - often `npm run build` + "frontend:build": "", + // This command has been replaced by frontend:dev:build. If frontend:dev:build is not specified will falls back to this command. \nIf this command is also not specified will falls back to frontend:build + "frontend:dev": "", + // This command is the dev equivalent of frontend:build. If not specified falls back to frontend:dev + "frontend:dev:build": "", + // This command is the dev equivalent of frontend:install. If not specified falls back to frontend:install + "frontend:dev:install": "", + // This command is run in a separate process on `wails dev`. Useful for 3rd party watchers or starting 3d party dev servers + "frontend:dev:watcher": "", + // URL to a 3rd party dev server to be used to serve assets, EG Vite. \nIf this is set to 'auto' then the devServerUrl will be inferred from the Vite output + "frontend:dev:serverUrl": "", + // Relative path to the directory that the auto-generated JS modules will be created + "wailsjsdir": "", + // The name of the binary + "outputfilename": "", + // The default time the dev server waits to reload when it detects a change in assets + "debounceMS": 100, + // Address to bind the wails dev sever to. Default: localhost:34115 + "devServer": "", + // Arguments passed to the application in shell style when in dev mode + "appargs": "", + // Defines if build hooks should be run though they are defined for an OS other than the host OS. + "runNonNativeBuildHooks": false, + "preBuildHooks": { + // The command that will be executed before a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed before a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH". The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed before every build: ${platform} is replaced with the "GOOS/GOARCH". + "*/*": "" + }, + "postBuildHooks": { + // The command that will be executed after a build of the specified GOOS/GOARCH: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/GOARCH" hook is executed before the "GOOS/*" and "*/*" hook. + "GOOS/GOARCH": "", + // The command that will be executed after a build of the specified GOOS: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. The "GOOS/*" hook is executed before the "*/*" hook. + "GOOS/*": "", + // The command that will be executed after every build: ${platform} is replaced with the "GOOS/GOARCH" and ${bin} with the path to the compiled binary. + "*/*": "" + }, + // Data used to populate manifests and version info. + "info": { + // The company name. Default: [The project name] + "companyName": "", + // The product name. Default: [The project name] + "productName": "", + // The version of the product. Default: '1.0.0' + "productVersion": "", + // The copyright of the product. Default: 'Copyright.........' + "copyright": "", + // A short comment of the app. Default: 'Built using Wails (https://wails.app)' + "comments": "" + }, + // '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": "" +} +``` + +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). diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..f45c13c46a6 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +sidebar_position: 7 +--- + +# Браузер + +Эти методы относятся к системному браузеру. + +### BrowserOpenURL + +Открывает данный URL-адрес в системном браузере. + +Go: `BrowserOpenURL(ctx context.Context, url string)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..805f68ed917 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# Clipboard + +This part of the runtime provides access to the operating system's clipboard.
The current implementation only handles text. + +### ClipboardGetText + +This method reads the currently stored text from the clipboard. + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
Returns: a string (if the clipboard is empty an empty string will be returned) or an error. + +JS: `ClipboardGetText(): Promise`
Returns: a promise with a string result (if the clipboard is empty an empty string will be returned). + +### ClipboardSetText + +This method writes a text to the clipboard. + +Go: `ClipboardSetText(ctx context.Context, text string) error`
Returns: an error if there is any. + +JS: `ClipboardSetText(text: string): Promise`
Returns: a promise with true result if the text was successfully set on the clipboard, false otherwise. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..9b3e6cf145c --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +sidebar_position: 5 +--- + +# Dialog + +This part of the runtime provides access to native dialogs, such as File Selectors and Message boxes. + +:::info JavaScript + +Dialog is currently unsupported in the JS runtime. + +::: + +### OpenDirectoryDialog + +Opens a dialog that prompts the user to select a directory. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Returns: Selected directory (blank if the user cancelled) or an error + +### OpenFileDialog + +Opens a dialog that prompts the user to select a file. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +Returns: Selected file (blank if the user cancelled) or an error + +### OpenMultipleFilesDialog + +Opens a dialog that prompts the user to select multiple files. Can be customised using [OpenDialogOptions](#opendialogoptions). + +Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)` + +Returns: Selected files (nil if the user cancelled) or an error + +### SaveFileDialog + +Opens a dialog that prompts the user to select a filename for the purposes of saving. Can be customised using [SaveDialogOptions](#savedialogoptions). + +Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)` + +Returns: The selected file (blank if the user cancelled) or an error + +### MessageDialog + +Displays a message using a message dialog. Can be customised using [MessageDialogOptions](#messagedialogoptions). + +Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)` + +Returns: The text of the selected button or an error + +## Options + +### OpenDialogOptions + +```go +type OpenDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + ResolvesAliases bool + TreatPackagesAsDirectories bool +} +``` + +| Field | Description | Win | Mac | Lin | +| -------------------------- | ---------------------------------------------- | --- | --- | --- | +| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ | +| DefaultFilename | The default filename | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ | +| CanCreateDirectories | Allow user to create directories | | ✅ | | +| ResolvesAliases | If true, returns the file not the alias | | ✅ | | +| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | | + +### SaveDialogOptions + +```go +type SaveDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + TreatPackagesAsDirectories bool +} +``` + +| Field | Description | Win | Mac | Lin | +| -------------------------- | ---------------------------------------------- | --- | --- | --- | +| DefaultDirectory | The directory the dialog will show when opened | ✅ | ✅ | ✅ | +| DefaultFilename | The default filename | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | A list of file filters | ✅ | ✅ | ✅ | +| ShowHiddenFiles | Show files hidden by the system | | ✅ | ✅ | +| CanCreateDirectories | Allow user to create directories | | ✅ | | +| TreatPackagesAsDirectories | Allow navigating into packages | | ✅ | | + +### MessageDialogOptions + +```go +type MessageDialogOptions struct { + Type DialogType + Title string + Message string + Buttons []string + DefaultButton string + CancelButton string +} +``` + +| Field | Description | Win | Mac | Lin | +| ------------- | -------------------------------------------------------------------------- | -------------- | --- | --- | +| Type | The type of message dialog, eg question, info... | ✅ | ✅ | ✅ | +| Title | Title for the dialog | ✅ | ✅ | ✅ | +| Message | The message to show the user | ✅ | ✅ | ✅ | +| Buttons | A list of button titles | | ✅ | | +| DefaultButton | The button with this text should be treated as default. Bound to `return`. | ✅[*](#windows) | ✅ | | +| CancelButton | The button with this text should be treated as cancel. Bound to `escape` | | ✅ | | + +#### Windows + +Windows has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Abort", "Retry", "Ignore", "Yes", "No", "Try Again" or "Continue". + +For Question dialogs, the default button is "Yes" and the cancel button is "No". This can be changed by setting the `DefaultButton` value to `"No"`. + +Example: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linux has standard dialog types in which the buttons are not customisable. The value returned will be one of: "Ok", "Cancel", "Yes", "No" + +#### Mac + +A message dialog on Mac may specify up to 4 buttons. If no `DefaultButton` or `CancelButton` is given, the first button is considered default and is bound to the `return` key. + +For the following code: + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "It's your turn!", + Message: "Select a number", + Buttons: []string{"one", "two", "three", "four"}, +}) +``` + +the first button is shown as default: + +```mdx-code-block +
+ +
+
+``` + +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 +
+ +
+
+``` + +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 +
+ +
+
+
+
+``` + +#### 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 +
+ +
+
+
+
+``` + +#### 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 +
+ +
+
+
+
+``` + +#### Mac + +Mac dialogs only have the concept of a single set of patterns to filter files. If multiple FileFilters are provided, Wails will use all the Patterns defined. + +Example: + +```go + selection, err := runtime.OpenFileDialog(b.ctx, runtime.OpenDialogOptions{ + Title: "Select File", + Filters: []runtime.FileFilter{ + { + DisplayName: "Images (*.png;*.jpg)", + Pattern: "*.png;*.jpg", + }, { + DisplayName: "Videos (*.mov;*.mp4)", + Pattern: "*.mov;*.mp4", + }, + }, + }) +``` + +This will result in the Open File dialog using `*.png,*.jpg,*.mov,*.mp4` as a filter. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..856ba6f0c26 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +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()`
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)`
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()`
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()`
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{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..aae8efccccf --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# Introduction + +The runtime is a library that provides utility methods for your application. There is both a Go and JavaScript runtime and the aim is to try and keep them at parity where possible. + +It has utility methods for: + +- [Window](window.mdx) +- [Menu](menu.mdx) +- [Dialog](dialog.mdx) +- [Events](events.mdx) +- [Browser](browser.mdx) +- [Log](log.mdx) +- [Clipboard](clipboard.mdx) + +The Go Runtime is available through importing `github.com/wailsapp/wails/v2/pkg/runtime`. All methods in this package take a context as the first parameter. This context should be obtained from the [OnStartup](../options.mdx#onstartup) or [OnDomReady](../options.mdx#ondomready) hooks. + +:::info Note + +Whilst the context will be provided to the [OnStartup](../options.mdx#onstartup) method, there's no guarantee the runtime will work in this method as the window is initialising in a different thread. If you wish to call runtime methods at startup, use [OnDomReady](../options.mdx#ondomready). + +::: + +The JavaScript library is available to the frontend via the `window.runtime` map. There is a runtime package generated when using `dev` mode that provides TypeScript declarations for the runtime. This should be located in the `wailsjs` directory in your frontend directory. + +### Hide + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +Hides the application. + +:::info Note + +On Mac, this will hide the application in the same way as the `Hide` menu item in standard Mac applications. This is different to hiding the window, but the application still being in the foreground. For Windows and Linux, this is currently the same as `WindowHide`. + +::: + +### Show + +Shows the application. + +:::info Note + +On Mac, this will bring the application back into the foreground. For Windows and Linux, this is currently the same as `WindowShow`. + +::: + +Go: `Show(ctx context.Context)`
JS: `Show()` + +### Quit + +Quits the application. + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### Environment + +Returns details of the current environment. + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### EnvironmentInfo + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..06f0423b0a8 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# Log + +The Wails runtime provides a logging mechanism that may be called from Go or JavaScript. Like most loggers, there are a number of log levels: + +- Trace +- Debug +- Info +- Warning +- Error +- Fatal + +The logger will output any log message at the current, or higher, log level. Example: The `Debug` log level will output all messages except `Trace` messages. + +### LogPrint + +Logs the given message as a raw message. + +Go: `LogPrint(ctx context.Context, message string)`
JS: `LogPrint(message: string)` + +### LogPrintf + +Logs the given message as a raw message. + +Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`
+ +### LogTrace + +Logs the given message at the `Trace` log level. + +Go: `LogTrace(ctx context.Context, message string)`
JS: `LogTrace(message: string)` + +### LogTracef + +Logs the given message at the `Trace` log level. + +Go: `LogTracef(ctx context.Context, format string, args ...interface{})`
+ +### LogDebug + +Logs the given message at the `Debug` log level. + +Go: `LogDebug(ctx context.Context, message string)`
JS: `LogDebug(message: string)` + +### LogDebugf + +Logs the given message at the `Debug` log level. + +Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`
+ +### LogInfo + +Logs the given message at the `Info` log level. + +Go: `LogInfo(ctx context.Context, message string)`
JS: `LogInfo(message: string)` + +### LogInfof + +Logs the given message at the `Info` log level. + +Go: `LogInfof(ctx context.Context, format string, args ...interface{})`
+ +### LogWarning + +Logs the given message at the `Warning` log level. + +Go: `LogWarning(ctx context.Context, message string)`
JS: `LogWarning(message: string)` + +### LogWarningf + +Logs the given message at the `Warning` log level. + +Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`
+ +### LogError + +Logs the given message at the `Error` log level. + +Go: `LogError(ctx context.Context, message string)`
JS: `LogError(message: string)` + +### LogErrorf + +Logs the given message at the `Error` log level. + +Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`
+ +### LogFatal + +Logs the given message at the `Fatal` log level. + +Go: `LogFatal(ctx context.Context, message string)`
JS: `LogFatal(message: string)` + +### LogFatalf + +Logs the given message at the `Fatal` log level. + +Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`
+ +### LogSetLogLevel + +Sets the log level. In JavaScript, the number relates to the following log levels: + +| Value | Log Level | +| ----- | --------- | +| 1 | Trace | +| 2 | Debug | +| 3 | Info | +| 4 | Warning | +| 5 | Error | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
JS: `LogSetLogLevel(level: number)` + +## Using a Custom Logger + +A custom logger may be used by providing it using the [Logger](../options.mdx#logger) application option. The only requirement is that the logger implements the `logger.Logger` interface defined in `github.com/wailsapp/wails/v2/pkg/logger`: + +```go title="logger.go" +type Logger interface { + Print(message string) + Trace(message string) + Debug(message string) + Info(message string) + Warning(message string) + Error(message string) + Fatal(message string) +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..6b6ceb77d69 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +sidebar_position: 6 +--- + +# Меню + +Эти методы относятся к меню приложения. + +:::info JavaScript + +В настоящее время меню не поддерживается в JS. + +::: + +### MenuSetApplicationMenu + +Задает меню приложения для данного [меню](../menus.mdx). + +Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)` + +### MenuUpdateApplicationMenu + +Обновляет меню приложения, поднимая все изменения в меню, переданное `MenuSetationMenu`. + +Go: `MenuUpdateApplicationMenu(ctx context.Context)` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..457c92ebff9 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# Screen + +These methods provide information about the currently connected screens. + +### ScreenGetAll + +Returns a list of currently connected screens. + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### Screen + +Go struct: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript interface: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..15f555c5a79 --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +sidebar_position: 4 +--- + +# Window + +These methods give control of the application window. + +### WindowSetTitle + +Sets the text in the window title bar. + +Go: `WindowSetTitle(ctx context.Context, title string)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen + +Makes the window full screen. + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen + +Restores the previous window dimensions and position prior to full screen. + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen + +Returns true if the window is full screen. + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter + +Centers the window on the monitor the window is currently on. + +Go: `WindowCenter(ctx context.Context)`
JS: `WindowCenter()` + +### WindowExecJS + +Executes arbitrary JS code in the window. + +This method runs the code in the browser asynchronously and returns immediately. If the script causes any errors, they will only be available in the browser console. + +Go: `WindowExecJS(ctx context.Context, js string)` + +### WindowReload + +Performs a "reload" (Reloads current page). + +Go: `WindowReload(ctx context.Context)`
JS: `WindowReload()` + +### WindowReloadApp + +Reloads the application frontend. + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme + +Windows only. + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
JS: `WindowSetSystemDefaultTheme()` + +Sets window theme to system default (dark/light). + +### WindowSetLightTheme + +Windows only. + +Go: `WindowSetLightTheme(ctx context.Context)`
JS: `WindowSetLightTheme()` + +Sets window theme to light. + +### WindowSetDarkTheme + +Windows only. + +Go: `WindowSetDarkTheme(ctx context.Context)`
JS: `WindowSetDarkTheme()` + +Sets window theme to dark. + +### WindowShow + +Shows the window, if it is currently hidden. + +Go: `WindowShow(ctx context.Context)`
JS: `WindowShow()` + +### WindowHide + +Hides the window, if it is currently visible. + +Go: `WindowHide(ctx context.Context)`
JS: `WindowHide()` + +### WindowIsNormal + +Returns true if the window not minimised, maximised or fullscreen. + +Go: `WindowIsNormal(ctx context.Context) bool`
JS: `WindowIsNormal() bool` + +### WindowSetSize + +Sets the width and height of the window. + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize + +Gets the width and height of the window. + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
JS: `WindowGetSize() : Size` + +### WindowSetMinSize + +Sets the minimum window size. Will resize the window if the window is currently smaller than the given dimensions. + +Setting a size of `0,0` will disable this constraint. + +Go: `WindowSetMinSize(ctx context.Context, width int, height int)`
JS: `WindowSetMinSize(width: number, height: number)` + +### WindowSetMaxSize + +Sets the maximum window size. Will resize the window if the window is currently larger than the given dimensions. + +Setting a size of `0,0` will disable this constraint. + +Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### WindowSetAlwaysOnTop + +Sets the window AlwaysOnTop or not on top. + +Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
JS: `WindowSetAlwaysOnTop(b: Boolen)` + +### WindowSetPosition + +Sets the window position relative to the monitor the window is currently on. + +Go: `WindowSetPosition(ctx context.Context, x int, y int)`
JS: `WindowSetPosition(x: number, y: number)` + +### WindowGetPosition + +Gets the window position relative to the monitor the window is currently on. + +Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
JS: `WindowGetPosition() : Position` + +### WindowMaximise + +Maximises the window to fill the screen. + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise + +Restores the window to the dimensions and position prior to maximising. + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised + +Returns true if the window is maximised. + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise + +Toggles between Maximised and UnMaximised. + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise + +Minimises the window. + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise + +Restores the window to the dimensions and position prior to minimising. + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised + +Returns true if the window is minimised. + +Go: `WindowIsMinimised(ctx context.Context) bool`
JS: `WindowIsMinimised() bool` + +### WindowSetBackgroundColour + +Sets the background colour of the window to the given RGBA colour definition. This colour will show through for all transparent pixels. + +Valid values for R, G, B and A are 0-255. + +:::info Windows + +On Windows, only alpha values of 0 or 255 are supported. Any value that is not 0 will be considered 255. + +::: + +Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +Opens tha native print dialog. + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## TypeScript Object Definitions + +### Position + +```ts +interface Position { + x: number; + y: number; +} +``` + +### Size + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..1af16f7745a --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# Dogs API + +```mdx-code-block +
+ +
+
+``` + +:::note + +This tutorial has been kindly provided by [@tatadan](https://twitter.com/tatadan) and forms part of their [Wails Examples Repository](https://github.com/tataDan/wails-v2-examples). + +::: + +In this tutorial we are going to develop an application that retrieves photos of dogs from the web and then displays them. + +### Create the project + +Let's create the application. From a terminal enter: `wails init -n dogs-api -t svelte` + +Note: We could optionally add `-ide vscode` or `-ide goland` to the end of this command if you wanted to add IDE support. + +Now let's `cd dogs-api` and start editing the project files. + +### Remove unused code + +We will start by removing some elements that we know we will not use: + +- Open `app.go` and remove the following lines: + +```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) +} +``` + +- Open `frontend/src/App.svelte` and delete all lines. +- Delete the `frontend/src/assets/images/logo-universal.png` file + +### Creating our application + +Now let's add our new Go code. + +Add the following struct declarations to `app.go` before the function definitions: + +```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 +} +``` + +Add the following functions to `app.go` (perhaps after the existing function definitions): + +```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 +} +``` + +Modify the `import` section of `app.go` to look like this: + +```go +import ( + "context" + "fmt" + "encoding/json" + "io/ioutil" + "log" + "net/http" + "sort" +) +``` + +Add the following lines to `frontend/src/App.svelte`: + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### Testing the application + +To generate the bindings and test the application, run `wails dev`. + +### Compiling the application + +To compile the application to a single, production grade binary, run `wails build`. diff --git a/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..77d128b188c --- /dev/null +++ b/website/i18n/ru/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +sidebar_position: 10 +--- + +# Hello World + +Цель этого урока — запустить наиболее базовое приложение, использующее Wails. Вы сможете: + +- Создавать новое Wails приложение +- Собирать приложение +- Запускать приложение + +:::note + +В этом уроке в качестве целевой платформы используется Windows. Вывод будет варьироваться в зависимости от вашей операционной системы. + +::: + +## Создаем новое Wails приложение + +Чтобы создать новое Wails приложение, использующее стандартный шаблон JS, вам нужно выполнить следующую команду: + +```bash +wails init -n helloworld +``` + +Вы должны увидеть что-то похожее на следующее: + +``` +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. +``` + +Это создаст новый каталог под названием `helloworld` в текущей директории. В этом каталоге вы найдете несколько файлов: + +``` +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 +``` + +## Сборка приложения + +Чтобы собрать приложение, перейдите в новую директорию `helloworld` и запустите следующую команду: + +```bash +wails build +``` + +Вы должны увидеть что-то похожее на следующее: + +``` +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 +Devtools: false +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. +``` + +Приложение собрано и сохранено в папке `build/bin`. + +## Запуск приложения + +Если мы откроем папку `build/bin` в Проводнике, то увидим исполняемый файл проекта: + +```mdx-code-block +
+ +
+
+``` + +Мы можем запустить его, просто дважды щелкнув по файлу `helloworld.exe`. + +На Mac, Wails генерирует файл `helloworld.app` который может быть запущен двойным щелчком. + +На Linux вы можете запустить приложение с помощью файла `./helloworld` из папки `build/bin`. + +Вы должны видеть приложение, работающее так, как ожидалось: + +```mdx-code-block +
+ +
+
+``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json new file mode 100644 index 00000000000..1374f0d5518 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/appendix/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Runtime", + "position": 70 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json new file mode 100644 index 00000000000..9827bf0c0fb --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "社区", + "position": 50 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx new file mode 100644 index 00000000000..8f8a54fcb3d --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/links.mdx @@ -0,0 +1,26 @@ +--- +sidebar_position: 2 +--- + +# 链接 + +此页面用于列出社区相关的链接。 请提交 PR(点击页面底部的 `编辑此页`)增加链接。 + +## Awesome Wails + +Wails 相关的 [优秀列表](https://github.com/wailsapp/awesome-wails)。 + +## 支持的频道 + +- [Wails Discord 服务器](https://discord.gg/JDdSxwjhGf) +- [Github Issues](https://github.com/wailsapp/wails/issues) +- [v2 测试版讨论板](https://github.com/wailsapp/wails/discussions/828) + +## 社交媒体 + +- [Twitter](https://twitter.com/wailsapp) +- [Wails 中文社区 QQ 群](https://qm.qq.com/cgi-bin/qm/qr?k=PmIURne5hFGNd7QWzW5qd6FV-INEjNJv&jump_from=webapi) - 群号:1067173054 + +## 其他教程和文章 + +- [Building of Bulletin Board](https://blog.customct.com/building-bulletin-board) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json new file mode 100644 index 00000000000..276e283b71f --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Showcase", + "position": 1 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..2bba85cb82d --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +[BulletinBoard](https://github.com/raguay/BulletinBoard) 应用程序是一个用于静态消息或对话框的通用消息板,用于获取用户的脚本信息。 它有一个用于创建新对话框的 TUI,后者可以使用这些对话框从用户那里获取信息。 它的设计是在您的系统上保持运行并根据需要显示信息,然后隐藏起来。 我有一个在我的系统上监视文件并在更改时将内容发送到 BulletinBoard 的进程。 它与我的工作流配合的很好。 还有一个用于向程序发送信息的 [Alfred 工作流](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow)。 该工作流也适用于 [EmailIt](https://github.com/raguay/EmailIt)。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx new file mode 100644 index 00000000000..5e1597d70af --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/cfntracker.mdx @@ -0,0 +1,35 @@ +# CFN Tracker + +```mdx-code-block +

+ +
+

+``` + +[CFN Tracker](https://github.com/williamsjokvist/cfn-tracker) - 跟踪任何《街头霸 +王 6》或 V CFN 个人资料的实时比赛。 检查[网站](https://cfn.williamsjokvist.se/) +开始。 + +## 特征 + +- 实时比赛追踪 +- 存储比赛日志和统计数据 +- 支持通过浏览器源向 OBS 显示实时统计数据 +- 支持 SF6 和 SFV +- 用户能够使用 CSS 创建自己的 OBS 浏览器主题 + +### 与 Wails 一起使用的主要技术 + +- [Task](https://github.com/go-task/task) - 包装 Wails CLI 以使常用命令易于使用 +- [React](https://github.com/facebook/react) - 因其丰富的生态系统而被选中 + (radix、framer-motion) +- [Bun](https://github.com/oven-sh/bun) - 用于快速依赖解析和构建时间 +- [Rod](https://github.com/go-rod/rod) - 用于身份验证和轮询更改的无头浏览器自动 + 化 +- [SQLite](https://github.com/mattn/go-sqlite3) - 用于存储匹配、会话和配置文件 +- [服务器发送事件](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - + 用于向 OBS 浏览器源发送跟踪更新的 http 流 +- [i18next](https://github.com/i18next/) - 使用后端连接器来服务来自 Go 层的本地 + 化对象 +- [xstate](https://github.com/statelyai/xstate) - 用于身份验证过程和跟踪的状态机 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..701e96b5a95 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[EmailIt](https://github.com/raguay/EmailIt/) 是一个 Wails v2 程序,它是一个基于 Markdown 的电子邮件发送器,只有九个记事本、用于处理文本的脚本和模板。 它还有一个脚本终端,用于在 EmailIt 中对系统中的文件运行脚本。 脚本和模板可以从命令行本身使用,也可以与 Alfred、Keyboard Maestro、Dropzone 或 PopClip 扩展一起使用。 它还支持从 GitHub 下载的脚本和主题。 文档不完整,但程序有效。 它是使用 Wails v2 和 Svelte 构建的,下载的是一个通用的 macOS 应用程序。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx new file mode 100644 index 00000000000..df788c69cbd --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/encrypteasy.mdx @@ -0,0 +1,12 @@ +# EncryptEasy + +```mdx-code-block +

+ +
+

+``` + +**[EncryptEasy](https://www.encrypteasy.app) 是一个简单易用的 PGP 加密工具,管理您和您的所有联系人密钥。 加密应该很简单。 使用 Wails 开发。** + +使用 PGP 加密消息是行业标准。 每个人都有私钥和公钥。 您的私钥需要保密,因此只有您可以阅读消息。 您的公钥会分发给任何想向您发送秘密加密消息的人。 管理密钥、加密消息和解密消息应该是一种流畅的体验。 EncryptEasy 就是要让它变得简单。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx new file mode 100644 index 00000000000..43f3289181e --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/espstudio.mdx @@ -0,0 +1,13 @@ +# ESP Studio + +```mdx-code-block +

+ +
+

+``` + +[ESP Studio](https://github.com/torabian/esp-studio) - 跨平台、桌面、云和嵌入式软件 +用于控制 ESP/Arduino 设备,以及构建复杂的物联网工作流程和控制系统 \ No newline at end of file diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx new file mode 100644 index 00000000000..a0566cccf7a --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/filehound.mdx @@ -0,0 +1,16 @@ +# FileHound Export Utility + +```mdx-code-block +

+ +
+

+``` + +[FileHound Export Utility](https://www.filehound.co.uk/) FileHound 是一个云文档管理平台,用于安全文件保留、业务流程自动化和 SmartCapture 功能。 + +FileHound Export Utility 允许 FileHound 管理员运行安全文档和数据提取任务以备选备份和恢复目的。 此应用程序将根据您选择的过滤器下载保存在 FileHound 中的所有文档和/或元数据。 元数据将以 JSON 和 XML 格式导出。 + +后端构建使用:Go 1.15 Wails 1.11.0 go-sqlite3 1.14.6 go-linq 3.2 + +前端使用:Vue 2.6.11 Vuex 3.4.0 TypeScript Tailwind 1.9.6 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx new file mode 100644 index 00000000000..61153563564 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/hiposter.mdx @@ -0,0 +1,10 @@ +# hiposter + +```mdx-code-block +

+ +
+

+``` + +[hiposter](https://github.com/obity/hiposter) 是一个简单高效的 HTTP API 测试客户端工具。 基于 Wails、Go 和 sveltejs。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx new file mode 100644 index 00000000000..f5552ed5ad7 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/minecraftupdater.mdx @@ -0,0 +1,14 @@ +# Minecraft Updater + +```mdx-code-block +

+ +
+

+``` + +[Minecraft Updater](https://github.com/Gurkengewuerz/MinecraftModUpdater) 是一个可以为你的用户更新和同步 Minecraft 模组的实用工具。 它使用 Wails2 和 React 构建,采用 [antd](https://ant.design/) 作为前端框架。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx new file mode 100644 index 00000000000..634ef3329bb --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/modalfilemanager.mdx @@ -0,0 +1,14 @@ +# Modal File Manager + +```mdx-code-block +

+ +
+

+``` + +[Modal File Manager](https://github.com/raguay/ModalFileManager) 是一个使用网络技术的双面板文件管理器。 我最初的设计是基于 NW.js 的,可以在 [这里](https://github.com/raguay/ModalFileManager-NWjs) 找到。 此版本使用相同的基于 Svelte 的前端代码(但自从 NW.js 脱离以来已进行了很大修改),但后端是 [Wails v2](https://wails.io/) 实现。 通过使用这个实现,我不再使用命令行 `rm`、`cp` 等命令,而是必须在系统上安装 git 才能下载主题和扩展。 它完全使用 Go 编码,运行速度比以前的版本快得多。 + +这个文件管理器是围绕与 Vim 相同的原则设计的:状态控制键盘操作。 状态的数量不是固定的,但非常可编程。 因此,可以创建和使用无数种键盘配置。 这是与其他文件管理器的主要区别。 可以从 GitHub 下载主题和扩展。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx new file mode 100644 index 00000000000..1df94bb1139 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/mollywallet.mdx @@ -0,0 +1,10 @@ +# Molley Wallet + +```mdx-code-block +

+ +
+

+``` + +[Molly Wallet](https://github.com/grvlle/constellation_wallet/) 是 Constellation 网络的官方 $DAG 钱包。 它允许用户以各种方式与 Hypergraph 网络进行交互,而不仅仅是产生 $DAG 交易。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..861e8d43c2b --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[October](https://october.utf9k.net) 是一个小型的 Wails 应用程序,它可以非常容易地从 [Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader) 中提取精彩片段,然后将它们转发到 [Readwise](https://readwise.io) 。 + +它的代码规模相对较小,所有平台版本的大小都不到10 MB ,而且这还是在没有启用 [UPX 压缩](https://upx.github.io/) 的情况下! + +相比之下,作者之前尝试使用 Electron 很快就膨胀到了几百兆字节。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx new file mode 100644 index 00000000000..baea5ba9218 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/optimus.mdx @@ -0,0 +1,10 @@ +# Optimus + +```mdx-code-block +

+ +
+

+``` + +[Optimus](https://github.com/splode/optimus) 是一款桌面图像优化应用程序。 它支持 WebP、JPEG 和 PNG 图像格式之间的转换和压缩。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx new file mode 100644 index 00000000000..40180200bef --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/portfall.mdx @@ -0,0 +1,10 @@ +# Portfall + +```mdx-code-block +

+ +
+

+``` + +[Portfall](https://github.com/rekon-oss/portfall) - 桌面 k8s 端口转发门户,可轻松访问你的所有集群 UI 。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..a7f07f4f5b6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[Restic-Browser](https://github.com/emuell/restic-browser) - 一个简单的、跨平台的 [restic](https://github.com/restic/restic) 备份 GUI ,用于浏览和恢复 restic 存储库。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..29514c8e5ba --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +为每个人提供简单、安全和免费的文件共享。 请访问 [Riftshare.app](https://riftshare.app) 了解更多信息。 + +## 功能 + +- 可以在本地网络和互联网之间轻松安全地共享文件 +- 支持通过 [魔法虫洞(magic-wormhole)](https://magic-wormhole.readthedocs.io/en/latest/) 安全地发送文件或目录 +- 与所有其他使用魔法虫洞(magic-wormhole)的应用程序兼容( magic-wormhole 或 wormhole-william CLI,wormhole-gui 等。) +- 自动压缩多个选定文件以便一次性发送 +- 发送和接收的完整动画、进度条和取消支持 +- 原生的操作系统文件选择功能 +- 接收文件后一键打开 +- 自动更新 - 不用担心有最新的版本! diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..85409d3c7bd --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp) 是一个用于显示脚本或 [Node-Red](https://nodered.org) 服务器输出的程序。 它运行 EmailIt 程序中定义的脚本,并显示输出结果。 可以使用来自 xBar 或 TextBar 的脚本,但目前只有 TextBar 的脚本运行良好。 它还可以显示你系统中的脚本输出。 ScriptBar 并没有把它们放在菜单栏中,而是提供一个方便的窗口,方便用户查看。 你可以使用多个标签页来显示不同的内容。 还可以保留访问次数最多的网站链接。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..67e0930beeb --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[Surge](https://getsurge.io/) 是一个 P2P 文件共享应用程序,旨在利用区块链技术实现100%匿名文件传输。 Surge 是端到端加密的、去中心化的以及开源的。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..349b8ce215e --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[Wally](https://ergodox-ez.com/pages/wally) 是 [Ergodox](https://ergodox-ez.com/) 键盘的官方固件刷写程序。 它看起来很不错,并且是一个使用 Wails 实现的绝妙示例:结合了 Go 语言的强大功能和 Web 开发世界丰富的图形工具。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx new file mode 100644 index 00000000000..1172a8c3366 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/warmine.mdx @@ -0,0 +1,19 @@ +# WarMine Minecraft 启动器 + +```mdx-code-block +

+ + +
+

+``` + +[Warmine Minecraft 启动器](https://warmine.ru/) 是一款 Wails 应用,它使您可以轻松地加入服务器并管理您的游戏账户。 + +启动器能够下载游戏文件, 检查游戏的完整性,使用自定义选项从后端启动游戏。 + +前端使用 Svelte 编写, 整个启动器大小约 9MB 并支持 Windows 7-11. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx new file mode 100644 index 00000000000..d8d74d360ad --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/wombat.mdx @@ -0,0 +1,10 @@ +# Wombat + +```mdx-code-block +

+ +
+

+``` + +[Wombat](https://github.com/rogchap/wombat) 是一个跨平台的 gRPC 客户端。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..12cefd304f5 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails) 是一款可以从 YouTube 下载音乐,创建离线播放列表并与朋友分享的应用程序。你的朋友们可以播放你的播放列表或将其下载到本地离线收听,并且该应用程序还内置了播放器。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx new file mode 100644 index 00000000000..fb487e87c79 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/community/templates.mdx @@ -0,0 +1,69 @@ +--- +sidebar_position: 1 +--- + +# 模板 + +此页面用作社区支持的模板列表。 请提交一个包含您的模板的 PR(点击页面底部的 `编辑此页`)。 要构建您自己的模板,请参考 [模板](../guides/templates) 指南。 + +要使用这些模板,请运行 `wails init -n "您的项目名" -t [下面的链接[@版本]]` + +如果不带版本后缀,默认使用的是主分支代码模板。 如果带有版本后缀,则使用该版本对应标签的代码模板。 + +示例:`wails init -n "Your Project Name" -t https://github.com/misitebao/wails-template-vue` + +:::warning 注意 + +**Wails 项目不维护也不对第 3 方模板负责** + +如果您不确定某个模板,请检查 `package.json` 和 `wails.json` 中安装的模块和运行的脚本。 + +::: + +## Vue + +- [wails-template-vue](https://github.com/misitebao/wails-template-vue) - 基于 Vue 生态的 Wails 模板(集成 TypeScript、黑暗主题、国际化、单页路由、TailwindCSS) +- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - 使用 Vite 的 Vue 3 TypeScript(以及添加功能的说明) +- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - 使用 Vite, Vuex, Vue Router, Sass, 和 ESLint + Prettier 的 Vue 3 TypeScript +- [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - 使用 JavaScript + Quasar V2(Vue 3, Vite, Sass, Pinia, ESLint, Prettier)的模板 +- [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - 使用 TypeScript + Quasar V2(Vue 3、Vite、Sass、Pinia、ESLint、Prettier、带 <script setup> 的Composition API)的模板 +- [wails-template-naive](https://github.com/tk103331/wails-template-naive) - 基于 Naive UI(一款 Vue 3 组件库)的 Wails 模板 + +## Angular + +- [wails-template-angular](https://github.com/mateothegreat/wails-template-angular) - Angular 15+ 已打包并准备投入生产。 +- [wails-angular-template](https://github.com/TAINCER/wails-angular-template) - 带有 TypeScript, Sass, 热重载, 代码拆分和 i18n 的 Angular + +## React + +- [wails-react-template](https://github.com/AlienRecall/wails-react-template) - 基于 reactjs 的模板 +- [wails-react-template](https://github.com/flin7/wails-react-template) - 基于 React 并支持实时开发模式的轻量级模板 +- [wails-vite-react-ts](https://github.com/lontten/wails-vite-react-ts) - 基于 Vite + React + TypeScript 的模板 +- [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - 一个 React + TypeScript + Vite + TailwindCSS 模板 +- [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - A template with Vite, React, TypeScript, TailwindCSS, and shadcn/ui + +## Svelte + +- [wails-svelte-template](https://github.com/raitonoberu/wails-svelte-template) - 基于 Svelte 的模板 +- [wails-vite-svelte-template](https://github.com/BillBuilt/wails-vite-svelte-template) - 使用 Svelte 和 Vite 的模板 +- [wails-vite-svelte-tailwind-template](https://github.com/BillBuilt/wails-vite-svelte-tailwind-template) - 使用 Svelte 和 Vite 和 TailwindCSS v3 的模板 +- [wails-svelte-tailwind-vite-template](https://github.com/PylotLight/wails-vite-svelte-tailwind-template/tree/master) - An updated template using Svelte v4.2.0 and Vite with TailwindCSS v3.3.3 +- [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - 基于 Next.js + TypeScript 的模板 + +## Solid + +- [wails-template-vite-solid-ts](https://github.com/xijaja/wails-template-solid-ts) - 使用 Solid + Ts + Vite 的模版。 +- [wails-template-vite-solid-js](https://github.com/xijaja/wails-template-solid-js) - 使用 Solid + Js + Vite 的模版。 + +## Elm + +- [wails-elm-template](https://github.com/benjamin-thomas/wails-elm-template) - 使用函数式编程和 **快速** 的热重载设置开发您的 GUI 应用程序 :tada: :rocket: +- [wails-template-elm-tailwind](https://github.com/rnice01/wails-template-elm-tailwind) - 结合 Elm + Tailwind CSS + Wails 的力量 :muscle: ! 支持热重载。 + +## HTMX + +- [wails-htmx-templ-chi-tailwind](https://github.com/PylotLight/wails-hmtx-templ-template) - Use a unique combination of pure htmx for interactivity plus templ for creating components and forms + +## 纯 JavaScript (Vanilla) + +- [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - 一个只有基本 JavaScript、HTML 和 CSS 的模板 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/developing-new-features.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/developing-new-features.mdx new file mode 100644 index 00000000000..9fc9025bd4b --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/developing-new-features.mdx @@ -0,0 +1,34 @@ +--- +sidebar_position: 20 +--- + +# 开发新功能 + +We are always keen to add features to Wails and expand on what the project can do. The process for adding new features are as follows: The process for adding new features are as follows: We are always keen to add features to Wails and expand on what the project can do. The process for adding new features are as follows: The process for adding new features are as follows: The process for adding new features are as follows: + +- Pick an enhancement ticket with the "TODO" label. Pick an enhancement ticket with the "TODO" label. Pick an enhancement ticket with the "TODO" label. It's preferable to select one from the current [Backlog](https://github.com/orgs/wailsapp/projects/1/views/1) but the choice is yours. +- Before developing, check that the ticket includes the following information: +- The purpose of the enhancement +- What is out of scope for the enhancement +- What platforms the enhancement targets (most features should be cross-platform unless there's a very specific reason) +- If the ticket does not include this information, feel free to request the information from the person who opened the ticket. Sometimes placeholder tickets are created and require more details Sometimes placeholder tickets are created and require more details Sometimes placeholder tickets are created and require more details +- Comment on the ticket stating you wish to develop the feature +- Clone the repository and create a branch with the format `feature/_` +- New features often require documentation so please ensure you have also added or updated the documentation as part of the changes +- Once the feature is ready for testing, create a draft PR. Once the feature is ready for testing, create a draft PR. Once the feature is ready for testing, create a draft PR. Please ensure the PR description has the test scenarios and test cases listed with checkmarks, so that others can know what still needs to be tested. Once the feature is ready for testing, create a draft PR. Once the feature is ready for testing, create a draft PR. Please ensure the PR description has the test scenarios and test cases listed with checkmarks, so that others can know what still needs to be tested. Once the feature is ready for testing, create a draft PR. Once the feature is ready for testing, create a draft PR. Please ensure the PR description has the test scenarios and test cases listed with checkmarks, so that others can know what still needs to be tested. +- Once all the testing is completed, please update the status of the PR from draft and leave a message. + +:::note +There is nothing stopping you from opening a ticket and working on it yourself, but please be aware that all +enhancement requests are reviewed for good fit. Not all ideas will be selected so it's best to have discussion +on the ticket first. +::: Not all ideas will be selected so it's best to have discussion +on the ticket first. +::: Not all ideas will be selected so it's best to have discussion +on the ticket first. +::: + +:::warning +Any PRs opened without a corresponding ticket may be rejected. +::: ::: +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/documenting.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/documenting.mdx new file mode 100644 index 00000000000..84e47290358 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/documenting.mdx @@ -0,0 +1,34 @@ +--- +sidebar_position: 40 +--- + +# 文档 + +This website is also the main documentation site for the project. Sometimes this gets out of date and needs some slight adjustments. Some of the documentation isn't written to the best standards either. Developing documentation is hard and so any contribution to this is greatly appreciated. Features without documentation are unfinished so to the project, it's _as important_ as the code. + +We generally do not create tickets for updating documentation so if there is text you think should be updated or rephrased then feel free to submit a PR for that. This site is in the main repository under the `website` directory. We use [Docusaurus](https://docusaurus.io/) to create the site so there is plenty of existing documentation and tutorials around to get started. This site is in the main repository under the `website` directory. We use [Docusaurus](https://docusaurus.io/) to create the site so there is plenty of existing documentation and tutorials around to get started. This site is in the main repository under the `website` directory. We use [Docusaurus](https://docusaurus.io/) to create the site so there is plenty of existing documentation and tutorials around to get started. + +To set up a local documentation development environment, do the following: + +- [Install npm](https://docs.npmjs.com/cli/v8/configuring-npm/install) +- `cd website` +- `npm install` +- `npm run start` + +After it has all installed and is running, you should see the site at [`http://localhost:3000`](http://localhost:3000). Any changes made to the site text will be immediately reflected in the browser. Any changes made to the site text will be immediately reflected in the browser. Any changes made to the site text will be immediately reflected in the browser. + +## Versioning + +We employ a versioning system where we have the "latest" documentation AKA "Next Version" which has all the changes that have occurred since the last release. We also keep the last release documentation as well as the version before that. We also keep the last release documentation as well as the version before that. We also keep the last release documentation as well as the version before that. + +There isn't usually a reason to update released documentation so we don't generally update the documents in the `versioned_docs` or `versioned_sidebars` directories. + +The "next version" docs are mainly in `website/docs` with some "version independent" documents in `src/pages`. Any updates should be made in the `website/docs` directory. Any updates should be made in the `website/docs` directory. Any updates should be made in the `website/docs` directory. + +## Languages + +The default documents of the Wails project are English documents. We use the "crowdin" tool to translate documents in other languages and synchronize them to the website. You can [join our project](https://crowdin.com/project/wails) and submit your translations to make contributions. + +### Add new language + +If you want to add a new language to the documentation, please follow the prompts to [fill in and submit an Issue](https://github.com/wailsapp/wails/issues/new?assignees=&labels=documentation&template=documentation.yml). After being confirmed by the maintainer, we will add the language to the "crowdin" and you will then be able to submit your translation. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/fixing-bugs.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/fixing-bugs.mdx new file mode 100644 index 00000000000..01eceeccd17 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/fixing-bugs.mdx @@ -0,0 +1,29 @@ +--- +sidebar_position: 30 +--- + +# 修复漏洞 + +The process for fixing bugs are as follows: + +- Check the current [Backlog](https://github.com/orgs/wailsapp/projects/1/views/1) and select a bug to fix +- Before developing, check that the ticket includes the following information: +- The scope of the issue including platforms affected +- The steps to reproduce. The steps to reproduce. The steps to reproduce. Sometimes bugs are opened that are not Wails issues and the onus is on the reporter to prove that it is a Wails issue with a minimal reproducible example +- The output of `wails doctor` +- If the ticket does not include this information, feel free to request the information from the person who opened the ticket. +- Comment on the ticket stating you wish to develop a fix +- Clone the repository and create a branch with the format `bugfix/_` +- Once the fix is ready for testing, create a draft PR. Once the fix is ready for testing, create a draft PR. Please ensure the PR description has the test scenarios and test cases listed with checkmarks, so that others can know what still needs to be tested. Once the fix is ready for testing, create a draft PR. Please ensure the PR description has the test scenarios and test cases listed with checkmarks, so that others can know what still needs to be tested. +- Once all the testing is completed, please update the status of the PR from draft and leave a message. + +:::note +There is nothing stopping you from opening a ticket and working on it yourself, but please be aware that all +bugfixes should be discussed as the approach may have unintended side effects. +::: ::: +::: + +:::warning +Any PRs opened without a corresponding ticket may be rejected. +::: ::: +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/setting-up-a-dev-environment.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/setting-up-a-dev-environment.mdx new file mode 100644 index 00000000000..1133e275dec --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/setting-up-a-dev-environment.mdx @@ -0,0 +1,30 @@ +--- +sidebar_position: 10 +--- + +# 设置开发环境 + +You can set up a development environment by doing the following: + +- Install the latest versions of Go and Git +- `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. + +To update projects to use the latest version, update the project's `go.mod` and ensure the following line is at the bottom of the file: + +`replace github.com/wailsapp/wails/v2 => ` + +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 back to a stable version, run: + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/ways-of-contributing.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/ways-of-contributing.mdx new file mode 100644 index 00000000000..3bbe9a889a0 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/contributing/ways-of-contributing.mdx @@ -0,0 +1,18 @@ +--- +sidebar_position: 1 +--- + +# 贡献方式 + +Wails is an open source, community driven project. We welcome anyone to join us in contributing to the project. This documentation is aimed at anyone wishing to get familiar with the project and the development processes. We welcome anyone to join us in contributing to the project. This documentation is aimed at anyone wishing to get familiar with the project and the development processes. + +There are many ways to contribute to the project: + +- Developing new features +- Fixing bugs +- Testing +- Documenting features +- Writing tutorials / guides +- Helping others on the issues + discussions boards + +Guides for these have been created in their own sections. Guides for these have been created in their own sections. Guides for these have been created in their own sections. Before getting started, please introduce yourself in the [Contributing to Wails](https://github.com/wailsapp/wails/discussions/1520) discussion. diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json new file mode 100644 index 00000000000..597b920dff9 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Getting Started", + "position": 10 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx new file mode 100644 index 00000000000..c4fe879bc4c --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/building.mdx @@ -0,0 +1,22 @@ +--- +sidebar_position: 6 +--- + +# 编译您的项目 + +从项目目录,运行 `wails build`。 这将编译您的项目并将构建的可用于生产的二进制文件保存在 `build/bin` 目录中。 + +如果您运行二进制文件,您应该会看到默认应用程序: + +```mdx-code-block +
+ +
+
+``` + +有关编译选项的更多详细信息,请参阅 [构建命令](../reference/cli#构建)。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx new file mode 100644 index 00000000000..a9020bc38d6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/development.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 5 +--- + +# 开发您的应用程序 + +您可以通过从项目目录运行 `wails dev` 在开发模式下运行您的应用程序。 这将执行以下操作: + +- 构建您的应用程序并运行它 +- 将您的 Go 代码绑定到前端,以便可以从 JavaScript 调用它 +- 使用 [Vite](https://vitejs.dev/) 的强大功能,将监视您的 Go 文件中的修改并在更改时重新构建/重新运行 +- 启动一个 [网络服务器](http://localhost:34115) 通过浏览器为您的应用程序提供服务。 这使您可以使用自己喜欢的浏览器扩展。 你甚至可以从控制台调用你的 Go 代码。 + +首先,在项目目录中运行 `wails dev`。 可以在 [此处](../reference/cli#开发) 找到有关这方面的更多信息。 + +即将提供:教程 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx new file mode 100644 index 00000000000..e6fddf1c5e6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/firstproject.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 2 +--- + +# 创建项目 + +## 项目生成 + +现在 CLI 已安装,您可以使用 `wails init` 命令生成一个新项目。 + +选择您最喜欢的框架: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + 使用 JavaScript 生成一个 Svelte 项目:

+ + wails init -n myproject -t svelte + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t svelte-ts + +
+ + 使用 JavaScript 生成一个 React 项目:

+ + wails init -n myproject -t react + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t react-ts + +
+ + 使用 JavaScript 生成一个 Vue 项目:

+ + wails init -n myproject -t vue + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t vue-ts + +
+ + 使用 JavaScript 生成一个 Preact 项目:

+ + wails init -n myproject -t preact + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t preact-ts + +
+ + 使用 JavaScript 生成一个 Lit 项目:

+ + wails init -n myproject -t lit + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t lit-ts + +
+ + 使用 JavaScript 生成一个 Vanilla 项目:

+ + wails init -n myproject -t vanilla + +如果您更愿意使用 TypeScript:
+ + wails init -n myproject -t vanilla-ts + +
+
+``` + +
+ +还有提供不同功能和框架的 [社区模板](../community/templates.mdx)。 + +要查看其他可用选项,您可以运行 `wails init -help`。 更多详细信息可以在 [初始化命令](../reference/cli#初始化) 中找到。 + +## 项目布局 + +Wails 项目有以下布局: + +``` +. +├── build/ +│ ├── appicon.png +│ ├── darwin/ +│ └── windows/ +├── frontend/ +├── go.mod +├── go.sum +├── main.go +└── wails.json +``` + +### 项目结构概要 + +- `/main.go` - 主应用 +- `/frontend/` - 前端项目文件 +- `/build/` - 项目构建目录 +- `/build/appicon.png` - 应用程序图标 +- `/build/darwin/` - Mac 特定的项目文件 +- `/build/windows/` - Windows 特定的项目文件 +- `/wails.json` - 项目配置 +- `/go.mod` - Go module 文件 +- `/go.sum` - Go module 校验文件 + +`frontend` 目录没有特定于 Wails 的内容,可以是您选择的任何前端项目。 + +`build` 目录在构建过程中使用。 这些文件可以修改以自定义您的构建。 如果从 build 目录中删除文件,将重新生成默认版本。 + +`go.mod` 中的默认模块名称是“changeme”。 您应该将其更改为更合适的内容。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx new file mode 100644 index 00000000000..3e8b2e39f0f --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/gettingstarted/installation.mdx @@ -0,0 +1,89 @@ +--- +sidebar_position: 1 +--- + +# 安装 + +## 支持的平台 + +- Windows 10/11 AMD64/ARM64 +- MacOS 10.13+ AMD64 +- MacOS 11.0+ ARM64 +- Linux AMD64/ARM64 + +## 依赖 + +Wails 有许多安装前需要的常见依赖项: + +- Go 1.18+ +- NPM (Node 15+) + +### Go + +从 [Go 下载页面](https://go.dev/dl/) 下载 Go。 + +确保您遵守官方的 [Go 安装说明](https://golang.org/doc/install#install)。 您还需要确保您的 `PATH` 环境变量包含您的 `~/go/bin` 目录路径。 重启终端并执行以下命令检查: + +- 检查 Go 是否安装正确: `go version` +- 检查 "~/go/bin" 是否在您的 PATH 变量中: `echo $PATH | grep go/bin` + +### NPM + +从 [Node 下载页面](https://nodejs.org/en/download/) 下载 NPM。 最好使用最新版本,因为这是我们通常会测试的版本。 + +运行 `npm --version` 进行验证。 + +## 平台特定依赖关系 + +您还需要安装平台特定的依赖项: + +```mdx-code-block +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + + Wails 要求安装 xcode 命令行工具。 这可以通过运行 xcode-select --install 来完成。 + + + Wails 要求安装 WebView2 运行时。 一些 Windows 安装已经安装了这个。 您可以使用 wails doctor 命令进行检查。 + + + Linux 需要标准的 gcc 构建工具以及 libgtk3libwebkit。 与其为不同的发行版列出大量命令,Wails 可以尝试确定针对您的特定发行版的安装命令。 安装后运行 wails doctor 以显示如何安装依赖项。 如果您的发行版/包管理器不受支持,请参阅 添加Linux发行版指南。 + + +``` + +## 可选依赖 + +- [UPX](https://upx.github.io/) 用于压缩您的应用程序。 +- [NSIS](https://wails.io/docs/guides/windows-installer/) 用于生成 Windows 安装程序。 + +## 安装 Wails + +运行 `go install github.com/wailsapp/wails/v2/cmd/wails@latest` 安装 Wails CLI。 + +注意:如果您遇到了类似于以下内容的错误: + +```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 +``` +请检查您是否已安装 Go 1.18+ ︰ +```shell +go version +``` + +## 系统检查 + +运行 `wails doctor` 将检查您是否安装了正确的依赖项。 如果没有,它会就缺少的内容提供建议以帮助纠正问题。 + +## `wails` 命令好像不见了? + +如果您的系统报告缺少 `wails` 命令,请确保您已正确遵循 Go 安装指南。 通常,这意味着您的用户 home 目录中的 `go/bin` 目录不在 `PATH` 环境变量中。 通常情况下还需要关闭并重新打开任何已打开的命令提示符,以便安装程序对环境所做的更改反映在命令提示符中。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json new file mode 100644 index 00000000000..5935dad936c --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Guides", + "position": 50 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx new file mode 100644 index 00000000000..e5061a6eaa8 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/angular.mdx @@ -0,0 +1,14 @@ +# Angular + +虽然 Wails 没有 Angular 模板,但可以将 Angular 与 Wails 一起使用。 + +## 开发模式 + +要让开发模式与 Angular 一起工作,您需要将以下内容添加到您的 `wails.json` 中: + +```json + "frontend:build": "npx ng build", + "frontend:install": "npm install", + "frontend:dev:watcher": "npx ng serve", + "frontend:dev:serverUrl": "http://localhost:4200", +``` \ No newline at end of file diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx new file mode 100644 index 00000000000..27217a9a6f2 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/application-development.mdx @@ -0,0 +1,215 @@ +# 应用开发 + +使用 Wails 开发应用程序没有硬性规定,但有一些基本准则。 + +## 应用程序设置 + +默认模板使用 `main.go` 配置和运行应用程序, 同时`app.go` 用于定义应用程序逻辑. + +`app.go`文件将定义一个结构体,该结构体有 2 个方法作为主应用程序的回调: + +```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) { +} +``` + +- 一旦 Wails 分配了它需要的资源,就会调用 startup 方法,它是创建资源、设置事件侦听器以及应用程序在启动时需要的任何其他东西的好地方。 它提供了一个 `context.Context`, 通常保存在一个结构体字段中。 调用 [运行时](../reference/runtime/intro) 需要此`context.Context`。 如果此方法返回错误,则应用程序将终止。 在开发模式下,错误会输出到控制台。 + +- Shutdown 方法将在关闭过程结束时由 Wails 调用。 这是释放内存和执行关闭任务的好地方。 + +`main.go` 文件通常由对`wails.Run()`的单个调用组成,它接受应用程序配置。 模板使用的模式是,在调用 `wails.Run()` 之前, 我们创建并保存一个在 `app.go` 中定义的结构体的实例在名为 `app` 的变量中。 这个配置是我们添加回调的地方: + +```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) + } +} + +``` + +可以在 [此处](../howdoesitwork#应用程序生命周期回调) 找到有关应用程序生命周期回调的更多信息。 + +## 绑定方法 + +您可能希望从前端调用 Go 方法。 这通常是通过向 `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) +} +``` + +在主应用程序中,`Bind` 字段是我们告诉 Wails 想要绑定什么: + +```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) + } +} + +``` + +这将绑定 `App` 结构中的所有公共方法(它永远不会绑定 startup 和 shutdown 方法)。 + +### 绑定多个结构体时处理 context + +如果您想为多个结构绑定方法,但希望每个结构都保留对 context 的引用,以便您可以使用运行时函数,一个好的方式是将上下文从 `OnStartup` 方法传递给您的结构实例: + +```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) + } +} +``` + +可以在 [此处](../howdoesitwork.mdx#method-binding) 找到有关绑定的更多信息。 + +## 应用程序菜单 + +Wails 支持向您的应用程序添加菜单。 这是通过将 [菜单结构体](../reference/menus#菜单结构体) 传递给应用程序配置来完成的。 常见做法是使用一个返回菜单的方法,更常见的是用作生命周期回调的 `App` 结构体上的方法。 + +```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) + } +} + +``` + +## 资产 + +Wails v2 处理资源的方式的伟大之处在于它不需要处理! 您唯一需要给 Wails 的是一个 `embed.FS`。 你如何做到这一点完全取决于你。 您可以像 vanilla 模板一样使用 vanilla html/css/js 文件。 您可能有一些复杂的构建系统,但这并不影响。 + +运行 `wails build` 时,它会检查项目根目录的 `wails.json` 文件。 文件中有 2 个字段会被读取: + +- "frontend:install" +- "frontend:build" + +第一个,如果有给定,将在 `frontend` 目录中执行以安装 node 模块。 第二个,如果有给定,将在 `frontend` 目录中执行以构建前端项目。 + +如果没有给出这两个字段,那么 Wails 不会对前端做任何操作。 它仅仅被用作 `embed.FS`。 + +### 资产处理程序 + +Wails v2 应用程序可以选择在 `options.App` 中定义一个 `http.Handler`,它允许连接到 AssetServer 以动态创建文件或处理 POST/PUT 请求。 GET 请求总是首先由 `assets` FS 处理。 如果 FS 没有找到请求的文件,请求将被转发到 `http.Handler` 服务。 如果指定,除了 GET 以外的任何请求都将由 `AssetsHandler` 直接处理。 也可以仅通过将 `nil` 指定为 `Assets` 选项来使用 `AssetsHandler`。 + +## 内置开发服务器 + +运行 `wails dev` 将启动内置的开发服务器,它将在您的项目目录中启动一个文件监听器。 默认情况下,如果有任何文件更改,wails 会检查它是否是应用程序文件(默认:.go,可使用 `-e` 标志配置)。 如果是,那么它将重新构建您的应用程序并重新启动它。 如果更改的文件在 assetdir 目录中,它会在很短的时间后重新加载。 + +开发服务器使用一种称为“防抖”的技术,这意味着它不会立即重新加载,因为可能会在短时间内更改多个文件。 当触发发生时,它会在发出重新加载之前等待一定的时间。 如果发生另一个触发,它会再次重置为等待时间。 默认情况下,此值为 100ms。 如果此值不适用于您的项目,则可以使用 `-debounce` 标志进行配置。 如果使用,此值将保存到您的项目配置中并成为默认值。 + +## 外部开发服务器 + +一些框架带有自己的实时重新加载服务器,但是它们将无法利用 Wails Go 绑定。 在这种情况下,最好运行一个监听脚本,将项目重新构建到构建目录中,Wails 将监视该目录。 有关示例,请参阅使用 [rollup](https://rollupjs.org/guide/en/) 的默认 svelte 模板。 + +### Create React App + +The process for a Create-React-App project is slightly more complicated. In order to support live frontend reloading the following configuration needs to be added to your `wails.json`: + +```json + "frontend:dev:watcher": "yarn start", + "frontend:dev:serverUrl": "http://localhost:3000", +``` + +The `frontend:dev:watcher` command will start the Create-React-App development server (hosted on port `3000` typically). The `frontend:dev:serverUrl` command then instructs Wails to serve assets from the development server when loading the frontend rather than from the build folder. In addition to the above, the `index.html` needs to be updated with the following: + +```html + + + + + +``` + +This is required as the watcher command that rebuilds the frontend prevents Wails from injecting the required scripts. This circumvents that issue by ensuring the scripts are always injected. With this configuration, `wails dev` can be run which will appropriately build the frontend and backend with hot-reloading enabled. Additionally, when accessing the application from a browser the React developer tools can now be used on a non-minified version of the application for straightforward debugging. Finally, for faster builds, `wails dev -s` can be run to skip the default building of the frontend by Wails as this is an unnecessary step. + +## Go 模块 + +默认的 Wails 模板会生成一个包含模块名称“changeme”的 `go.mod` 文件。 您应该在项目生成后将其更改为更合适的内容。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx new file mode 100644 index 00000000000..fd81a974d04 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/crossplatform-build.mdx @@ -0,0 +1,66 @@ +# Crossplatform build with 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. + +An action that facilitates building a Wails app is available at: +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: +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: + +```yaml +name: Wails build + +on: + push: + tags: + # Match any new tag + - '*' + +env: + # Necessary for most environments as build failure can occur due to OOM issues + NODE_OPTIONS: "--max-old-space-size=4096" + +jobs: + build: + strategy: + # Failure in one platform build won't impact the others + fail-fast: false + matrix: + build: + - name: 'App' + platform: 'linux/amd64' + os: 'ubuntu-latest' + - name: 'App' + platform: 'windows/amd64' + os: 'windows-latest' + - name: 'App' + platform: 'darwin/universal' + os: 'macos-latest' + + runs-on: ${{ matrix.build.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Build wails + uses: dAppServer/wails-build-action@v2.2 + id: build + with: + build-name: ${{ matrix.build.name }} + build-platform: ${{ matrix.build.platform }} + package: false + go-version: '1.20' +``` + +This example offers opportunities for various enhancements, including: + +- 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) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx new file mode 100644 index 00000000000..e86b651845d --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/custom-protocol-schemes.mdx @@ -0,0 +1,204 @@ +# Custom Protocol Scheme association + +Custom Protocols feature allows you to associate specific custom protocol with your app so that when users open links with this protocol, +your app is launched to handle them. This can be particularly useful to connect your desktop app with your web app. +In this guide, we'll walk through the steps to implement custom protocols in Wails app. + +## Set Up Custom Protocol Schemes Association: + +To set up custom protocol, you need to modify your application's wails.json file. +In "info" section add a "protocols" section specifying the protocols your app should be associated with. + +For example: + +```json +{ + "info": { + "protocols": [ + { + "scheme": "myapp", + "description": "My App Protocol", + "role": "Editor" + } + ] + } +} +``` + +| Property | Description | +| :---------- | :------------------------------------------------------------------------------------ | +| scheme | Custom Protocol scheme. e.g. myapp | +| description | Windows-only. The description. | +| role | macOS-only. The app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnUrlOpen: func(url string) { println(url) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### Windows + +On Windows Custom Protocol Schemes is supported only with NSIS installer. During installation, the installer will create a +registry entry for your schemes. When you open url with your app, new instance of app is launched and url is passed +as argument to your app. To handle this you should parse command line arguments in your app. Example: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there (note that `%u` is important in Exec). Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=x-scheme-handler/myapp; +``` + +2. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +``` + +3. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using nfpm: + +```sh +nfpm pkg --packager deb --target . +``` + +7. Now when your package is installed, your app will be associated with custom protocol scheme. When you open url 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +You also can enable single instance lock for your app. In this case, when you open url 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx new file mode 100644 index 00000000000..647348462af --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -0,0 +1,136 @@ +# 动态资产 + +如果你想为你的前端动态加载或生成资产,你可以使用 [AssetsHandler 选项](../reference/options#资产处理程序) 来实现。 AssetsHandler 是一个通用的 `http.Handler`,对于资产服务器上的任何非 GET 请求以及由于找不到文件而无法从捆绑资产提供服务的 GET 请求,都会调用它。 + +通过安装自定义 AssetsHandler,您可以使用自定义资产服务器提供您自己的资产。 + +## 示例 + +在我们的示例项目中,我们将创建一个简单的资产处理程序,它将从磁盘加载文件: + +```go title=main.go {17-36,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) + } +} +``` + +当我们在开发模式使用 `wails dev` 运行应用程序时,我们将看到以下输出: + +``` +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' +DEB | [ExternalAssetHandler] Loading 'http://localhost:3001/favicon.ico' failed, using AssetHandler +Requesting file: favicon.ico +``` + +如您所见,当默认资产服务器无法提供 `favicon.ico` 文件时,将调用资产处理程序。 + +如果您右键单击主应用程序并选择“检查”以调出开发工具,您可以通过在控制台中输入以下内容来测试此功能: + +``` +let response = await fetch('does-not-exist.txt'); +``` + +这将在 devtools 中产生错误。 我们可以看到错误是我们所期望的,由我们的自定义资产处理程序返回: + +```mdx-code-block +

+ +

+``` + +但是,如果我们请求 `go.mod`,我们将看到以下输出: + +```mdx-code-block +

+ +

+``` + +此技术可用于将图像直接加载到页面中。 如果我们更新了默认的 vanilla 模板并替换了 logo 图像: + +```html + +``` + +和: + +```html + +``` + +然后我们会看到以下内容: + +```mdx-code-block +

+ +

+``` + +:::warning + +以这种方式暴露您的文件系统是一种安全风险。 建议您正确管理对文件系统的访问。 + +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx new file mode 100644 index 00000000000..167955b12d7 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/file-association.mdx @@ -0,0 +1,244 @@ +# File Association + +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. + +## Set Up File Association: + +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. + +For example: + +```json +{ + "info": { + "fileAssociations": [ + { + "ext": "wails", + "name": "Wails", + "description": "Wails Application File", + "iconName": "wailsFileIcon", + "role": "Editor" + }, + { + "ext": "jpg", + "name": "JPEG", + "description": "Image File", + "iconName": "jpegFileIcon", + "role": "Editor" + } + ] + } +} +``` + +| 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 app’s role with respect to the type. Corresponds to CFBundleTypeRole. | + +## Platform Specifics: + +### 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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + Mac: &mac.Options{ + OnFileOpen: func(filePaths []string) { println(filestring) }, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +### 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` + +### 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. + +1. Create a .desktop file for your app and specify file associations there. Example: + +```ini +[Desktop Entry] +Categories=Office +Exec=/usr/bin/wails-open-file %u +Icon=wails-open-file.png +Name=wails-open-file +Terminal=false +Type=Application +MimeType=application/x-wails;application/x-test +``` + +2. Create mime types file. Example: + +```xml + + + + Wails Application File + + + +``` + +3. Create icons for your file types. SVG icons are recommended. +4. Prepare postInstall/postRemove scripts for your package. Example: + +```sh +# reload mime types to register file associations +update-mime-database /usr/share/mime +# reload desktop database to load app in list of available +update-desktop-database /usr/share/applications +# update icons +update-icon-caches /usr/share/icons/* +``` + +5. Configure nfpm to use your scripts and files. Example: + +```yaml +name: "wails-open-file" +arch: "arm64" +platform: "linux" +version: "1.0.0" +section: "default" +priority: "extra" +maintainer: "FooBarCorp " +description: "Sample Package" +vendor: "FooBarCorp" +homepage: "http://example.com" +license: "MIT" +contents: +- src: ../bin/wails-open-file + dst: /usr/bin/wails-open-file +- src: ./main.desktop + dst: /usr/share/applications/wails-open-file.desktop +- src: ./application-wails-mime.xml + dst: /usr/share/mime/packages/application-x-wails.xml +- src: ./application-test-mime.xml + dst: /usr/share/mime/packages/application-x-test.xml +- src: ../appicon.svg + dst: /usr/share/icons/hicolor/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/hicolor/scalable/mimetypes/application-x-test.svg +# copy icons to Yaru theme as well. For some reason Ubuntu didn't pick up fileicons from hicolor theme +- src: ../appicon.svg + dst: /usr/share/icons/Yaru/scalable/apps/wails-open-file.svg +- src: ../wailsFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-wails.svg +- src: ../testFileIcon.svg + dst: /usr/share/icons/Yaru/scalable/mimetypes/application-x-test.svg +scripts: + postinstall: ./postInstall.sh + postremove: ./postRemove.sh +``` + +6. Build your .deb package using 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: + +```go title="main.go" +func main() { + argsWithoutProg := os.Args[1:] + + if len(argsWithoutProg) != 0 { + println("launchArgs", argsWithoutProg) + } +} +``` + +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: + +```go title="main.go" +func main() { + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx new file mode 100644 index 00000000000..50b89b33bd1 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frameless.mdx @@ -0,0 +1,87 @@ +# 无边框应用 + +Wails 支持无边框应用程序。 这可以通过使用 [应用程序参数选项](../reference/options#应用程序参数选项) 中的 [无边框](../reference/options#无边框) 字段来实现。 + +Wails 为拖动窗口提供了一个简单的解决方案:任何具有 `--wails-draggable:drag` CSS 样式的 HTML 元素都将充当“拖动句柄”。 此属性适用于所有子元素。 如果您需要指示嵌套元素不应拖动,则在该元素上使用“--wails-draggable:no-drag”属性。 + +```html + + + + + + + +
+ + +
+
+ + + + +``` + +对于一些项目,由于动态样式,可能无法使用 CSS 变量。 在这种情况下,您可以使用 `CSSDragProperty` 和 `CSSDragValue` 应用程序选项来定义将用于指示可拖动区域的属性和值: + +```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 + + + + + + alwaysontop + + +
+ + + +``` + +:::info 全屏 + +如果您允许您的应用程序全屏显示,则此拖动功能将被禁用。 + +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx new file mode 100644 index 00000000000..7c424686348 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/frontend.mdx @@ -0,0 +1,72 @@ +# 前端 + +## 脚本注入 + +当 Wails 为您的 `index.html` 提供服务时,默认情况下,它会将 2 个脚本注入 `` 标签以加载 `/wails/ipc.js` 和 `/wails/runtime.js`。 这些文件分别安装绑定和运行时。 + +下面的代码显示了这些默认注入的位置: + +```html + + + injection example + + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + +``` + +### 覆盖默认脚本注入 + +为了给开发人员提供更大的灵活性,有一个 meta 标签可用于自定义此行为: + +```html + +``` + +选项如下: + +| 值 | 描述 | +| ------------------- | -------------------------- | +| noautoinjectruntime | 禁用自动注入 `/wails/runtime.js` | +| noautoinjectipc | 禁用自动注入 `/wails/ipc.js` | +| noautoinject | 禁用所有脚本自动注入 | + +可以使用多个选项,前提是它们以逗号分隔。 + +此代码完全有效并且与自动注入版本的操作相同: + +```html + + + injection example + + + + + + +
Please enter your name below 👇
+
+ + +
+ + + + + + +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx new file mode 100644 index 00000000000..a7642a7c015 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/ides.mdx @@ -0,0 +1,127 @@ +# 集成开发环境 + +Wails 旨在提供出色的开发体验。 为此,我们现在支持生成 IDE 特定配置以提供更顺畅的项目设置。 + +目前,我们支持 [Visual Studio Code](https://code.visualstudio.com/),但我们希望尽快支持其他 IDE,例如 Goland。 + +## Visual Studio Code + +```mdx-code-block +

+ +

+``` + +使用 `-ide vscode` 标志生成项目时,IDE 文件将与其他项目文件一起创建。 这些文件放置在 `.vscode` 目录中,并为调试应用程序提供正确的配置。 + +生成的 2 个文件是 `tasks.json` 和 `launch.json`。 以下是为默认 vanilla 项目生成的文件: + +```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": {} + } + ] +} +``` + +### 配置安装和构建步骤 + +`tasks.json` 文件对于默认项目很简单,因为不需要 `npm install` 或 `npm run build` 的步骤。 对于具有前端构建步骤的项目,例如 svelte 模板,我们需要编辑 `tasks.json` 以添加安装和构建步骤: + +```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 功能增强 + +将来,我们希望生成一个 `tasks.json` 自动包含安装和构建步骤的文件。 + +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx new file mode 100644 index 00000000000..f282894e495 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux-distro-support.mdx @@ -0,0 +1,103 @@ +# Linux 发行版支持 + +## 概述 + +Wails 提供 Linux 支持,但为所有可用发行版提供安装说明是一项不可能完成的任务。 相反,Wails 会尝试确定您开发应用程序所需的包是否可以通过系统的包管理器获得。 目前,我们支持以下包管理器: + +- apt +- dnf +- emerge +- eopkg +- nixpkgs +- pacman +- zypper + +## 添加包名 + +在某些情况下,您的发行版使用受支持的包管理器之一,但包名称不同。 例如,您可能使用 Ubuntu 衍生产品,但 gtk 的包名称可能不同。 Wails 尝试通过遍历包名称列表来找到正确的包。 包列表存储在 `v2/internal/system/packagemanager` 目录中的包管理器特定文件中。 在我们的示例中,是 `v2/internal/system/packagemanager/apt.go`。 + +在此文件中,包列表由以下 `Packages()` 方法定义: + +```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}, + }, + } +} +``` + +假设在我们的 linux 发行版中,`libgtk-3` 以 `lib-gtk3-dev` 的名称打包。 我们可以通过添加以下行来添加对此的支持: + +```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}, + }, + } +} +``` + +## 添加新的包管理器 + +要添加新的包管理器,请执行以下步骤: + +- 在 `v2/internal/system/packagemanager` 中创建一个名为 `.go` 的新文件,其中 `` 是包管理器的名称。 +- 定义一个符合 `pm.go` 中定义的包管理器接口的结构体。 + +```go +type PackageManager interface { + Name() string + Packages() packagemap + PackageInstalled(*Package) (bool, error) + PackageAvailable(*Package) (bool, error) + InstallCommand(*Package) string +} +``` + +- `Name()` 应该返回包管理器的名称 +- `Packages()` 应该返回一个 `packagemap`,它为依赖项提供候选文件名 +- `PackageInstalled()` 如果安装了指定的包,应该返回`true` +- `PackageAvailable()` 如果指定的软件包未安装但可以安装,则应返回`true` +- `InstallCommand()` 应该返回确切的命令来安装指定的包名 + +查看其他包管理器代码以了解其工作原理。 + +:::info 记住 + +如果您添加了对新包管理器的支持,请不要忘记更新此页面! + +::: diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx new file mode 100644 index 00000000000..dfcdc5fb23a --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/linux.mdx @@ -0,0 +1,18 @@ +# Linux + +此页面包含与开发适用于 Linux 的 Wails 应用程序相关的其他指南。 + +## video 标签不能触发 "ended" 事件 + +使用视频标签时,视频播放完毕后不会触发“结束”事件。 这是 WebkitGTK 中的一个错误,但是您可以使用以下解决方法来修复它: + +```js +videoTag.addEventListener("timeupdate", (event) => { + if (event.target.duration - event.target.currentTime < 0.2) { + let ended = new Event("ended"); + event.target.dispatchEvent(ended); + } +}); +``` + +资料来源:[讨论板](https://github.com/wailsapp/wails/issues/1729#issuecomment-1212291275) 上的 [Lyimmi](https://github.com/Lyimmi) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx new file mode 100644 index 00000000000..a80900fe676 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/local-development.mdx @@ -0,0 +1,55 @@ +# 本地开发 + +## 概述 + +Wails 一直在开发中,新版本会定期“标记”。 这通常发生在 `master` 分支上所有较新的代码都经过测试并确认有效时。 如果您需要尚未发布的错误修复或功能,可以通过以下步骤使用最新的“前沿风险”版本: + +- `git clone https://github.com/wailsapp/wails` +- `cd wails/v2/cmd/wails` +- `go install` + +注意:您将项目克隆到的目录现在将被称为“clonedir”。 + +现在,Wails CLI 将是最新版本。 + +### 更新您的项目 + +要更新项目以使用最新版本的 Wails 库,请更新项目 `go.mod` 并确保以下行位于文件底部: + +`replace github.com/wailsapp/wails/v2 => ` + +示例: + +在 Windows 上:`replace github.com/wailsapp/wails/v2 => C:\Users\leaan\Documents\wails-v2-beta\wails\v2` + +在'nix 上:`replace github.com/wailsapp/wails/v2 => /home/me/projects/wails/v2` + +要恢复到稳定版本,请运行: + +`go install github.com/wailsapp/wails/v2/cmd/wails@latest` + +## 测试一个分支 + +如果要测试一个分支,请按照上面的说明进行操作,但请确保在安装之前切换要测试的分支: + +- `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` + +确保如上所述 [更新您的项目](#更新您的项目)。 + +## 测试 PR + +如果您想测试 PR,请按照上面的说明进行操作,但请确保在安装前获取 PR 并切换分支。 请替换 `[IDofThePR]` 为 github.com 上显示的 PR 的 ID: + +- `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` + +确保如上所述 [更新您的项目](#更新您的项目)。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx new file mode 100644 index 00000000000..b57afca88af --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mac-appstore.mdx @@ -0,0 +1,97 @@ +# Mac 应用商店指南 + +本页面简要概述了如何将您的 Wails 应用程序提交到 Mac 应用商店。 + +## 前提条件 + +- 您需要有一个 Apple 开发者帐户。 请在 [Apple Developer Program](https://developer.apple.com/support/compare-memberships/) 网站上找到更多信息 +- 您需要在开发人员门户上创建证书(Certificates)、标识符(Identifiers)和应用程序。 更多内容请见下文 +- 你的本地机器上需要安装 Xcode 命令行工具 + +#### 创建证书和标识符 + +1. 前往您的 [Apple 开发者帐户](https://developer.apple.com/account/) +2. 在 `证书(Certificates)、标识符(Identifiers)和个人资料(Profiles)` 下,单击 `标识符(Identifiers)` 并注册新的应用程序 ID。 使用格式 (com.example.app) +3. 在同一页面下,单击 `证书(Certificates)`并为 Mac App Store 分发生成新证书(Certificates)。 下载它们并将证书导入本地计算机上的秘钥串。 + +#### 创建应用程序提交 + +1. 前往 [App Store Connect](https://appstoreconnect.apple.com/apps) 网站 +2. 注册一个新应用程序并链接您在上一步中创建的包 ID +3. 根据 Apple 的要求,使用正确的屏幕截图、描述等填充您的应用程序 +4. 创建新版本的应用 + +#### 创建配置文件 +1. 转到 [Apple 开发者资料](https://developer.apple.com/account/resources/profiles/list) 页面 +2. 为 Mac App Store Distribution 添加新的配置文件 +3. 将 Profile Type 设置为 Mac 并为上面创建的应用程序选择 App ID +4. 选择 Mac App Distribution 证书 +5. 命名嵌入式配置文件并下载创建的配置文件。 + +## Mac 应用商店流程 + +#### 启用 Apple 的 App Sandbox + +提交到 Mac 应用商店的应用程序必须在 Apple 的 [App Sandbox](https://developer.apple.com/app-sandboxing/) 下运行。 您必须创建一个 `entitlements.plist` 文件才能使其工作。 建议在此路径 `{PROJECT_DIR}/build/darwin/entitlements.plist` 下创建此文件。 + +**示例授权文件** + +这是来自 [RiftShare](https://github.com/achhabra2/riftshare) 应用程序的示例授权文件。 作为参考,请输入您的应用所需的权限。 有关详细信息,请参阅 [此站点](https://developer.apple.com/documentation/bundleresources/entitlements)。 您需要将团队 ID 和应用程序名称替换为您上面注册的名称。 + +```xml title="entitlements.plist" + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.application-identifier + TEAM_ID.APP_NAME + com.apple.developer.team-identifier + TEAM_ID + + +``` + +上面 **添加嵌入式配置文件** 创建的配置文件需要添加到应用程序的根目录中。 它需要命名为 embedded.provisionprofile。 + +#### 构建并签署应用程序包 + +以下是用于构建和签署您的应用程序以提交 Mac 应用商店的示例脚本。 它假定您正在从根项目目录运行脚本。 + +请注意,用于签署应用程序和签署安装程序的证书是不同的。 请确保两者都导入到秘钥串中。 在秘钥串中找到字符串并将它们插入下面。 在下面填充您的证书名称和应用程序名称。 运行以下脚本将在您的应用程序的根目录中生成一个签名的 `app.pkg` 文件。 + +```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 + +cp ./embedded.provisionprofile "./build/bin/$APP_NAME.app/Contents" + +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 +``` + +#### 上传应用程序包 + +您需要上传生成的包文件并将其关联到您的应用程序,然后才能提交以供审核。 + +1. 从 Mac 应用商店下载 [Transporter App](https://apps.apple.com/us/app/transporter/id1450874784) +2. 打开它并使用您的 Apple ID 登录 +3. 单击 + 号并选择您在上一步中生成的 `APP_NAME.pkg` 文件。 上传它 +4. 返回 [App Store Connect](https://appstoreconnect.apple.com/apps) 站点并导航回您的应用程序提交。 选择您准备在 App 商店上提供的版本。 在 `Build` 下选择您通过 Transporter 上传的包。 + +好了! 您现在可以使用该网站提交您的应用程序以供审核。 几个工作日后,如果一切顺利,您应该会在 Mac 应用商店上看到您的应用程序。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx new file mode 100644 index 00000000000..83de0fdfd8f --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/manual-builds.mdx @@ -0,0 +1,95 @@ +# 手动构建 + +Wails CLI 为项目做了很多繁重的工作,但有时需要手动构建项目。 本文档将讨论 CLI 执行的不同操作以及如何以不同方式实现这一点。 + +## 构建过程 + +当使用 `wails build` 或 `wails dev` 时,Wails CLI 会执行一个通用的构建过程: + + - 安装前端依赖 + - 构建前端项目 + - 生成构建资产 + - 编译应用程序 + - [可选]压缩应用程序 + +### 安装前端依赖 + +#### 命令行步骤 + +- 如果给出了 `-s` 标志,则跳过此步骤 +- 检查 `wails.json` 中是否有安装命令 `frontend:install` +- 如果没有,则跳过此步骤 +- 如果有,则检查前端目录中是否存在 `package.json`。 如果不存在,则跳过这一步 +- 从 `package.json` 文件内容生成 MD5 +- 检查 `package.json.md5` 是否存在,如果存在,则将其内容(MD5 sum)与生成的内容进行比较,以查看内容是否已更改。 如果相同,则跳过此步骤 +- 如果 `package.json.md5` 不存在,则使用生成的 MD5 并创建它 +- 如果现在需要构建,或者 `node_modules` 不存在,或者给出了`-f` 标志,则在前端目录中执行安装命令 + +#### 手动步骤 + +这一步可以从命令行或带有 `npm install` 的前端脚本完成. + +### 构建前端项目 + +#### Wails 命令行 + +- 如果给出了 `-s` 标志,则跳过此步骤 +- 检查 `wails.json` 中是否有构建命令 `frontend:build` +- 如果没有,则跳过此步骤 +- 如果有,就在 frontend 目录下执行它 + +#### 手动步骤 + +这一步可以从命令行或带有前端构建脚本 `npm run build` 的脚本或任何前端构建脚本完成。 + +### 生成资产 + +#### Wails 命令行 + +- 如果设置了`-nopackage` 标志,则跳过此阶段 +- 如果 `build/appicon.png` 文件不存在,则创建一个默认文件 +- 对于 Windows,请参阅 [ Windows](#windows) +- 如果 `build/windows/icon.ico` 不存在,它将从 `build/appicon.png` 图像创建它。 + +##### Windows + +- 如果 `build/windows/icon.ico` 不存在,它将从 `build/appicon.png` 创建 256、128、64、48、32 和 16 大小的图标。 这是使用 [winicon](https://github.com/leaanthony/winicon) 完成的。 +- 如果 `build/windows/.manifest` 文件不存在,它会从默认版本创建它。 +- 将应用程序编译为生产版本(如上所述)。 +- 使用 [winres](https://github.com/tc-hib/winres) 将 icon 和 manifest 打包到一个 `.syso` 文件。 + +#### 手动步骤 + +- 使用[winicon](https://github.com/leaanthony/winicon)命令行工具或者其他工具创建`icon.ico` +- 为您的应用程序创建或者更新 `.manifest` 文件 +- 使用 [winres 命令行](https://github.com/tc-hib/go-winres) 生成一个 `.syso` 文件 + +### 编译应用程序 + +#### Wails 命令行 + +- 如果提供了 `-clean` 标志,则删除并重新创建 `build` 目录 +- 对于 `wails dev`,使用以下默认 Go 标志:`-tags dev -gcflags "all=-N -l"` +- 对于 `wails build`,使用以下默认 Go 标志:`-tags desktop,production -ldflags "-w -s"` + - 在 Windows 上,是 `-ldflags "-w -h -H windowsgui"` +- 传递给 CLI 的附加标签使用 `-tags` 添​​加到默认值中 +- 传递给 CLI 的附加 `ldflags-ldflags` 添加到默认值 +- 传递 `-o` 标志 +- 将使用指定的 Go 编译器 `-compiler` 进行编译 + +#### 手动步骤 + +- 对于 dev 构建,最少的命令是:`go build -tags dev -gcflags "all=-N -l"` +- 对于生产构建,最少的命令是:`go build -tags desktop,production -ldflags "-w -s -H windowsgui"` +- 确保在与 `.syso` 文件相同的目录中进行编译 + +### 压缩应用程序 + +#### Wails 命令行 + +- 如果 `-upx` 已给出标志,将运行 `upx` 程序以使用默认设置压缩应用程序 +- 如果也传递了 `-upxflags` 标志,则使用这些标志而不是默认 + +#### 手动步骤 + +- 手动运行 `upx [flags]` 以压缩应用程序。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx new file mode 100644 index 00000000000..9699ccc63db --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/migrating.mdx @@ -0,0 +1,193 @@ +# 从 v1 迁移 + +## 概述 + +Wails v2 与 v1 相比有重大变化。 本文档旨在重点介绍迁移现有项目的更改和步骤。 + +### 创建应用程序 + +在 v1 中,使用 `wails.CreateApp` 来创建主应用程序,使用 `app.Bind` 来添加绑定,然后使用 `app.Run()` 运行应用程序。 + +示例: + +```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() +``` + +在 v2 中,只有一个 `wails.Run()` 方法接受 [应用程序参数选项](../reference/options#应用程序参数选项)。 + +```go title="v2" + err := wails.Run(&options.App{ + Title: "MyApp", + Width: 800, + Height: 600, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + basic, + }, + }) +``` + +### 绑定 + +在 v1 中,可以绑定任意函数和结构。 在 v2 中,这已被简化为仅绑定结构体。 以前 v1 传递给 `Bind()` 中的方法的结构实例现在在 [应用程序参数选项 ](../reference/options#应用程序参数选项)`Bind` 字段中指定: + +```go title="v1" + app := wails.CreateApp(/* options */) + app.Bind(basic) +``` + +```go title="v2" + err := wails.Run(&options.App{ + /* other options */ + Bind: []interface{}{ + basic, + }, + }) +``` + +在 v1 中,绑定方法可用于前端的 `window.backend`。 这已更改为 `window.go`。 + +### 应用程序生命周期 + +在 v1 中,绑定结构中有 2 个特殊方法:`WailsInit()` 和 `WailsShutdown()`。 作为应用程序选项的一部分,这些已被 3 个生命周期钩子替换: + +- [应用启动回调](../reference/options.mdx#onstartup) +- [应用退出回调](../reference/options.mdx#onshutdown) +- [前端 Dom 加载完成回调](../reference/options.mdx#ondomready) + +注意:[ 前端 Dom 加载完成回调](../reference/options#前端-dom-加载完成回调)替换了 v1 中的 `wails:ready` 系统事件。 + +这些方法可以是标准函数,但通常的做法是让它们成为结构的一部分: + +```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 +} +... +``` + +### 运行时 + +v2 中的运行时比 v1 丰富得多,支持菜单、窗口操作和更好的对话框。 方法的签名略有变化 - 请参阅 [运行时](../reference/runtime/intro)。 + +在 v1 中,[运行时](../reference/runtime/intro) 可通过传递给 `WailsInit()`。 在 v2 中,运行时已移出到它自己的包。 运行时中的每个方法都采用 `context.Context` 传递给了 [应用启动回调](../reference/options#应用启动回调)方法。 + +```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!") +} +} +} + +``` + +### 资产 + +在 v2 最大的变化是资源的处理方式。 + +在 v1 中,资源通过 2 个应用程序参数选项传递: + +- `JS` - 应用程序的 JavaScript +- `CSS` - 应用程序的 CSS + +这意味着生成单个 JS 和 CSS 文件的责任在于开发人员。 这本质上需要使用繁琐的打包程序,例如 webpack。 + +在 v2 中,Wails 不对您的前端资源做任何预设,就像网络服务器一样。 您的所有应用程序资源都作为 `embed.FS`。 + +**这意味着不需要捆绑您的资产、将图像编码为 Base64 或尝试使用捆绑器配置的黑暗艺术来使用自定义字体**。 + +在启动时,Wails 将扫描给定的`embed.FS`的`index.html`并将其位置用作所有其他应用程序资源的根路径 - 就像网络服务器一样。 + +示例:应用程序具有以下项目布局。 所有最终资源都放在 `frontend/dist`目录中: + +```shell +. +├── build/ +├── frontend/ +│ └── dist/ +│ ├── index.html +│ ├── main.js +│ ├── main.css +│ └── logo.svg +├── main.go +└── wails.json +``` + +应用程序可以通过简单地创建一个 `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, + }, + }) +} +``` + +当然,如果您愿意,也可以使用打包工具。 唯一的要求是在 Wails 中使用 `embed.FS` 将最终的程序资源目录传递给 [应用程序参数选项](../reference/options#应用程序参数选项) 的 `Assets` 键。 + +### 项目配置 + +在 v1 中,项目配置存储在项目根的 `project.json` 文件中。 在 v2 中,项目配置存储在项目根部的 `wails.json` 文件中。 + +文件的格式略有不同。 下面是区别: + +

+ +| v1 | v2 | 记录 | +| ------------------ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| name | name | | +| description | | 移除 | +| author / name | author / name | | +| author / email | author / email | | +| version | version | | +| binaryname | outputfilename | 变更 | +| frontend / dir | | 移除 | +| frontend / install | frontend:install | 变更 | +| frontend / build | frontend:build | 变更 | +| frontend / bridge | | 移除 | +| frontend / serve | | 移除 | +| tags | | 移除 | +| | wailsjsdir | 生成 wailsjs 模块的目录 | +| | assetdir | 为开发模式编译的前端资产的目录。 这通常是推断的,可以留空。 | +| | reloaddirs | 以逗号分隔的附加目录列表,用于监视更改并在开发模式下触发重新加载。 只有一些更高级的资产配置才需要这样做。 | + +

diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx new file mode 100644 index 00000000000..13e54ec4678 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/mouse-buttons.mdx @@ -0,0 +1,25 @@ +# 鼠标按钮 + +Wails 运行时拦截鼠标单击以确定无框窗口是否需要调整大小或需要移动窗口。 有人询问如何检测鼠标点击何时发生,因为 `window.onclick` 没有正确报告鼠标按钮。 下面的代码展示了如何检测鼠标点击: + +```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 + } +} +``` + +参考:https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx new file mode 100644 index 00000000000..c37150a4078 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/obfuscated.mdx @@ -0,0 +1,40 @@ +# 混淆构建 + +Wails 支持使用 [garble](https://github.com/burrowers/garble) 来混淆您的应用程序。 + +要生成混淆构建,您可以将 `-obfuscate` 标志与 `wails build` 命令一起使用: + +```bash +wails build -obfuscated +``` + +要自定义混淆设置,您可以使用以下 `-garbleargs` 标志: + +```bash +wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed" +``` + +这些设置可能会保留在您的 [项目配置](../reference/project-config) 中。 + +## 工作原理 + +在标准构建中,所有绑定的方法都在前端的 `window.go` 变量下可用。 调用这些方法时,会使用完全限定的函数名调用相应的后端方法。 使用混淆构建时,使用 ID 而不是绑定方法的名称。 目录中生成的绑定 `wailsjs` 使用这些 ID 调用后端函数。 + +:::note + +为确保您的应用程序在混淆模式下工作,您必须使用 `wailsjs` 应用程序目录下生成的绑定。 + +::: + +## 示例 + +从绑定中导入“Greet” 方法,如下所示: + +```js +import { Greet } from "../../wailsjs/go/main/App"; + +// snip +Greet("World"); +``` + +将确保该方法在混淆模式下正常工作,因为绑定将使用 ID 重新生成并更新调用机制。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx new file mode 100644 index 00000000000..64673dafd7d --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/overscroll.mdx @@ -0,0 +1,10 @@ +# 滚动超出 + +[Overscroll](https://developer.mozilla.org/zh-CN/docs/Web/CSS/overscroll-behavior) 是当您滚动超出页面内容边界时有时会获得的“弹跳效果”。 这在移动应用程序中很常见。 这可以使用 CSS 禁用: + +```css +html { + height: 100%; + overflow: hidden; +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..33704c645bc --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,47 @@ +# 路由 + +路由是一种在应用程序中切换视图的流行方式。 此页面提供了有关如何执行此操作的一些指导。 + +## Vue + +在 Vue 中推荐的路由方法是 [Hash 模式](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 + +在 Angular 中推荐的路由方法是 [HashLocationStrategy](https://codecraft.tv/courses/angular/routing/routing-strategies/#_hashlocationstrategy): + +```ts +RouterModule.forRoot(routes, { useHash: true }); +``` + +## React + +在 React 中推荐的路由方法是 [HashRouter](https://reactrouter.com/en/main/router-components/hash-router): + +```jsx +import { HashRouter } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx new file mode 100644 index 00000000000..7ce7dc9b2fa --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/signing.mdx @@ -0,0 +1,387 @@ +# 代码签名 + +这是有关如何在 MacOS 和 Windows 上对使用 Wails 生成的二进制文件进行签名的指南。 该指南将针对 CI 环境,更具体地说是 GitHub Actions。 + +## Windows + +首先,您需要一个代码签名证书。 如果您还没有,Microsoft 的信息页面会 [在此处](https://docs.microsoft.com/en-us/windows-hardware/drivers/dashboard/get-a-code-signing-certificate) 列出一些提供商。 请注意,除非您需要编写内核级软件,例如设备驱动程序,否则不需要 EV 证书。 为了签署你的 Wails 应用程序,一个标准的代码签名证书就可以了。 + +在针对自动构建系统之前,与您的证书提供商核实如何在您的本地计算机上签署您的二进制文件可能是一个好主意,这样您就知道是否有任何特殊要求。 例如,[这里](https://www.ssl.com/how-to/using-your-code-signing-certificate/) 是 SSL.com 的 Windows 代码签名指南。 如果您知道如何在本地签名,则可以更轻松地解决 CI 环境中的任何潜在问题。 例如,SSL.com 代码签名证书需要 [SignTool.exe](https://docs.microsoft.com/en-us/windows/win32/seccrypto/signtool) 的 `/tr` 标志, 而其他提供商可能只需要 `/tr` 标志来提供时间戳服务器。 用于签署 [此类](https://github.com/Dana-Prajea/code-sign-action) Windows 二进制文件的流行 GitHub Actions 不支持 SignTool.exe 上的 `/tr` 标志。 因此,本指南将重点介绍使用 PowerShell 命令手动签署我们的应用程序,但如果您愿意,可以使用类似 [代码签名操作](https://github.com/Dana-Prajea/code-sign-action) 的操作。 + +首先,让我们确保我们能够在我们的 GitHub CI 中构建我们的 Wails 应用程序。 这是一个小型工作流模板: + +```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/* +``` + +接下来,我们需要让 GitHub 工作流访问我们的签名证书。 这是通过将您的 .pfx 或 .p12 证书编码为 base64 字符串来完成的。 要在 PowerShell 中执行此操作,您可以使用以下命令,假设您的证书名为“my-cert.p12”: + +```PowerShell +certutil -encode .\my-cert.p12 my-cert-base64.txt +``` + +您现在应该拥有带有 base64 编码证书的 .txt 文件。 它应该以 _-----BEGIN CERTIFICATE-----_ 开头并以 _-----END CERTIFICATE-----_ 结尾。 现在你需要在 GitHub 上创建两个 action secret。 导航到 _Settings -> Secrets -> Actions_ 并创建以下两个 secrets: + +- **WIN_SIGNING_CERT** 您的 base64 编码证书文本的内容。 +- **WIN_SIGNING_CERT_PASSWORD** 您的证书密码的内容。 + +现在我们准备好使用以下两种方法之一在我们的工作流程中实现签名: + +### 方法一:使用命令签名 + +此方法使用 PowerShell 命令对我们的应用程序进行签名,并让您控制整个签名过程。 + +在该 `"Build Wails app"` 步骤之后,我们可以将以下步骤添加到我们的工作流程中: + +```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 /t /f certificate\certificate.pfx /p '${{ secrets.WIN_SIGNING_CERT_PASSWORD }}' + +``` + +此脚本为您的证书文件创建一个新目录,从我们的 base64 密钥创建证书文件,将其转换为 .pfx 文件,最后对二进制文件进行签名。 最后一行需要替换以下变量: + +- **签名算法**:通常是 sha256。 +- **时间戳服务器**:与您的证书一起使用的时间戳服务器的 URL。 +- **二进制路径**:要签名的二进制文件的路径。 + +鉴于我们的 Wails 配置将 `outputfilename` 设置为“app.exe”并且我们拥有来自 SSL.com 的证书,这将是我们的工作流程: + +```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/* +``` + +### 方法二:Action自动签名 + +可以使用像 [这样](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate) 的 Windows 代码签名操作,但请注意,它需要证书的 SHA1 哈希和证书名称。 查看如何在 Action 的 [市场](https://github.com/marketplace/actions/code-sign-a-file-with-pfx-certificate) 上配置它的示例。 + +--- + +## MacOS + +首先,您需要 Apple 提供的代码签名证书。 如果您没有,简单的谷歌搜索将帮助您获得一个。 获得证书后,您需要将其导出并将其编码为 base64。 本 [教程](https://localazy.com/blog/how-to-automatically-sign-macos-apps-using-github-actions) 向您展示了如何以简单的方式做到这一点。 导出 .p12 证书文件后,您可以使用以下命令将其编码为 base64,如教程中所示: + +```bash +base64 Certificates.p12 | pbcopy +``` + +现在您已准备好创建一些 GitHub 项目 secrets,就像在 Windows 中一样: + +- **APPLE_DEVELOPER_CERTIFICATE_P12_BASE64** 您新复制的 base64 证书的内容。 +- **APPLE_DEVELOPER_CERTIFICATE_PASSWORD** 与您的证书密码的内容。 +- **APPLE_PASSWORD** 包含您可以在 [此处](https://appleid.apple.com/account/manage) 生成的 Apple-ID 帐户的应用程序特定密码的内容。 + +让我们确保我们能够在我们的 GitHub Action 工作流程中构建我们的 Wails 应用程序。 这是一个小模板: + +```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/* +``` + +对于 macOS 上的代码签名,[gon](https://github.com/mitchellh/gon) 是一个非常方便的工具,用于代码签名和与 Apple 服务器通信,也是用 Go 编写的,将在本指南中使用。 + +在 `Build Wails 应用` 步骤之后,将以下内容添加到工作流中: + +```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" + } +} +``` + +其中 `source` 是您的 Wails 二进制文件,`bundle_id` 是您的捆绑包 ID,`apple_id` 包含您之前创建的 Apple ID 用户名和 App-Specific 密码,`sign.application_identity` 是您的身份,您可以通过运行以下命令找到它: + +```bash +security find-identity -v -p codesigning +``` + +2. entitlements.plist: + +```plist + + + + + com.apple.security.app-sandbox + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + +``` + +在此文件中,您可以配置应用所需的权利,例如 如果您的应用使用相机,相机权限。 在 [此处](https://developer.apple.com/documentation/bundleresources/entitlements) 阅读有关权利的更多信息。 + +确保您已使用您在 `gon-sign.json` 中输入的相同包 ID 更新了 `Info.plist` 文件。 这是一个示例 `Info.plist` 文件: + +```plist + + + CFBundlePackageTypeAPPL + CFBundleNameMyApp + CFBundleExecutableapp + CFBundleIdentifierapp.myapp + CFBundleVersion0.1.0 + CFBundleGetInfoStringMy app is cool and nice and chill and + CFBundleShortVersionString0.1.0 + CFBundleIconFileiconfile + LSMinimumSystemVersion10.13.0 + NSHighResolutionCapabletrue + LSApplicationCategoryTypepublic.app-category.utilities + NSHumanReadableCopyright© Me + +``` + +现在我们准备好在构建 Wails 应用程序后在我们的工作流程中添加签名步骤: + +```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 +``` + +请注意,与 Apple 签署二进制文件可能需要几分钟到几小时。 + +## 组合工作流文件: + +这是我们结合了 Windows + macOS 的 GitHub 工作流文件: + +```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/* +``` + +# 尾注 + +本指南受 RiftShare 项目及其工作流程的启发,强烈建议在 [此处](https://github.com/achhabra2/riftshare/blob/main/.github/workflows/build.yaml) 查看。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx new file mode 100644 index 00000000000..dc7706f8ffa --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/single-instance-lock.mdx @@ -0,0 +1,81 @@ +# Single Instance Lock + +Single instance lock is a mechanism that allows you to prevent multiple instances of your app from running at the same time. +It is useful for apps that are designed to open files from the command line or from the OS file explorer. + +## Important + +Single Instance Lock does not implement a secure communications protocol between instances. When using single instance lock, +your app should treat any data passed to it from second instance callback as untrusted. +You should verify that args that you receive are valid and don't contain any malicious data. + +## How it works + +Windows: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via a shared window using [SendMessage](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage) +macOS: Single instance lock is implemented using a named mutex. The mutex name is generated from the unique id that you provide. Data is passed to the first instance via [NSDistributedNotificationCenter](https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter) +Linux: Single instance lock is implemented using [dbus](https://www.freedesktop.org/wiki/Software/dbus/). The dbus name is generated from the unique id that you provide. Data is passed to the first instance via [dbus](https://www.freedesktop.org/wiki/Software/dbus/) + +## Usage + +When creating your app, you can enable single instance lock by passing a `SingleInstanceLock` struct to the `App` struct. +Use the `UniqueId` field to specify a unique id for your app. +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. +The `OnSecondInstanceLaunch` field is used to specify a callback that is called when a second instance of your app is launched. +The callback receives a `SecondInstanceData` struct that contains the command line arguments passed to the second instance and the working directory of the second instance. + +Note that OnSecondInstanceLaunch don't trigger windows focus. +You need to call `runtime.WindowUnminimise` and `runtime.Show` to bring your app to the front. +Note that on linux systems window managers may prevent your app from being brought to the front to avoid stealing focus. + +```go title="main.go" +var wailsContext *context.Context + +// NewApp creates a new App application struct +func NewApp() *App { + return &App{} +} + +// startup is called when the app starts. The context is saved +// so we can call the runtime methods +func (a *App) startup(ctx context.Context) { + wailsContext = &ctx +} + +func (a *App) onSecondInstanceLaunch(secondInstanceData options.SecondInstanceData) { + secondInstanceArgs = secondInstanceData.Args + + println("user opened second instance", strings.Join(secondInstanceData.Args, ",")) + println("user opened second from", secondInstanceData.WorkingDirectory) + runtime.WindowUnminimise(*wailsContext) + runtime.Show(*wailsContext) + go runtime.EventsEmit(*wailsContext, "launchArgs", secondInstanceArgs) +} + +func main() { + // Create an instance of the app structure + app := NewApp() + + // Create application with options + err := wails.Run(&options.App{ + Title: "wails-open-file", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1}, + OnStartup: app.startup, + SingleInstanceLock: &options.SingleInstanceLock{ + UniqueId: "e3984e08-28dc-4e3d-b70a-45e961589cdc", + OnSecondInstanceLaunch: app.onSecondInstanceLaunch, + }, + Bind: []interface{}{ + app, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx new file mode 100644 index 00000000000..4651c422ed1 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/sveltekit.mdx @@ -0,0 +1,153 @@ +# SvelteKit + +This guide will go into: + +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. Minimal Installation Steps + +##### Install Wails for Svelte. + +- `wails init -n myapp -t svelte` + +##### Delete the svelte frontend. + +- Navigate into your newly created myapp folder. +- Delete the folder named "frontend" + +##### While in the Wails project root. Use your favorite package manager and install SvelteKit as the new frontend. Follow the prompts. + +- `npm create svelte@latest frontend` + +##### Modify 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. + +##### Modify main.go. + +- The first comment `//go:embed all:frontend/dist` needs to be changed to `//go:embed all:frontend/build` + +##### Install/remove dependencies using your favorite package manager. + +- Navigate into your "frontend" folder. +- `npm i` +- `npm uninstall @sveltejs/adapter-auto` +- `npm i -D @sveltejs/adapter-static` + +##### Change adapter in svelte.config.js + +- First line of file change `import adapter from '@sveltejs/adapter-auto';` to `import adapter from '@sveltejs/adapter-static';` + +##### Put SvelteKit into SPA mode with prerendering. + +- 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` + +##### Test 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. + +## 2. Install Script + +##### 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. + +- 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` + +##### sveltekit-wails.sh: + +``` +manager=$1 +project=$2 +brand=$3 +wails init -n $project -t svelte +cd $project +sed -i "s|npm|$manager|g" wails.json +sed -i 's|"auto",|"auto",\n "wailsjsdir": "./frontend/src/lib",|' wails.json +sed -i "s|all:frontend/dist|all:frontend/build|" main.go +if [[ -n $brand ]]; then + mv frontend/src/App.svelte +page.svelte + sed -i "s|'./assets|'\$lib/assets|" +page.svelte + sed -i "s|'../wails|'\$lib/wails|" +page.svelte + mv frontend/src/assets . +fi +rm -r frontend +$manager create svelte@latest frontend +if [[ -n $brand ]]; then + mv +page.svelte frontend/src/routes/+page.svelte + mkdir frontend/src/lib + mv assets frontend/src/lib/ +fi +cd frontend +$manager i +$manager uninstall @sveltejs/adapter-auto +$manager i -D @sveltejs/adapter-static +echo -e "export const prerender = true\nexport const ssr = false" > src/routes/+layout.ts +sed -i "s|-auto';|-static';|" svelte.config.js +cd .. +wails dev +``` + +## 3. Important Notes + +##### Server files will cause build failures. + +- \+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. + +##### The Wails runtime unloads with full page navigations! + +- Anything that causes full page navigations: `window.location.href = '//'` 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('//')` 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 `` of myapp/frontend/src/app.html + +``` + +... + + + +... + +``` + +See https://wails.io/docs/guides/frontend for more information. + +##### Inital data can be loaded and refreshed from +page.ts/+page.js to +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. + +##### Error Handling + +- 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. + +``` +import { WindowReloadApp } from '$lib/wailsjs/runtime/runtime' +export async function handleError() { + WindowReloadApp() +} +``` + +##### Using Forms and handling functions + +- The simplest way is to call a function from the form is the standard, bind:value your variables and prevent submission `` +- 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: + +``` + { + cancel() + console.log(Object.fromEntries(formData)) + console.log(formElement) + console.log(submitter) + handle() +}}> +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx new file mode 100644 index 00000000000..7f701203d1c --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/templates.mdx @@ -0,0 +1,97 @@ +# 模板 + +Wails 从预先创建的模板生成项目。 在 v1 中,这是一组难以维护的项目,这些项目可能会过时。 在 v2 中,为了增强社区的能力,为模板添加了一些新功能: + +- 能够从 [远程模板](../reference/cli#远程模板) 生成项目 +- 帮助创建自己的模板的工具 + +## 创建模板 + +要创建模板,您可以使用 `wails generate template` 命令。 要生成默认模板,请运行: + +`wails generate template -name mytemplate` + +这将使用默认文件创建“mytemplate”目录: + +```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 +``` + +### 模板概述 + +默认模板包含以下文件和目录: + +| 文件名 / 目录 | 描述 | +| --------------- | ----------------- | +| NEXTSTEPS.md | 有关如何完成模板的说明 | +| README.md | 随模板发布的 README | +| app.tmpl.go | `app.go` 模板文件 | +| frontend/ | 包含前端资源的目录 | +| go.mod.tmpl | `go.mod` 模板文件 | +| main.tmpl.go | `main.go` 模板文件 | +| template.json | 模板元数据 | +| wails.tmpl.json | `wails.json` 模板文件 | + +此时,建议按照 `NEXTSTEPS.md` 中的步骤操作。 + +## 从现有项目创建模板 + +通过在生成模板时将路径传递给项目,可以从现有的前端项目创建模板。 我们现在将介绍如何创建 Vue 3 模板: + +- 安装 vue cli: `npm install -g @vue/cli` +- 创建默认项目:`vue create vue3-base` + - 选择 `Default (Vue 3) ([Vue 3] babel, eslint)` +- 项目生成后,运行: + +```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... +``` + +- 现在可以按照 `NEXTSTEPS.md` 中指定的方式定制模板。 +- 一旦文件准备完毕,就可以通过运行命令来测试它:`wails init -n my-vue3-project -t .\wails-vue3-template\` +- 要测试新项目,请运行:`cd my-vue3-project` then `wails build` +- 项目编译完成后,运行它:`.\build\bin\my-vue3-project.exe` +- 您应该有了一个功能齐全的 Vue3 应用程序: + +```mdx-code-block +
+ +
+``` + +## 发布模板 + +发布模板只是将文件推送到 GitHub。 鼓励以下最佳实践: + +- 从前端目录中删除任何不需要的文件和目录(例如:.git) +- 确保 `template.json` 完整,尤其是 `helpurl` +- 将文件推送到 GitHub +- 在 [社区模板](../community/templates) 页面上创建 PR +- 在 [模板公告](https://github.com/wailsapp/wails/discussions/825) 讨论板上发布模板 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx new file mode 100644 index 00000000000..3f12baf7d60 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/troubleshooting.mdx @@ -0,0 +1,368 @@ +# 故障排除 + +各种故障排除技巧。 + +## `wails` 命令好像不见了? + +如果您的系统报告缺少 `wails` 命令,请确保您已正确遵循 Go 安装指南。 通常,这意味着您的用户 home 目录中的 `go/bin` 目录不在 `PATH` 环境变量中。 通常情况下还需要关闭并重新打开任何已打开的命令提示符,以便安装程序对环境所做的更改反映在命令提示符中。 + +## 我的应用程序正在显示白屏/空白屏幕 + +检查您的应用程序是否包含正确目录中的资产。 在您的 `main.go` 文件中,您将拥有类似于以下代码的内容: + +```go +//go:embed all:frontend/dist +var assets embed.FS +``` + +检查它是否 `frontend/dist` 包含您的应用程序资产。 + +### Mac + +如果在 Mac 上发生这种情况,请尝试将以下内容添加到您的 `Info.plist`: + +```xml +NSAppTransportSecurity + + NSAllowsLocalNetworking + + +``` + +参考:https://github.com/wailsapp/wails/issues/1504#issuecomment-1174317433 + +## Mac 应用程序无效 + +如果您构建的应用程序在 finder 中如下所示: + +```mdx-code-block +

+ +

+``` + +您的申请很可能 `info.plist` 是无效的。 更新 `build/.app/Contents/info.plist`文件 并检查数据是否有效,比如:检查二进制名称是否正确。 要保留更改,请将文件复制回 `build/darwin` 目录。 + +## 我的应用程序未在 Windows 资源管理器中显示正确的图标 + +如果您的应用程序未显示正确的图标,请尝试删除位于 `C:\Users\<您的用户名>\AppData\Local` 目录中的隐藏 `IconCache.db` 文件。 这将强制 Windows 重建图标缓存。 + +来源:https://github.com/wailsapp/wails/issues/2360#issuecomment-1556070036 + +## 无法使用可变参数 + +如果您有使用可变参数定义的后端方法,例如: + +```go +func (a *App) TestFunc(msg string, args ...interface{}) error { + // Code +} +``` + +像这样从前端调用此方法将失败: + +```js +var msg = "Hello: "; +var args = ["Go", "JS"]; +window.go.main.App.TestFunc(msg, ...args) + .then((result) => { + //do things here + }) + .catch((error) => { + //handle error + }); +``` + +解决方法: + +```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 + }); +``` + +致谢:https://github.com/wailsapp/wails/issues/1186 + +## 我正在尝试安装Wails时获取代理错误 + +如果您遇到这样的错误: + +``` +"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. +``` + +这可能是因为官方 Go Proxy 被阻止(中国用户报告了这一点)。 解决方案是手动设置代理,例如: + +``` +go env -w GO111MODULE=on +go env -w GOPROXY=https://goproxy.cn,direct +``` + +来源:https://github.com/wailsapp/wails/issues/1233 + +## 没有生成正确的 TypeScript 类型 + +有时生成的 TypeScript 没有正确的类型。 `ts_type` 为了缓解这种情况,可以使用 struct 标签指定应该生成哪些类型。 有关详细信息,请阅读 [此](https://github.com/tkrajina/typescriptify-golang-structs#custom-types) 内容。 + +## 当我离开 `index.html`时,我无法在前端调用方法 + +如果您导航 `index.html` 到一个新的 html 文件,上下文将会丢失。 这可以通过将以下导入添加到 `` 您导航到的任何新页面的部分来解决: + +```html + + + + +``` + +来源:https://github.com/wailsapp/wails/discussions/1512 + +## 运行 `wails dev` 出现 `too many open files` 错误 + +默认情况下,macOS 最多只能打开 256 个文件。 这会影响 `wails dev` 命令 可以通过在终端中运行:`ulimit -n 1024` 来增加此限制。 + +FSNotify 正在 [寻求转移到苹果](https://github.com/fsnotify/fsnotify/issues/11)。 如果这不能很快完成,我们将创建自己的实现,在 [此处](https://github.com/wailsapp/wails/issues/1733) 跟踪。 + +## 我的 Mac 应用程序给了我奇怪的编译错误 + +一些用户报告看到编译错误,如下所示: + +```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))) +``` + +这 _通常_ 是由于您正在运行的操作系统版本和安装的 XCode 命令行工具的版本不匹配。 如果您看到这样的错误,请尝试将您的 XCode 命令行工具升级到最新版本。 + +如果重新安装 Xcode 命令工具仍然失败,您可以通过以下方式检查工具包所在的路径: + +`xcode-select -p` + +如果显示 `/Applications/Xcode.app/Contents/Developer` ,运行 `sudo xcode-select --twitter /Library/Developer/CommandLineTools` + +来源:https://github.com/wailsapp/wails/issues/1806 和 https://github.com/wailsapp/wails/issues/1140#issuecomment-1290446496 + +## My application won't compile on Mac + +如果您遇到这样的错误: + +```shell +l1@m2 GoEasyDesigner % go build -tags dev -gcflags "all=-N -l" +/Users/l1/sdk/go1.20.5/pkg/tool/darwin_arm64/link: running clang failed: exit status 1 +Undefined symbols for architecture arm64: + "_OBJC_CLASS_$_UTType", referenced from: + objc-class-ref in 000016.o +ld: symbol(s) not found for architecture arm64 +clang: error: linker command failed with exit code 1 (use -v to see invocation) +``` +Ensure you have the latest SDK installed. If so and you're still experiencing this issue, try the following: + +```shell +export CGO_LDFLAGS="-framework UniformTypeIdentifiers" && go build -tags dev -gcflags "all=-N -l" +``` + +Sources: https://github.com/wailsapp/wails/pull/2925#issuecomment-1726828562 + + +-- + +## 无法启动服务:主机版本“x.x.x”与二进制版本“x.x.x”不匹配 + +最好将 `frontend/node_modules` 和 `frontend/package-lock.json` 添加到您的 `.gitignore` 中。 否则,当在另一台可能安装了不同版本 Node 的机器上打开您的存储库时,您可能无法运行您的应用程序。 + +如果发生这种情况,只需删除 `frontend/node_modules` 和 `frontend/package-lock.json` 并再次运行 `wails build` 或 `wails dev` 命令。 + +## 构建过程停留在“生成绑定” + +绑定生成过程在特殊模式下运行应用程序。 如果应用程序有意或无意地包含一个无限循环(即在 `wails.Run()` 结束后不退出),这可能导致构建过程停留在绑定生成阶段。 请确保您的代码正确退出。 + +## Mac application flashes white at startup + +This is due to the default background of the webview being white. If you want to use the window background colour instead, you can make the webview background transparent using the following config: + +```go + err := wails.Run(&options.App{ + Title: "macflash", + Width: 1024, + Height: 768, + // Other settings + Mac: &mac.Options{ + WebviewIsTransparent: true, + }, + }) +``` + +## I get a "Microsoft Edge can't read or write to its data directory" error when running my program as admin on Windows + +You set your program to require admin permissions and it worked great! Unfortunately, some users are seeing a "Microsoft Edge can't read or write to its data directory" error when running it. + +When a Windows machine has two local accounts: + +- Alice, an admin +- Bob, a regular user + +Bob sees a UAC prompt when running your program. Bob enters Alice's admin credentials into this prompt. The app launches with admin permissions under Alice's account. + +Wails instructs WebView2 to store user data at the specified `WebviewUserDataPath`. It defaults to `%APPDATA%\[BinaryName.exe]`. + +Because the application is running under Alice's account, `%APPDATA%\[BinaryName.exe]` resolves to `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`. + +WebView2 [creates some child processes under Bob's logged-in account instead of Alice's admin account](https://github.com/MicrosoftEdge/WebView2Feedback/issues/932#issue-807464179). Since Bob cannot access `C:\Users\Alice\AppData\Roaming\[BinaryName.exe]`, the "Microsoft Edge can't read or write to its data directory" error is shown. + +Possible solution #1: + +Refactor your application to work without constant admin permissions. If you just need to perform a small set of admin tasks (such as running an updater), you can run your application with the minimum permissions and then use the `runas` command to run these tasks with admin permissions as needed: + +```go +//go:build windows + +package sample + +import ( + "golang.org/x/sys/windows" + "syscall" +) + +// Calling RunAs("C:\path\to\my\updater.exe") shows Bob a UAC prompt. Bob enters Alice's admin credentials. The updater launches with admin permissions under Alice's account. +func RunAs(path string) error { + verbPtr, _ := syscall.UTF16PtrFromString("runas") + exePtr, _ := syscall.UTF16PtrFromString(path) + cwdPtr, _ := syscall.UTF16PtrFromString("") + argPtr, _ := syscall.UTF16PtrFromString("") + + var showCmd int32 = 1 //SW_NORMAL + + err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd) + if err != nil { + return err + } + return nil +} +``` + +Possible solution #2: + +Run your application with extended permissions. If you absolutely must run with constant admin permissions, WebView2 will function correctly if you use a data directory accessible by both users and you also launch your app with the `SeBackupPrivilege`, `SeDebugPrivilege`, and `SeRestorePrivilege` permissions. Here's an example: + +```go +package main + +import ( + "embed" + "os" + "runtime" + + "github.com/fourcorelabs/wintoken" + "github.com/hectane/go-acl" + "github.com/wailsapp/wails/v2" + "github.com/wailsapp/wails/v2/pkg/options" + "github.com/wailsapp/wails/v2/pkg/options/assetserver" + "github.com/wailsapp/wails/v2/pkg/options/windows" +) + +//go:embed all:frontend/dist +var assets embed.FS + +const ( + fixedTokenKey = "SAMPLE_RANDOM_KEY" + fixedTokenVal = "with-fixed-token" + webviewDir = "C:\\ProgramData\\Sample" +) + +func runWithFixedToken() { + println("Re-launching self") + token, err := wintoken.OpenProcessToken(0, wintoken.TokenPrimary) //pass 0 for own process + if err != nil { + panic(err) + } + defer token.Close() + + token.EnableTokenPrivileges([]string{ + "SeBackupPrivilege", + "SeDebugPrivilege", + "SeRestorePrivilege", + }) + + cmd := exec.Command(os.Args[0]) + cmd.Args = os.Args + cmd.Env = os.Environ() + cmd.Env = append(cmd.Env, fmt.Sprintf("%v=%v", fixedTokenKey, fixedTokenVal)) + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Token: syscall.Token(token.Token())} + if err := cmd.Run(); err != nil { + println("Error after launching self:", err) + os.Exit(1) + } + println("Clean self launch :)") + os.Exit(0) +} + +func main() { + if runtime.GOOS == "windows" && os.Getenv(fixedTokenKey) != fixedTokenVal { + runWithFixedToken() + } + + println("Setting data dir to", webviewDir) + if err := os.MkdirAll(webviewDir, os.ModePerm); err != nil { + println("Failed creating dir:", err) + } + if err := acl.Chmod(webviewDir, 0777); err != nil { + println("Failed setting ACL on dir:", err) + } + + app := NewApp() + + err := wails.Run(&options.App{ + Title: "sample-data-dir", + Width: 1024, + Height: 768, + AssetServer: &assetserver.Options{ + Assets: assets, + }, + Bind: []interface{}{ + app, + }, + Windows: &windows.Options{ + WebviewUserDataPath: webviewDir, + }, + }) + + if err != nil { + println("Error:", err.Error()) + } +} +``` + +If you use a data directory accessible by both users but not the extended privileges, you will receive a WebView2 `80010108 The object invoked has disconnected from its clients` error. + +Possible future solution #3: [run WebView2 using an in-memory mode if implemented](https://github.com/MicrosoftEdge/WebView2Feedback/issues/3637#issuecomment-1728300982). + +## WebView2 installation succeeded, but the wails doctor command shows that it is not installed + +If you have installed WebView2, but the `wails doctor` command shows that it is not installed, it is likely that the WebView2 runtime installed was for a different architecture. You can download the correct runtime from [here](https://developer.microsoft.com/en-us/microsoft-edge/webview2/). + +Source: https://github.com/wailsapp/wails/issues/2917 + +## WebVie2wProcess failed with kind + +If your Windows app generates this kind of error, you can check out what the error means [here](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2processfailedkind?view=webview2-winrt-1.0.2045.28). + diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx new file mode 100644 index 00000000000..ea2d1b99d5b --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/vscode.mdx @@ -0,0 +1,82 @@ + +# Visual Studio Code + +此页面提供在使用带有 Wails 的 Visual Studio Code 时的各种提示和技巧。 + +## Vetur 配置 + +非常感谢 [@Lyimmi](https://github.com/Lyimmi) 的这个提示。 最初张贴 [在这里](https://github.com/wailsapp/wails/issues/1791#issuecomment-1228158349)。 + +Vetur 是一个流行的 Visual Studio Code 插件,它为 Vue 项目提供语法高亮和代码完成。 在 VSCode 中加载 Wails 项目时,Vetur 会抛出错误,因为它期望在根目录中找到前端项目。 要解决此问题,您可以执行以下操作: + +在项目根目录创建一个以 `vetur.config.js` 命名的文件。 + +```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' + ] + } + ] +} +``` + +接下来,配置 `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" + ] +} +``` +这应该使您现在可以按预期使用 Vetur。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx new file mode 100644 index 00000000000..02c73c16ca3 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows-installer.mdx @@ -0,0 +1,58 @@ +# NSIS 安装程序 + +```mdx-code-block +

+ +
+

+``` + +Wails 支持使用 [NSIS 安装程序](https://nsis.sourceforge.io/) 生成 Windows 安装程序。 + +## 安装 NSIS + +### Windows + +安装程序可在 [NSIS 下载页面](https://nsis.sourceforge.io/Download) 上找到。 + +如果您使用 chocolatey 包管理器,请运行以下脚本: + +``` +choco install nsis +``` + +如果手动安装 NSIS,则需要将 NSIS 安装目录中包含 `makensis.exe` 的 *Bin* 目录添加到 PATH 中。 [这是](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/) 一个关于如何在 Windows 上添加到 PATH 的好教程。 + +### Linux + +应该可以通过您的发行版的软件包管理器获得 `nsis` 包。 + +### MacOS + +NSIS 可通 homebrew 安装:`brew install nsis`。 + +## 生成安装程序 + +创建新项目时,Wails 会在 `build/windows/installer` 中生成 NSIS 配置文件。 从 `installer/info.json` 读取配置数据,并配置为使用项目的 `wails.json` 信息部分: + +```json +// ... + "Info": { + "companyName": "My Company Name", + "productName": "Wails Vite", + "productVersion": "1.0.0", + "copyright": "Copyright.........", + "comments": "Built using Wails (https://wails.io)" + }, +``` + +要为您的应用程序生成安装程序,请使用 `wails build` 的 `-nsis` 标志: + +``` +wails build -nsis +``` + +现在可用安装程序将生成在 `build/bin` 目录中。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx new file mode 100644 index 00000000000..0fc857c81c7 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/guides/windows.mdx @@ -0,0 +1,61 @@ +# Windows + +此页面包含了在 Windows 上开发 Wails 应用程序相关的其他指南。 + +## 处理 WebView2 运行时依赖 + +为 Windows 构建 Wails 应用程序时对 Microsoft [WebView2 运行时](https://developer.microsoft.com/en-us/microsoft-edge/webview2/) 有要求。 默认情况下,Windows 11 会安装它,但有些机器不会。 Wails 提供了一种简单的方法来处理这种依赖关系。 + +通过在构建时使用 `-webview2` 标志, 您可以决定在未检测到合适的运行时的时候(包括安装的运行时是否太旧)应用程序将执行的操作。 四个选项是: + +1. Download(下载) +2. Embed(内嵌) +3. Browser(浏览器) +4. Error(报错) + +### Download(下载) + +此选项将提示用户在未找到合适的运行时时,提供从 Microsoft 的 WebView2 官方站点下载并运行引导程序。 如果用户继续,官方引导程序将被下载并运行。 + +### Embed(内嵌) + +此选项将官方引导程序嵌入到应用程序中。 如果没有找到合适的运行时,应用程序将提供并运行引导程序。 这将使二进制大小增加约 150k。 + +### Browser(浏览器) + +此选项将提示用户没有找到合适的运行时时,提供打开浏览器到 WebView2 官方页面,可以下载和安装引导程序。 然后应用程序将会退出,安装的操作留给用户。 + +### Error(报错) + +如果未找到合适的运行时间,则会向用户显示错误并且不采取进一步措施。 + +## 固定版本运行时 + +处理 webview2 依赖的另一种方法是自己发送。 您可以下载 [固定版本的运行时](https://developer.microsoft.com/microsoft-edge/webview2/#download-section) 并将其捆绑或与您的应用程序一起下载。 + +此外,您应该在启动 wails 时在结构体 `windows.Options` 中指定 webview2 运行时的固定版本的路径。 + +```go + wails.Run(&options.App{ + Windows: &windows.Options{ + WebviewBrowserPath: "", + }, + }) +``` + +注意:当 `WebviewBrowserPath` 指定时,`error` 策略将在最小要求版本不匹配或运行时路径无效的情况下被强制执行。 + +## 创建其他程序 + +当生成其他程序(例如脚本)时,您将看到屏幕上出现该窗口。 要隐藏窗口,可以使用以下代码: + +```go +cmd := exec.Command("your_script.exe") +cmd.SysProcAttr = &syscall.SysProcAttr{ + HideWindow: true, + CreationFlags: 0x08000000, +} +cmd.Start() +``` + +[sithembiso](https://github.com/sithembiso) 在 [讨论板](https://github.com/wailsapp/wails/discussions/1734#discussioncomment-3386172) 上提供的解决方案。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx new file mode 100644 index 00000000000..bd9fb078ba6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/howdoesitwork.mdx @@ -0,0 +1,369 @@ +--- +sidebar_position: 20 +--- + +# 它是如何工作的? + +Wails 应用程序是一个带有一个 webkit 前端的标准的 Go 应用程序。 应用程序的 Go 部分由应用程序代码和一个运行时库组成, 该库提供了许多有用的操作,例如控制应用程序窗口。 前端是一个 webkit 窗口,将显示前端资源。 前端还可以使用运行时库的 JavaScript 版本。 最后,可以将 Go 方法绑定到前端,这些将显示为可以调用的 JavaScript 方法,就像它们是原生 JavaScript 方法一样。 + +```mdx-code-block +
+ +
+``` + +## 主应用程序 + +### 概述 + +主应用程序由对 `wails.Run()` 的调用组成。 它接受描述应用程序窗口大小、窗口标题、要使用的资源等应用程序配置。 基本应用程序可能如下所示: + +```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) +} +``` + +### 选项概要 + +此示例设置了以下选项: + +- `Title` - 应该出现在窗口标题栏中的文本 +- `Width` & `Height` - 窗口的尺寸 +- `Assets` - 应用程序的前端资产 +- `OnStartup` - 创建窗口并即将开始加载前端资源时的回调 +- `OnShutdown` - 应用程序即将退出时的回调 +- `Bind` - 我们希望向前端暴露的一部分结构体实例 + +完整的应用程序参数选项列表可以在 [参数选项](./reference/options) 中找到。 + +#### 资产 + +`Assets` 选项是必须的,因为您不能拥有没有前端资产的 Wails 应用程序。 这些资产可以是您希望在 Web 应用程序中找到的任何文件 - html、js、css、svg、png 等。 **不需要生成资源包** - 普通文件即可。 当应用程序启动时,它将尝试从您的资产中加载 `index.html`,并且那时起前端基本上将作为浏览器工作。 值得注意的是 `embed.FS` 对文件所在的位置没有要求。 嵌入路径很可能使用了相对于您的主应用程序代码的嵌套目录,例如 `frontend/dist`: + +```go title="main.go" +//go:embed all:frontend/dist +var assets embed.FS +``` + +启动时,Wails 将遍历嵌入的文件,寻找包含的 `index.html`。 所有其他资源将相对于该目录加载。 + +由于可用于生产的二进制文件使用包含在 `embed.FS` 中的文件,因此应用程序不需要附带任何外部文件。 + +在开发模式下使用 `wails dev` 命令,资产从磁盘加载,任何更改都会导致“实时重新加载”。 资产的位置将从 `embed.FS` 推断。 + +更多细节可以在 [应用开发指南](./guides/application-development) 中找到。 + +#### 应用程序生命周期回调 + +在即将加载前端 `index.html` 之前,会对 [应用启动回调](./reference/options#应用启动回调) 中提供的函数进行调用。 一个标准的 Go context 被传递给这个方法。 调用运行时需要此 context ,因此标准模式是在此方法中保存对它的引用。 在应用程序关闭之前,以同样的方式调用 [应用退出回调](./reference/options#应用退出回调),并再次使用上下文 在应用程序关闭之前,以同样的方式调用 [应用退出回调](./reference/options#应用退出回调),并再次使用上下文 当前端加载完 `index.html` 中所有资源时,还有一个 [前端 Dom 加载完成回调](./reference/options#前端-dom-加载完成回调) ,相当于 JavaScript 中的 [`body onload`](https://www.w3schools.com/jsref/event_onload.asp) 事件。 还可以通过设置 [应用关闭前回调](./reference/options#应用关闭前回调) 选项来控制窗口关闭(或应用程序退出)事件。 + +#### 方法绑定 + +`Bind` 选项是 Wails 应用程序中最重要的参数选项之一。 它指定向前端暴露哪些结构体方法。 想想传统 web 应用程序中的 "Controllers" 之类的结构 。 当应用程序启动时,它会检查 `Bind` 字段中列出的结构体实例, 确定哪些方法是公开的(以大写字母开头),并生成前端可以调用的这些方法的 JavaScript 版本。 + +:::info 注意 + +Wails 要求您传入结构体的 _实例_ 以使其正确绑定 + +::: + +在此示例中,我们创建一个新的 `App` 实例,然后将此实例添加到 `wails.Run` 中的 `Bind` 选项: + +```go {17,27} 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) +} +``` + +您可以绑定任意数量的结构体。 只需确保创建它的实例并将其传递给 `Bind`: + +```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{}, + }, + }) + +``` + +当您运行 `wails dev`(或 `wails generate module`)时,将生成一个前端模块,其中包含以下内容: + +- 所有绑定方法的 JavaScript 绑定 +- 所有绑定方法的 TypeScript 声明 +- 绑定方法用作输入或输出的所有 Go 结构的 TypeScript 声明 + +这使得使用相同的强类型数据结构从前端调用 Go 代码变得异常简单。 + +## 前端 + +### 概述 + +前端是由 webkit 渲染的文件集合。 这就合二为一的浏览器和网络服务器。 您可以使用的框架或库[^1]几乎没有限制。 前端和 Go 代码之间的主要交互点是: + +- 调用绑定的 Go 方法 +- 调用运行时方法 + +### 调用绑定的 Go 方法 + +当您使用 `wails dev` 运行应用程序时,它将自动在名为 `wailsjs/go` 的目录中为您的结构体生成 JavaScript 绑定(您也可以通过运行 `wails generate module` 来执行此操作)。 生成的文件反映了应用程序中的包名称。 在上面的例子中,我们绑定了有公开方法 `Greet` 的 `app`。 这将导致生成以下文件: + +```bash +wailsjs + └─go + └─main + ├─App.d.ts + └─App.js +``` + +在这里我们可以看到有一个 `main` 包,其中包含绑定 `App` 结构体的 JavaScript 绑定,以及这些方法的 TypeScript 声明文件。 要从我们的前端调用 `Greet`,我们只需导入该方法并像普通的 JavaScript 函数一样调用它: + +```javascript +// ... +import { Greet } from "../wailsjs/go/main/App"; + +function doGreeting(name) { + Greet(name).then((result) => { + // Do something with result + }); +} +``` + +TypeScript 声明文件为您提供了绑定方法的正确类型: + +```ts +export function Greet(arg1: string): Promise; +``` + +生成的方法返回一个 Promise 成功的调用将导致 Go 调用的第一个返回值被传递给 `resolve` 处理程序。 不成功的调用是当 Go 方法的第二个返回值具有错误类型时,将错误实例传递回调用者。 这通过 `reject` 处理程序传回的。 在上面的示例中,`Greet` 只返回一个 `string`,因此 JavaScript 调用永远不会 reject - 除非将无效数据传递给它。 + +所有数据类型都在 Go 和 JavaScript 之间正确转换。 包括结构体。 如果您从 Go 调用返回一个结构体,它将作为 JavaScript 类返回到您的前端。 + +:::info 注意 + +结构体字段 _必须_ 具有有效的 `json` 标签,以包含在生成的 TypeScript 中。 + +目前不支持嵌套匿名结构体。 + +::: + +也可以将结构体发送回 Go。 作为期望的结构体的参数传递的任何 JavaScript map/class 都将转换为该结构体类型。 为了使这个过程更容易,在 `开发` 模式下,会生成一个 TypeScript 模块,声明绑定方法中使用的所有结构体类型。 使用此模块,可以构建原生 JavaScript 对象并将其发送到 Go 代码。 + +还支持在其签名中使用结构的 Go 方法。 绑定方法(作为参数或返回类型)指定的所有 Go 结构体都将作为 Go 代码包装器模块的一部分自动生成 TypeScript 版本。 使用这些,可以在 Go 和 JavaScript 之间共享相同的数据模型。 + +示例:我们更新 `Greet` 方法以接受一个 `Person` 而不是字符串: + +```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) +} +``` + +`wailsjs/go/main/App.js` 文件仍将包含以下代码: + +```js title="App.js" +export function Greet(arg1) { + return window["go"]["main"]["App"]["Greet"](arg1); +} +``` + +但是 `wailsjs/go/main/App.d.ts` 文件将使用以下代码进行更新: + +```ts title="App.d.ts" +import { main } from "../models"; + +export function Greet(arg1: main.Person): Promise; +``` + +正如我们所见,“main”命名空间是从一个新的“models.ts”文件中导入的。 该文件包含我们绑定方法使用的所有结构体定义。 在此示例中,这是一个 `Person` 结构。 如果我们查看 `models.ts`,我们可以看到模型是如何定义的: + +```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; + } + } +} +``` + +只要您将 TypeScript 作为前端构建配置的一部分,您就可以通过以下方式使用这些模型: + +```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); + }); +} +``` + +生成的绑定和 TypeScript 模型的结合构成了一个强大的开发环境。 + +有关绑定的更多信息,请参见 [应用开发指南](guides/application-development.mdx) 的 [绑定方法](guides/application-development.mdx#绑定方法) 部分。 + +### 调用运行时方法 + +JavaScript 运行时位于`window.runtime`并包含许多方法来执行各种任务,例如发出事件或执行日志记录操作: + +```js title="mycode.js" +window.runtime.EventsEmit("my-event", 1); +``` + +更多关于 JS 运行时的细节可以在 [运行时参考](reference/runtime/intro) 中找到。 + +[^1]: 有一小部分库使用了 WebView 中不支持的功能。 对于这种情况,通常有替代方案和解决方法。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx new file mode 100644 index 00000000000..caf230e8d0f --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/introduction.mdx @@ -0,0 +1,73 @@ +--- +sidebar_position: 1 +--- + +# 简介 + +Wails 是一个可让您使用 Go 和 Web 技术编写桌面应用的项目。 + +将它看作为 Go 的快并且轻量的 Electron 替代品。 您可以使用 Go 的灵活性和强大功能,结合丰富的现代前端,轻松的构建应用程序。 + +### 功能 + +- 原生菜单、对话框、主题和半透明 +- Windows、macOS 和 linux 支持 +- 内置 Svelte、React 、Preact 、Vue、Lit 和 Vanilla JS 的模板 +- 从 JavaScript 轻松调用 Go 方法 +- 自动将 Go 结构体转换为 TypeScript 模块 +- Windows 上不需要 CGO 或外部 DLL +- 使用 [Vite ](https://vitejs.dev/) 的实时开发模式 +- 可以轻松创建、构建和打包应用的强大命令行工具 +- 丰富的 [运行时库](/docs/reference/runtime/intro) +- 使用 Wails 构建的应用程序兼容 Apple & Microsoft 商店 + +这是 varly - 一个使用 Wails 编写的 MacOS 和 Windows 桌面应用。 它不仅看起来很强,它使用原生菜单和半透明 - 你希望从现代原生应用中得到的一切 + +```mdx-code-block +

+ +

+``` + +### 快速启动模板 + +Wails 带有许多预配置的模板,可让您快速启动和运行应用程序。 有以下框架的模板:Svelte、React、Vue、Preact、Lit 和 Vanilla。 每个模板都有 JavaScript 和 TypeScript 版本。 + +### 原生元素 + +Wails 使用专门构建的库来处理窗口、菜单、对话框等原生元素,因此您可以构建美观、功能丰富的桌面应用程序。 + +**It does not embed a browser**, so it delivers a small runtime. Instead, it reuses the native rendering engine for the platform. 在 Windows 上,是基于 Chromium 构建的新 Microsoft Webview2 库。 + +### Go 和 JavaScript 互操作 + +Wails 自动使您的 Go 方法可用于 JavaScript,因此您可以从前端按名称调用它们! 它甚至会生成 Go 方法使用的结构体的 TypeScript 版本,因此您可以在 Go 和 JavaScript 之间传递相同的数据结构。 + +### 运行时库 + +Wails 为 Go 和 JavaScript 提供了一个运行时库,它可以处理现代应用程序需要的很多东西,比如事件、日志记录、对话框等。 + +### 实时开发体验 + +#### 自动重新构建 + +当您在“开发”模式下运行您的应用程序时,Wails 会将您的应用程序构建为原生桌面应用程序,但会从磁盘读取您的资源。 它将检测您的 Go 代码的任何更改并自动重新构建和重新启动您的应用程序。 + +#### 自动重新加载 + +当检测到对您的应用程序资产的更改时,您正在运行的应用程序将“重新加载”,几乎立即反映您的更改 + +#### 在浏览器中开发您的应用程序 + +如果您更喜欢在浏览器中调试和开发,那么 Wails 可以满足您的需求。 正在运行的应用程序还有一个网络服务器,它将在连接到它的任何浏览器中运行您的应用程序。 当您的资源在磁盘上发生变化时,它会刷新。 + +### 可用于生产的原生二进制文件 + +当您准备好完成应用程序的最终构建时,CLI 会将其编译为单个可执行文件,并将所有资源打包到其中。 在 Windows 和 MacOS 上,可以创建用于分发的原生包。 使用打包工具后生成的资源(图标、info.plist、清单文件等)是您项目的一部分,可以自定义,让您完全控制应用程序的构建方式。 + +### 工具 + +Wails CLI 提供了一种简单的方法来生成、构建和打包您的应用程序。 它将完成创建图标的繁重工作,使用最佳设置编译您的应用程序,并提供可分发的、可用于生产的二进制文件。 可以从许多入门模板中进行选择,以快速启动和运行! diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json new file mode 100644 index 00000000000..ebb337b8360 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Reference", + "position": 40 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx new file mode 100644 index 00000000000..d28d2732c30 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/cli.mdx @@ -0,0 +1,240 @@ +--- +sidebar_position: 2 +--- + +# 命令行 + +Wails CLI 有许多用于管理项目的命令。 所有命令都以此方式运行: + +`wails <命令> <标志>` + +## 初始化 + +`wails init` 用于生成项目。 + +| 标志 | 描述 | 默认 | +|:--------- |:---------------------------------------------- |:-------:| +| -n "项目名称" | 项目名称。 **强制必填** | | +| -d "项目目录" | 要创建的项目目录 | 项目名 | +| -g | 初始化 git 存储库 | | +| -l | 可用项目模板列表 | | +| -q | 禁止输出到控制台 | | +| -t "模板名称" | 要使用的项目模板。 这可能是默认模板的名称或托管在 github 上的远程模板的 URL 。 | vanilla | +| -ide | 生成 IDE 项目文件 | | +| -f | 强制构建应用 | false | + +示例: `wails init -n test -d mytestproject -g -ide vscode -q` + +这将在 "mytestproject" 目录生成一个名为 "test" 的项目,初始化 git,生成 vscode 项目文件并静默执行。 + +可以在 [此处](../guides/ides) 找到有关在 Wails 中使用 IDE 的更多信息。 + +### 远程模板 + +支持远程模板(托管在 GitHub )并且可以使用模板项目的 URL 进行安装。 + +示例: `wails init -n test -t https://github.com/leaanthony/testtemplate[@v1.0.0]` + +可以在 [此处](../community/templates.mdx) 找到社区维护的模板列表 + +:::warning 注意 + +**Wails 项目不维护也不对第 3 方模板负责** + +如果您不确定某个模板,请检查 `package.json` 和 `wails.json` 中安装的模块和运行的脚本。 + +::: + +## 构建 + +`wails build` 用于将您的项目编译为生产可用的二进制文件。 + +| 标志 | 描述 | 默认 | +|:--------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |:---------------------------------------------------------------------------------------------------------- | +| -clean | 清理 `build/bin` 目录 | | +| -compiler "编译器" | 使用不同的 go 编译器来构建,例如 go1.15beta1 | go | +| -debug | Retains debug information in the application and shows the debug console. 允许在应用程序窗口中使用 devtools | | +| -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 | 打印构建命令但不执行它 | | +| -f | 强制构建应用 | | +| -garbleargs | 传递给 garble 的参数 | `-literals -tiny -seed=random` | +| -ldflags "标志" | 传递给编译器的额外 ldflags | | +| -m | 编译前跳过 mod tidy | | +| -nopackage | 不打包应用程序 | | +| -nocolour | 在输出中禁用颜色 | | +| -nosyncgomod | 不同步 go.mod 中的 Wails 版本 | | +| -nsis | 为 Windows 生成 NSIS 安装程序 | | +| -o 文件名 | 输出文件名 | | +| -obfuscated | 使用 [garble](https://github.com/burrowers/garble) 混淆应用程序 | | +| -platform | 为指定的 [平台](../reference/cli#平台)(逗号分割)构建,例如: `windows/arm64`。 `windows/arm64`。 注意,如果不给出架构,则使用 `runtime.GOARCH`。 | 如果给定环境变量 platform = `GOOS` 否则等于 `runtime.GOOS`。
如果给定环境变量 arch = `GOARCH` 否则等于 `runtime.GOARCH`. | +| -race | 使用 Go 的竞态检测器构建 | | +| -s | 跳过前端构建 | | +| -skipbindings | 跳过 bindings 生成 | | +| -tags "额外标签" | 构建标签以传递给 Go 编译器。 必须引用。 空格或逗号(但不能同时使用)分隔 | | +| -trimpath | 从生成的可执行文件中删除所有文件系统路径。 | | +| -u | 更新项目的 `go.mod` 以使用与 CLI 相同版本的 Wails | | +| -upx | 使用 “upx” 压缩最终二进制文件 | | +| -upxflags | 传递给 upx 的标志 | | +| -v int | 详细级别 (0 - silent, 1 - default, 2 - verbose) | 1 | +| -webview2 | WebView2 安装策略:download,embed,browser,error. | download | +| -windowsconsole | 保留Windows构建控制台窗口 | | + +有关 `webview2` 标志的详细描述,请参阅 [Windows 系统指南](../guides/windows)。 + +如果您更喜欢使用标准 Go 工具进行构建,请参阅 [手动构建指南](../guides/manual-builds)。 + +示例: + +`wails build -clean -o myproject.exe` + +:::info + +在 Mac 上,应用程序将被绑定到 `Info.plist`,而不是 `Info.dev.plist`。 + +::: + +:::info 苹果芯片上的 UPX + +在苹果芯片上使用 UPX 相关的 [问题](https://github.com/upx/upx/issues/446)。 + +::: + +:::info Windows 上的 UPX + +一些防病毒软件供应商误将 `upx` 压缩的二进制文件标记为病毒,请查看相关 [问题](https://github.com/upx/upx/issues/437)。 + +::: + +### 平台 + +支持的平台有: + +| 平台 | 描述 | +|:---------------- |:--------------------------------------------- | +| darwin | MacOS + architecture of build machine | +| darwin/amd64 | MacOS 10.13+ AMD64 | +| darwin/arm64 | MacOS 11.0+ ARM64 | +| darwin/universal | MacOS AMD64+ARM64 universal application | +| windows | Windows 10/11 + architecture of build machine | +| windows/amd64 | Windows 10/11 AMD64 | +| windows/arm64 | Windows 10/11 ARM64 | +| linux | Linux + architecture of build machine | +| linux/amd64 | Linux AMD64 | +| linux/arm64 | Linux ARM64 | + +## 诊断检查 + +`wails doctor` 将运行诊断程序以确保您的系统已准备好进行开发。 + +示例: + +``` +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! + +``` + +## 开发 + +`wails dev` 用于以 "实时开发" 模式运行您的应用。 这意味着: + +- 应用程序的 `go.mod` 将被更新为与 Wails CLI 相同的版本 +- 应用程序被编译并自动运行 +- 一个观察者被启动,如果它检测到您的 go 文件的变化,它将触发您的开发应用程序的重新构建 +- 启动一个网络服务器 `http://localhost:34115`,通过 http 为您的应用程序(不仅仅是前端)提供服务。 这允许您使用您喜欢的浏览器开发扩展 +- 所有应用程序资源都从磁盘加载。 如果它们被更改,应用程序将自动重新加载(而不是重新构建)。 所有连接的浏览器也将重新加载 +- 生成的 JS 模块提供以下内容: +- 带有自动生成的 JSDoc 的 Go 方法的 JavaScript 包装器,提供代码提示 +- 您的 Go 结构的 TypeScript 版本,可以构建并传递给您的 go 方法 +- 生成第二个 JS 模块,为运行时提供包装器 + TS 声明 +- 在 macOS 上,它将应用程序捆绑到一个 `.app` 文件中并运行它。 开发模式将使用 `build/darwin/Info.dev.plist` 。 + +| 标志 | 描述 | 默认 | +|:---------------------------- |:-------------------------------------------------------------------------------------------------------------------------------- |:----------------- | +| -appargs "参数" | 以 shell 样式传递给应用程序的参数 | | +| -assetdir "./path/to/assets" | 从给定目录提供资产,而不是使用提供的资产 FS | `wails.json` 中的值 | +| -browser | 在启动时打开浏览器到 `http://localhost:34115` | | +| -compiler "编译器" | 使用不同的 go 编译器来构建,例如 go1.15beta1 | go | +| -debounce | 检测到资产更改后等待重新加载的时间 | 100 (毫秒) | +| -devserver "host:port" | 将 wails 开发服务器绑定到的地址 | "localhost:34115" | +| -extensions | 触发重新构建的扩展(逗号分隔) | go | +| -forcebuild | 强制构建应用程序 | | +| -frontenddevserverurl "url" | 使用 3rd 方开发服务器 url 提供资产,例如:Vite | "" | +| -ldflags "标志" | 传递给编译器的额外 ldflags | | +| -loglevel "日志级别" | 要使用的日志级别 - Trace, Debug, Info, Warning, Error | Debug(调试) | +| -nocolour | 关闭彩色命令行输出 | false | +| -noreload | 资产更改时禁用自动重新加载 | | +| -nosyncgomod | 不同步 go.mod 中的 Wails 版本 | false | +| -race | 使用 Go 的竞态检测器构建 | false | +| -reloaddirs | 触发重新加载的附加目录(逗号分隔) | `wails.json` 中的值 | +| -s | 跳过前端构建 | false | +| -save | 将指定的 `assetdir`、 `reloaddirs`、 `wailsjsdir`、 `debounce` 、 `devserver` 和 `frontenddevserverurl` 标志的值保存到 `wails.json` 以成为后续调用的默认值。 | | +| -skipbindings | 跳过 bindings 生成 | | +| -tags "额外标签" | 传递给编译器的构建标签(引号和空格分隔) | | +| -v | 详细级别 (0 - silent, 1 - standard, 2 - verbose) | 1 | +| -wailsjsdir | 生成生成的Wails JS模块的目录 | `wails.json` 中的值 | + +示例: + +`wails dev -assetdir ./frontend/dist -wailsjsdir ./frontend/src -browser` + +此命令将执行以下操作: + +- 构建应用程序并运行它(更多细节在 [这里](../guides/manual-builds)) +- 在 `./frontend/src` 中生成 Wails JS 模块 +- 监听 `./frontend/dist` 中文件的更新并在更改时重新加载 +- 打开浏览器并连接到应用程序 + +有更多关于在现有框架脚本中使用此功能的 [信息](../guides/application-development.mdx#live-reloading)。 + +## 生成 + +### 模板 + +Wails 使用模板来生成项目。 `wails generate template` 命令有助于构建模板,以使它可以用于生成项目。 + +| 标志 | 描述 | +|:-------------- |:--------------- | +| -name | 模板名称(必填) | +| -frontend "路径" | 要在模板中使用的前端项目的路径 | + +有关创建模板的更多详细信息,请参阅 [模板指南](../guides/templates)。 + +### 模块 + +`wails generate module` 命令允许您为应用程序手动生成 `wailsjs` 目录。 + +## 更新 + +`wails update` 将更新 Wails CLI 的版本。 + +| 标志 | 描述 | +|:------------- |:----------- | +| -pre | 更新到最新的预发布版本 | +| -version "版本" | 安装指定版本的 CLI | + +## 版本 + +`wails version` 仅输出当前的 CLI 版本。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx new file mode 100644 index 00000000000..4e87c3f48f8 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/menus.mdx @@ -0,0 +1,230 @@ +--- +sidebar_position: 4 +--- + +# 菜单 + +可以将应用程序菜单添加到 Wails 项目。 可以通过定义一个 [菜单结构体](#菜单结构体) 并设置 [`菜单选项`](../reference/options#菜单) 或者通过调用运行时方法 [设置应用程序菜单](../reference/runtime/menu#设置应用程序菜单) 来将应用程序菜单添加到 Wails 项目。 + +如何创建菜单的示例: + +```go + + app := NewApp() + + AppMenu := menu.NewMenu() + FileMenu := AppMenu.AddSubmenu("File") + FileMenu.AddText("&Open", keys.CmdOrCtrl("o"), openFile) + FileMenu.AddSeparator() + FileMenu.AddText("Quit", keys.CmdOrCtrl("q"), func(_ *menu.CallbackData) { + runtime.Quit(app.ctx) + }) + + if runtime.GOOS == "darwin" { + AppMenu.Append(menu.EditMenu()) // on macos platform, we should append EditMenu to enable Cmd+C,Cmd+V,Cmd+Z... shortcut + } + + err := wails.Run(&options.App{ + Title: "Menus Demo", + Width: 800, + Height: 600, + Menu: AppMenu, // reference the menu above + Bind: []interface{}{ + app, + }, + ) + // ... +``` + +也可以通过更新菜单结构体并调用 [更新应用程序菜单](../reference/runtime/menu#更新应用程序菜单) 来动态更新菜单 。 + +上面的示例使用辅助方法,但是可以手动构建菜单结构。 + +## 菜单结构体 + +Menu 是 MenuItem 的集合: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Menu struct { + Items []*MenuItem +} +``` + +对于应用程序菜单,每个 MenuItem 代表一个菜单,例如“编辑”。 + +提供了一个简单的辅助方法来构建菜单: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +func NewMenuFromItems(first *MenuItem, rest ...*MenuItem) *Menu +``` + +这使得代码的布局更像菜单的布局,而无需在创建菜单项后手动添加它们。 或者,您可以只创建菜单项并将它们手动添加到菜单中。 + +## 菜单项结构体 + +MenuItem 表示菜单中的一个项目。 + +```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 +} +``` + +| 字段 | 类型 | 注解 | +| ----------- | ------------------------------------ | ---------------------------- | +| Label | string | 菜单文字 | +| Accelerator | [\*keys.Accelerator](#accelerator) | 此菜单项的键绑定 | +| 类型 | [类型](#type) | 菜单项的类型 | +| Disabled | bool | 禁用菜单项 | +| Hidden | bool | 隐藏此菜单项 | +| Checked | bool | 添加检查项目 (复选框和单选类型) | +| SubMenu | [\*Menu](#menu) | 设置子菜单 | +| Click | [Callback](#callback) | 单击菜单时的回调函数 | +| Role | string | 定义此菜单项的 [角色](#角色)。 暂时只支持 Mac | + +### 快捷键 + +加速器(有时称为键盘快捷键)定义了按键和菜单项之间的绑定。 Wails 将加速器定义为一个组合或键 + [修饰符](#修饰符)。 它们在 `"github.com/wailsapp/wails/v2/pkg/menu/keys"` 包中提供。 + +示例: + +```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") +``` + +键是键盘上除了`+`的任何字符,它被定义为`加号`。 有些键不能表示为字符,因此可以使用一组命名字符: + +| | | | | +|:-----------:|:-----:|:---------:|:---------:| +| `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` | `page up` | | +| `page down` | `f15` | `f30` | | + +Wails 还支持使用与 Electron 相同的语法来解析加速器。 这对于将加速器存储在配置文件中很有用。 + +示例: + +```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") +``` + +#### 修饰符 + +以下修饰符是可以与加速键结合使用的键: + +```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" +) +``` + +许多辅助方法可用于使用修饰符创建加速器: + +```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 +``` + +可以使用 `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) +``` + +### 类型 + +每个菜单项必须有一个类型,有 5 种类型可用: + +```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" +) +``` + +为方便起见,提供了帮助方法来快速创建菜单项: + +```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 +``` + +您还可以使用“添加”助手直接在菜单上创建菜单项: + +```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 +``` + +关于单选组的说明:单选组被定义为在菜单中彼此相邻的多个单选菜单项。 这意味着您不需要将项目组合在一起,因为它是自动的。 但是,这也意味着您不能有 2 个彼此相邻的无线电组 - 它们之间必须有一个非无线电项目。 + +### 回调 + +每个菜单项都可能有一个回调,在单击该项时执行: + +```go title="Package: github.com/wailsapp/wails/v2/pkg/menu" +type Callback func(*CallbackData) + +type CallbackData struct { + MenuItem *MenuItem +} +``` + +该函数被赋予一个 `CallbackData` 结构,该结构指示哪个菜单项触发了回调。 这在使用可能共享回调的单选组时很有用。 + +### 角色 + +:::info 角色 + +目前仅 Mac 支持角色。 + +::: + +一个菜单项可能有一个角色,它本质上是一个预定义的菜单项。 我们目前支持以下角色: + +| 角色 | 描述 | +| ------------ | ---------------------------------------- | +| AppMenuRole | 标准的 Mac 应用程序菜单。 可以使用 `menu.AppMenu()` 创建 | +| EditMenuRole | 标准的 Mac 编辑菜单。 可以使用 `menu.EditMenu()` 创建 | diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx new file mode 100644 index 00000000000..d6c559d8d69 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/options.mdx @@ -0,0 +1,869 @@ +--- +sidebar_position: 3 +--- + +# 参数选项 + +## 应用程序参数选项 + +该 `Options.App` 结构包含应用程序配置。 它被传递给 `wails.Run()` 方法: + +```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", + EnableDefaultContextMenu: false, + EnableFraudulentWebsiteDetection: false, + ZoomFactor: 1.0, + IsZoomControlEnabled: false, + Bind: []interface{}{ + app, + }, + ErrorFormatter: func(err error) any { return err.Error() }, + 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(), + WebviewGpuDisabled: false, + }, + 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, + WebviewGpuPolicy: linux.WebviewGpuPolicyAlways, + ProgramName: "wails" + }, + Debug: options.Debug{ + OpenInspectorOnStartup: false, + }, + }) + + if err != nil { + log.Fatal(err) + } +} + +``` + +### 标题 + +窗口标题栏中显示的文本。 + +名称:Title
类型:`string` + +### 宽度 + +窗口的初始宽度。 + +名称:Width
类型:`int`
默认值:1024. + +### 高度 + +窗口的初始高度。 + +名称:Height
类型:`int`
默认值:768 + +### 禁用调整窗口尺寸 + +默认情况下,主窗口可调整大小。 将此设置为 `true` 将使其保持固定大小。 + +名称:DisableResize
类型:`bool` + +### 全屏 + +已弃用:请使用 [窗口启动状态](#窗口启动状态). + +### 窗口启动状态 + +定义窗口在启动时应如何呈现。 + +| 值 | Win | Mac | Lin | +| -------------- | --- | --- | --- | +| Fullscreen(全屏) | ✅ | ✅ | ✅ | +| Maximised(最大化) | ✅ | ✅ | ✅ | +| Minimised(最小化) | ✅ | ❌ | ✅ | + +名称:WindowStartState
类型:`options.WindowStartState` + +### 无边框 + +设置为`true`时,窗口将没有边框或标题栏。 另请参阅 [无边框窗口](../guides/frameless)。 + +名称:Frameless
类型:`bool` + +### 最小宽度 + +这将设置窗口的最小宽度。 如果给出的值 `Width` 小于这个值,窗口将被设置为 `MinWidth` 默认值。 + +名称:MinWidth
类型:`int` + +### 最小高度 + +这将设置窗口的最小高度。 如果给出的值 `Height` 小于这个值,窗口将被设置为 `MinHeight` 默认值。 + +名称:MinHeight
类型:`int` + +### 最大宽度 + +这将设置窗口的最大宽度。 如果给出的值 `Width` 大于这个值,窗口将被设置为 `MaxWidth` 默认值。 + +名称:MaxWidth
类型:`int` + +### 最大高度 + +这将设置窗口的最大高度。 如果给出的值 `Height` 大于这个值,窗口将被设置为 `MaxHeight` 默认值。 + +名称:MaxHeight
类型:`int` + +### 启动时隐藏窗口 + +设置为 `true` 时,应用程序将被隐藏,直到调用 [显示窗口](../reference/runtime/window#显示窗口)。 + +名称:StartHidden
类型:`bool` + +### 关闭时隐藏窗口 + +默认情况下,关闭窗口将关闭应用程序。 将此设置为 `true` 意味着关闭窗口将隐藏窗口。 + +隐藏窗口。 + +名称:HideWindowOnClose
类型:`bool` + +### 背景颜色 + +此值是窗口的默认背景颜色。 示例:options.NewRGBA(255,0,0,128) - 红色,透明度为 50% + +名称:BackgroundColour
类型:`*options.RGBA`
默认值:white + +### 窗口固定在最顶层 + +窗口在失去焦点时应保持在其他窗口之上。 + +名称:AlwaysOnTop
类型:`bool` + +### 资产 + +已弃用:请在 [AssetServer 特定选项](#资产服务器) 上使用资产。 + +### 资产处理程序 + +已弃用:请在 [AssetServer 特定选项](#资产服务器) 上使用资产处理程序。 + +### 资产服务器 + +这定义了资产服务器特定的选项。 它允许使用静态资产自定义资产服务器,使用 `http.Handler` 动态地提供资产或使用 `assetsserver.Middleware` 钩到请求链。 + +并非当前支持 `http.Request` 的所有功能,请参阅以下功能矩阵: + +| 功能 | Win | Mac | Lin | +| ----------------------- | --- | --- | ------ | +| GET | ✅ | ✅ | ✅ | +| POST | ✅ | ✅ | ✅ [^1] | +| PUT | ✅ | ✅ | ✅ [^1] | +| PATCH | ✅ | ✅ | ✅ [^1] | +| DELETE | ✅ | ✅ | ✅ [^1] | +| Request Headers | ✅ | ✅ | ✅ [^1] | +| Request Body | ✅ | ✅ | ✅ [^2] | +| Request Body Streaming | ✅ | ✅ | ✅ [^2] | +| Response StatusCodes | ✅ | ✅ | ✅ [^1] | +| Response Headers | ✅ | ✅ | ✅ [^1] | +| Response Body | ✅ | ✅ | ✅ | +| Response Body Streaming | ❌ | ✅ | ✅ | +| WebSockets | ❌ | ❌ | ❌ | +| HTTP Redirects 30x | ✅ | ❌ | ❌ | + +名称: AssetServer
类型: `*assetserver.Options` + +#### 资产 + +应用程序要使用的静态前端资产。 + +首先尝试从 `fs.FS` 提供 GET 请求。 如果 `fs.FS` 为该文件返回 `os.ErrNotExist`,则请求处理将回退到 [处理程序](#处理程序) 并尝试服务来自它的 GET 请求。 + +如果设置为 nil,则所有 GET 请求都将转发给 [处理程序](#处理程序)。 + +名称: Assets
类型: `fs.FS` + +#### 处理程序 + +资产处理程序是一个通用的 `http.Handler`,用于对无法找到的资产进行后备处理。 + +由于 `os.ErrNotExist`,对于每个无法从 [资产](#资产) 提供服务的 GET 请求,都会调用该处理程序。 此外,所有非 GET 请求将始终从此处理程序提供服务。 如果未定义,则调用处理程序的结果如下: + +- GET 请求: `http.StatusNotFound` +- 其他请求: `http.StatusMethodNotAllowed` + +注意:当与前端 DevServer 结合使用时,可能会有一些限制,例如。 Vite 在不包含文件扩展名的每个路径上提供 index.html。 + +名称:AssetsHandler
类型:`http.Handler` + +#### 中间件 + +中间件是一个 HTTP 中间件,它允许挂钩到资产服务器请求链。 它允许动态跳过默认请求处理程序,例如实现专门的路由等。 调用中间件来构建资产服务器使用的新 `http.Handler`,它还接收资产服务器使用的默认处理程序作为参数。 + +如果未定义,则执行默认的资产服务器请求链。 + +名称: Middleware
类型: `assetserver.Middleware` + +### 菜单 + +应用程序要使用的菜单。 [菜单参考](../reference/runtime/menu) 中有关菜单的更多详细信息。 + +:::note + +在 Mac 上,如果未指定菜单,将创建一个默认菜单。 + +::: + +名称:Menu
类型:`*menu.Menu` + +### 日志 + +应用程序要使用的记录器。 有关日志记录的更多详细信息,请参阅 [日志参考](../reference/runtime/log)。 + +名称:Logger
类型:`logger.Logger`
默认值:Logs to Stdout + +### 日志级别 + +默认日志级别。 有关日志记录的更多详细信息,请参阅 [日志参考](../reference/runtime/log)。 + +名称:LogLevel
类型:`logger.LogLevel`
默认值:开发模式为 `Info`, 生产模式为 `Error` + +### 生产日志级别 + +生产构建的默认日志级别。 有关日志记录的更多详细信息,请参阅 [日志参考](../reference/runtime/log)。 + +名称:LogLevelProduction
类型:`logger.LogLevel`
默认值:`Error` + +### 应用启动回调 + +此回调在前端创建之后调用,但在 `index.html` 加载之前调用。 它提供了应用程序上下文。 + +名称:OnStartup
类型:`func(ctx context.Context)` + +### 前端 Dom 加载完成回调 + +在前端加载完毕 `index.html` 及其资源后调用此回调。 它提供了应用程序上下文。 + +名称:OnDomReady
类型:`func(ctx context.Context)` + +### 应用退出回调 + +在前端被销毁之后,应用程序终止之前,调用此回调。 它提供了应用程序上下文。 + +名称:OnShutdown
类型:`func(ctx context.Context)` + +### 应用关闭前回调 + +如果设置了此回调,它将在通过单击窗口关闭按钮或调用`runtime.Quit`即将退出应用程序时被调用. 返回 `true` 将导致应用程序继续,`false` 将继续正常关闭。 返回 true 将导致应用程序继续,false 将继续正常关闭。 这有助于与用户确认他们希望退出程序。 + +示例: + +```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" +} +``` + +名称:OnBeforeClose
类型:`func(ctx context.Context) bool` + +### CSS 拖动属性 + +指示用于标识哪些元素可用于拖动窗口的 CSS 属性。 默认值:`--wails-draggable` + +名称:CSSDragProperty
类型:`string` + +### CSS 拖动值 + +指示 `CSSDragProperty` 样式应该具有什么值才能拖动窗口。 默认值:`drag` + +名称:CSSDragValue
类型:`string` + +### EnableDefaultContextMenu + +EnableDefaultContextMenu enables the browser's default context-menu in 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. + +When this option is enabled, by default the context-menu will only be shown for text contexts (where Cut/Copy/Paste is needed), to override this behavior, you can use the CSS property `--default-contextmenu` on any HTML element (including the `body`) with the following values : + +| CSS Style | Behavior | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--default-contextmenu: auto;` | (**default**) will show the default context menu only if :
contentEditable is true OR text has been selected OR element is input or textarea | +| `--default-contextmenu: show;` | will always show the default context menu | +| `--default-contextmenu: hide;` | will always hide the default context menu | + +This rule is inherited like any normal CSS rule, so nesting works as expected. + +:::note +This filtering functionality is only enabled in production, so in development and in debug build, the full context-menu is always available everywhere. +::: + +:::warning +This filtering functionality is NOT a security measure, the developer should expect that the full context-menu could be leaked anytime which could contain commands like (Download image, Reload, Save webpage), if this is a concern, the developer SHOULD NOT enable the default context-menu. +::: + + +Name: EnableDefaultContextMenu
Type: `bool` + +### 启用欺诈网站检测 + +EnableFraudulentWebsiteDetection 启用针对欺诈内容(例如恶意软件或网络钓鱼尝试)的扫描服务。 这些服务可能会从你的应用中发送信息,比如导航到苹果和微软的云服务的url和其他内容。 + +名称:EnableFraudulentWebsiteDetection
类型:`bool` + +### 缩放比例 + +名称:ZoomFactor
类型:`float64` + +这定义了 WebView2 的缩放比例。 这是匹配 Edge 用户激活放大或缩小的选项 + +### 启用缩放比例 + +名称:IsZoomControlEnabled
类型:`bool` + +这将允许用户更改缩放比例。 请注意,可以在选项中设置缩放比例,但不允许在运行时更改它。 适用于屏幕固定的或类似的应用程序。 + +### 绑定 + +定义需要绑定到前端的方法的结构实例切片。 + +名称:Bind
类型:`[]interface{}` + +### ErrorFormatter + +A function that determines how errors are formatted when returned by a JS-to-Go method call. The returned value will be marshalled as JSON. + +Name: ErrorFormatter
Type: `func (error) any` + +### Windows + +这定义了 [Windows 特定的选项](#windows)。 + +名称:Windows
类型:`*windows.Options` + +#### Webview 透明 + +当使用 `alpha` 值 `0` 时,将此设置为 true 将使 webview 背景透明。 这意味着如果您在 CSS 中使用 `rgba(0,0,0,0)` 作为 `background-color`,则主机窗口将显示出来。 通常与 [窗口半透明](#窗口半透明) 结合使用以制作看起来冷冰冰的应用程序。 + +名称:WebviewIsTransparent
类型:`bool` + +#### 窗口半透明 + +将此设置为 `true` 将使窗口半透明。 通常与 [Webview 透明](#webview-透明) 结合使用。 + +对于 build 22621 之前的 Windows 11 版本,将使用 [BlurBehind](https://learn.microsoft.com/en-us/windows/win32/dwm/blur-ovw) 方法来实现半透明,这可能会很慢。 对于构建 build 22621 之后的 Windows 11 版本,这将启用速度更快的新半透明类型。 默认情况下,使用的半透明类型将由 Windows 确定。 要对此进行配置,请使用 [背景类型](#背景类型) 选项。 + +名称:WindowIsTranslucent
类型:`bool` + +#### 背景类型 + +:::note + +需要 Windows 11 build 22621 或更高版本。 + +::: + +设置窗口的半透明类型。 这仅在 [窗口半透明](#窗口半透明) 设置为 `true` 时适用。 + +名称:BackdropType
类型:`windows.BackdropType` + +值可以是以下之一: + +| 值 | 描述 | +| ------- | -------------------------------------------------------------------------------- | +| Auto | 让 Windows 决定使用哪个背景 | +| None | 不要使用半透明 | +| Acrylic | 使用 [亚克力](https://learn.microsoft.com/en-us/windows/apps/design/style/acrylic) 效果 | +| Mica | 使用 [Mica](https://learn.microsoft.com/en-us/windows/apps/design/style/mica) 效果 | +| Tabbed | 使用 Tabbed。 这是一个类似于 Mica 的背景。 | + +#### 禁用窗口图标 + +将此设置为 `true` 将删除标题栏左上角的图标。 + +名称:DisableWindowIcon
类型:`bool` + +#### 禁用无边框窗口装饰 + +将此设置为 `true` 将移除 [无边框](#无边框) 模式下的窗口装饰。 这意味着将不会有`Aero 阴影` 和 `圆角`显示在窗口上。 请注意,'圆角' 只在 Windows 11 上支持。 + +名称:DisableFramelessWindowDecorations
类型:`bool` + +#### Webview 用户数据路径 + +这定义了 WebView2 存储用户数据的路径。 如果为空将使用 `%APPDATA%\[BinaryName.exe]`。 + +名称:WebviewUserDataPath
类型:`string` + +#### Webview 浏览器路径 + +这定义了带有 WebView2 可执行文件和库的目录的路径 如果为空,则使用系统中安装的 webview2 + +有关固定版本运行时分发的重要信息: + +- [如何获取和提取运行时](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#details-about-the-fixed-version-runtime-distribution-mode) +- [固定版本的已知问题](https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#known-issues-for-fixed-version) +- [WebView2 Runtime 固定版本的路径不应包含 \Edge\Application](https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/webview2-idl?view=webview2-1.0.1245.22#createcorewebview2environmentwithoptions) + +名称:WebviewBrowserPath
类型:`string` + +#### 主题 + +最低 Windows 版本:Windows 10 2004/20H1 + +这定义了应用程序应该使用的主题: + +| 值 | 描述 | +| ------------- | -------------------------------------------- | +| SystemDefault | _默认_。 主题将基于系统默认值。 如果用户更改了他们的主题,应用程序将更新以使用新设置 | +| Dark | 该应用程序将只使用深色主题 | +| Light | 该应用程序将专门使用浅色主题 | + +名称:Theme
类型:`windows.Theme` + +#### 自定义主题 + +:::note + +最低 Windows 版本:Windows 10/11 2009/21H2 Build 22000 + +::: + +允许您为浅色和深色模式以及窗口处于活动或非活动状态的 TitleBar、TitleText 和 Border 指定自定义颜色。 + +名称:CustomTheme
类型:`windows.CustomTheme` + +##### 自定义主题类型 + +CustomTheme 结构体使用 `int32` 指定颜色值。 它们采用标准(!)Windows 格式:`0x00BBGGAA`。 These are in the standard(!) Windows format of: `0x00BBGGAA`. 提供了一个辅助函数来将 RGB 转换为这种格式:`windows.RGB(r,g,b uint8)`。 + +注意:任何未提供的值都将默认为黑色。 + +```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 +} +``` + +示例: + +```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), + }, +``` + +#### 消息 + +一个如果找不到有效的 webview2 运行时,webview2 安装程序所使用的字符串结构。 + +名称:Messages
类型:`*windows.Messages` + +您可以选择支持的任意语言定制此选项。 + +#### 重置尺寸防抖间隔 + +ResizeDebounceMS 是调整窗口大小时去抖动 webview2 重绘的时间量。 默认值 (0) 将尽可能快地执行重绘。 + +名称:ResizeDebounceMS
类型:`uint16` + +#### 待机回调 + +如果设置,当 Windows 启动切换到低功耗模式(挂起/休眠)时将调用此函数 + +名称:OnSuspend
类型:`func()` + +#### 恢复回调 + +如果设置,当 Windows 从低功耗模式(挂起/休眠)恢复时将调用此函数 + +名称:OnResume
类型:`func()` + +#### 禁用 Webview GPU 硬件加速 + +设置为 `true` 将禁用 webview 的 GPU 硬件加速。 + +名称:WebviewGpuIsDisabled
类型:`bool` + +#### EnableSwipeGestures + +Setting this to `true` will enable swipe gestures for the webview. + +Name: EnableSwipeGestures
Type: `bool` + +### Mac + +这定义了 [Mac 特定的选项](#mac)。 + +名称:Mac
类型:`*mac.Options` + +#### 标题栏 + +TitleBar 结构提供了配置标题栏外观的能力。 + +名称:TitleBar
类型:[`*mac.TitleBar`](#标题栏结构体) + +##### 标题栏结构体 + +可以使用 TitleBar 选项自定义应用程序的标题栏: + +```go +type TitleBar struct { + TitlebarAppearsTransparent bool + HideTitle bool + HideTitleBar bool + FullSizeContent bool + UseToolbar bool + HideToolbarSeparator bool +} +``` + +| 设置 | 描述 | +| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| TitlebarAppearsTransparent | 使标题栏透明。 这具有隐藏标题栏和内容填充窗口的效果。 [苹果文档](https://developer.apple.com/documentation/appkit/nswindow/1419167-titlebarappearstransparent?language=objc) | +| HideTitle | 隐藏窗口的标题。 [苹果文档](https://developer.apple.com/documentation/appkit/nswindowtitlevisibility?language=objc) | +| HideTitleBar | 从 style mask 中删除 [NSWindowStyleMaskTitled](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktitled/) | +| FullSizeContent | 使 webview 填满整个窗口。 [苹果文档](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemaskfullsizecontentview) | +| UseToolbar | 向窗口添加默认工具栏。 [苹果文档](https://developer.apple.com/documentation/appkit/nstoolbar?language=objc) | +| HideToolbarSeparator | 删除工具栏下方的线条。 [苹果文档](https://developer.apple.com/documentation/appkit/nstoolbar/1516954-showsbaselineseparator?language=objc) | + +预配置的标题栏设置可用: + +| 设置 | 示例 | +| --------------------------- | ---------------------------------------------- | +| `mac.TitleBarDefault()` | ![](/img/reference/titlebar-default.webp) | +| `mac.TitleBarHidden()` | ![](/img/reference/titlebar-hidden.webp) | +| `mac.TitleBarHiddenInset()` | ![](/img/reference/titlebar-hidden-inset.webp) | + +示例: + +```go +Mac: &mac.Options{ + TitleBar: mac.TitleBarHiddenInset(), +} +``` + +单击 [此处](https://github.com/lukakerr/NSWindowStyles) 获取有关自定义标题栏的一些灵感。 + +#### 外观 + +Appearance 用于根据 Apple 的 [NSAppearance](https://developer.apple.com/documentation/appkit/nsappearancename?language=objc) 名称设置您的应用程序的样式。 + +名称:Appearance
类型:[`mac.AppearanceType`](#外观类型) + +##### 外观类型 + +您可以指定应用程序的 [外观](https://developer.apple.com/documentation/appkit/nsappearance?language=objc)。 + +| 值 | 描述 | +| ----------------------------------------------------- | --------------- | +| DefaultAppearance | 使用默认系统值 | +| NSAppearanceNameAqua | 标准日间系统外观 | +| NSAppearanceNameDarkAqua | 标准黑夜系统外观 | +| NSAppearanceNameVibrantLight | 轻盈灵动的外观 | +| NSAppearanceNameAccessibilityHighContrastAqua | 标准白天系统外观的高对比度版本 | +| NSAppearanceNameAccessibilityHighContrastDarkAqua | 标准黑夜系统外观的高对比度版本 | +| NSAppearanceNameAccessibilityHighContrastVibrantLight | 轻盈灵动外观的高对比度版本 | +| NSAppearanceNameAccessibilityHighContrastVibrantDark | 深色活力外观的高对比度版本 | + +示例: + +```go +Mac: &mac.Options{ + Appearance: mac.NSAppearanceNameDarkAqua, +} +``` + +#### Webview 透明 + +当使用 `alpha` 值 `0` 时,将此设置为 true 将使 webview 背景透明。 这意味着如果您在 CSS 中使用 `rgba(0,0,0,0)` 作为 `background-color`,则主机窗口将显示出来。 通常与 [窗口半透明](#窗口半透明-1) 结合使用以制作看起来冷冰冰的应用程序。 + +名称:WebviewIsTransparent
类型:`bool` + +#### 窗口半透明 + +将此设置为 `true` 将使窗口半透明。 通常与[Webview 透明](#webview-透明) 结合使用以制作冰霜效果的应用程序。 + +名称:WindowIsTranslucent
类型:`bool` + +#### Preferences + +The Preferences struct provides the ability to configure the Webview preferences. + +Name: Preferences
Type: [`*mac.Preferences`](#preferences-struct) + +##### Preferences struct + +You can specify the webview preferences. + +```go +type Preferences struct { + TabFocusesLinks u.Bool + TextInteractionEnabled u.Bool + FullscreenEnabled u.Bool +} +``` + +| 设置 | 描述 | +| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 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) | + +示例: + +```go +Mac: &mac.Options{ + Preferences: &mac.Preferences{ + TabFocusesLinks: mac.Enabled, + TextInteractionEnabled: mac.Disabled, + FullscreenEnabled: mac.Enabled, + } +} +``` + +#### 关于 + +此配置允许您在“AppMenu”角色创建的应用程序菜单中设置“关于”菜单项的标题、消息和图标。 + +名称:About
类型:[`*mac.AboutInfo`](#关于结构体) + +##### 关于结构体 + +```go + +type AboutInfo struct { + Title string + Message string + Icon []byte +} +``` + +如果提供了这些设置,“关于”菜单项将出现在应用程序菜单中(使用`AppMenu` role 时)。 建议这样配置: + +```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, + }, + }, + }) + Mac: &mac.Options{ + About: &mac.AboutInfo{ + Title: "My Application", + Message: "© 2021 Me", + Icon: icon, + }, + }, + }) + Mac: &mac.Options{ + About: &mac.AboutInfo{ + Title: "My Application", + Message: "© 2021 Me", + Icon: icon, + }, + }, + }) +``` + +“关于”菜单项将出现在应用程序菜单中: + +```mdx-code-block +
+ +
+
+``` + +单击后,将打开一个关于消息框: + +```mdx-code-block +
+ +
+
+``` + +### Linux + +这定义了 [Linux 特定的选项](#linux)。 + +名称:Linux
类型:`*linux.Options` + +#### 图标 + +设置代表窗口的图标。 当窗口最小化(也称为图标化)时使用此图标。 + +名称:Icon
类型:`[]byte` + +一些窗口管理器或桌面环境也可能将其放置在窗口框架中,或在其他上下文中显示。 在其他情况下,根本不使用该图标,因此您的预计情况可能会有所不同。 + +注意:Wayland 上的 Gnome 至少不显示此图标。 要在那里有一个应用程序图标,必须使用一个`.desktop`文件。 在 KDE 上它应该可以工作。 + +图标应该以自然绘制的任何尺寸提供;也就是说,在传递图像之前不要缩放图像。 缩放将延迟到当所需的最终尺寸已知的最后一刻,以获得最佳质量。 + +#### 窗口半透明 + +将此设置为 `true` 将使窗口半透明。 某些窗口管理员可能忽略它,或导致黑窗口。 + +名称:WindowIsTranslucent
类型:`bool` + +#### Webview GPU 策略 + +该选项用于决定 webview 的硬件加速策略。 + +名称:WebviewGpuPolicy
类型:[`options.WebviewGpuPolicy`](#webviewgpupolicy-type)
默认:`WebviewGpuPolicyAlways` + +##### Webview GPU 策略类型 + +| 值 | 描述 | +| ------------------------ | --------------------- | +| WebviewGpuPolicyAlways | 始终启用硬件加速 | +| WebviewGpuPolicyOnDemand | 根据 Web 内容的请求启用/禁用硬件加速 | +| WebviewGpuPolicyNever | 硬件加速始终处于禁用状态 | + +#### 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). + +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. + +Name: ProgramName
Type: string
+ +### 调试 + +这定义了用于调试构建的 [调试特定选项](#调试)。 + +名称: Debug
类型: `options.Debug` + +#### 启动时打开检查器 + +设置为 `true` 将在应用程序启动时打开 Web 检查器。 + +名称: OpenInspectorOnStartup
类型: `bool` + +[^1]: 这需要 WebKit2GTK 2.36+ 支持,并且您的应用程序需要使用构建标签 `webkit2_36` 来构建以激活对此功能的支持。 这也会将您应用程序的 WebKit2GTK 最低要求提高到 2.36。 +[^2]: 这需要 WebKit2GTK 2.40+ 支持,并且您的应用程序需要使用构建标签 `webkit2_40` 来构建以激活对此功能的支持。 这也将您的应用程序的 WebKit2GTK 最低要求提高到 2.40。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx new file mode 100644 index 00000000000..dc2a96b8a19 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/project-config.mdx @@ -0,0 +1,104 @@ +--- +sidebar_position: 5 +--- + +# 项目配置 + +项目配置在项目目录中的 `wails.json` 文件中。 配置的结构是: + +```json5 +{ + // 项目配置版本 + "version": "", + // 项目名称 + "name": "", + // 包含编译资产的目录的相对路径,这通常是推断的并且可以留空 + "assetdir": "", + // 触发重新加载的附加目录(逗号分隔),这仅用于某些高级资产配置 + "reloaddirs": "", + // 构建文件所在的目录。默认为“build” + "build:dir": "", + // 前端目录的相对路径。默认为“frontend” + "frontend:dir": "", + // 安装 Node 依赖的命令,在前端目录运行 - 通常是`npm install` + "frontend:install": "", + // 构建资产的命令,在前端目录中运行 - 通常是 `npm run build` + "frontend:build": "", + // 此命令已被 frontend:dev:build 取代。如果未指定 frontend:dev:build 将回退到此命令。 + // 如果此命令也未指定,将回退到 frontend:build + "frontend:dev": "", + // 此命令是 frontend:build 的 dev 等价物。 + // 如果未指定回退到 frontend:dev + "frontend:dev:build": "", + // 此命令是 frontend:install 的 dev 等价物。如果未指定回退到 frontend:install + "frontend:dev:install": "", + // 此命令在 `wails dev`上的单独进程中运行。用于第 3 方观察者或启动 3d 方开发服务器 + "frontend:dev:watcher": "", + // 用于服务资产的第 3 方开发服务器的 URL,比如 Vite。 + // 如果设置为 'auto' 那么 devServerUrl 将从 Vite 输出中推断出来 + "frontend:dev:serverUrl": "", + // 创建自动生成的 JS 模块的目录的相对路径 + "wailsjsdir": "", + // 二进制文件的名称 + "outputfilename": "", + // 开发服务器在检测到资产更改时等待重新加载的默认时间 + "debounceMS": 100, + // 将 wails 开发服务器绑定到的地址。默认为:localhost:34115 + "devServer": "", + // 在开发模式下以 shell 样式传递给应用程序的参数 + "appargs": "", + // 定义是否应该运行构建 Hooks,尽管它们是为主机操作系统以外的操作系统定义的。 + "runNonNativeBuildHooks": false, + // 构建前 Hooks + "preBuildHooks": { + // 在构建指定的 GOOS/GOARCH 之前将执行的命令:${platform} 被替换为“GOOS/GOARCH”。 + // “GOOS/GOARCH” hook 在“GOOS/*”和“*/*” hook 之前执行。 + "GOOS/GOARCH": "", + // 在指定 GOOS 的构建之前将执行的命令:${platform} 被替换为“GOOS/GOARCH”。 + // “GOOS/*” hook 在“*/*” hook 之前执行。 + "GOOS/*": "", + // 将在每次构建之前执行的命令:${platform} 替换为“GOOS/GOARCH”。 + "*/*": "" + }, + // 构建后 Hooks + "postBuildHooks": { + // 在构建指定的 GOOS/GOARCH 之后将执行的命令:${platform} 替换为“GOOS/GOARCH”, + // ${bin} 替换为已编译二进制文件的路径。 “GOOS/GOARCH” hook 在“GOOS/*”和“*/*” hook 之前执行。 + "GOOS/GOARCH": "", + // 在构建指定的 GOOS 之后将执行的命令:${platform} 替换为“GOOS/GOARCH”, + // ${bin} 替换为已编译二进制文件的路径。 “GOOS/*” hook 在“*/*” hook 之前执行。 + "GOOS/*": "", + // 每次构建后将执行的命令:${platform} 替换为“GOOS/GOARCH”, + // ${bin} 替换为已编译二进制文件的路径。 + "*/*": "" + }, + // 用于填充 manifest 和版本信息的数据。 + "info": { + // 公司名称。 默认值:[项目名] + "companyName": "", + // 产品名称。 默认值:[项目名] + "productName": "", + // 产品版本。默认值:'1.0.0' + "productVersion": "", + // 产品的版权。默认值:'Copyright.........' + "copyright": "", + // 该应用程序的简短评论。默认值:'Built using Wails (https://wails.app)' + "comments": "" + }, + // 'multiple': 每个架构一个安装程序。 + // 'single': 适用于正在构建的所有体系结构的单一通用安装程序。 + // 默认值:'multiple' + "nsisType": "", + // 应用程序是否应该被混淆。默认值:false + "obfuscated": "", + // 使用 obfuscated 标志时传递给乱码命令的参数 + "garbleargs": "" +} + +``` + +该文件将在运行 `wails build` 或 `wails dev` 时,由 Wails CLI 读取。 + +`wails build/dev` 命令中的 `assetdir`、`reloaddirs`、`wailsjsdir`、`debounceMS`、`devserver` 和 `frontenddevserverurl` 标志将覆盖项目配置并作为后续运行的默认值。 + +此文件的 `JSON Schema` 位于 [此处](https://wails.io/schemas/config.v2.json)。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json new file mode 100644 index 00000000000..ac6d5548816 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Runtime", + "position": 1 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx new file mode 100644 index 00000000000..0829be25f70 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/browser.mdx @@ -0,0 +1,13 @@ +--- +sidebar_position: 7 +--- + +# Browser 浏览器 + +这些方法与系统浏览器相关。 + +### BrowserOpenURL 浏览器打开 URL + +使用系统默认浏览器打开给定的 URL。 + +Go: `BrowserOpenURL(ctx context.Context, url string)`
JS: `BrowserOpenURL(url string)` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx new file mode 100644 index 00000000000..845dbc9f612 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/clipboard.mdx @@ -0,0 +1,23 @@ +--- +sidebar_position: 8 +--- + +# Clipboard 剪贴板 + +运行时的这一部分提供了对操作系统剪贴板的访问。
当前实现仅处理文本。 + +### ClipboardGetText 剪贴板获取文本 + +从剪切板读取当前存储的文本。 + +Go: `ClipboardGetText(ctx context.Context) (string, error)`
返回: 一个字符串(如果剪贴板为空,将返回一个空字符串)或一个错误。 + +JS: `ClipboardGetText(): Promise`
返回: 带有字符串结果的 Promise(如果剪贴板为空,将返回空字符串)。 + +### ClipboardSetText 剪贴板设置文本 + +将文本写入剪切板。 + +Go: `ClipboardSetText(ctx context.Context, text string) error`
返回: 如果存在错误,则会出现错误。 + +JS: `ClipboardSetText(text: string): Promise`
返回值: 一个Promise,如果文本成功地设置在剪贴板上,结果为 true,否则为 false。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx new file mode 100644 index 00000000000..7fd7f9640ae --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/dialog.mdx @@ -0,0 +1,302 @@ +--- +sidebar_position: 5 +--- + +# Dialog 对话框 + +运行时的这一部分提供对原生对话框的调用,例如文件选择器和消息框。 + +:::info JavaScript + +JS 运行时当前不支持对话框。 + +::: + +### OpenDirectoryDialog 打开选择目录对话框 + +打开一个对话框,提示用户选择目录。 可以使用 [ 打开选择文件对话框参数选项](#打开选择文件对话框参数选项) 进行自定义。 + +Go: `OpenDirectoryDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +返回值: 所选目录(如果用户取消则为空白)或错误 + +### OpenFileDialog 打开选择文件对话框 + +打开一个对话框,提示用户选择文件。 可以使用 [ 打开选择文件对话框参数选项](#打开选择文件对话框参数选项) 进行自定义。 + +Go: `OpenFileDialog(ctx context.Context, dialogOptions OpenDialogOptions) (string, error)` + +返回值: 所选文件(如果用户取消则为空白)或错误 + +### OpenMultipleFilesDialog 打开选择多文件对话框 + +打开一个对话框,提示用户选择多个文件。 可以使用 [ 打开选择文件对话框参数选项](#打开选择文件对话框参数选项) 进行自定义。 + +Go: `OpenMultipleFilesDialog(ctx context.Context, dialogOptions OpenDialogOptions) ([]string, error)` + +返回值: 选定的文件(如果用户取消则为 nil)或错误 + +### SaveFileDialog 保存文件对话框 + +打开一个对话框,提示用户选择文件名以进行保存。 可以使用 [保存文件对话框参数选项](#保存文件对话框参数选项) 自定义。 + +Go: `SaveFileDialog(ctx context.Context, dialogOptions SaveDialogOptions) (string, error)` + +返回值: 所选文件(如果用户取消则为空白)或错误 + +### MessageDialog 消息对话框 + +使用消息对话框显示消息。 可以使用 [消息对话框参数选项](#消息对话框参数选项) 进行自定义。 + +Go: `MessageDialog(ctx context.Context, dialogOptions MessageDialogOptions) (string, error)` + +返回值: 所选按钮的文本或错误 + +## 参数选项 + +### 打开选择文件对话框参数选项 + +```go +type OpenDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + ResolvesAliases bool + TreatPackagesAsDirectories bool +} +``` + +| 字段 | 描述 | Win | Mac | Lin | +| -------------------------- | ------------------- | --- | --- | --- | +| DefaultDirectory | 对话框打开时显示的目录 | ✅ | ✅ | ✅ | +| DefaultFilename | 默认文件名 | ✅ | ✅ | ✅ | +| Title | 对话框的标题 | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | 文件过滤器列表 | ✅ | ✅ | ✅ | +| ShowHiddenFiles | 显示系统隐藏的文件 | | ✅ | ✅ | +| CanCreateDirectories | 允许用户创建目录 | | ✅ | | +| ResolvesAliases | 如果为 true,则返回文件而不是别名 | | ✅ | | +| TreatPackagesAsDirectories | 允许导航到包 | | ✅ | | + +### 保存文件对话框参数选项 + +```go +type SaveDialogOptions struct { + DefaultDirectory string + DefaultFilename string + Title string + Filters []FileFilter + ShowHiddenFiles bool + CanCreateDirectories bool + TreatPackagesAsDirectories bool +} +``` + +| 字段 | 描述 | Win | Mac | Lin | +| -------------------------- | ----------- | --- | --- | --- | +| DefaultDirectory | 对话框打开时显示的目录 | ✅ | ✅ | ✅ | +| DefaultFilename | 默认文件名 | ✅ | ✅ | ✅ | +| Title | 对话框的标题 | ✅ | ✅ | ✅ | +| [Filters](#filefilter) | 文件过滤器列表 | ✅ | ✅ | ✅ | +| ShowHiddenFiles | 显示系统隐藏的文件 | | ✅ | ✅ | +| CanCreateDirectories | 允许用户创建目录 | | ✅ | | +| TreatPackagesAsDirectories | 允许导航到包 | | ✅ | | + +### 消息对话框参数选项 + +```go +type MessageDialogOptions struct { + Type DialogType + Title string + Message string + Buttons []string + DefaultButton string + CancelButton string +} +``` + +| 字段 | 描述 | Win | Mac | Lin | +| ------------- | ------------------------------ | -------------- | --- | --- | +| 类型 | 消息对话框的类型,例如问题、信息... | ✅ | ✅ | ✅ | +| Title | 对话框的标题 | ✅ | ✅ | ✅ | +| Message | 向用户显示的消息 | ✅ | ✅ | ✅ | +| Buttons | 按钮标题列表 | | ✅ | | +| DefaultButton | 带有此文本的按钮应被视为默认按钮。 必定 `return`。 | ✅[*](#windows) | ✅ | | +| CancelButton | 带有此文本的按钮应被视为取消。 必定 `escape` | | ✅ | | + +#### Windows + +Windows 具有标准对话框类型,其中的按钮不可自定义。 返回的值将是以下之一:"Ok"、"Cancel"、"Abort"、"Retry"、"Ignore"、"Yes"、"No"、"Try Again"或"Continue"。 + +对于问题对话框,默认按钮是 “是”,取消按钮是 “否”。 可以通过将 `默认按钮` 值设置为 `"否"` 来改变这一点。 + +示例: +```go + result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{ + Type: runtime.QuestionDialog, + Title: "Question", + Message: "Do you want to continue?", + DefaultButton: "No", + }) +``` + +#### Linux + +Linux 有标准的对话框类型,其中的按钮是不可定制的。 返回的值将是以下之一:“Ok”、“Cancel”、“Yes”、“No” + +#### Mac + +Mac 上的消息对话框最多可以指定 4 个按钮。 如果没有 `DefaultButton` 或 `CancelButton` 给出,第一个按钮被认为是默认的并绑定到 `return` 键。 + +对于以下代码: + +```go +selection, err := runtime.MessageDialog(b.ctx, runtime.MessageDialogOptions{ + Title: "It's your turn!", + Message: "Select a number", + Buttons: []string{"one", "two", "three", "four"}, +}) +``` + +第一个按钮显示为默认值: + +```mdx-code-block +
+ +
+
+``` + +如果我们指定 `DefaultButton` 为“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", +}) +``` + +第二个按钮显示为默认值。 当 `return` 被按下时,则返回数值“two”。 + +```mdx-code-block +
+ +
+
+``` + +如果我们现在指定`CancelButton`为“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", +}) +``` + +带有“three”的按钮显示在对话框的底部。 当 `escape` 被按下时,则返回值“three”: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### 对话框类型 + +```go +const ( + InfoDialog DialogType = "info" + WarningDialog DialogType = "warning" + ErrorDialog DialogType = "error" + QuestionDialog DialogType = "question" + ) +``` + +### 文件过滤 + +```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 允许您在对话框中使用多个文件过滤器。 每个 FileFilter 将在对话框中显示为一个单独的条目: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Linux + +Linux 允许您在对话框中使用多个文件过滤器。 每个 FileFilter 将在对话框中显示为一个单独的条目: + +```mdx-code-block +
+ +
+
+
+
+``` + +#### Mac + +Mac 对话框只有一组模式来过滤文件的概念。 如果提供了多个 FileFilters,Wails 将使用所有定义的模式。 + +示例: + +```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", + }, + }, + }) +``` + +这将导致使用 `*.png,*.jpg,*.mov,*.mp4` 作为过滤器打开文件对话框。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx new file mode 100644 index 00000000000..7788eed7b4c --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/events.mdx @@ -0,0 +1,37 @@ +--- +sidebar_position: 2 +--- + +# Events 事件 + +Wails 运行时提供了一个统一的事件系统,其中事件可以由 Go 或 JavaScript 发出或接收。 可选地,数据可以与事件一起传递。 侦听器将接收本地数据类型中的数据。 + +### EventsOn 添加事件侦听器 + +此方法为给定的事件名称设置一个侦听器。 当 [触发指定事件](#触发指定事件) 名为 `eventName` 类型的事件时,将触发回调。 与触发事件一起发送的任何其他数据都将传递给回调。 它返回 一个函数来取消侦听器。 + +Go: `EventsOn(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOn(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOff 移除事件侦听器 + +此方法取消注册给定事件名称的侦听器,可选地,可以通过 `additionalEventNames` 取消注册多个侦听器。 + +Go: `EventsOff(ctx context.Context, eventName string, additionalEventNames ...string)`
JS: `EventsOff(eventName string, ...additionalEventNames)` + +### EventsOnce 添加只触发一次的事件侦听器 + +此方法为给定的事件名称设置一个侦听器,但只会触发一次。 它返回 一个函数来取消侦听器。 + +Go: `EventsOnce(ctx context.Context, eventName string, callback func(optionalData ...interface{})) func()`
JS: `EventsOnce(eventName string, callback function(optionalData?: any)): () => void` + +### EventsOnMultiple 添加指定对多触发次数的事件侦听器 + +此方法为给定的事件名称设置一个侦听器,但最多只能触发 `counter` 次。 它返回 一个函数来取消侦听器。 + +Go: `EventsOnMultiple(ctx context.Context, eventName string, callback func(optionalData ...interface{}), counter int) func()`
JS: `EventsOnMultiple(eventName string, callback function(optionalData?: any), counter int): () => void` + +### EventsEmit 触发指定事件 + +此方法触发指定的事件。 可选数据可以与事件一起传递。 这将触发任意事件侦听器。 + +Go: `EventsEmit(ctx context.Context, eventName string, optionalData ...interface{})`
JS: `EventsEmit(eventName: string, ...optionalData: any)` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx new file mode 100644 index 00000000000..107e2def8e2 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/intro.mdx @@ -0,0 +1,85 @@ +--- +sidebar_position: 1 +--- + +# 简介 + +运行时是一个为应用程序提供实用方法的库。 有 Go 和 JavaScript 运行时,目的是在可能的情况下尝试使它们保持一致。 + +它具有以下实用方法: + +- [窗口](window.mdx) +- [菜单](menu.mdx) +- [对话框](dialog.mdx) +- [事件](events.mdx) +- [浏览器](browser.mdx) +- [日志](log.mdx) +- [剪切板](clipboard.mdx) + +Go 运行时可通过导入 `github.com/wailsapp/wails/v2/pkg/runtime` 获取。 此包中的所有方法都将 context 作为第一个参数。 此 context 应该从 [应用启动回调](../options.mdx#onstartup) 或 [前端 Dom 加载完成回调](../options.mdx#ondomready) 回调方法中获取。 + +:::info 注意 + +虽然上下文将提供给 [应用启动回调](../../reference/options#应用启动回调) 方法,但不能保证运行时将在此方法中工作,因为窗口正在不同的线程中初始化。 如果您希望在启动时调用运行时方法,请使用 [前端 Dom 加载完成回调](../../reference/options#前端-dom-加载完成回调) 方法。 + +::: + +JavaScript 库可通过 `window.runtime` 提供给前端。 使用 `开发` 模式时会生成一个运行时包,该包为运行时提供 TypeScript 声明。 这应该位于您的前端目录的`wailsjs`目录中。 + +### 隐藏 + +Go: `Hide(ctx context.Context)`
JS: `Hide()` + +隐藏应用程序。 + +:::info 注意 + +`Hide` 在 Mac 上,这将以与标准 Mac 应用程序中的菜单项相同的方式隐藏应用程序。 这与隐藏窗口不同,但应用程序仍处于前台。 对于 Windows 和 Linux,这与 `WindowHide` 相同。 + +::: + +### 显示 + +显示应用程序。 + +:::info 注意 + +在 Mac 上,这会将应用程序带回前台。 对于 Windows 和 Linux,这目前与 `WindowShow` 相同。 + +::: + +Go: `Show(ctx context.Context)`
JS: `Show()` + +### 退出 + +退出应用程序。 + +Go: `Quit(ctx context.Context)`
JS: `Quit()` + +### 环境 + +返回当前环境的详细信息。 + +Go: `Environment(ctx context.Context) EnvironmentInfo`
JS: `Environment(): Promise` + +#### 环境信息 + +Go: + +```go +type EnvironmentInfo struct { + BuildType string + Platform string + Arch string +} +``` + +JS: + +```ts +interface EnvironmentInfo { + buildType: string; + platform: string; + arch: string; +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx new file mode 100644 index 00000000000..d109faab2ee --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/log.mdx @@ -0,0 +1,130 @@ +--- +sidebar_position: 3 +--- + +# Log 日志 + +Wails 运行时提供了一种可以从 Go 或 JavaScript 调用日志记录的机制。 像大多数记录器一样,有许多日志级别: + +- Trace(追踪) +- Debug(调试) +- Info(信息) +- Warning(警告) +- Error(错误) +- Fatal(致命) + +记录器将输出当前或更高日志级别的任何日志消息。 示例:`Debug`日志级别将输出除`Trace`消息之外的所有消息。 + +### LogPrint Print 日志 + +将给定的消息记录为原始消息。 + +Go: `LogPrint(ctx context.Context, message string)`
JS: `LogPrint(message: string)` + +### LogPrintf 格式化 Print 日志 + +将给定的消息记录为原始消息。 + +Go: `LogPrintf(ctx context.Context, format string, args ...interface{})`
+ +### LogTrace Trace 日志 + +在 `Trace` 日志级别记录给定的消息。 + +Go: `LogTrace(ctx context.Context, message string)`
JS: `LogTrace(message: string)` + +### LogTracef 格式化 Trace 日志 + +在 `Trace` 日志级别记录给定的消息。 + +Go: `LogTracef(ctx context.Context, format string, args ...interface{})`
+ +### LogDebug Debug 日志 + +在 `Debug` 日志级别记录给定的消息。 + +Go: `LogDebug(ctx context.Context, message string)`
JS: `LogDebug(message: string)` + +### LogDebugf 格式化 Debug 日志 + +在 `Debug` 日志级别记录给定的消息。 + +Go: `LogDebugf(ctx context.Context, format string, args ...interface{})`
+ +### LogInfo Info 日志 + +在`Info`日志级别记录给定的消息。 + +Go: `LogInfo(ctx context.Context, message string)`
JS: `LogInfo(message: string)` + +### LogInfof 格式化 Info 日志 + +在`Info`日志级别记录给定的消息。 + +Go: `LogInfof(ctx context.Context, format string, args ...interface{})`
+ +### LogWarning Warning 日志 + +在 `Warning` 日志级别记录给定的消息。 + +Go: `LogWarning(ctx context.Context, message string)`
JS: `LogWarning(message: string)` + +### LogWarningf 格式化 Warning 日志 + +在 `Warning` 日志级别记录给定的消息。 + +Go: `LogWarningf(ctx context.Context, format string, args ...interface{})`
+ +### LogError Error 日志 + +在 `Error` 日志级别记录给定的消息。 + +Go: `LogError(ctx context.Context, message string)`
JS: `LogError(message: string)` + +### LogErrorf 格式化 Error 日志 + +在 `Error` 日志级别记录给定的消息。 + +Go: `LogErrorf(ctx context.Context, format string, args ...interface{})`
+ +### LogFatal Fatal 日志 + +在 `Fatal` 日志级别记录给定的消息。 + +Go: `LogFatal(ctx context.Context, message string)`
JS: `LogFatal(message: string)` + +### LogFatalf 格式化 Fatal 日志 + +在 `Fatal` 日志级别记录给定的消息。 + +Go: `LogFatalf(ctx context.Context, format string, args ...interface{})`
+ +### LogSetLogLevel 设置日志级别 + +设置日志级别。 在 JavaScript 中,该数字与以下日志级别有关: + +| 值 | 日志等级 | +| - | ----------- | +| 1 | Trace(追踪) | +| 2 | Debug(调试) | +| 3 | Info(信息) | +| 4 | Warning(警告) | +| 5 | Error(错误) | + +Go: `LogSetLogLevel(ctx context.Context, level logger.LogLevel)`
JS: `LogSetLogLevel(level: number)` + +## 使用自定义日志 + +可以通过使用应用程序参数选项 [日志](../../reference/options#日志) 提供自定义记录器来使用它。 唯一的要求是记录器实现在 `github.com/wailsapp/wails/v2/pkg/logger` 里 `logger.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) +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx new file mode 100644 index 00000000000..9d176d06a61 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/menu.mdx @@ -0,0 +1,25 @@ +--- +sidebar_position: 6 +--- + +# Menu 菜单 + +这些方法与应用程序菜单相关。 + +:::info JavaScript + +JS 运行时当前不支持菜单。 + +::: + +### MenuSetApplicationMenu 设置应用程序菜单 + +将应用程序菜单设置为给定的 [菜单](../menus.mdx)。 + +Go: `MenuSetApplicationMenu(ctx context.Context, menu *menu.Menu)` + +### MenuUpdateApplicationMenu 更新应用程序菜单 + +获取传递给 `MenuSetApplicationMenu` 的菜单的任意更改更新应用程序菜单。 + +Go: `MenuUpdateApplicationMenu(ctx context.Context)` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx new file mode 100644 index 00000000000..457c92ebff9 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/screen.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 9 +--- + +# Screen + +These methods provide information about the currently connected screens. + +### ScreenGetAll + +Returns a list of currently connected screens. + +Go: `ScreenGetAll(ctx context.Context) []screen`
+JS: `ScreenGetAll()` + +#### Screen + +Go struct: + +```go +type Screen struct { + IsCurrent bool + IsPrimary bool + Width int + Height int +} +``` + +Typescript interface: + +```ts +interface Screen { + isCurrent: boolean; + isPrimary: boolean; + width : number + height : number +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx new file mode 100644 index 00000000000..3b405c76bcb --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/reference/runtime/window.mdx @@ -0,0 +1,227 @@ +--- +sidebar_position: 4 +--- + +# Window 窗口 + +这些方法可以控制应用程序窗口。 + +### WindowSetTitle 窗口标题 + +设置窗口标题栏中的文本。 + +Go: `WindowSetTitle(ctx context.Context, title string)`
JS: `WindowSetTitle(title: string)` + +### WindowFullscreen 窗口全屏 + +使窗口全屏。 + +Go: `WindowFullscreen(ctx context.Context)`
JS: `WindowFullscreen()` + +### WindowUnfullscreen 窗口取消全屏 + +恢复全屏之前的先前窗口尺寸和位置。 + +Go: `WindowUnfullscreen(ctx context.Context)`
JS: `WindowUnfullscreen()` + +### WindowIsFullscreen 窗口是否全屏 + +如果窗口是全屏的,则返回 true。 + +Go: `WindowIsFullscreen(ctx context.Context) bool`
JS: `WindowIsFullscreen() bool` + +### WindowCenter 窗口居中 + +使窗口在当前窗口所在的监视器上居中。 + +Go: `WindowCenter(ctx context.Context)`
JS: `WindowCenter()` + +### WindowExecJS 窗口执行JS代码 + +在窗口中执行任意 JS 代码。 + +此方法在浏览器中异步运行代码并立即返回。 如果脚本导致任何错误,它们将只在浏览器控制台中可用。 + +Go: `WindowExecJS(ctx context.Context, js string)` + +### WindowReload 窗口重新加载 + +执行“重新加载”(重新加载当前页面)。 + +Go: `WindowReload(ctx context.Context)`
JS: `WindowReload()` + +### WindowReloadApp 重新加载应用程序前端。 + +重新加载应用程序前端。 + +Go: `WindowReloadApp(ctx context.Context)`
JS: `WindowReloadApp()` + +### WindowSetSystemDefaultTheme 窗口设置系统默认主题 + +仅限 Windows。 + +Go: `WindowSetSystemDefaultTheme(ctx context.Context)`
JS: `WindowSetSystemDefaultTheme()` + +将窗口主题设置为系统默认值(暗/亮)。 + +### WindowSetLightTheme 窗口设置浅色主题 + +仅限 Windows。 + +Go: `WindowSetLightTheme(ctx context.Context)`
JS: `WindowSetLightTheme()` + +将窗口主题设置为浅色。 + +### WindowSetDarkTheme 窗口设置深色主题 + +仅限 Windows。 + +Go: `WindowSetDarkTheme(ctx context.Context)`
JS: `WindowSetDarkTheme()` + +将窗口主题设置为深色。 + +### WindowShow 显示窗口 + +显示窗口,如果它当前是隐藏的。 + +Go: `WindowShow(ctx context.Context)`
JS: `WindowShow()` + +### WindowHide 隐藏窗口 + +如果当前可见,则隐藏窗口。 + +Go: `WindowHide(ctx context.Context)`
JS: `WindowHide()` + +### WindowIsNormal 窗口是否为正常 + +如果窗口未最小化、最大化或全屏,则返回 true。 + +Go: `WindowIsNormal(ctx context.Context) bool`
JS: `WindowIsNormal() bool` + +### WindowSetSize 设置窗口尺寸 + +设置窗口的宽度和高度。 + +Go: `WindowSetSize(ctx context.Context, width int, height int)`
JS: `WindowSetSize(width: number, height: number)` + +### WindowGetSize 获取窗口尺寸 + +获取窗口的宽度和高度。 + +Go: `WindowGetSize(ctx context.Context) (width int, height int)`
JS: `WindowGetSize() : Size` + +### WindowSetMinSize 设置窗口最小尺寸 + +设置窗口最小尺寸。 如果窗口当前小于给定尺寸,将调整窗口大小。 + +设置大小 `0,0` 将禁用此约束。 + +Go: `WindowSetMinSize(ctx context.Context, width int, height int)`
JS: `WindowSetMinSize(width: number, height: number)` + +### WindowSetMaxSize 设置窗口最大尺寸 + +设置窗口最大尺寸。 如果窗口当前大于给定尺寸,将调整窗口大小。 + +设置大小 `0,0` 将禁用此约束。 + +Go: `WindowSetMaxSize(ctx context.Context, width int, height int)`
JS: `WindowSetMaxSize(width: number, height: number)` + +### WindowSetAlwaysOnTop 设置窗口置顶 + +设置窗口置顶或取消置顶。 + +Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
JS: `WindowSetAlwaysOnTop(b: Boolen)` + +### WindowSetPosition 设置窗口位置 + +设置相对于窗口当前所在监视器的窗口位置。 + +Go: `WindowSetPosition(ctx context.Context, x int, y int)`
JS: `WindowSetPosition(x: number, y: number)` + +### WindowGetPosition 获取窗口位置 + +获取相对于窗口当前所在监视器的窗口位置。 + +Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
JS: `WindowGetPosition() : Position` + +### WindowMaximise 窗口最大化 + +最大化窗口以填满屏幕。 + +Go: `WindowMaximise(ctx context.Context)`
JS: `WindowMaximise()` + +### WindowUnmaximise 窗口取消最大化 + +将窗口恢复到最大化之前的尺寸和位置。 + +Go: `WindowUnmaximise(ctx context.Context)`
JS: `WindowUnmaximise()` + +### WindowIsMaximised 窗口是否最大化 + +如果窗口最大化,则返回 true。 + +Go: `WindowIsMaximised(ctx context.Context) bool`
JS: `WindowIsMaximised() bool` + +### WindowToggleMaximise 窗口最大化切换 + +在最大化和未最大化之间切换。 + +Go: `WindowToggleMaximise(ctx context.Context)`
JS: `WindowToggleMaximise()` + +### WindowMinimise 窗口最小化。 + +最小化窗口。 + +Go: `WindowMinimise(ctx context.Context)`
JS: `WindowMinimise()` + +### WindowUnminimise 窗口取消最小化 + +将窗口恢复到最小化之前的尺寸和位置。 + +Go: `WindowUnminimise(ctx context.Context)`
JS: `WindowUnminimise()` + +### WindowIsMinimised 窗口是否最小化 + +如果窗口最小化,则返回 true。 + +Go: `WindowIsMinimised(ctx context.Context) bool`
JS: `WindowIsMinimised() bool` + +### WindowSetBackgroundColour 窗口设置背景色 + +将窗口的背景颜色设置为给定的 RGBA 颜色定义。 这种颜色将显示所有透明像素。 + +R、G、B 和 A 的有效值为 0-255。 + +:::info Windows + +在 Windows 上,仅支持 0 或 255 的 alpha 值。 任何非 0 的值都将被视为 255。 + +::: + +Go: `WindowSetBackgroundColour(ctx context.Context, R, G, B, A uint8)`
JS: `WindowSetBackgroundColour(R, G, B, A)` + +### WindowPrint + +Opens tha native print dialog. + +Go: `WindowPrint(ctx context.Context)`
JS: `WindowPrint()` + +## TypeScript 对象定义 + +### Position(位置) + +```ts +interface Position { + x: number; + y: number; +} +``` + +### Size(尺寸) + +```ts +interface Size { + w: number; + h: number; +} +``` diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json new file mode 100644 index 00000000000..dfac1d175e6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Tutorials", + "position": 70 +} diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx new file mode 100644 index 00000000000..cb5d4d79ce6 --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/dogsapi.mdx @@ -0,0 +1,245 @@ +--- +sidebar_position: 20 +--- + +# 狗狗 API + +```mdx-code-block +
+ +
+
+``` + +:::note + +本教程由 [@tatadan](https://twitter.com/tatadan) 友情提供,是他们的 [Wails Examples Repository](https://github.com/tataDan/wails-v2-examples) 的一部分。 + +::: + +在本教程中,我们将开发一个应用程序,从网络上检索狗的照片,然后显示它们。 + +### 创建项目 + +让我们创建应用程序。 从终端输入:`wails init -n dogs-api -t svelte` + +注意:如果您想添加 IDE 支持,我们可以选择在此命令的末尾添加 `-ide vscode` 或 `-ide goland`。 + +现在让我们 `cd dogs-api` 开始编辑项目文件。 + +### 删除未使用的代码 + +我们将从删除一些我们知道不会使用的元素开始: + +- 打开 `app.go` 并删除以下行: + +```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) +} +``` + +- 打开 `frontend/src/App.svelte` 并删除所有行。 +- 删除 `frontend/src/assets/images/logo-universal.png` 文件 + +### 创建应用程序 + +现在让我们添加新的 Go 代码。 + +在函数定义之前添加以下结构声明到 `app.go`: + +```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 +} +``` + +将以下函数添加到 `app.go`(可能在现有函数定义之后): + +```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 +} +``` + +将 `app.go` 的 `import` 部分修改为如下所示: + +```go +import ( + "context" + "fmt" + "encoding/json" + "io/ioutil" + "log" + "net/http" + "sort" +) +``` + +将以下行添加到 `frontend/src/App.svelte`: + + +```html + + +

Dogs API

+
+ + Click on down arrow to select a breed + + +
+
+{#if showRandomPhoto} + No dog found +{/if} +{#if showBreedPhotos} + {#each photos as photo} + No dog found + {/each} +{/if} + + +``` + + +### 创建应用程序 + +要生成绑定并测试应用程序,请运行 `wails dev`。 + +### 编译应用程序 + +要将应用程序编译为单个可用于生产的二进制文件,请运行 `wails build`。 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx new file mode 100644 index 00000000000..863f7ac8f0a --- /dev/null +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-v2.9.0/tutorials/helloworld.mdx @@ -0,0 +1,123 @@ +--- +sidebar_position: 10 +--- + +# 你好世界 + +本教程的目的是让您使用 Wails 启动并运行最基本的应用程序。 你将可以: + +- 创建一个新的 Wails 应用 +- 构建应用 +- 运行应用 + +:::note + +本教程使用 Windows 作为目标平台。 根据您的操作系统,输出会略有不同。 + +::: + +## 创建一个新的 Wails 应用 + +使用默认的 vanilla JS 模板创建新的 Wails 程序, 您需要运行这个指令: + +```bash +wails init -n helloworld +``` + +您应该会看到如下输出: + +``` +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. +``` + +这将在当前目录中创建一个名为 `helloworld` 的新目录。 在此目录中,您将找到许多文件: + +``` +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 +``` + +## 构建应用 + +要构建应用程序,请切换到新的 `helloword` 项目目录并运行以下命令: + +```bash +wails build +``` + +您应该会看到如下输出: + +``` +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 +Devtools: false +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. +``` + +这已经编译了应用程序并将其保存在 `build/bin` 目录中。 + +## 运行应用 + +如果我们在 Windows 文件管理器中查看 `build/bin` 目录,我们应该看到我们的项目二进制文件: + +```mdx-code-block +
+ +
+
+``` + +我们可以通过简单的双击 `helloworld.exe` 文件来运行它。 + +在 Mac 上,Wails 生成一个 `helloworld.app` 文件,可以通过双击来运行。 + +在 Linux 上,您可以从 `build/bin` 目录使用 `./helloword` 运行应用程序。 + +您应该看到应用程序正常工作: + +```mdx-code-block +
+ +
+
+``` diff --git a/website/src/pages/changelog.mdx b/website/src/pages/changelog.mdx index d3a68c8e7a5..391f474d1f6 100644 --- a/website/src/pages/changelog.mdx +++ b/website/src/pages/changelog.mdx @@ -14,6 +14,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## v2.9.0 - 2024-06-16 + ### Added - Added Drag & Drop (files or folders) support for Windows and Linux. Added by [@lyimmi](https://github.com/lyimmi) in [PR](https://github.com/wailsapp/wails/pull/3203). Based on the work of [@ayatkyo](https://github.com/ayatkyo) for Windows in [PR](https://github.com/wailsapp/wails/pull/2774). - Added Drag & Drop (files or folders) support for macOS. Added by [@APshenkin](https://github.com/APshenkin) in [PR](https://github.com/wailsapp/wails/pull/3250). diff --git a/website/versioned_docs/version-v2.9.0/appendix/_category_.json b/website/versioned_docs/version-v2.9.0/appendix/_category_.json new file mode 100644 index 00000000000..83af4ca28fd --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/appendix/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Appendix", + "position": 70 +} diff --git a/website/versioned_docs/version-v2.9.0/community/_category_.json b/website/versioned_docs/version-v2.9.0/community/_category_.json new file mode 100644 index 00000000000..524986e1e49 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Community", + "position": 50 +} diff --git a/website/versioned_docs/version-v2.8.0/community/links.mdx b/website/versioned_docs/version-v2.9.0/community/links.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/links.mdx rename to website/versioned_docs/version-v2.9.0/community/links.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/_category_.json b/website/versioned_docs/version-v2.9.0/community/showcase/_category_.json new file mode 100644 index 00000000000..276e283b71f --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Showcase", + "position": 1 +} diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/bulletinboard.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/bulletinboard.mdx new file mode 100644 index 00000000000..37be75135ed --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/bulletinboard.mdx @@ -0,0 +1,10 @@ +# BulletinBoard + +```mdx-code-block +

+ +
+

+``` + +The [BulletinBoard](https://github.com/raguay/BulletinBoard) application is a versital message board for static messages or dialogs to get information from the user for a script. It has a TUI for creating new dialogs that can latter be used to get information from the user. It's design is to stay running on your system and show the information as needed and then hide away. I have a process for watching a file on my system and sending the contents to BulletinBoard when changed. It works great with my workflows. There is also an [Alfred workflow](https://github.com/raguay/MyAlfred/blob/master/Alfred%205/EmailIt.alfredworkflow) for sending information to the program. The workflow is also for working with [EmailIt](https://github.com/raguay/EmailIt). diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/cfntracker.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/cfntracker.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/cfntracker.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/cfntracker.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/emailit.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/emailit.mdx new file mode 100644 index 00000000000..c1817b70fff --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/emailit.mdx @@ -0,0 +1,10 @@ +# EmailIt + +```mdx-code-block +

+ +
+

+``` + +[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 scripts terminal to run scripts in EmailIt on files in your system. The scripts and templates can be used from the commandline itself or with the Alfred, Keyboard Maestro, Dropzone, or PopClip extensions. It also supports scripts and themes downloaded form GitHub. Documentation is not complete, but the programs works. It’s built using Wails2 and Svelte, and the download is a universal macOS application. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/encrypteasy.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/encrypteasy.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/encrypteasy.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/encrypteasy.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/espstudio.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/espstudio.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/espstudio.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/espstudio.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/filehound.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/filehound.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/filehound.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/filehound.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/hiposter.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/hiposter.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/hiposter.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/hiposter.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/mchat.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/mchat.mdx new file mode 100644 index 00000000000..aa535a6f83e --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/mchat.mdx @@ -0,0 +1,10 @@ +# Mchat + +```mdx-code-block +

+ +
+

+``` + +[Official page](https://marcio199226.github.io/mchat-site/public/) Fully anonymous end2end encrypted chat. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/minecraftupdater.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/minecraftupdater.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/minecraftupdater.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/minecraftupdater.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/modalfilemanager.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/modalfilemanager.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/modalfilemanager.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/modalfilemanager.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/mollywallet.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/mollywallet.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/mollywallet.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/mollywallet.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/october.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/october.mdx new file mode 100644 index 00000000000..66d634dc519 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/october.mdx @@ -0,0 +1,14 @@ +# October + +```mdx-code-block +

+ +
+

+``` + +[October](https://october.utf9k.net) is a small Wails application that makes it really easy to extract highlights from [Kobo eReaders](https://en.wikipedia.org/wiki/Kobo_eReader) and then forward them to [Readwise](https://readwise.io). + +It has a relatively small scope with all platform versions weighing in under 10MB, and that's without enabling [UPX compression](https://upx.github.io/)! + +In contrast, the author's previous attempts with Electron quickly bloated to several hundred megabytes. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/optimus.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/optimus.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/optimus.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/optimus.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/portfall.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/portfall.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/portfall.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/portfall.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/restic-browser.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/restic-browser.mdx new file mode 100644 index 00000000000..3646384ecad --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/restic-browser.mdx @@ -0,0 +1,12 @@ +# Restic Browser + +```mdx-code-block +

+ +
+

+``` + +[Restic-Browser](https://github.com/emuell/restic-browser) - A simple, cross-platform [restic](https://github.com/restic/restic) backup GUI for browsing and restoring restic repositories. diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/riftshare.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/riftshare.mdx new file mode 100644 index 00000000000..9928b478576 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/riftshare.mdx @@ -0,0 +1,21 @@ +# RiftShare + +```mdx-code-block +

+ +
+

+``` + +Easy, Secure, and Free file sharing for everyone. Learn more at [Riftshare.app](https://riftshare.app) + +## Features + +- Easy secure file sharing between computers both in the local network and through the internet +- Supports sending files or directories securely through the [magic wormhole protocol](https://magic-wormhole.readthedocs.io/en/latest/) +- Compatible with all other apps using magic wormhole (magic-wormhole or wormhole-william CLI, wormhole-gui, etc.) +- Automatic zipping of multiple selected files to send at once +- Full animations, progress bar, and cancellation support for sending and receiving +- Native OS File Selection +- Open files in one click once received +- Auto Update - don't worry about having the latest release! diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/scriptbar.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/scriptbar.mdx new file mode 100644 index 00000000000..3e41eb32abf --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/scriptbar.mdx @@ -0,0 +1,10 @@ +# ScriptBar + +```mdx-code-block +

+ +
+

+``` + +[ScriptBar](https://GitHub.com/raguay/ScriptBarApp) is a program to show the output of scripts or [Node-Red](https://nodered.org) server. It runs scripts defined in EmailIt program and shows the output. Scripts from xBar or TextBar can be used, but currently on the TextBar scripts work well. It also displays the output of scripts on your system. ScriptBar doesn't put them in the menubar, but has them all in a convient window for easy viewing. You can have multiple tabs to have many different things show. You can also keep the links to your most visited web sites. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/snippetexpander.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/snippetexpander.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/snippetexpander.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/snippetexpander.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/surge.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/surge.mdx new file mode 100644 index 00000000000..c3b3fb4c06d --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/surge.mdx @@ -0,0 +1,10 @@ +# Surge + +```mdx-code-block +

+ +
+

+``` + +[Surge](https://getsurge.io/) is a p2p filesharing app designed to utilize blockchain technologies to enable 100% anonymous file transfers. Surge is end-to-end encrypted, decentralized and open source. diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/tinyrdm.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/tinyrdm.mdx new file mode 100644 index 00000000000..e3124bab727 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/tinyrdm.mdx @@ -0,0 +1,11 @@ +# Tiny RDM + +```mdx-code-block +

+ + +
+

+``` + +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. diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/wally.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/wally.mdx new file mode 100644 index 00000000000..7408aa5854f --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/wally.mdx @@ -0,0 +1,10 @@ +# Wally + +```mdx-code-block +

+ +
+

+``` + +[Wally](https://ergodox-ez.com/pages/wally) is the official firmware flasher for [Ergodox](https://ergodox-ez.com/) keyboards. It looks great and is a fantastic example of what you can achieve with Wails: the ability to combine the power of Go and the rich graphical tools of the web development world. diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/warmine.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/warmine.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/warmine.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/warmine.mdx diff --git a/website/versioned_docs/version-v2.8.0/community/showcase/wombat.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/wombat.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/community/showcase/wombat.mdx rename to website/versioned_docs/version-v2.9.0/community/showcase/wombat.mdx diff --git a/website/versioned_docs/version-v2.9.0/community/showcase/ytd.mdx b/website/versioned_docs/version-v2.9.0/community/showcase/ytd.mdx new file mode 100644 index 00000000000..5db428f722c --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/community/showcase/ytd.mdx @@ -0,0 +1,10 @@ +# Ytd + +```mdx-code-block +

+ +
+

+``` + +[Ytd](https://github.com/marcio199226/ytd/tree/v2-wails) is an app for downloading tracks from youtube, creating offline playlists and share them with your friends, your friends will be able to playback your playlists or download them for offline listening, has an built-in player. diff --git a/website/versioned_docs/version-v2.8.0/community/templates.mdx b/website/versioned_docs/version-v2.9.0/community/templates.mdx similarity index 90% rename from website/versioned_docs/version-v2.8.0/community/templates.mdx rename to website/versioned_docs/version-v2.9.0/community/templates.mdx index b531dcc8755..44689684934 100644 --- a/website/versioned_docs/version-v2.8.0/community/templates.mdx +++ b/website/versioned_docs/version-v2.9.0/community/templates.mdx @@ -24,8 +24,6 @@ If you are unsure about a template, inspect `package.json` and `wails.json` for ## Vue - [wails-template-vue](https://github.com/misitebao/wails-template-vue) - Wails template based on Vue ecology (Integrated TypeScript, Dark theme, Internationalization, Single page routing, TailwindCSS) -- [wails-vite-vue-ts](https://github.com/codydbentley/wails-vite-vue-ts) - Vue 3 TypeScript with Vite (and instructions to add features) -- [wails-vite-vue-the-works](https://github.com/codydbentley/wails-vite-vue-the-works) - Vue 3 TypeScript with Vite, Vuex, Vue Router, Sass, and ESLint + Prettier - [wails-template-quasar-js](https://github.com/sgosiaco/wails-template-quasar-js) - A template using JavaScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier) - [wails-template-quasar-ts](https://github.com/sgosiaco/wails-template-quasar-ts) - A template using TypeScript + Quasar V2 (Vue 3, Vite, Sass, Pinia, ESLint, Prettier, Composition API with <script setup>) - [wails-template-naive](https://github.com/tk103331/wails-template-naive) - Wails template based on Naive UI (A Vue 3 Component Library) @@ -41,7 +39,6 @@ If you are unsure about a template, inspect `package.json` and `wails.json` for - [wails-react-template](https://github.com/flin7/wails-react-template) - A minimal template for React that supports live development - [wails-template-nextjs](https://github.com/LGiki/wails-template-nextjs) - A template using Next.js and 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-next-tailwind-shadcnui-ts](https://github.com/vxxvvxxv/wails-next-tailwind-shadcnui-ts) - A template using Next.js (with app router + dark theme), TypeScript, TailwindCSS, and shadcn/ui - [wails-vite-react-ts-tailwind-template](https://github.com/hotafrika/wails-vite-react-ts-tailwind-template) - A template for React + TypeScript + Vite + TailwindCSS - [wails-vite-react-ts-tailwind-shadcnui-template](https://github.com/Mahcks/wails-vite-react-tailwind-shadcnui-ts) - A template with Vite, React, TypeScript, TailwindCSS, and shadcn/ui @@ -70,3 +67,8 @@ If you are unsure about a template, inspect `package.json` and `wails.json` for ## Pure JavaScript (Vanilla) - [wails-pure-js-template](https://github.com/KiddoV/wails-pure-js-template) - A template with nothing but just basic JavaScript, HTML, and CSS + + +## Lit (web components) + +- [wails-lit-shoelace-esbuild-template](https://github.com/Braincompiler/wails-lit-shoelace-esbuild-template) - Wails template providing frontend with lit, Shoelace component library + pre-configured prettier and typescript. diff --git a/website/versioned_docs/version-v2.9.0/gettingstarted/_category_.json b/website/versioned_docs/version-v2.9.0/gettingstarted/_category_.json new file mode 100644 index 00000000000..597b920dff9 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/gettingstarted/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Getting Started", + "position": 10 +} diff --git a/website/versioned_docs/version-v2.8.0/gettingstarted/building.mdx b/website/versioned_docs/version-v2.9.0/gettingstarted/building.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/gettingstarted/building.mdx rename to website/versioned_docs/version-v2.9.0/gettingstarted/building.mdx diff --git a/website/versioned_docs/version-v2.8.0/gettingstarted/development.mdx b/website/versioned_docs/version-v2.9.0/gettingstarted/development.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/gettingstarted/development.mdx rename to website/versioned_docs/version-v2.9.0/gettingstarted/development.mdx diff --git a/website/versioned_docs/version-v2.8.0/gettingstarted/firstproject.mdx b/website/versioned_docs/version-v2.9.0/gettingstarted/firstproject.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/gettingstarted/firstproject.mdx rename to website/versioned_docs/version-v2.9.0/gettingstarted/firstproject.mdx diff --git a/website/versioned_docs/version-v2.8.0/gettingstarted/installation.mdx b/website/versioned_docs/version-v2.9.0/gettingstarted/installation.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/gettingstarted/installation.mdx rename to website/versioned_docs/version-v2.9.0/gettingstarted/installation.mdx diff --git a/website/versioned_docs/version-v2.9.0/guides/_category_.json b/website/versioned_docs/version-v2.9.0/guides/_category_.json new file mode 100644 index 00000000000..5935dad936c --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/guides/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Guides", + "position": 50 +} diff --git a/website/versioned_docs/version-v2.8.0/guides/angular.mdx b/website/versioned_docs/version-v2.9.0/guides/angular.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/angular.mdx rename to website/versioned_docs/version-v2.9.0/guides/angular.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/application-development.mdx b/website/versioned_docs/version-v2.9.0/guides/application-development.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/application-development.mdx rename to website/versioned_docs/version-v2.9.0/guides/application-development.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/crossplatform-build.mdx b/website/versioned_docs/version-v2.9.0/guides/crossplatform-build.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/crossplatform-build.mdx rename to website/versioned_docs/version-v2.9.0/guides/crossplatform-build.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/custom-protocol-schemes.mdx b/website/versioned_docs/version-v2.9.0/guides/custom-protocol-schemes.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/custom-protocol-schemes.mdx rename to website/versioned_docs/version-v2.9.0/guides/custom-protocol-schemes.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/dynamic-assets.mdx b/website/versioned_docs/version-v2.9.0/guides/dynamic-assets.mdx similarity index 92% rename from website/versioned_docs/version-v2.8.0/guides/dynamic-assets.mdx rename to website/versioned_docs/version-v2.9.0/guides/dynamic-assets.mdx index 0516fb72954..8d1debceff7 100644 --- a/website/versioned_docs/version-v2.8.0/guides/dynamic-assets.mdx +++ b/website/versioned_docs/version-v2.9.0/guides/dynamic-assets.mdx @@ -1,5 +1,14 @@ # Dynamic Assets +:::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 + +::: + 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 diff --git a/website/versioned_docs/version-v2.8.0/guides/file-association.mdx b/website/versioned_docs/version-v2.9.0/guides/file-association.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/file-association.mdx rename to website/versioned_docs/version-v2.9.0/guides/file-association.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/frameless.mdx b/website/versioned_docs/version-v2.9.0/guides/frameless.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/frameless.mdx rename to website/versioned_docs/version-v2.9.0/guides/frameless.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/frontend.mdx b/website/versioned_docs/version-v2.9.0/guides/frontend.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/frontend.mdx rename to website/versioned_docs/version-v2.9.0/guides/frontend.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/ides.mdx b/website/versioned_docs/version-v2.9.0/guides/ides.mdx similarity index 98% rename from website/versioned_docs/version-v2.8.0/guides/ides.mdx rename to website/versioned_docs/version-v2.9.0/guides/ides.mdx index f22aefe9ea6..5fe5a7bb966 100644 --- a/website/versioned_docs/version-v2.8.0/guides/ides.mdx +++ b/website/versioned_docs/version-v2.9.0/guides/ides.mdx @@ -3,7 +3,7 @@ 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. +Currently, we support [Visual Studio Code](https://code.visualstudio.com/) and [Goland](https://www.jetbrains.com/go/). ## Visual Studio Code diff --git a/website/versioned_docs/version-v2.8.0/guides/linux-distro-support.mdx b/website/versioned_docs/version-v2.9.0/guides/linux-distro-support.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/linux-distro-support.mdx rename to website/versioned_docs/version-v2.9.0/guides/linux-distro-support.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/linux.mdx b/website/versioned_docs/version-v2.9.0/guides/linux.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/linux.mdx rename to website/versioned_docs/version-v2.9.0/guides/linux.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/local-development.mdx b/website/versioned_docs/version-v2.9.0/guides/local-development.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/local-development.mdx rename to website/versioned_docs/version-v2.9.0/guides/local-development.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/mac-appstore.mdx b/website/versioned_docs/version-v2.9.0/guides/mac-appstore.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/mac-appstore.mdx rename to website/versioned_docs/version-v2.9.0/guides/mac-appstore.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/manual-builds.mdx b/website/versioned_docs/version-v2.9.0/guides/manual-builds.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/manual-builds.mdx rename to website/versioned_docs/version-v2.9.0/guides/manual-builds.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/migrating.mdx b/website/versioned_docs/version-v2.9.0/guides/migrating.mdx similarity index 99% rename from website/versioned_docs/version-v2.8.0/guides/migrating.mdx rename to website/versioned_docs/version-v2.9.0/guides/migrating.mdx index 45c9cf7a038..28dbca5563f 100644 --- a/website/versioned_docs/version-v2.8.0/guides/migrating.mdx +++ b/website/versioned_docs/version-v2.9.0/guides/migrating.mdx @@ -97,7 +97,7 @@ func (b *Basic) startup(ctx context.Context) { 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). +to 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 diff --git a/website/versioned_docs/version-v2.8.0/guides/mouse-buttons.mdx b/website/versioned_docs/version-v2.9.0/guides/mouse-buttons.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/mouse-buttons.mdx rename to website/versioned_docs/version-v2.9.0/guides/mouse-buttons.mdx diff --git a/website/versioned_docs/version-v2.9.0/guides/nixos-font.mdx b/website/versioned_docs/version-v2.9.0/guides/nixos-font.mdx new file mode 100644 index 00000000000..141e4d68caa --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/guides/nixos-font.mdx @@ -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/"; + ''; +``` diff --git a/website/versioned_docs/version-v2.8.0/guides/obfuscated.mdx b/website/versioned_docs/version-v2.9.0/guides/obfuscated.mdx similarity index 98% rename from website/versioned_docs/version-v2.8.0/guides/obfuscated.mdx rename to website/versioned_docs/version-v2.9.0/guides/obfuscated.mdx index 2e7906c4067..c35fb003845 100644 --- a/website/versioned_docs/version-v2.8.0/guides/obfuscated.mdx +++ b/website/versioned_docs/version-v2.9.0/guides/obfuscated.mdx @@ -14,7 +14,7 @@ To customise the obfuscation settings, you can use the `-garbleargs` flag: wails build -obfuscated -garbleargs "-literals -tiny -seed=myrandomseed" ``` -These settings may be persisted in your [project config](../reference/project-config). +These settings may be persisted in your [project config](../reference/project-config.mdx). ## How it works diff --git a/website/versioned_docs/version-v2.8.0/guides/overscroll.mdx b/website/versioned_docs/version-v2.9.0/guides/overscroll.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/overscroll.mdx rename to website/versioned_docs/version-v2.9.0/guides/overscroll.mdx diff --git a/website/versioned_docs/version-v2.9.0/guides/routing.mdx b/website/versioned_docs/version-v2.9.0/guides/routing.mdx new file mode 100644 index 00000000000..63a081ffd83 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/guides/routing.mdx @@ -0,0 +1,68 @@ +# 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/en/main/router-components/hash-router): + +```jsx +import { HashRouter, Routes, Route } from "react-router-dom"; + +ReactDOM.render( + + {/* The rest of your app goes here */} + + } exact /> + } /> + } /> + {/* more... */} + + , + root +); +``` + +## Svelte + +The recommended approach for routing in Svelte is [svelte-spa-router](https://github.com/ItalyPaleAle/svelte-spa-router): + +```svelte + + + import("./routes/Products.svelte"), + }), + "/settings": Settings, + "*": NotFound, + }} +/> +``` diff --git a/website/versioned_docs/version-v2.8.0/guides/signing.mdx b/website/versioned_docs/version-v2.9.0/guides/signing.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/signing.mdx rename to website/versioned_docs/version-v2.9.0/guides/signing.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/single-instance-lock.mdx b/website/versioned_docs/version-v2.9.0/guides/single-instance-lock.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/single-instance-lock.mdx rename to website/versioned_docs/version-v2.9.0/guides/single-instance-lock.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/sveltekit.mdx b/website/versioned_docs/version-v2.9.0/guides/sveltekit.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/sveltekit.mdx rename to website/versioned_docs/version-v2.9.0/guides/sveltekit.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/templates.mdx b/website/versioned_docs/version-v2.9.0/guides/templates.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/templates.mdx rename to website/versioned_docs/version-v2.9.0/guides/templates.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/troubleshooting.mdx b/website/versioned_docs/version-v2.9.0/guides/troubleshooting.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/troubleshooting.mdx rename to website/versioned_docs/version-v2.9.0/guides/troubleshooting.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/vscode.mdx b/website/versioned_docs/version-v2.9.0/guides/vscode.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/vscode.mdx rename to website/versioned_docs/version-v2.9.0/guides/vscode.mdx diff --git a/website/versioned_docs/version-v2.8.0/guides/windows-installer.mdx b/website/versioned_docs/version-v2.9.0/guides/windows-installer.mdx similarity index 98% rename from website/versioned_docs/version-v2.8.0/guides/windows-installer.mdx rename to website/versioned_docs/version-v2.9.0/guides/windows-installer.mdx index c65dc6d3422..d8672222f20 100644 --- a/website/versioned_docs/version-v2.8.0/guides/windows-installer.mdx +++ b/website/versioned_docs/version-v2.9.0/guides/windows-installer.mdx @@ -21,7 +21,7 @@ The installer is available on the [NSIS Download](https://nsis.sourceforge.io/Do You can install with [Scoop](https://scoop.sh/) (which will automatically add it to your PATH): ``` -scoop add bucket extras +scoop bucket add extras scoop install nsis ``` diff --git a/website/versioned_docs/version-v2.8.0/guides/windows.mdx b/website/versioned_docs/version-v2.9.0/guides/windows.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/guides/windows.mdx rename to website/versioned_docs/version-v2.9.0/guides/windows.mdx diff --git a/website/versioned_docs/version-v2.8.0/howdoesitwork.mdx b/website/versioned_docs/version-v2.9.0/howdoesitwork.mdx similarity index 99% rename from website/versioned_docs/version-v2.8.0/howdoesitwork.mdx rename to website/versioned_docs/version-v2.9.0/howdoesitwork.mdx index 6e23d5eb94d..48243f4eb41 100644 --- a/website/versioned_docs/version-v2.8.0/howdoesitwork.mdx +++ b/website/versioned_docs/version-v2.9.0/howdoesitwork.mdx @@ -88,7 +88,7 @@ This example has the following options set: - `OnShutdown` - A callback for when the application is about to quit - `Bind` - A slice of struct instances that we wish to expose to the frontend -A full list of application options can be found in the [Options Reference](reference/options). +A full list of application options can be found in the [Options Reference](reference/options.mdx). #### Assets @@ -418,7 +418,7 @@ export namespace main { if (!a) { return a; } - if (a.slice) { + if (a.slice && a.map) { return (a as any[]).map((elem) => this.convertValues(elem, classs)); } else if ("object" === typeof a) { if (asMap) { @@ -466,4 +466,4 @@ tasks such as emit an event or perform logging operations: window.runtime.EventsEmit("my-event", 1); ``` -More details about the JS runtime can be found in the [Runtime Reference](reference/runtime/intro). +More details about the JS runtime can be found in the [Runtime Reference](reference/runtime/intro.mdx). diff --git a/website/versioned_docs/version-v2.8.0/introduction.mdx b/website/versioned_docs/version-v2.9.0/introduction.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/introduction.mdx rename to website/versioned_docs/version-v2.9.0/introduction.mdx diff --git a/website/versioned_docs/version-v2.9.0/reference/_category_.json b/website/versioned_docs/version-v2.9.0/reference/_category_.json new file mode 100644 index 00000000000..ebb337b8360 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/reference/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Reference", + "position": 40 +} diff --git a/website/versioned_docs/version-v2.8.0/reference/cli.mdx b/website/versioned_docs/version-v2.9.0/reference/cli.mdx similarity index 99% rename from website/versioned_docs/version-v2.8.0/reference/cli.mdx rename to website/versioned_docs/version-v2.9.0/reference/cli.mdx index dc8b3293f81..9bb41d10c67 100644 --- a/website/versioned_docs/version-v2.8.0/reference/cli.mdx +++ b/website/versioned_docs/version-v2.9.0/reference/cli.mdx @@ -20,7 +20,7 @@ The Wails CLI has a number of commands that are used for managing your projects. | -l | List available project templates | | | -q | Suppress output to console | | | -t "template name" | The project template to use. This can be the name of a default template or a URL to a remote template hosted on github. | vanilla | -| -ide | Generate IDE project files | | +| -ide | Generate IDE project files `vscode` or `goland` | | | -f | Force build application | false | Example: diff --git a/website/versioned_docs/version-v2.8.0/reference/menus.mdx b/website/versioned_docs/version-v2.9.0/reference/menus.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/menus.mdx rename to website/versioned_docs/version-v2.9.0/reference/menus.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/options.mdx b/website/versioned_docs/version-v2.9.0/reference/options.mdx similarity index 95% rename from website/versioned_docs/version-v2.8.0/reference/options.mdx rename to website/versioned_docs/version-v2.9.0/reference/options.mdx index 619b8eaf276..a6026f12662 100644 --- a/website/versioned_docs/version-v2.8.0/reference/options.mdx +++ b/website/versioned_docs/version-v2.9.0/reference/options.mdx @@ -64,6 +64,12 @@ func main() { UniqueId: "c9c8fd93-6758-4144-87d1-34bdb0a8bd60", OnSecondInstanceLaunch: app.onSecondInstanceLaunch, }, + DragAndDrop: &options.DragAndDrop{ + EnableFileDrop: false, + DisableWebViewDrop: false, + CSSDropProperty: "--wails-drop-target", + CSSDropValue: "drop", + }, Windows: &windows.Options{ WebviewIsTransparent: false, WindowIsTranslucent: false, @@ -109,7 +115,6 @@ func main() { Appearance: mac.NSAppearanceNameDarkAqua, WebviewIsTransparent: true, WindowIsTranslucent: false, - DisableZoom: false, About: &mac.AboutInfo{ Title: "My Application", Message: "© 2021 Me", @@ -315,6 +320,15 @@ If not defined, the result is the following in cases where the Handler would hav - GET request: `http.StatusNotFound` - Other request: `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 + +::: + 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. @@ -529,6 +543,52 @@ Callback that is called when a second instance of your app is launched. Name: OnSecondInstanceLaunch
Type: `func(secondInstanceData SecondInstanceData)` +### Drag and Drop + +Defines the behavior of drag and drop events on the window. + +Name: DragAndDrop
+Type: `options.DragAndDrop` + +#### EnableFileDrop + +EnableFileDrop enables wails' drag and drop functionality that returns the dropped in files' absolute paths. + +When it is set to `true` the [runtime methods](../reference/runtime/draganddrop.mdx) can be used.
+Or you can listen for the `wails:file-drop` event with [runtime EventsOn method](../reference/runtime/events.mdx#eventson) both on the +Javascript and GO side to implement any functionality you would like. + +The event returns the coordinates of the drop and a file path slice. + +Name: EnableFileDrop
+Type: `bool`
+Default: `false` + +#### DisableWebViewDrop + +Disables the webview's drag and drop functionality. + +It can be used to prevent accidental opening of dragged in files in the webview, when there is no need for drag and drop. + +Name: DisableWebViewDrop
+Type: `bool`
+Default: `false` + +#### CSSDropProperty + +CSS property to test for drag and drop target elements. + +Name: CSSDropProperty
+Type: `string`
+Default: `--wails-drop-target` + +#### CSSDropValue + +The CSS Value that the CSSDropProperty must have to be a valid drop target. Default "drop" + +Name: CSSDropValue
+Type: `string`
+Default: `drop` ### Windows @@ -898,13 +958,6 @@ Mac: &mac.Options{ } ``` -#### DisableZoom - -By default, the window is zoomable. Setting this to `true` will disable the zoom button (green button). - -Name: DisableZoom
-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. diff --git a/website/versioned_docs/version-v2.8.0/reference/project-config.mdx b/website/versioned_docs/version-v2.9.0/reference/project-config.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/project-config.mdx rename to website/versioned_docs/version-v2.9.0/reference/project-config.mdx diff --git a/website/versioned_docs/version-v2.9.0/reference/runtime/_category_.json b/website/versioned_docs/version-v2.9.0/reference/runtime/_category_.json new file mode 100644 index 00000000000..ac6d5548816 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/reference/runtime/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Runtime", + "position": 1 +} diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/browser.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/browser.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/browser.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/browser.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/clipboard.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/clipboard.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/clipboard.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/clipboard.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/dialog.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/dialog.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/dialog.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/dialog.mdx diff --git a/website/versioned_docs/version-v2.9.0/reference/runtime/draganddrop.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/draganddrop.mdx new file mode 100644 index 00000000000..ca24e968bc0 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/reference/runtime/draganddrop.mdx @@ -0,0 +1,38 @@ +--- +sidebar_position: 10 +--- + +# Drag And Drop + +::: + +This part of the runtime handles dragging and dropping files and or folders in to the window.
+ +To enable this functionality you have to set [EnableFileDrop](../../reference/options.mdx#enablefiledrop) to `true` +in [Application Options](../../reference/options.mdx#drag-and-drop). + +### OnFileDrop + +This method handles the drop event on the window. + +Go: `OnFileDrop(ctx context.Context, callback func(x, y int, paths []string))`
+Calls the callback function with the coordinates inside the window where the drag was released and a slice of absolute file paths. + +JS: `OnFileDrop(callback: (x: number, y: number, paths: string[]) => void, useDropTarget: boolean) :void`
+Calls the callback function with the coordinates inside the window where the drag was released and a slice of absolute file paths. + +When the `useDropTarget` is `true` in addition to calling the callback when the drop happens, it registers event listeners on +the window that are listening for the drag coordinates and checks if the mouse is over an element that has the +[CSSDropProperty](../../reference/options.mdx#cssdropproperty) style. If the element has the required property +it adds the `wails-drop-target-active` class to the element's class list and removes it when the mouse moves off of it. + + +### OnFileDropOff + +This method removes all registered listeners and handlers for drag and drop events. + +Go: `OnFileDropOff(ctx context.Context)`
+Returns: has no return value. + +JS: `OnFileDropOff(): void`
+Returns: has no return value. diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/events.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/events.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/events.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/events.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/intro.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/intro.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/intro.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/intro.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/log.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/log.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/log.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/log.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/menu.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/menu.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/menu.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/menu.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/screen.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/screen.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/reference/runtime/screen.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/screen.mdx diff --git a/website/versioned_docs/version-v2.8.0/reference/runtime/window.mdx b/website/versioned_docs/version-v2.9.0/reference/runtime/window.mdx similarity index 94% rename from website/versioned_docs/version-v2.8.0/reference/runtime/window.mdx rename to website/versioned_docs/version-v2.9.0/reference/runtime/window.mdx index 69ed1fe2b1f..625cd5e448d 100644 --- a/website/versioned_docs/version-v2.8.0/reference/runtime/window.mdx +++ b/website/versioned_docs/version-v2.9.0/reference/runtime/window.mdx @@ -32,7 +32,7 @@ JS: `WindowUnfullscreen()` Returns true if the window is full screen. Go: `WindowIsFullscreen(ctx context.Context) bool`
-JS: `WindowIsFullscreen() bool` +JS: `WindowIsFullscreen() Promise` ### WindowCenter @@ -110,7 +110,7 @@ JS: `WindowHide()` Returns true if the window not minimised, maximised or fullscreen. Go: `WindowIsNormal(ctx context.Context) bool`
-JS: `WindowIsNormal() bool` +JS: `WindowIsNormal() Promise` ### WindowSetSize @@ -124,7 +124,7 @@ JS: `WindowSetSize(width: number, height: number)` Gets the width and height of the window. Go: `WindowGetSize(ctx context.Context) (width int, height int)`
-JS: `WindowGetSize() : Size` +JS: `WindowGetSize(): Promise` ### WindowSetMinSize @@ -151,7 +151,7 @@ JS: `WindowSetMaxSize(width: number, height: number)` Sets the window AlwaysOnTop or not on top. Go: `WindowSetAlwaysOnTop(ctx context.Context, b bool)`
-JS: `WindowSetAlwaysOnTop(b: Boolen)` +JS: `WindowSetAlwaysOnTop(b: boolean)` ### WindowSetPosition @@ -165,7 +165,7 @@ JS: `WindowSetPosition(x: number, y: number)` Gets the window position relative to the monitor the window is currently on. Go: `WindowGetPosition(ctx context.Context) (x int, y int)`
-JS: `WindowGetPosition() : Position` +JS: `WindowGetPosition(): Promise` ### WindowMaximise @@ -186,7 +186,7 @@ JS: `WindowUnmaximise()` Returns true if the window is maximised. Go: `WindowIsMaximised(ctx context.Context) bool`
-JS: `WindowIsMaximised() bool` +JS: `WindowIsMaximised() Promise` ### WindowToggleMaximise @@ -214,7 +214,7 @@ JS: `WindowUnminimise()` Returns true if the window is minimised. Go: `WindowIsMinimised(ctx context.Context) bool`
-JS: `WindowIsMinimised() bool` +JS: `WindowIsMinimised() Promise` ### WindowSetBackgroundColour diff --git a/website/versioned_docs/version-v2.9.0/tutorials/_category_.json b/website/versioned_docs/version-v2.9.0/tutorials/_category_.json new file mode 100644 index 00000000000..dfac1d175e6 --- /dev/null +++ b/website/versioned_docs/version-v2.9.0/tutorials/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Tutorials", + "position": 70 +} diff --git a/website/versioned_docs/version-v2.8.0/tutorials/dogsapi.mdx b/website/versioned_docs/version-v2.9.0/tutorials/dogsapi.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/tutorials/dogsapi.mdx rename to website/versioned_docs/version-v2.9.0/tutorials/dogsapi.mdx diff --git a/website/versioned_docs/version-v2.8.0/tutorials/helloworld.mdx b/website/versioned_docs/version-v2.9.0/tutorials/helloworld.mdx similarity index 100% rename from website/versioned_docs/version-v2.8.0/tutorials/helloworld.mdx rename to website/versioned_docs/version-v2.9.0/tutorials/helloworld.mdx diff --git a/website/versioned_sidebars/version-v2.8.0-sidebars.json b/website/versioned_sidebars/version-v2.9.0-sidebars.json similarity index 100% rename from website/versioned_sidebars/version-v2.8.0-sidebars.json rename to website/versioned_sidebars/version-v2.9.0-sidebars.json diff --git a/website/versions.json b/website/versions.json index afe89969e01..731ec46ad5c 100644 --- a/website/versions.json +++ b/website/versions.json @@ -1 +1 @@ -["v2.8.1","v2.8.0"] \ No newline at end of file +["v2.9.0","v2.8.1"] \ No newline at end of file