diff --git a/.gitignore b/.gitignore index 9ef160d94..19125fbf5 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ /magpie-dev-backend /magpie-dev.new /internal/update/launcher-*.com +/internal/gui/assets.zip diff --git a/Makefile b/Makefile index 416cae669..5f71ee84f 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,14 @@ ifeq ($(shell go env GOOS),android) TAGS = nogui endif -.PHONY: build cli install test test-ui app icons release release-cli release-windows release-linux clean dev dev-once +.PHONY: assets-pack build-release build cli install test test-ui app icons release release-cli release-windows release-linux clean dev dev-once + +# A release build embeds the UI's files as one zip instead of the tree +# (internal/gui/assets_packed.go): a Windows or Linux download is the raw +# binary, and the scripts, styles and svgs are a quarter of their size packed. +# The zip is not kept in git; every release target makes it first. +assets-pack: + @go run ./build/assetpack internal/gui/assets internal/gui/assets.zip build: go build -tags "$(TAGS)" -trimpath -ldflags="$(LDFLAGS)" -o magpie . @@ -40,6 +47,9 @@ build: cli: CGO_ENABLED=0 go build -tags nogui -trimpath -ldflags="$(LDFLAGS)" -o magpie . +build-release: assets-pack + go build -tags "$(TAGS) packedassets" -trimpath -ldflags="$(LDFLAGS)" -o magpie . + install: go install -tags "$(TAGS)" -trimpath -ldflags="$(LDFLAGS)" . @@ -57,7 +67,7 @@ test-ui: node --test --test-concurrency=$(UI_TEST_CONCURRENCY) $(UI_TESTS) # macOS bundle: menu bar app with no Dock icon (LSUIElement). -app: build +app: build-release @rm -rf magpie.app @mkdir -p magpie.app/Contents/MacOS magpie.app/Contents/Resources @cp magpie magpie.app/Contents/MacOS/magpie @@ -93,17 +103,17 @@ icons: --minimum-deployment-target 11.0 --app-icon AppIcon --output-partial-info-plist build/darwin/actool/partial.plist >/dev/null @mv build/darwin/actool/Assets.car build/darwin/Assets.car && rm -rf build/darwin/actool -release: clean build +release: clean build-release @mkdir -p dist @cp magpie dist/magpie-$(shell go env GOOS)-$(shell go env GOARCH) @$(MAKE) --no-print-directory release-cli -release-cli: +release-cli: assets-pack @mkdir -p dist @for t in $(TARGETS); do \ os=$${t%/*}; arch=$${t#*/}; ext=""; [ $$os = windows ] && ext=.exe; \ echo " $$os/$$arch (cli)"; \ - CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -tags nogui -trimpath -ldflags="$(LDFLAGS)" -o dist/magpie-cli-$$os-$$arch$$ext . || exit 1; \ + CGO_ENABLED=0 GOOS=$$os GOARCH=$$arch go build -tags "nogui packedassets" -trimpath -ldflags="$(LDFLAGS)" -o dist/magpie-cli-$$os-$$arch$$ext . || exit 1; \ done # The desktop app for Windows: the system WebView2 needs no cgo, so both @@ -116,25 +126,25 @@ release-cli: # commit in them every release wrote a new one though the launcher was the # same (TestLauncherSameAtEveryCommit). WINVER = $(shell echo $(VERSION) | sed -E 's/^v//; s/[^0-9.].*//') -release-windows: +release-windows: assets-pack @mkdir -p dist @go run github.com/tc-hib/go-winres@v0.3.3 make --in build/windows/winres.json --arch amd64,arm64 --out rsrc \ --file-version "$(or $(WINVER),0.0.0)" --product-version "$(or $(WINVER),0.0.0)" @for arch in amd64 arm64; do \ echo " windows/$$arch (app)"; \ CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -trimpath -buildvcs=false -ldflags="-s -w" -o internal/update/launcher-$$arch.com ./internal/update/launcher || exit 1; \ - CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -tags production,comlauncher -trimpath -ldflags="$(LDFLAGS) -H windowsgui" -o dist/magpie-windows-$$arch.exe . || exit 1; \ + CGO_ENABLED=0 GOOS=windows GOARCH=$$arch go build -tags production,comlauncher,packedassets -trimpath -ldflags="$(LDFLAGS) -H windowsgui" -o dist/magpie-windows-$$arch.exe . || exit 1; \ done; rm -f rsrc_windows_*.syso internal/update/launcher-*.com # The desktop app for Linux links GTK 3 and WebKitGTK 4.1 through cgo, so it # is built natively, one arch per machine. -release-linux: +release-linux: assets-pack @mkdir -p dist @echo " linux/$(shell go env GOARCH) (app)" - @go build -tags "$(TAGS)" -trimpath -ldflags="$(LDFLAGS)" -o dist/magpie-linux-$(shell go env GOARCH) . + @go build -tags "$(TAGS) packedassets" -trimpath -ldflags="$(LDFLAGS)" -o dist/magpie-linux-$(shell go env GOARCH) . clean: - rm -rf magpie magpie.exe magpie.app dist rsrc_windows_*.syso internal/update/launcher-*.com + rm -rf magpie magpie.exe magpie.app dist internal/gui/assets.zip rsrc_windows_*.syso internal/update/launcher-*.com # Development: the UI is served from internal/gui/assets and the window # reloads itself when a file there is saved. With fswatch installed, the diff --git a/build/assetpack/main.go b/build/assetpack/main.go new file mode 100644 index 000000000..78579866f --- /dev/null +++ b/build/assetpack/main.go @@ -0,0 +1,91 @@ +// assetpack writes the GUI's assets as one zip, which a release build +// embeds in place of the tree (entries are under assets/, as go:embed names them) (-tags packedassets, internal/gui/assets_packed.go): +// the scripts, styles and svgs shrink to a quarter, where a Windows or Linux +// download is the raw binary. Usage: go run ./build/assetpack +package main + +import ( + "archive/zip" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strings" +) + +// already compressed: deflating them only costs time +var stored = map[string]bool{".png": true, ".jpg": true, ".jpeg": true, ".webm": true, ".mp4": true, ".woff": true, ".woff2": true, ".ico": true} + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: assetpack ") + os.Exit(2) + } + if err := pack(os.Args[1], os.Args[2]); err != nil { + fmt.Fprintln(os.Stderr, "assetpack:", err) + os.Exit(1) + } +} + +func pack(dir, out string) error { + var names []string + err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + // go:embed of a folder leaves out names that begin with . or _ + if p != dir && (strings.HasPrefix(d.Name(), ".") || strings.HasPrefix(d.Name(), "_")) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } + if d.Type().IsRegular() { + rel, err := filepath.Rel(dir, p) + if err != nil { + return err + } + names = append(names, filepath.ToSlash(rel)) + } + return nil + }) + if err != nil { + return err + } + sort.Strings(names) + tmp := out + ".tmp" + f, err := os.Create(tmp) + if err != nil { + return err + } + zw := zip.NewWriter(f) + for _, n := range names { + b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(n))) + if err != nil { + f.Close() + return err + } + h := &zip.FileHeader{Name: "assets/" + n, Method: zip.Deflate} + if stored[strings.ToLower(path.Ext(n))] { + h.Method = zip.Store + } + w, err := zw.CreateHeader(h) + if err == nil { + _, err = w.Write(b) + } + if err != nil { + f.Close() + return err + } + } + if err := zw.Close(); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, out) +} diff --git a/docs/reference.md b/docs/reference.md index 0bce15128..570bc728d 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3293,6 +3293,11 @@ make release-windows # dist/: the Windows app, amd64 and arm64 (cross-compiles) make release-linux # dist/: the Linux app for this machine's arch ``` +The release targets and `make app` pack the UI's files into one zip first +(`make assets-pack`, `build/assetpack`; embedded by `-tags packedassets`), +which takes about 6 MB off each binary. `make build`, `make cli` and the +tests embed the tree as it is. + Linux needs `libgtk-3-dev` and `libwebkit2gtk-4.1-dev` for the app build (the Makefile adds the `gtk3` tag; with plain `go build`, pass `-tags gtk3`); Windows uses the WebView2 runtime that ships with the OS. diff --git a/internal/gui/api.go b/internal/gui/api.go index 7547bc6ec..fbcda942d 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -10,7 +10,6 @@ import ( "cmp" "context" "crypto/sha256" - "embed" "encoding/hex" "encoding/json" "errors" @@ -151,9 +150,6 @@ var cliBehindVal string // Version is the build's version string, shown in Settings. var Version = "dev" -//go:embed assets -var assets embed.FS - // Windows is what the API needs from the host application. type Windows interface { HidePanel() diff --git a/internal/gui/assets_embed.go b/internal/gui/assets_embed.go new file mode 100644 index 000000000..01925d52d --- /dev/null +++ b/internal/gui/assets_embed.go @@ -0,0 +1,11 @@ +//go:build !packedassets + +package gui + +import "embed" + +// The UI's files, as they are in the tree. A release build packs them +// (assets_packed.go). +// +//go:embed assets +var assets embed.FS diff --git a/internal/gui/assets_packed.go b/internal/gui/assets_packed.go new file mode 100644 index 000000000..f038d2914 --- /dev/null +++ b/internal/gui/assets_packed.go @@ -0,0 +1,112 @@ +//go:build packedassets + +package gui + +import ( + "archive/zip" + "bytes" + "errors" + "io" + "io/fs" + "sync" + "time" + + _ "embed" +) + +// A release build embeds the UI's files as one zip (build/assetpack, run by +// the Makefile before it builds): the scripts and styles are a quarter of +// their size, where the Windows and Linux downloads are the raw binary. A +// file is unpacked the first time it is asked for and kept, as the page's +// short list of files is all there is. +// +//go:embed assets.zip +var assetsZip []byte + +var assets = &packedAssets{} + +type packedAssets struct { + once sync.Once + zr *zip.Reader + err error + mu sync.Mutex + files map[string][]byte +} + +func (p *packedAssets) reader() (*zip.Reader, error) { + p.once.Do(func() { p.zr, p.err = zip.NewReader(bytes.NewReader(assetsZip), int64(len(assetsZip))) }) + return p.zr, p.err +} + +// load unpacks a file, once; dir is true for a folder. +func (p *packedAssets) load(name string) (b []byte, st fs.FileInfo, dir bool, err error) { + zr, err := p.reader() + if err != nil { + return nil, nil, false, err + } + f, err := zr.Open(name) + if err != nil { + return nil, nil, false, err + } + defer f.Close() + if st, err = f.Stat(); err != nil || st.IsDir() { + return nil, st, err == nil, err + } + p.mu.Lock() + b, ok := p.files[name] + p.mu.Unlock() + if ok { + return b, st, false, nil + } + if b, err = io.ReadAll(f); err != nil { + return nil, nil, false, err + } + p.mu.Lock() + if p.files == nil { + p.files = map[string][]byte{} + } + p.files[name] = b + p.mu.Unlock() + return b, st, false, nil +} + +// Open gives a file that seeks (a range request for a video needs it) and, +// as an embedded file does, has no modification time. +func (p *packedAssets) Open(name string) (fs.File, error) { + b, st, dir, err := p.load(name) + if err != nil { + return nil, err + } + if dir { + zr, _ := p.reader() + return zr.Open(name) + } + return &packedFile{Reader: bytes.NewReader(b), info: packedInfo{st, int64(len(b))}}, nil +} + +func (p *packedAssets) ReadFile(name string) ([]byte, error) { + b, _, dir, err := p.load(name) + if err != nil { + return nil, err + } + if dir { + return nil, &fs.PathError{Op: "read", Path: name, Err: errors.New("is a directory")} + } + return bytes.Clone(b), nil +} + +type packedFile struct { + *bytes.Reader + info packedInfo +} + +func (f *packedFile) Stat() (fs.FileInfo, error) { return f.info, nil } +func (f *packedFile) Close() error { return nil } + +type packedInfo struct { + fs.FileInfo + size int64 +} + +func (i packedInfo) Size() int64 { return i.size } +func (i packedInfo) ModTime() time.Time { return time.Time{} } diff --git a/internal/gui/assets_packed_test.go b/internal/gui/assets_packed_test.go new file mode 100644 index 000000000..81b1e553c --- /dev/null +++ b/internal/gui/assets_packed_test.go @@ -0,0 +1,80 @@ +//go:build packedassets + +package gui + +import ( + "bytes" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "sort" + "testing" +) + +// The packed UI must be the tree's: every file, byte for byte, and no other. +// Run after `go run ./build/assetpack internal/gui/assets internal/gui/assets.zip`. +func TestPackedAssetsAreTheTree(t *testing.T) { + tree := os.DirFS("assets") + var want []string + fs.WalkDir(tree, ".", func(p string, d fs.DirEntry, err error) error { + if err == nil && d.Type().IsRegular() { + want = append(want, p) + } + return nil + }) + if len(want) < 100 { + t.Fatalf("only %d files in the tree", len(want)) + } + var got []string + fs.WalkDir(assets, "assets", func(p string, d fs.DirEntry, err error) error { + if err == nil && d.Type().IsRegular() { + got = append(got, p[len("assets/"):]) + } + return nil + }) + sort.Strings(want) + sort.Strings(got) + if len(got) != len(want) { + t.Fatalf("packed has %d files, the tree %d", len(got), len(want)) + } + for i, n := range want { + if got[i] != n { + t.Fatalf("file %d: packed %q, tree %q", i, got[i], n) + } + a, _ := fs.ReadFile(tree, n) + b, err := assets.ReadFile("assets/" + n) + if err != nil || !bytes.Equal(a, b) { + t.Fatalf("%s differs from the tree (err %v)", n, err) + } + } +} + +// The page is served as the tree's was: index at /, a range of a video, 404. +func TestPackedAssetsServe(t *testing.T) { + h := http.FileServer(http.FS(staticFS())) + get := func(path, rng string) *httptest.ResponseRecorder { + r := httptest.NewRequest("GET", path, nil) + if rng != "" { + r.Header.Set("Range", rng) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w + } + idx, _ := os.ReadFile("assets/index.html") + if w := get("/", ""); w.Code != 200 || !bytes.Equal(w.Body.Bytes(), idx) { + t.Fatalf("/ gave %d, %d bytes (index.html is %d)", w.Code, w.Body.Len(), len(idx)) + } + webm, _ := os.ReadFile("assets/plugins/redact/xq_light.webm") + w := get("/plugins/redact/xq_light.webm", "bytes=100-199") + if w.Code != 206 || !bytes.Equal(w.Body.Bytes(), webm[100:200]) { + t.Fatalf("range of the video gave %d, %d bytes", w.Code, w.Body.Len()) + } + if w := get("/nope.js", ""); w.Code != 404 { + t.Fatalf("a missing file gave %d", w.Code) + } + if lm := get("/app.js", "").Header().Get("Last-Modified"); lm != "" { + t.Fatalf("Last-Modified %q: an embedded file has none", lm) + } +}