Compare commits

..

2 Commits

Author SHA1 Message Date
Lea Anthony 204f33805f Disable runtime option in assetserver
Runtime off by default in v3
2023-03-27 20:53:31 +11:00
Lea Anthony c96cc3ff27 Initial implementation 2023-03-27 20:12:03 +11:00
224 changed files with 11774 additions and 5129 deletions
-30
View File
@@ -1,30 +0,0 @@
name: Generate Contributors Image
on:
schedule:
- cron: '0 1 * * 0' # At 01:00 on Sunday.
push:
branches:
- master
jobs:
contributors:
runs-on: ubuntu-latest
if: github.repository == 'wailsapp/wails'
steps:
- uses: actions/checkout@v3
- uses: wow-actions/contributors-list@v1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
svgPath: website/static/img/contributors.svg
noCommit: true
- name: Create Pull Request
uses: peter-evans/create-pull-request@v4
with:
commit-message: "chore: update contributors.svg"
add-paths: "website/static/img/contributors.svg"
title: Update Contributors Image
body: Generated new image
branch: update-contributors
delete-branch: true
+1 -1
View File
@@ -22,12 +22,12 @@ jobs:
website/**/*.json
- name: Set node
if: steps.verify-changed-files.outputs.files_changed != 'true'
uses: actions/setup-node@v2
with:
node-version: 16.x
- name: Push files
if: steps.verify-changed-files.outputs.files_changed == 'true'
env:
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
run: |
-1
View File
@@ -35,4 +35,3 @@ v2/cmd/wails/internal/commands/initialise/templates/testtemplates/
/v3/.task
/v3/examples/build/bin/testapp
/websitev3/site/
/v3/examples/plugins/bin/testapp
+3 -3
View File
@@ -1775,9 +1775,9 @@
}
},
"node_modules/undici": {
"version": "5.21.0",
"resolved": "https://registry.npmjs.org/undici/-/undici-5.21.0.tgz",
"integrity": "sha512-HOjK8l6a57b2ZGXOcUsI5NLfoTrfmbOl90ixJDl0AEFG4wgHNDQxtZy15/ZQp7HhjkpaGlp/eneMgtsu1dIlUA==",
"version": "5.13.0",
"resolved": "https://registry.npmmirror.com/undici/-/undici-5.13.0.tgz",
"integrity": "sha512-UDZKtwb2k7KRsK4SdXWG7ErXiL7yTGgLWvk2AXO1JMjgjh404nFo6tWSCM2xMpJwMPx3J8i/vfqEh1zOqvj82Q==",
"dependencies": {
"busboy": "^1.6.0"
},
+1 -1
View File
@@ -41,7 +41,7 @@ func printBulletPoint(text string, args ...any) {
fatal(err.Error())
}
t = strings.Trim(t, "\n\r")
pterm.Printfln(t, args...)
pterm.Printf(t, args...)
}
func printFooter() {
+43 -6
View File
@@ -78,6 +78,7 @@ import (
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"runtime"
@@ -87,7 +88,6 @@ import (
"unsafe"
"github.com/wailsapp/wails/v2/pkg/assetserver"
"github.com/wailsapp/wails/v2/pkg/assetserver/webview"
"github.com/wailsapp/wails/v2/internal/binding"
"github.com/wailsapp/wails/v2/internal/frontend"
@@ -166,7 +166,10 @@ func NewFrontend(ctx context.Context, appoptions *options.App, myLogger *logger.
}
result.assets = assets
go result.startRequestProcessor()
// Start 10 processors to handle requests in parallel
for i := 0; i < 10; i++ {
go result.startRequestProcessor()
}
}
go result.startMessageProcessor()
@@ -458,16 +461,50 @@ func processMessage(message *C.char) {
messageBuffer <- goMessage
}
var requestBuffer = make(chan webview.Request, 100)
var requestBuffer = make(chan unsafe.Pointer, 100)
func (f *Frontend) startRequestProcessor() {
for request := range requestBuffer {
f.assets.ServeWebViewRequest(request)
request.Release()
f.processRequest(request)
C.g_object_unref(C.gpointer(request))
}
}
//export processURLRequest
func processURLRequest(request unsafe.Pointer) {
requestBuffer <- webview.NewRequest(request)
// Increment reference counter to allow async processing, will be decremented after the processing
// has been finished by a worker.
C.g_object_ref(C.gpointer(request))
requestBuffer <- request
}
func (f *Frontend) processRequest(request unsafe.Pointer) {
req := (*C.WebKitURISchemeRequest)(request)
uri := C.webkit_uri_scheme_request_get_uri(req)
goURI := C.GoString(uri)
rw := &webKitResponseWriter{req: req}
defer rw.Close()
f.assets.ProcessHTTPRequestLegacy(
rw,
func() (*http.Request, error) {
method := webkit_uri_scheme_request_get_http_method(req)
r, err := http.NewRequest(method, goURI, nil)
if err != nil {
return nil, err
}
r.Header = webkit_uri_scheme_request_get_http_headers(req)
if r.URL.Host != f.startURL.Host {
if r.Body != nil {
r.Body.Close()
}
return nil, fmt.Errorf("Expected host '%s' in request, but was '%s'", f.startURL.Host, r.URL.Host)
}
return r, nil
})
}
@@ -12,12 +12,10 @@ import (
"github.com/wailsapp/wails/v2/pkg/options"
"github.com/wailsapp/wails/v2/pkg/options/linux"
"github.com/wailsapp/wails/v2/pkg/assetserver/webview"
)
func validateWebKit2Version(options *options.App) {
if C.webkit_get_major_version() == 2 && C.webkit_get_minor_version() >= webview.Webkit2MinMinorVersion {
if C.webkit_get_major_version() == 2 && C.webkit_get_minor_version() >= webkit2MinMinorVersion {
return
}
@@ -26,6 +24,6 @@ func validateWebKit2Version(options *options.App) {
msg = options.Linux.Messages
}
v := fmt.Sprintf("2.%d.0", webview.Webkit2MinMinorVersion)
v := fmt.Sprintf("2.%d.0", webkit2MinMinorVersion)
showModalDialogAndExit("WebKit2GTK", fmt.Sprintf(msg.WebKit2GTKMinRequired, v))
}
@@ -1,6 +1,6 @@
//go:build linux && webkit2_36
package webview
package linux
/*
#cgo linux pkg-config: gtk+-3.0 webkit2gtk-4.0 libsoup-2.4
@@ -15,9 +15,11 @@ import (
"net/http"
"strings"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/assetserver"
)
const Webkit2MinMinorVersion = 36
const webkit2MinMinorVersion = 36
func webkit_uri_scheme_request_get_http_method(req *C.WebKitURISchemeRequest) string {
method := C.GoString(C.webkit_uri_scheme_request_get_http_method(req))
@@ -49,7 +51,7 @@ func webkit_uri_scheme_request_finish(req *C.WebKitURISchemeRequest, code int, h
C.webkit_uri_scheme_response_set_status(resp, C.guint(code), cReason)
C.free(unsafe.Pointer(cReason))
cMimeType := C.CString(header.Get(HeaderContentType))
cMimeType := C.CString(header.Get(assetserver.HeaderContentType))
C.webkit_uri_scheme_response_set_content_type(resp, cMimeType)
C.free(unsafe.Pointer(cMimeType))
@@ -1,6 +1,6 @@
//go:build linux && !webkit2_36
package webview
package linux
/*
#cgo linux pkg-config: gtk+-3.0 webkit2gtk-4.0
@@ -14,9 +14,11 @@ import (
"fmt"
"net/http"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/assetserver"
)
const Webkit2MinMinorVersion = 0
const webkit2MinMinorVersion = 0
func webkit_uri_scheme_request_get_http_method(_ *C.WebKitURISchemeRequest) string {
return http.MethodGet
@@ -31,7 +33,7 @@ func webkit_uri_scheme_request_finish(req *C.WebKitURISchemeRequest, code int, h
return fmt.Errorf("StatusCodes not supported: %d - %s", code, http.StatusText(code))
}
cMimeType := C.CString(header.Get(HeaderContentType))
cMimeType := C.CString(header.Get(assetserver.HeaderContentType))
C.webkit_uri_scheme_request_finish(req, stream, C.gint64(streamLength), cMimeType)
C.free(unsafe.Pointer(cMimeType))
return nil
@@ -1,7 +1,7 @@
//go:build linux
// +build linux
package webview
package linux
/*
#cgo linux pkg-config: gtk+-3.0 webkit2gtk-4.0 gio-unix-2.0
@@ -20,31 +20,28 @@ import (
"strconv"
"syscall"
"unsafe"
"github.com/wailsapp/wails/v2/pkg/assetserver"
)
type responseWriter struct {
type webKitResponseWriter struct {
req *C.WebKitURISchemeRequest
header http.Header
wroteHeader bool
finished bool
w io.WriteCloser
wErr error
}
func (rw *responseWriter) Header() http.Header {
func (rw *webKitResponseWriter) Header() http.Header {
if rw.header == nil {
rw.header = http.Header{}
}
return rw.header
}
func (rw *responseWriter) Write(buf []byte) (int, error) {
if rw.finished {
return 0, errResponseFinished
}
func (rw *webKitResponseWriter) Write(buf []byte) (int, error) {
rw.WriteHeader(http.StatusOK)
if rw.wErr != nil {
return 0, rw.wErr
@@ -52,14 +49,14 @@ func (rw *responseWriter) Write(buf []byte) (int, error) {
return rw.w.Write(buf)
}
func (rw *responseWriter) WriteHeader(code int) {
if rw.wroteHeader || rw.finished {
func (rw *webKitResponseWriter) WriteHeader(code int) {
if rw.wroteHeader {
return
}
rw.wroteHeader = true
contentLength := int64(-1)
if sLen := rw.Header().Get(HeaderContentLength); sLen != "" {
if sLen := rw.Header().Get(assetserver.HeaderContentLength); sLen != "" {
if pLen, _ := strconv.ParseInt(sLen, 10, 64); pLen > 0 {
contentLength = pLen
}
@@ -75,7 +72,7 @@ func (rw *responseWriter) WriteHeader(code int) {
}
rw.w = w
stream := C.g_unix_input_stream_new(C.int(rFD), C.gboolean(1))
stream := C.g_unix_input_stream_new(C.int(rFD), gtkBool(true))
defer C.g_object_unref(C.gpointer(stream))
if err := webkit_uri_scheme_request_finish(rw.req, code, rw.Header(), stream, contentLength); err != nil {
@@ -84,22 +81,13 @@ func (rw *responseWriter) WriteHeader(code int) {
}
}
func (rw *responseWriter) Finish() error {
if !rw.wroteHeader {
rw.WriteHeader(http.StatusNotImplemented)
}
if rw.finished {
return nil
}
rw.finished = true
func (rw *webKitResponseWriter) Close() {
if rw.w != nil {
rw.w.Close()
}
return nil
}
func (rw *responseWriter) finishWithError(code int, err error) {
func (rw *webKitResponseWriter) finishWithError(code int, err error) {
if rw.w != nil {
rw.w.Close()
rw.w = &nopCloser{io.Discard}
+9 -30
View File
@@ -2,11 +2,8 @@ package assetserver
import (
"bytes"
"fmt"
"math/rand"
"net/http"
"net/http/httptest"
"strings"
"golang.org/x/net/html"
@@ -45,10 +42,8 @@ type AssetServer struct {
// Use http based runtime
runtimeHandler RuntimeHandler
// plugin scripts
pluginScripts map[string]string
assetServerWebView
disableRuntime bool
}
func NewAssetServerMainPage(bindingsJSON string, options *options.App, servingFromDisk bool, logger Logger, runtime RuntimeAssets) (*AssetServer, error) {
@@ -95,16 +90,6 @@ func (d *AssetServer) UseRuntimeHandler(handler RuntimeHandler) {
d.runtimeHandler = handler
}
func (d *AssetServer) AddPluginScript(pluginName string, script string) {
if d.pluginScripts == nil {
d.pluginScripts = make(map[string]string)
}
pluginName = strings.ReplaceAll(pluginName, "/", "_")
pluginName = html.EscapeString(pluginName)
pluginScriptName := fmt.Sprintf("/plugin_%s_%d.js", pluginName, rand.Intn(100000))
d.pluginScripts[pluginScriptName] = script
}
func (d *AssetServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if isWebSocket(req) {
// Forward WebSockets to the distinct websocket handler if it exists
@@ -165,11 +150,6 @@ func (d *AssetServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
d.writeBlob(rw, path, content)
default:
// Check if this is a plugin script
if script, ok := d.pluginScripts[path]; ok {
d.writeBlob(rw, path, []byte(script))
return
}
d.handler.ServeHTTP(rw, req)
}
}
@@ -187,21 +167,16 @@ func (d *AssetServer) processIndexHTML(indexHTML []byte) ([]byte, error) {
}
}
if err := insertScriptInHead(htmlNode, runtimeJSPath); err != nil {
return nil, err
if !d.disableRuntime {
if err := insertScriptInHead(htmlNode, runtimeJSPath); err != nil {
return nil, err
}
}
if err := insertScriptInHead(htmlNode, ipcJSPath); err != nil {
return nil, err
}
// Inject plugins
for scriptName := range d.pluginScripts {
if err := insertScriptInHead(htmlNode, scriptName); err != nil {
return nil, err
}
}
var buffer bytes.Buffer
err = html.Render(&buffer, htmlNode)
if err != nil {
@@ -234,3 +209,7 @@ func (d *AssetServer) logError(message string, args ...interface{}) {
d.logger.Error("[AssetServer] "+message, args...)
}
}
func (d *AssetServer) DisableRuntime() {
d.disableRuntime = true
}
@@ -1,85 +0,0 @@
//go:build linux
// +build linux
package webview
/*
#cgo linux pkg-config: gtk+-3.0 webkit2gtk-4.0 gio-unix-2.0
#include "gtk/gtk.h"
#include "webkit2/webkit2.h"
*/
import "C"
import (
"io"
"net/http"
"unsafe"
)
// NewRequest creates as new WebViewRequest based on a pointer to an `WebKitURISchemeRequest`
//
// Please make sure to call Release() when finished using the request.
func NewRequest(webKitURISchemeRequest unsafe.Pointer) Request {
webkitReq := (*C.WebKitURISchemeRequest)(webKitURISchemeRequest)
req := &request{req: webkitReq}
req.AddRef()
return req
}
var _ Request = &request{}
type request struct {
req *C.WebKitURISchemeRequest
header http.Header
body io.ReadCloser
rw *responseWriter
}
func (r *request) AddRef() error {
C.g_object_ref(C.gpointer(r.req))
return nil
}
func (r *request) Release() error {
C.g_object_unref(C.gpointer(r.req))
return nil
}
func (r *request) URL() (string, error) {
return C.GoString(C.webkit_uri_scheme_request_get_uri(r.req)), nil
}
func (r *request) Method() (string, error) {
return webkit_uri_scheme_request_get_http_method(r.req), nil
}
func (r *request) Header() (http.Header, error) {
if r.header != nil {
return r.header, nil
}
r.header = webkit_uri_scheme_request_get_http_headers(r.req)
return r.header, nil
}
func (r *request) Body() (io.ReadCloser, error) {
if r.body != nil {
return r.body, nil
}
// WebKit2GTK has currently no support for request bodies.
r.body = http.NoBody
return r.body, nil
}
func (r *request) Response() ResponseWriter {
if r.rw != nil {
return r.rw
}
r.rw = &responseWriter{req: r.req}
return r.rw
}
@@ -1,20 +1,9 @@
package webview
import (
"errors"
"net/http"
)
const (
HeaderContentLength = "Content-Length"
HeaderContentType = "Content-Type"
)
var (
errRequestStopped = errors.New("request has been stopped")
errResponseFinished = errors.New("response has been finished")
)
// A ResponseWriter interface is used by an HTTP handler to
// construct an HTTP response for the WebView.
type ResponseWriter interface {
@@ -69,10 +69,16 @@ import "C"
import (
"encoding/json"
"errors"
"net/http"
"unsafe"
)
var (
errRequestStopped = errors.New("request has been stopped")
errResponseFinished = errors.New("response has been finished")
)
var _ ResponseWriter = &responseWriter{}
type responseWriter struct {
+1 -1
View File
@@ -207,7 +207,7 @@ func printBulletPoint(text string, args ...any) {
fatal(err.Error())
}
t = strings.Trim(t, "\n\r")
pterm.Printfln(t, args...)
pterm.Printf(t, args...)
}
func GenerateBindings(buildOptions *Options) error {
+3 -7
View File
@@ -31,7 +31,8 @@ Informal and incomplete list of things needed in v3.
- [x] Screens
- [x] Clipboard
- [x] Application
- [ ] Create `.d.ts` file
- [ ] Move to typescript module
- [ ] Move WML to plugin
## Templates
@@ -41,9 +42,4 @@ Informal and incomplete list of things needed in v3.
## Runtime
- [ ] To log or not to log?
- [ ] Unify cross-platform events, eg. `onClose`
## Plugins
- [ ] Move logins to `v3/plugins`
- [ ] Expose application logger to plugins
- [ ] Unify cross-platform events, eg. `onClose`
-72
View File
@@ -108,75 +108,3 @@ This attribute specifies which javascript event should trigger the action. The d
<button data-wml-event="hover-box" data-wml-trigger="mouseover">Hover over me!</button>
```
## Plugins
Plugins are a way to extend the functionality of your Wails application.
### Creating a plugin
Plugins are standard Go structure that adhere to the following interface:
```go
type Plugin interface {
Name() string
Init(*application.App) error
Shutdown()
CallableByJS() []string
InjectJS() string
}
```
The `Name()` method returns the name of the plugin. This is used for logging purposes.
The `Init(*application.App) error` method is called when the plugin is loaded. The `*application.App`
parameter is the application that the plugin is being loaded into. Any errors will prevent
the application from starting.
The `Shutdown()` method is called when the application is shutting down.
The `CallableByJS()` method returns a list of exported functions that can be called from
the frontend. These method names must exactly match the names of the methods exported
by the plugin.
The `InjectJS()` method returns JavaScript that should be injected into all windows as they are created. This is useful for adding custom JavaScript functions that complement the plugin.
### Tips
#### Enums
In Go, enums are often defined as a type and a set of constants. For example:
```go
type MyEnum int
const (
MyEnumOne MyEnum = iota
MyEnumTwo
MyEnumThree
)
```
Due to incompatibility between Go and JavaScript, custom types cannot be used in this way. The best strategy is to use a type alias for float64:
```go
type MyEnum = float64
const (
MyEnumOne MyEnum = iota
MyEnumTwo
MyEnumThree
)
```
In Javascript, you can then use the following:
```js
const MyEnum = {
MyEnumOne: 0,
MyEnumTwo: 1,
MyEnumThree: 2
}
```
- Why use `float64`? Can't we use `int`?
- Because JavaScript doesn't have a concept of `int`. Everything is a `number`, which translates to `float64` in Go. There are also restrictions on casting types in Go's reflection package, which means using `int` doesn't work.
-5
View File
@@ -25,11 +25,6 @@ func main() {
generate.NewSubCommandFunction("icons", "Generate icons", commands.GenerateIcons)
generate.NewSubCommandFunction("syso", "Generate Windows .syso file", commands.GenerateSyso)
generate.NewSubCommandFunction("bindings", "Generate bindings + models", commands.GenerateBindings)
plugin := app.NewSubCommand("plugin", "Plugin tools")
//plugin.NewSubCommandFunction("list", "List plugins", commands.PluginList)
plugin.NewSubCommandFunction("init", "Initialise a new plugin", commands.PluginInit)
//plugin.NewSubCommandFunction("add", "Add a plugin", commands.PluginAdd)
err := app.Run()
if err != nil {
pterm.Error.Println(err)
+6 -3
View File
@@ -20,13 +20,13 @@ func main() {
Mac: application.MacOptions{
ApplicationShouldTerminateAfterLastWindowClosed: true,
},
Assets: application.AssetOptions{
FS: assets,
},
})
mainWindow := app.NewWebviewWindowWithOptions(&application.WebviewWindowOptions{
Title: "Context Menu Demo",
Assets: application.AssetOptions{
FS: assets,
},
Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent,
TitleBar: application.MacTitleBarHiddenInsetUnified,
@@ -36,6 +36,9 @@ func main() {
app.NewWebviewWindowWithOptions(&application.WebviewWindowOptions{
Title: "Context Menu Demo",
Assets: application.AssetOptions{
FS: assets,
},
Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent,
TitleBar: application.MacTitleBarHiddenInsetUnified,
+3 -3
View File
@@ -20,13 +20,13 @@ func main() {
Mac: application.MacOptions{
ApplicationShouldTerminateAfterLastWindowClosed: true,
},
Assets: application.AssetOptions{
FS: assets,
},
})
window := app.NewWebviewWindowWithOptions(&application.WebviewWindowOptions{
Title: "Drag-n-drop Demo",
Assets: application.AssetOptions{
FS: assets,
},
Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent,
TitleBar: application.MacTitleBarHiddenInsetUnified,

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