5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-04 23:11:53 +08:00
wails/v3/pkg/application/application_options.go
Fabio Massaioli 90b7ea944d
[v3] New binding generator (#3468)
* Support variadic arguments and slice, pointer types

* Fix computation of type namespaces

* Improve comments and general formatting

* Set default values correctly for composite types

* Add templates for bindings

Additionally:
* fixes generation of tuple return type
* improves imports and namespacing in JS mode
* general cleanup of generated code

* Simplify import list construction

* Refactor type generation code

Improves support for unknown types (encoded as any) and maps (using
Typescript index signatures)

* Support slices with pointer elements

* Match encoding/json behaviour in struct parser

* Update tests and example

* Add tests for complex method signatures and json tag parsing

* Add test `function_multiple_files`

* Attempt looking up idents with missing denotation

* Update test data

* fix quoted bool field

* Test quoted booleans

* Delete old parser code

* Remove old test data

* Update bindgen flags

* Makes call by ID the default

* Add package loading code

* Add static analyser

* Temporarily ignore binding generation code

* Add complex slice expressions test

* Fix variable reference analysis

* Unwrap casts to interface types

* Complete code comments

* Refactor static analyser

* Restrict options struct usage

* Update tests

* Fix method selector sink and source processing

* Improve Set API

* Add package info collector

* Rename analyser package to analyse

* Improve template functions

* Add index file templates

* Add glue code for binding generation

* Refactor collection and rendering code

* Implement binding generator

* Implement global index generation

* Improve marshaler and alias handling

* Use package path in binding calls by name

* Implement model collection and rendering

* Fix wrong exit condition in analyser

* Fix enum rendering

* Generate shortcuts for all packages.

* Implement generator tests

* Ignore non-pointer bound types

* Treat main package specially

* Compute stats

* Plug new API into generate command

* Support all named types

* Update JS runtime

* Report dual role types

* Remove go1.22 syntax

* Fix type assertion in TS bindings

* encoding/json compliance for arrays and slices

* Ignore got files in testdata

* Cleanup type rendering mechanism

* Update JS runtime

* Implement generic models

* Add missing field in renderer initialisation

* Improve generic creation code

* Add generic model test

* Add error reporting infrastructure

* Support configurable file names

* Detect file naming collisions

* Print final error report

* New shortcut file structure + collision detection

* Update test layout and data

* Autoconfiguration for analyser tests

* Live progress reporting

* Update code comments

* Fix model doc rendering

* Simplify name resolution

* Add test for out of tree types

* Fix generic creation code

* Fix potential collisions between methods and models

* Fix generic class alias rendering

* Report model discovery in debug mode

* Add interface mode for JS

* Collect interface method comments

* Add interface methods test

* Unwrap generic instantiations in method receivers

* Fix rendering of nullable types in interface mode

* Fix rendering of class aliases

* Expose promise cancel method to typescript

* Update test data

* Update binding example

* Fix rendering of aliased quoted type params

* Move to strongly typed bindings

* Implement lightweight analyser

* Update test cases

* Update binding example

* Add complex instantiation test

* Load full dependency tree

* Rewrite collector

* Update renderer to match new collector

* Update generator to match new collector

* Update test data

* Update binding example

* Configure includes and injections by language

* Improve system path resolution

* Support rich conditions in inject/include directives

* Fix error handling in Generator.Generate

* Retrieve compiled go file paths from fileset

* Do not rely on struct info in struct flattening algorithm

* Fix doc comment for findDeclaraion

* Fix bugs in embedded field handling

* Fix bugs and comments in package collection

* Remove useless fields from ServiceInfo

* Fix empty line at the beginning of TS indexes

* Remove global index and shortcuts

* Remove generation tests for individual packages

* Enforce lower-case file names

* Update test data

* Improve error reporting

* Update binding example

* Reintroduce go1.22 syntax

* Improve relative import path computation

* Improve alias support

* Add alias test

* Update test data

* Remove no services error

* Rename global analyser test

* Add workaround and test for bug in typeutil.Map

* Update test data

* Do not split fully qualified names

* Update typeutil package and remove workaround

* Unify alias/named type handling

* Fix rendering of generic named class aliases

* Fix rendering of array types

* Minor tweaks and cleanups

* Rmove namespaced export construct

* Update test data

* Update binding example

* Break type cycles

* Fix typo in comment

* Fix creation code for cyclic types

* Fix type of variadic params in interface mode

* Update test data

* Fix bad whitespace

* Refactor type assertions inside bound methods

* Update test data

* Rename field application.Options.Bind to Services

* Rename parser package to generator

* Update binding example

* Update test data

* Update generator readme

* Add typescript test harness

* Move test output to new subfolder

* Fix code generation bugs

* Use .js extensions in TS mode imports

* Update test data

* Revert default generator output dir to frontend/bindings

* Bump runtime package version

* Update templates

* Update changelog

* Improve newline handling

---------

Co-authored-by: Andreas Bichinger <andreas.bichinger@gmail.com>
2024-05-19 20:40:44 +10:00

211 lines
7.9 KiB
Go

package application
import (
"io/fs"
"log/slog"
"net/http"
"github.com/wailsapp/wails/v3/internal/assetserver"
)
// Service wraps a bound type instance.
// The zero value of Service is invalid.
// Valid values may only be obtained by calling [NewService].
type Service struct {
instance any
}
// NewService returns a Service value wrapping the given pointer.
// If T is not a named type, the returned value is invalid.
func NewService[T any](instance *T) Service {
return Service{instance}
}
func (s Service) Instance() any {
return s.instance
}
// Options contains the options for the application
type Options struct {
// Name is the name of the application (used in the default about box)
Name string
// Description is the description of the application (used in the default about box)
Description string
// Icon is the icon of the application (used in the default about box)
Icon []byte
// Mac is the Mac specific configuration for Mac builds
Mac MacOptions
// Windows is the Windows specific configuration for Windows builds
Windows WindowsOptions
// Linux is the Linux specific configuration for Linux builds
Linux LinuxOptions
// Services allows you to bind Go methods to the frontend.
Services []Service
// BindAliases allows you to specify alias IDs for your bound methods.
// Example: `BindAliases: map[uint32]uint32{1: 1411160069}` states that alias ID 1 maps to the Go method with ID 1411160069.
BindAliases map[uint32]uint32
// Logger i a slog.Logger instance used for logging Wails system messages (not application messages).
// If not defined, a default logger is used.
Logger *slog.Logger
// LogLevel defines the log level of the Wails system logger.
LogLevel slog.Level
// Assets are the application assets to be used.
Assets AssetOptions
// Plugins is a map of plugins used by the application
Plugins map[string]Plugin
// Flags are key value pairs that are available to the frontend.
// This is also used by Wails to provide information to the frontend.
Flags map[string]any
// PanicHandler is called when a panic occurs
PanicHandler func(any)
// DisableDefaultSignalHandler disables the default signal handler
DisableDefaultSignalHandler bool
// KeyBindings is a map of key bindings to functions
KeyBindings map[string]func(window *WebviewWindow)
// OnShutdown is called when the application is about to terminate.
// This is useful for cleanup tasks.
// The shutdown process blocks until this function returns
OnShutdown func()
// ShouldQuit is a function that is called when the user tries to quit the application.
// If the function returns true, the application will quit.
// If the function returns false, the application will not quit.
ShouldQuit func() bool
// This blank field ensures types from other packages
// are never convertible to Options.
// This property, in turn, improves the accuracy of the binding generator.
_ struct{}
}
// AssetOptions defines the configuration of the AssetServer.
type AssetOptions struct {
// Handler which serves all the content to the WebView.
Handler http.Handler
// 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.
//
// This middleware injects itself before any of Wails internal middlewares.
//
// If not defined, the default AssetServer request chain is executed.
//
// Multiple Middlewares can be chained together with:
// ChainMiddleware(middleware ...Middleware) Middleware
Middleware Middleware
// DisableLogging disables logging of the AssetServer. By default, the AssetServer logs every request.
DisableLogging bool
}
// Middleware defines HTTP middleware that can be applied to the AssetServer.
// The handler passed as next is the next handler in the chain. One can decide to call the next handler
// or implement a specialized handling.
type Middleware func(next http.Handler) http.Handler
// ChainMiddleware allows chaining multiple middlewares to one middleware.
func ChainMiddleware(middleware ...Middleware) Middleware {
return func(h http.Handler) http.Handler {
for i := len(middleware) - 1; i >= 0; i-- {
h = middleware[i](h)
}
return h
}
}
// AssetFileServerFS returns a http handler which serves the assets from the fs.FS.
// If an external devserver has been provided 'FRONTEND_DEVSERVER_URL' the files are being served
// from the external server, ignoring the `assets`.
func AssetFileServerFS(assets fs.FS) http.Handler {
return assetserver.NewAssetFileServer(assets)
}
// BundledAssetFileServer returns a http handler which serves the assets from the fs.FS.
// If an external devserver has been provided 'FRONTEND_DEVSERVER_URL' the files are being served
// from the external server, ignoring the `assets`.
// It also serves the compiled runtime.js file at `/wails/runtime.js`.
// It will provide the production runtime.js file from the embedded assets if the `production` tag is used.
func BundledAssetFileServer(assets fs.FS) http.Handler {
return assetserver.NewBundledAssetFileServer(assets)
}
/******** Mac Options ********/
// ActivationPolicy is the activation policy for the application.
type ActivationPolicy int
const (
// ActivationPolicyRegular is used for applications that have a user interface,
ActivationPolicyRegular ActivationPolicy = iota
// ActivationPolicyAccessory is used for applications that do not have a main window,
// such as system tray applications or background applications.
ActivationPolicyAccessory
ActivationPolicyProhibited
)
// MacOptions contains options for macOS applications.
type MacOptions struct {
// ActivationPolicy is the activation policy for the application. Defaults to
// applicationActivationPolicyRegular.
ActivationPolicy ActivationPolicy
// If set to true, the application will terminate when the last window is closed.
ApplicationShouldTerminateAfterLastWindowClosed bool
}
/****** Windows Options *******/
// WindowsOptions contains options for Windows applications.
type WindowsOptions struct {
// WndProcInterceptor is a function that will be called for every message sent in the application.
// Use this to hook into the main message loop. This is useful for handling custom window messages.
// If `shouldReturn` is `true` then `returnCode` will be returned by the main message loop.
// If `shouldReturn` is `false` then returnCode will be ignored and the message will be processed by the main message loop.
WndProcInterceptor func(hwnd uintptr, msg uint32, wParam, lParam uintptr) (returnCode uintptr, shouldReturn bool)
// DisableQuitOnLastWindowClosed disables the auto quit of the application if the last window has been closed.
DisableQuitOnLastWindowClosed bool
// Path where the WebView2 stores the user data. If empty %APPDATA%\[BinaryName.exe] will be used.
// If the path is not valid, a messagebox will be displayed with the error and the app will exit with error code.
WebviewUserDataPath string
// Path to the directory with WebView2 executables. If empty WebView2 installed in the system will be used.
WebviewBrowserPath string
}
/********* Linux Options *********/
// LinuxOptions contains options for Linux applications.
type LinuxOptions struct {
// DisableQuitOnLastWindowClosed disables the auto quit of the application if the last window has been closed.
DisableQuitOnLastWindowClosed bool
// ProgramName 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]
//
//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.
//
//[see the docs]: https://docs.gtk.org/glib/func.set_prgname.html
ProgramName string
}