diff --git a/Dockerfile b/Dockerfile index 996b3f6..731cda9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,6 +6,7 @@ COPY go.mod go.sum ./ RUN go mod download COPY cmd/ ./cmd/ +COPY internal/ ./internal/ RUN CGO_ENABLED=0 go build -o /out/spectogram ./cmd/spectogram FROM python:3.11-alpine diff --git a/cmd/spectogram/main.go b/cmd/spectogram/main.go index 9400010..34fe78d 100644 --- a/cmd/spectogram/main.go +++ b/cmd/spectogram/main.go @@ -17,10 +17,7 @@ import ( "sort" "strings" - "github.com/faiface/beep" - "github.com/faiface/beep/mp3" - "github.com/faiface/beep/wav" - "gonum.org/v1/gonum/dsp/fourier" + engine "go-spectrogram-plotly/internal/spectrogram" ) const ( @@ -28,63 +25,19 @@ const ( defaultHopSize = 512 ) -// Config controls the short-time Fourier transform and the exported view. -type Config struct { - FFTSize int - HopSize int - Channel string - MinDB float64 - MaxDB float64 - MaxFrames int -} +// Config is shared by the CLI and desktop app. +type Config = engine.Config func defaultConfig() Config { - return Config{FFTSize: defaultFFTSize, HopSize: defaultHopSize, Channel: "mono", MinDB: -100, MaxDB: 0} -} - -func (c Config) validate() error { - if c.FFTSize < 2 || c.FFTSize&(c.FFTSize-1) != 0 { - return errors.New("fft size must be a power of two and at least 2") - } - if c.HopSize < 1 || c.HopSize > c.FFTSize { - return errors.New("hop size must be between 1 and fft size") - } - if c.MinDB >= c.MaxDB { - return errors.New("min-db must be smaller than max-db") - } - if c.MaxFrames < 0 { - return errors.New("max-frames cannot be negative") - } - switch c.Channel { - case "mono", "left", "right", "mid", "side": - return nil - default: - return fmt.Errorf("unsupported channel %q (use mono, left, right, mid, or side)", c.Channel) - } + return engine.DefaultConfig() } // Metadata makes every data point interpretable without relying on defaults. -type Metadata struct { - SchemaVersion int `json:"schemaVersion"` - SampleRate int `json:"sampleRate"` - Channels int `json:"channels"` - Channel string `json:"channel"` - FFTSize int `json:"fftSize"` - HopSize int `json:"hopSize"` - FrameStride int `json:"frameStride"` - FrequencyStepHz float64 `json:"frequencyStepHz"` - TimeStepSeconds float64 `json:"timeStepSeconds"` - MinDB float64 `json:"minDb"` - MaxDB float64 `json:"maxDb"` - DurationSeconds float64 `json:"durationSeconds"` -} +type Metadata = engine.Metadata // Spectrogram is the JSON document consumed by the viewer. Data is indexed as // data[timeFrame][frequencyBin], with values in dBFS. -type Spectrogram struct { - Metadata Metadata `json:"metadata"` - Data [][]float64 `json:"data"` -} +type Spectrogram = engine.Result func main() { if len(os.Args) > 1 && os.Args[1] == "serve" { @@ -170,31 +123,10 @@ func run(input, output, jsonOut string) error { } func runWithConfig(input, output, jsonOut string, config Config) error { - if err := config.validate(); err != nil { - return err - } - f, err := os.Open(input) - if err != nil { + if err := config.Validate(); err != nil { return err } - defer f.Close() - - var streamer beep.StreamSeekCloser - var format beep.Format - switch strings.ToLower(filepath.Ext(input)) { - case ".mp3": - streamer, format, err = mp3.Decode(f) - case ".wav": - streamer, format, err = wav.Decode(f) - default: - return fmt.Errorf("unsupported file format: %s", filepath.Ext(input)) - } - if err != nil { - return err - } - defer streamer.Close() - - spectrogram, err := streamSpectrogram(streamer, int(format.SampleRate), format.NumChannels, config) + spectrogram, err := engine.AnalyzeFile(input, config) if err != nil { return err } @@ -212,124 +144,6 @@ func runWithConfig(input, output, jsonOut string, config Config) error { return nil } -// streamSpectrogram performs the STFT while retaining only one working window. -func streamSpectrogram(streamer beep.Streamer, sampleRate, channels int, config Config) (Spectrogram, error) { - if err := config.validate(); err != nil { - return Spectrogram{}, err - } - if sampleRate <= 0 { - return Spectrogram{}, errors.New("audio has an invalid sample rate") - } - collector := newFrameCollector(config.MaxFrames) - fft := fourier.NewFFT(config.FFTSize) - window := make([]float64, 0, config.FFTSize) - buffer := make([][2]float64, 4096) - var sampleCount int - - for { - n, ok := streamer.Stream(buffer) - for i := 0; i < n; i++ { - window = append(window, selectChannel(buffer[i], config.Channel)) - sampleCount++ - if len(window) == config.FFTSize { - collector.add(computeFrame(window, fft, config)) - copy(window, window[config.HopSize:]) - window = window[:config.FFTSize-config.HopSize] - } - } - if !ok { - break - } - } - - stride := collector.stride - return Spectrogram{ - Metadata: Metadata{ - SchemaVersion: 1, SampleRate: sampleRate, Channels: channels, Channel: config.Channel, - FFTSize: config.FFTSize, HopSize: config.HopSize, FrameStride: stride, - FrequencyStepHz: float64(sampleRate) / float64(config.FFTSize), - TimeStepSeconds: float64(config.HopSize*stride) / float64(sampleRate), - MinDB: config.MinDB, MaxDB: config.MaxDB, - DurationSeconds: float64(sampleCount) / float64(sampleRate), - }, - Data: collector.frames, - }, nil -} - -func selectChannel(sample [2]float64, channel string) float64 { - switch channel { - case "left": - return sample[0] - case "right": - return sample[1] - case "side": - return (sample[0] - sample[1]) / 2 - default: // mono and mid - return (sample[0] + sample[1]) / 2 - } -} - -func computeFrame(samples []float64, fft *fourier.FFT, config Config) []float64 { - windowed := applyHannWindow(append([]float64(nil), samples...)) - spectrum := fft.Coefficients(nil, windowed) - frame := make([]float64, config.FFTSize/2) - // The Hann window has a coherent gain of 0.5, so a full-scale sine - // aligned to an FFT bin has magnitude N/4 after windowing. - denominator := float64(config.FFTSize) / 4 - for i := range frame { - magnitude := math.Hypot(real(spectrum[i]), imag(spectrum[i])) / denominator - db := 20 * math.Log10(math.Max(magnitude, 1e-12)) - frame[i] = clamp(db, config.MinDB, config.MaxDB) - } - return frame -} - -// frameCollector bounds output width by repeatedly averaging adjacent frames. -// The source stream is still processed continuously, so decoded audio is never -// accumulated in memory. -type frameCollector struct { - maxFrames int - frames [][]float64 - stride int - seen int -} - -func newFrameCollector(maxFrames int) *frameCollector { - return &frameCollector{maxFrames: maxFrames, stride: 1} -} - -func (c *frameCollector) add(frame []float64) { - if c.maxFrames == 0 { - c.frames = append(c.frames, frame) - c.seen++ - return - } - if len(c.frames) >= c.maxFrames { - c.frames = averagePairs(c.frames) - c.stride *= 2 - } - if c.seen%c.stride == 0 { - c.frames = append(c.frames, frame) - } - c.seen++ -} - -func averagePairs(frames [][]float64) [][]float64 { - result := make([][]float64, 0, (len(frames)+1)/2) - for i := 0; i < len(frames); i += 2 { - if i+1 == len(frames) { - result = append(result, frames[i]) - continue - } - row := make([]float64, len(frames[i])) - for j := range row { - row[j] = (frames[i][j] + frames[i+1][j]) / 2 - } - result = append(result, row) - } - return result -} - func writeJSON(path string, spectrogram Spectrogram) error { data, err := json.Marshal(spectrogram) if err != nil { diff --git a/cmd/spectogram/main_test.go b/cmd/spectogram/main_test.go index 3b73ade..d85b900 100644 --- a/cmd/spectogram/main_test.go +++ b/cmd/spectogram/main_test.go @@ -1,207 +1,29 @@ package main import ( - "encoding/json" - "image/color" - "image/png" - "math" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" - - "github.com/faiface/beep" - "github.com/faiface/beep/wav" ) -func TestApplyHannWindow(t *testing.T) { - samples := make([]float64, 8) - for i := range samples { - samples[i] = 1 - } - got := applyHannWindow(samples) - if math.Abs(got[0]) > 1e-9 || math.Abs(got[len(got)-1]) > 1e-9 { - t.Fatal("Hann window must taper at both ends") - } - for i := 0; i < len(got)/2; i++ { - if math.Abs(got[i]-got[len(got)-1-i]) > 1e-9 { - t.Fatal("Hann window must be symmetric") - } - } -} - -func TestApplyHannWindowSingleSampleIsFinite(t *testing.T) { - got := applyHannWindow([]float64{1}) - if len(got) != 1 || math.IsNaN(got[0]) { - t.Fatalf("single sample must remain finite: %v", got) - } -} - -func TestConfigValidation(t *testing.T) { - for _, config := range []Config{ - {FFTSize: 1000, HopSize: 10, Channel: "mono", MinDB: -100, MaxDB: 0}, - {FFTSize: 64, HopSize: 65, Channel: "mono", MinDB: -100, MaxDB: 0}, - {FFTSize: 64, HopSize: 32, Channel: "banana", MinDB: -100, MaxDB: 0}, - {FFTSize: 64, HopSize: 32, Channel: "mono", MinDB: 0, MaxDB: 0}, - } { - if err := config.validate(); err == nil { - t.Fatalf("expected invalid config: %+v", config) - } - } -} - -func TestStreamSpectrogramIncludesExactFinalWindowAndMetadata(t *testing.T) { - config := Config{FFTSize: 64, HopSize: 32, Channel: "mono", MinDB: -100, MaxDB: 0} - stream := stereoSineStreamer(128, 8, 8000, 1, 1) - got, err := streamSpectrogram(stream, 8000, 2, config) - if err != nil { - t.Fatal(err) - } - if len(got.Data) != 3 { - t.Fatalf("got %d frames, want 3 including exact final frame", len(got.Data)) - } - if got.Metadata.SchemaVersion != 1 || got.Metadata.SampleRate != 8000 || got.Metadata.Channels != 2 { - t.Fatalf("unexpected metadata: %+v", got.Metadata) - } - if got.Metadata.FrequencyStepHz != 125 || got.Metadata.TimeStepSeconds != 0.004 { - t.Fatalf("unexpected physical axis metadata: %+v", got.Metadata) - } -} - -func TestStreamSpectrogramSinePeakAndDBFS(t *testing.T) { - config := Config{FFTSize: 256, HopSize: 128, Channel: "left", MinDB: -100, MaxDB: 0} - got, err := streamSpectrogram(stereoSineStreamer(512, 1000, 25600, 1, 0), 25600, 2, config) - if err != nil { - t.Fatal(err) - } - peak := 0 - for i := range got.Data[0] { - if got.Data[0][i] > got.Data[0][peak] { - peak = i - } - } - if peak != 10 { - t.Fatalf("peak bin = %d, want 10", peak) - } - if math.Abs(got.Data[0][peak]) > 0.1 { - t.Fatalf("full-scale bin should be near 0 dBFS, got %f", got.Data[0][peak]) - } -} - -func TestChannelSelection(t *testing.T) { - sample := [2]float64{0.8, -0.2} - if selectChannel(sample, "left") != 0.8 || selectChannel(sample, "right") != -0.2 { - t.Fatal("left/right selection failed") - } - if math.Abs(selectChannel(sample, "mono")-0.3) > 1e-9 || math.Abs(selectChannel(sample, "side")-0.5) > 1e-9 { - t.Fatal("mid/side selection failed") - } -} - -func TestFrameCollectorBoundsOutput(t *testing.T) { - c := newFrameCollector(4) - for i := 0; i < 40; i++ { - c.add([]float64{float64(i)}) - } - if len(c.frames) > 4 { - t.Fatalf("stored %d frames, limit is 4", len(c.frames)) - } - if c.stride <= 1 { - t.Fatalf("expected downsampling, got stride %d", c.stride) - } -} - -func TestViridisColor(t *testing.T) { - low := viridisColor(-100, -100, 0).(color.RGBA) - high := viridisColor(0, -100, 0).(color.RGBA) - if low != (color.RGBA{68, 1, 84, 255}) || high != (color.RGBA{253, 231, 37, 255}) { - t.Fatalf("unexpected Viridis endpoints: %#v %#v", low, high) - } -} - -func TestWriteOutputsCreateParentDirs(t *testing.T) { - dir := t.TempDir() - s := Spectrogram{Metadata: Metadata{FFTSize: 4, MinDB: -100, MaxDB: 0}, Data: [][]float64{{-10, -5}, {-8, -1}}} - jsonPath := filepath.Join(dir, "json", "spectrogram.json") - pngPath := filepath.Join(dir, "images", "spectrogram.png") - if err := writeJSON(jsonPath, s); err != nil { - t.Fatal(err) - } - if err := writeImage(pngPath, s); err != nil { - t.Fatal(err) - } - data, err := os.ReadFile(jsonPath) - if err != nil { - t.Fatal(err) - } - var decoded Spectrogram - if err := json.Unmarshal(data, &decoded); err != nil || decoded.Metadata.FFTSize != 4 { - t.Fatalf("invalid structured JSON: %v %+v", err, decoded) - } - f, err := os.Open(pngPath) - if err != nil { - t.Fatal(err) - } - defer f.Close() - if _, err := png.Decode(f); err != nil { - t.Fatalf("invalid PNG: %v", err) - } -} - func TestServerListsAndServesGeneratedData(t *testing.T) { dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "one.json"), []byte(`{"ok":true}`), 0644); err != nil { t.Fatal(err) } server := newServer(t.TempDir(), dir) - listRequest := httptest.NewRequest(http.MethodGet, "/api/spectrograms", nil) - listResponse := httptest.NewRecorder() - server.ServeHTTP(listResponse, listRequest) - if listResponse.Code != http.StatusOK || !strings.Contains(listResponse.Body.String(), "/data/one.json") { - t.Fatalf("unexpected list response: %d %s", listResponse.Code, listResponse.Body.String()) - } - dataRequest := httptest.NewRequest(http.MethodGet, "/data/one.json", nil) - dataResponse := httptest.NewRecorder() - server.ServeHTTP(dataResponse, dataRequest) - if dataResponse.Code != http.StatusOK || dataResponse.Body.String() != `{"ok":true}` { - t.Fatalf("unexpected data response: %d %s", dataResponse.Code, dataResponse.Body.String()) + response := httptest.NewRecorder() + server.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/spectrograms", nil)) + if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), "/data/one.json") { + t.Fatalf("unexpected response: %d %s", response.Code, response.Body.String()) } } -func TestRunEndToEnd(t *testing.T) { - dir := t.TempDir() - wavPath := filepath.Join(dir, "INPUT.WAV") - f, err := os.Create(wavPath) - if err != nil { - t.Fatal(err) +func TestRunRejectsUnsupportedInput(t *testing.T) { + if err := run(filepath.Join(t.TempDir(), "audio.txt"), "out.png", "out.json"); err == nil { + t.Fatal("expected unsupported input error") } - format := beep.Format{SampleRate: 44100, NumChannels: 2, Precision: 2} - if err := wav.Encode(f, stereoSineStreamer(44100, 440, 44100, 1, 1), format); err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - if err := run(wavPath, filepath.Join(dir, "png", "out.png"), filepath.Join(dir, "data", "out.json")); err != nil { - t.Fatal(err) - } -} - -func stereoSineStreamer(numSamples int, frequency, sampleRate, left, right float64) beep.Streamer { - index := 0 - return beep.StreamerFunc(func(samples [][2]float64) (int, bool) { - if index >= numSamples { - return 0, false - } - n := 0 - for n < len(samples) && index < numSamples { - v := math.Sin(2 * math.Pi * frequency * float64(index) / sampleRate) - samples[n] = [2]float64{left * v, right * v} - n++ - index++ - } - return n, true - }) } diff --git a/desktop/spectogram-desktop/.gitignore b/desktop/spectogram-desktop/.gitignore new file mode 100644 index 0000000..5d7826e --- /dev/null +++ b/desktop/spectogram-desktop/.gitignore @@ -0,0 +1,11 @@ +.task +bin +frontend/dist +frontend/node_modules +build/linux/appimage/build +build/windows/nsis/MicrosoftEdgeWebview2Setup.exe +# Mobile generated (per-machine; overlays hold absolute paths) +build/ios/xcode/overlay.json +build/ios/xcode/gen/ +build/android/overlay.json +build/android/gen/ \ No newline at end of file diff --git a/desktop/spectogram-desktop/README.md b/desktop/spectogram-desktop/README.md new file mode 100644 index 0000000..ad12c3f --- /dev/null +++ b/desktop/spectogram-desktop/README.md @@ -0,0 +1,59 @@ +# Welcome to Your New Wails3 Project! + +Congratulations on generating your Wails3 application! This README will guide you through the next steps to get your project up and running. + +## Getting Started + +1. Navigate to your project directory in the terminal. + +2. To run your application in development mode, use the following command: + + ``` + wails3 dev + ``` + + This will start your application and enable hot-reloading for both frontend and backend changes. + +3. To build your application for production, use: + + ``` + wails3 build + ``` + + This will create a production-ready executable in the `build` directory. + +## Exploring Wails3 Features + +Now that you have your project set up, it's time to explore the features that Wails3 offers: + +1. **Check out the examples**: The best way to learn is by example. Visit the `examples` directory in the `v3/examples` directory to see various sample applications. + +2. **Run an example**: To run any of the examples, navigate to the example's directory and use: + + ``` + go run . + ``` + + Note: Some examples may be under development during the alpha phase. + +3. **Explore the documentation**: Visit the [Wails3 documentation](https://v3.wails.io/) for in-depth guides and API references. + +4. **Join the community**: Have questions or want to share your progress? Join the [Wails Discord](https://discord.gg/JDdSxwjhGf) or visit the [Wails discussions on GitHub](https://github.com/wailsapp/wails/discussions). + +## Project Structure + +Take a moment to familiarize yourself with your project structure: + +- `frontend/`: Contains your frontend code (HTML, CSS, JavaScript/TypeScript) +- `main.go`: The entry point of your Go backend +- `app.go`: Define your application structure and methods here +- `wails.json`: Configuration file for your Wails project + +## Next Steps + +1. Modify the frontend in the `frontend/` directory to create your desired UI. +2. Add backend functionality in `main.go`. +3. Use `wails3 dev` to see your changes in real-time. +4. When ready, build your application with `wails3 build`. + +Happy coding with Wails3! If you encounter any issues or have questions, don't hesitate to consult the documentation or reach out to the Wails community. diff --git a/desktop/spectogram-desktop/Taskfile.yml b/desktop/spectogram-desktop/Taskfile.yml new file mode 100644 index 0000000..585f0c6 --- /dev/null +++ b/desktop/spectogram-desktop/Taskfile.yml @@ -0,0 +1,70 @@ +version: '3' + +vars: + APP_NAME: "spectogram-desktop" + BIN_DIR: "bin" + PACKAGE_MANAGER: '{{.PACKAGE_MANAGER | default "npm"}}' + VITE_PORT: '{{.WAILS_VITE_PORT | default 9245}}' + # Target OS for build/package/run. Defaults to the host OS, and is overridden + # by `wails3 build GOOS=...` (or the GOOS env var) for cross-compilation. The + # tasks below dispatch to the matching platform Taskfile via this variable. + GOOS: '{{.GOOS | default OS}}' + +includes: + common: ./build/Taskfile.yml + windows: ./build/windows/Taskfile.yml + darwin: ./build/darwin/Taskfile.yml + linux: ./build/linux/Taskfile.yml + ios: ./build/ios/Taskfile.yml + android: ./build/android/Taskfile.yml + +tasks: + build: + summary: Builds the application + cmds: + - task: "{{.GOOS}}:build" + + package: + summary: Packages a production build of the application + cmds: + - task: "{{.GOOS}}:package" + + run: + summary: Runs the application + cmds: + - task: "{{.GOOS}}:run" + + dev: + summary: Runs the application in development mode + cmds: + - wails3 dev -config ./build/config.yml -port {{.VITE_PORT}} + + install:msix:tools: + summary: Installs tools required for Windows MSIX packaging + cmds: + - task: windows:install:msix:tools + + setup:docker: + summary: Builds Docker image for cross-compilation (~800MB download) + cmds: + - task: common:setup:docker + + build:server: + summary: Builds the application in server mode (no GUI, HTTP server only) + cmds: + - task: common:build:server + + run:server: + summary: Runs the application in server mode + cmds: + - task: common:run:server + + build:docker: + summary: Builds a Docker image for server mode deployment + cmds: + - task: common:build:docker + + run:docker: + summary: Builds and runs the Docker image + cmds: + - task: common:run:docker diff --git a/desktop/spectogram-desktop/analysisservice.go b/desktop/spectogram-desktop/analysisservice.go new file mode 100644 index 0000000..0033107 --- /dev/null +++ b/desktop/spectogram-desktop/analysisservice.go @@ -0,0 +1,68 @@ +package main + +import ( + "encoding/json" + "image" + "image/color" + "image/png" + "os" + "path/filepath" + + "go-spectrogram-plotly/internal/spectrogram" +) + +// AnalysisService is the Wails binding for the shared Go DSP engine. +type AnalysisService struct{} + +// DefaultConfig supplies UI-friendly defaults without duplicating CLI values. +func (s *AnalysisService) DefaultConfig() spectrogram.Config { + return spectrogram.DefaultConfig() +} + +// Analyze reads a WAV or MP3 file and returns its metadata-rich spectrogram. +func (s *AnalysisService) Analyze(path string, config spectrogram.Config) (spectrogram.Result, error) { + return spectrogram.AnalyzeFile(path, config) +} + +// SaveJSON exports an analysis result without requiring the desktop UI to +// handle filesystem access directly. +func (s *AnalysisService) SaveJSON(path string, result spectrogram.Result) error { + data, err := json.Marshal(result) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil && filepath.Dir(path) != "." { + return err + } + return os.WriteFile(path, data, 0644) +} + +// SavePNG exports a compact Viridis-like image of the analyzed result. +func (s *AnalysisService) SavePNG(path string, result spectrogram.Result) error { + if len(result.Data) == 0 { + return os.ErrInvalid + } + height := result.Metadata.FFTSize / 2 + img := image.NewRGBA(image.Rect(0, 0, len(result.Data), height)) + for x, row := range result.Data { + for y, value := range row { + t := (value - result.Metadata.MinDB) / (result.Metadata.MaxDB - result.Metadata.MinDB) + if t < 0 { + t = 0 + } + if t > 1 { + t = 1 + } + img.Set(x, height-y-1, color.RGBA{uint8(68 + 185*t), uint8(1 + 230*t), uint8(84 - 47*t), 255}) + } + } + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil && filepath.Dir(path) != "." { + return err + } + f, err := os.Create(path) + if err != nil { + return err + } + defer f.Close() + return png.Encode(f, img) +} diff --git a/desktop/spectogram-desktop/build/Taskfile.yml b/desktop/spectogram-desktop/build/Taskfile.yml new file mode 100644 index 0000000..9714b9e --- /dev/null +++ b/desktop/spectogram-desktop/build/Taskfile.yml @@ -0,0 +1,398 @@ +version: '3' + +tasks: + go:mod:tidy: + summary: Runs `go mod tidy` + internal: true + # Universal/multi-arch builds invoke this concurrently from parallel deps; + # two `go mod tidy` processes racing on go.mod can corrupt it (#4637). + run: once + cmds: + - go mod tidy + + install:frontend:deps: + summary: Install frontend dependencies + run: once + cmds: + - task: install:frontend:deps:{{.PACKAGE_MANAGER}} + + install:frontend:deps:npm: + dir: frontend + sources: + - package.json + - package-lock.json + generates: + - node_modules + preconditions: + - sh: npm version + msg: "Looks like npm isn't installed. Npm is part of the Node installer: https://nodejs.org/en/download/" + cmds: + - npm install + + install:frontend:deps:bun: + dir: frontend + sources: + - package.json + - bun.lock + - bun.lockb + generates: + - node_modules + preconditions: + - sh: bun --version + msg: "bun not found" + cmds: + - bun install + + install:frontend:deps:pnpm: + dir: frontend + sources: + - package.json + - pnpm-lock.yaml + generates: + - node_modules + preconditions: + - sh: pnpm --version + msg: "pnpm not found" + cmds: + - pnpm install + + install:frontend:deps:yarn: + dir: frontend + sources: + - package.json + - yarn.lock + status: + - test -d node_modules || test -f .pnp.cjs + preconditions: + - sh: yarn --version + msg: "yarn not found" + cmds: + - yarn install + + build:frontend: + label: build:frontend (DEV={{.DEV}} RUNNER={{.PACKAGE_MANAGER}}) + summary: Build the frontend project + # darwin:build:universal runs its per-arch builds as parallel deps, each of + # which depends on this task. Without run:once the two executions race: + # one regenerates frontend/bindings (-clean deletes it first) while the + # other's bundler is reading it, failing intermittently with + # 'Could not resolve "./bindings/"' (#4637). + run: once + dir: frontend + sources: + - "**/*" + - exclude: node_modules/**/* + generates: + - dist/**/* + deps: + - task: install:frontend:deps + - task: generate:bindings + vars: + BUILD_FLAGS: + ref: .BUILD_FLAGS + OBFUSCATED: + ref: .OBFUSCATED + cmds: + - task: frontend:run + vars: + SCRIPT: '{{if eq .DEV "true"}}build:dev{{else}}build{{end}}' + env: + PRODUCTION: '{{if eq .DEV "true"}}false{{else}}true{{end}}' + + frontend:run: + summary: Run a frontend script with selected runner + cmds: + - task: frontend:run:{{.PACKAGE_MANAGER}} + vars: + SCRIPT: "{{.SCRIPT}}" + vars: + SCRIPT: "{{.SCRIPT}}" + + frontend:run:npm: + dir: frontend + cmds: + - npm run {{.SCRIPT}} -q + vars: + SCRIPT: "{{.SCRIPT}}" + + frontend:run:yarn: + dir: frontend + cmds: + - yarn {{.SCRIPT}} + vars: + SCRIPT: "{{.SCRIPT}}" + + frontend:run:pnpm: + dir: frontend + cmds: + - pnpm run {{.SCRIPT}} + vars: + SCRIPT: "{{.SCRIPT}}" + + frontend:run:bun: + dir: frontend + cmds: + - bun run {{.SCRIPT}} + vars: + SCRIPT: "{{.SCRIPT}}" + + frontend:vendor:puppertino: + summary: Fetches Puppertino CSS into frontend/public for consistent mobile styling + sources: + - frontend/public/puppertino/puppertino.css + generates: + - frontend/public/puppertino/puppertino.css + cmds: + - | + set -euo pipefail + mkdir -p frontend/public/puppertino + # If bundled Puppertino exists, prefer it. Otherwise, try to fetch, but don't fail build on error. + if [ ! -f frontend/public/puppertino/puppertino.css ]; then + echo "No bundled Puppertino found. Attempting to fetch from GitHub..." + if curl -fsSL https://raw.githubusercontent.com/codedgar/Puppertino/main/dist/css/full.css -o frontend/public/puppertino/puppertino.css; then + curl -fsSL https://raw.githubusercontent.com/codedgar/Puppertino/main/LICENSE -o frontend/public/puppertino/LICENSE || true + echo "Puppertino CSS downloaded to frontend/public/puppertino/puppertino.css" + else + echo "Warning: Could not fetch Puppertino CSS. Proceeding without download since template may bundle it." + fi + else + echo "Using bundled Puppertino at frontend/public/puppertino/puppertino.css" + fi + # Ensure index.html includes Puppertino CSS and button classes + INDEX_HTML=frontend/index.html + if [ -f "$INDEX_HTML" ]; then + if ! grep -q 'href="/puppertino/puppertino.css"' "$INDEX_HTML"; then + # Insert Puppertino link tag after style.css link + awk ' + /href="\/style.css"\/?/ && !x { print; print " "; x=1; next }1 + ' "$INDEX_HTML" > "$INDEX_HTML.tmp" && mv "$INDEX_HTML.tmp" "$INDEX_HTML" + fi + # Replace default .btn with Puppertino primary button classes if present + sed -E -i'' 's/class=\"btn\"/class=\"p-btn p-prim-col\"/g' "$INDEX_HTML" || true + fi + + + + generate:bindings: + summary: Generates bindings for the frontend + run: once + deps: + - task: go:mod:tidy + sources: + - "**/*.[jt]s" + - exclude: frontend/**/* + - frontend/bindings/**/* # Rerun when switching between dev/production mode causes changes in output + - "**/*.go" + - go.mod + - go.sum + generates: + - frontend/bindings/**/* + cmds: + - wails3 generate bindings -f '{{.BUILD_FLAGS}}' -clean=true{{if eq .OBFUSCATED "true"}} -obfuscated{{end}} -ts -i + + generate:icons: + summary: Generates Windows `.ico` and Mac `.icns` from an image; on macOS, `-iconcomposerinput appicon.icon -macassetdir darwin` also produces `Assets.car` from a `.icon` file (skipped on other platforms). + run: once + dir: build + sources: + - "appicon.png" + - "appicon.icon" + generates: + - "darwin/icons.icns" + - "windows/icon.ico" + cmds: + - wails3 generate icons -input appicon.png -macfilename darwin/icons.icns -windowsfilename windows/icon.ico -iconcomposerinput appicon.icon -macassetdir darwin + + dev:frontend: + summary: Runs the frontend in development mode + deps: + - task: install:frontend:deps + cmds: + - task: frontend:dev:{{.PACKAGE_MANAGER}} + + frontend:dev:npm: + dir: frontend + cmds: + - npm run dev -- --port {{.VITE_PORT}} --strictPort + + frontend:dev:yarn: + dir: frontend + cmds: + - yarn dev --port {{.VITE_PORT}} --strictPort + + frontend:dev:pnpm: + dir: frontend + cmds: + - pnpm dev --port {{.VITE_PORT}} --strictPort + + frontend:dev:bun: + dir: frontend + cmds: + - bun run dev --port {{.VITE_PORT}} --strictPort + + update:build-assets: + summary: Updates the build assets + dir: build + cmds: + - wails3 update build-assets -name "{{.APP_NAME}}" -binaryname "{{.APP_NAME}}" -config config.yml -dir . + + build:server: + summary: Builds the application in server mode (no GUI, HTTP server only) + desc: | + Builds a production server binary by default: -tags server,production, + -trimpath and a stripped binary, mirroring the desktop `build` task. + Server mode runs as a pure HTTP server without native GUI dependencies. + + Usage: task build:server [DEV=true] [OBFUSCATED=true] [EXTRA_TAGS=tag1,tag2] + DEV=true development server (-tags server, no strip, inlining kept) + OBFUSCATED=true obfuscated build via garble (requires garble installed) + EXTRA_TAGS additional comma-separated build tags + deps: + - task: build:frontend + vars: + DEV: + ref: .DEV + BUILD_FLAGS: + ref: .BUILD_FLAGS + OBFUSCATED: + ref: .OBFUSCATED + preconditions: + - sh: '{{if eq .OBFUSCATED "true"}}command -v garble >/dev/null 2>&1{{else}}true{{end}}' + msg: "garble is required for obfuscated builds. Install it with: go install mvdan.cc/garble@v0.16.0 (requires Go 1.24+). See https://github.com/burrowers/garble/releases for version/toolchain compatibility." + cmds: + - '{{if eq .OBFUSCATED "true"}}garble {{.GARBLE_ARGS}} build{{else}}go build{{end}} {{.BUILD_FLAGS}} -o "{{.BIN_DIR}}/{{.APP_NAME}}-server{{exeExt}}"' + vars: + BUILD_FLAGS: '-tags server{{if eq .DEV "true"}}{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -buildvcs=false -gcflags=all="-l"{{else}},production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s"{{end}}' + + run:server: + summary: Builds and runs a development server (DEV=true) + deps: + - task: build:server + vars: + DEV: "true" + cmds: + - '"./{{.BIN_DIR}}/{{.APP_NAME}}-server{{exeExt}}"' + + build:docker: + summary: Builds a Docker image for server mode deployment + desc: | + Creates a minimal Docker image containing the production server binary. + Defaults to a pure-Go static binary on a distroless/static base. The + production frontend is built first so the embedded assets are current. + + Usage: task build:docker [TAG=myapp:latest] [CGO_ENABLED=1] [GO_IMAGE=...] [RUNTIME_IMAGE=...] + For CGO apps, set CGO_ENABLED=1 with libc-compatible builder/runtime images, e.g.: + task build:docker CGO_ENABLED=1 GO_IMAGE=golang:bookworm RUNTIME_IMAGE=gcr.io/distroless/base-debian12 + deps: + # Build the production frontend so frontend/dist (embedded by the Go build + # inside the image) is present and current in the Docker build context. + # Pass the server,production tags so binding generation analyses the same + # build the Docker image compiles, not the default-tag build. + - task: build:frontend + vars: + BUILD_FLAGS: "-tags server,production" + cmds: + - >- + docker build + --build-arg CGO_ENABLED={{.CGO_ENABLED | default "0"}} + --build-arg GO_IMAGE={{.GO_IMAGE | default "golang:alpine"}} + --build-arg RUNTIME_IMAGE={{.RUNTIME_IMAGE | default "gcr.io/distroless/static-debian12"}} + -t {{.TAG | default (printf "%s:latest" .APP_NAME)}} + -f build/docker/Dockerfile.server . + vars: + TAG: "{{.TAG}}" + preconditions: + - sh: docker info > /dev/null 2>&1 + msg: "Docker is required. Please install Docker first." + - sh: test -f build/docker/Dockerfile.server + msg: "Dockerfile.server not found. Run 'wails3 update build-assets' to generate it." + + run:docker: + summary: Builds and runs the Docker image + desc: | + Builds the Docker image and runs it, exposing port 8080. + Usage: task run:docker [TAG=myapp:latest] [PORT=8080] + Note: The internal container port is always 8080. The PORT variable + only changes the host port mapping. Ensure your app uses port 8080 + or modify the Dockerfile to match your ServerOptions.Port setting. + deps: + - task: build:docker + vars: + TAG: + ref: .TAG + cmds: + - docker run --rm -p {{.PORT | default "8080"}}:8080 {{.TAG | default (printf "%s:latest" .APP_NAME)}} + vars: + TAG: "{{.TAG}}" + PORT: "{{.PORT}}" + + setup:docker: + summary: Builds Docker image for cross-compilation (~800MB download) + desc: | + Builds the Docker image needed for cross-compiling to any platform. + Run this once to enable cross-platform builds from any OS. + cmds: + - docker build -t wails-cross -f build/docker/Dockerfile.cross build/docker/ + preconditions: + - sh: docker info > /dev/null 2>&1 + msg: "Docker is required. Please install Docker first." + + ios:device:list: + summary: Lists connected iOS devices (UDIDs) + cmds: + - xcrun xcdevice list + + ios:run:device: + summary: Build, install, and launch on a physical iPhone using Apple tools (xcodebuild/devicectl) + vars: + PROJECT: '{{.PROJECT}}' # e.g., build/ios/xcode/.xcodeproj + SCHEME: '{{.SCHEME}}' # e.g., ios.dev + CONFIG: '{{.CONFIG | default "Debug"}}' + DERIVED: '{{.DERIVED | default "build/ios/DerivedData"}}' + UDID: '{{.UDID}}' # from `task ios:device:list` + BUNDLE_ID: '{{.BUNDLE_ID}}' # e.g., com.yourco.wails.ios.dev + TEAM_ID: '{{.TEAM_ID}}' # optional, if your project is not already set up for signing + preconditions: + - sh: xcrun -f xcodebuild + msg: "xcodebuild not found. Please install Xcode." + - sh: xcrun -f devicectl + msg: "devicectl not found. Please update to Xcode 15+ (which includes devicectl)." + - sh: test -n '{{.PROJECT}}' + msg: "Set PROJECT to your .xcodeproj path (e.g., PROJECT=build/ios/xcode/App.xcodeproj)." + - sh: test -n '{{.SCHEME}}' + msg: "Set SCHEME to your app scheme (e.g., SCHEME=ios.dev)." + - sh: test -n '{{.UDID}}' + msg: "Set UDID to your device UDID (see: task ios:device:list)." + - sh: test -n '{{.BUNDLE_ID}}' + msg: "Set BUNDLE_ID to your app's bundle identifier (e.g., com.yourco.wails.ios.dev)." + cmds: + - | + set -euo pipefail + echo "Building for device: UDID={{.UDID}} SCHEME={{.SCHEME}} PROJECT={{.PROJECT}}" + XCB_ARGS=( + -project "{{.PROJECT}}" + -scheme "{{.SCHEME}}" + -configuration "{{.CONFIG}}" + -destination "id={{.UDID}}" + -derivedDataPath "{{.DERIVED}}" + -allowProvisioningUpdates + -allowProvisioningDeviceRegistration + ) + # Optionally inject signing identifiers if provided + if [ -n '{{.TEAM_ID}}' ]; then XCB_ARGS+=(DEVELOPMENT_TEAM={{.TEAM_ID}}); fi + if [ -n '{{.BUNDLE_ID}}' ]; then XCB_ARGS+=(PRODUCT_BUNDLE_IDENTIFIER={{.BUNDLE_ID}}); fi + xcodebuild "${XCB_ARGS[@]}" build | xcpretty || true + # If xcpretty isn't installed, run without it + if [ "${PIPESTATUS[0]}" -ne 0 ]; then + xcodebuild "${XCB_ARGS[@]}" build + fi + # Find built .app + APP_PATH=$(find "{{.DERIVED}}/Build/Products" -type d -name "*.app" -maxdepth 3 | head -n 1) + if [ -z "$APP_PATH" ]; then + echo "Could not locate built .app under {{.DERIVED}}/Build/Products" >&2 + exit 1 + fi + echo "Installing: $APP_PATH" + xcrun devicectl device install app --device "{{.UDID}}" "$APP_PATH" + echo "Launching: {{.BUNDLE_ID}}" + xcrun devicectl device process launch --device "{{.UDID}}" --stderr console --stdout console "{{.BUNDLE_ID}}" diff --git a/desktop/spectogram-desktop/build/android/Taskfile.yml b/desktop/spectogram-desktop/build/android/Taskfile.yml new file mode 100644 index 0000000..980b700 --- /dev/null +++ b/desktop/spectogram-desktop/build/android/Taskfile.yml @@ -0,0 +1,464 @@ +version: '3' + +includes: + common: ../Taskfile.yml + +vars: + APP_ID: '{{.APP_ID | default "com.wails.app"}}' + MIN_SDK: '21' + TARGET_SDK: '35' + # The emulator runs the host architecture; physical devices are arm64 + HOST_ARCH: + sh: '[ "$(uname -m)" = "x86_64" ] && echo "amd64" || echo "arm64"' + # System-image ABI for the host, used in the "create an AVD" hint below. + ANDROID_ABI: + sh: '[ "$(uname -m)" = "arm64" ] && echo "arm64-v8a" || echo "x86_64"' + # SDK location: $ANDROID_HOME / $ANDROID_SDK_ROOT, else the per-OS default + # (macOS: ~/Library/Android/sdk, Linux/other: ~/Android/Sdk) + SDK_ROOT: + sh: 'echo "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$([ -d "$HOME/Library/Android/sdk" ] && echo "$HOME/Library/Android/sdk" || echo "$HOME/Android/Sdk")}}"' + ADB: + sh: 'command -v adb || echo "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$([ -d "$HOME/Library/Android/sdk" ] && echo "$HOME/Library/Android/sdk" || echo "$HOME/Android/Sdk")}}/platform-tools/adb"' + EMULATOR: + sh: 'command -v emulator || echo "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$([ -d "$HOME/Library/Android/sdk" ] && echo "$HOME/Library/Android/sdk" || echo "$HOME/Android/Sdk")}}/emulator/emulator"' + # avdmanager lives under cmdline-tools//bin; used to auto-create an + # AVD when none exists (mirrors the iOS `ensure-simulator` auto-create flow). + AVDMANAGER: + sh: 'command -v avdmanager || ls "${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$([ -d "$HOME/Library/Android/sdk" ] && echo "$HOME/Library/Android/sdk" || echo "$HOME/Android/Sdk")}}"/cmdline-tools/*/bin/avdmanager 2>/dev/null | sort -V | tail -1 || true' + +tasks: + install:deps: + summary: Check and install Android development dependencies + cmds: + - go run build/android/scripts/deps/install_deps.go + env: + TASK_FORCE_YES: '{{if .YES}}true{{else}}false{{end}}' + prompt: This will check and install Android development dependencies. Continue? + + build: + summary: Creates a debug build of the application for Android + deps: + - task: common:go:mod:tidy + - task: generate:android:overlay + - task: common:build:frontend + vars: + BUILD_FLAGS: + ref: .BUILD_FLAGS + PRODUCTION: + ref: .PRODUCTION + cmds: + - echo "Building Android app {{.APP_NAME}}..." + - task: compile:go:shared + vars: + ARCH: '{{.ARCH | default .HOST_ARCH}}' + vars: + BUILD_FLAGS: '{{if eq .PRODUCTION "true"}}-tags production,android -trimpath -buildvcs=false -ldflags="-w -s"{{else}}-tags android,debug -buildvcs=false -gcflags=all="-l"{{end}}' + env: + PRODUCTION: '{{.PRODUCTION | default "false"}}' + + compile:go:shared: + summary: Compile Go code to shared library (.so) + cmds: + - | + # Locate the NDK: $ANDROID_NDK_HOME, or the newest installed NDK + NDK_ROOT="$ANDROID_NDK_HOME" + if [ -z "$NDK_ROOT" ]; then + SDK_ROOT="{{.SDK_ROOT}}" + NDK_ROOT=$(ls -d "$SDK_ROOT"/ndk/* 2>/dev/null | sort -V | tail -1) + fi + if [ -z "$NDK_ROOT" ] || [ ! -d "$NDK_ROOT" ]; then + echo "Error: Android NDK not found" + echo "Install one with: sdkmanager 'ndk;26.3.11579264' (or set ANDROID_NDK_HOME)" + exit 1 + fi + + # Determine toolchain based on host OS + case "$(uname -s)" in + Darwin) HOST_TAG="darwin-x86_64" ;; + Linux) HOST_TAG="linux-x86_64" ;; + *) echo "Unsupported host OS"; exit 1 ;; + esac + + TOOLCHAIN="$NDK_ROOT/toolchains/llvm/prebuilt/$HOST_TAG" + + # Set compiler based on architecture + case "{{.ARCH}}" in + arm64) + export CC="$TOOLCHAIN/bin/aarch64-linux-android{{.MIN_SDK}}-clang" + export CXX="$TOOLCHAIN/bin/aarch64-linux-android{{.MIN_SDK}}-clang++" + export GOARCH=arm64 + JNI_DIR="arm64-v8a" + ;; + amd64|x86_64) + export CC="$TOOLCHAIN/bin/x86_64-linux-android{{.MIN_SDK}}-clang" + export CXX="$TOOLCHAIN/bin/x86_64-linux-android{{.MIN_SDK}}-clang++" + export GOARCH=amd64 + JNI_DIR="x86_64" + ;; + *) + echo "Unsupported architecture: {{.ARCH}}" + exit 1 + ;; + esac + + export CGO_ENABLED=1 + export GOOS=android + + mkdir -p {{.BIN_DIR}} + mkdir -p build/android/app/src/main/jniLibs/$JNI_DIR + + go build -buildmode=c-shared -overlay build/android/overlay.json {{.BUILD_FLAGS}} \ + -o build/android/app/src/main/jniLibs/$JNI_DIR/libwails.so + vars: + BUILD_FLAGS: '{{if eq .PRODUCTION "true"}}-tags production,android -trimpath -buildvcs=false -ldflags="-w -s"{{else}}-tags android,debug -buildvcs=false -gcflags=all="-l"{{end}}' + + compile:go:all-archs: + summary: Compile Go code for all Android architectures (fat APK) + cmds: + - task: compile:go:shared + vars: + ARCH: arm64 + - task: compile:go:shared + vars: + ARCH: amd64 + + package: + summary: Packages a production build of the application into a signed release APK + desc: | + Builds for arm64 by default (covers 99%+ of real devices). Set ARCH=amd64 + for emulator-only APKs, or use package:fat for a universal APK. + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: '{{.ARCH | default "arm64"}}' + cmds: + - task: assemble:apk:release + + package:fat: + summary: Packages a production build for all architectures (fat APK) + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: arm64 + cmds: + - task: compile:go:shared + vars: + ARCH: amd64 + PRODUCTION: "true" + - task: assemble:apk:release + + bundle: + summary: Packages a production AAB (Android App Bundle) for Play Store submission + desc: | + Builds for arm64 by default. Set ARCH=amd64 for emulator builds, or use + bundle:fat for a universal AAB. + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: '{{.ARCH | default "arm64"}}' + cmds: + - task: assemble:aab:release + + bundle:fat: + summary: Packages a production AAB for all architectures + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: arm64 + cmds: + - task: compile:go:shared + vars: + ARCH: amd64 + PRODUCTION: "true" + - task: assemble:aab:release + + assemble:apk: + summary: Assembles a debug APK using Gradle + preconditions: + - sh: 'command -v java >/dev/null || [ -n "$JAVA_HOME" ]' + msg: "Java not found. Install a JDK (e.g. brew install openjdk@21) and/or set JAVA_HOME" + cmds: + - | + cd build/android + # The exec bit is lost when gradlew is extracted from the embedded + # build assets, so restore it before invoking the wrapper. + chmod +x ./gradlew + ./gradlew assembleDebug + cp app/build/outputs/apk/debug/app-debug.apk "../../{{.BIN_DIR}}/{{.APP_NAME}}.apk" + echo "APK created: {{.BIN_DIR}}/{{.APP_NAME}}.apk" + + assemble:apk:release: + summary: Assembles a release APK using Gradle (signed with the debug keystore unless ANDROID_KEYSTORE_FILE is set) + preconditions: + - sh: 'command -v java >/dev/null || [ -n "$JAVA_HOME" ]' + msg: "Java not found. Install a JDK (e.g. brew install openjdk@21) and/or set JAVA_HOME" + cmds: + - | + cd build/android + # The exec bit is lost when gradlew is extracted from the embedded + # build assets, so restore it before invoking the wrapper. + chmod +x ./gradlew + ./gradlew assembleRelease + cp app/build/outputs/apk/release/app-release.apk "../../{{.BIN_DIR}}/{{.APP_NAME}}.apk" + echo "Release APK created: {{.BIN_DIR}}/{{.APP_NAME}}.apk" + + assemble:aab: + summary: Assembles a debug AAB (Android App Bundle) using Gradle + preconditions: + - sh: 'command -v java >/dev/null || [ -n "$JAVA_HOME" ]' + msg: "Java not found. Install a JDK (e.g. brew install openjdk@21) and/or set JAVA_HOME" + cmds: + - | + cd build/android + # The exec bit is lost when gradlew is extracted from the embedded + # build assets, so restore it before invoking the wrapper. + chmod +x ./gradlew + ./gradlew bundleDebug + cp app/build/outputs/bundle/debug/app-debug.aab "../../{{.BIN_DIR}}/{{.APP_NAME}}.aab" + echo "AAB created: {{.BIN_DIR}}/{{.APP_NAME}}.aab" + + assemble:aab:release: + summary: Assembles a release AAB for Play Store upload (signed with the debug keystore unless ANDROID_KEYSTORE_FILE is set) + preconditions: + - sh: 'command -v java >/dev/null || [ -n "$JAVA_HOME" ]' + msg: "Java not found. Install a JDK (e.g. brew install openjdk@21) and/or set JAVA_HOME" + cmds: + - | + # With Play App Signing, the keystore configured here is your UPLOAD + # key: Google verifies the upload with it, then re-signs the app with + # the app signing key it manages for distribution. + if [ -z "$ANDROID_KEYSTORE_FILE" ]; then + echo "WARNING: ANDROID_KEYSTORE_FILE is not set, so this AAB will be" + echo "signed with the debug keystore. Google Play rejects debug-signed" + echo "bundles. Set ANDROID_KEYSTORE_FILE, ANDROID_KEYSTORE_PASSWORD," + echo "ANDROID_KEY_ALIAS and ANDROID_KEY_PASSWORD before uploading." + fi + cd build/android + # The exec bit is lost when gradlew is extracted from the embedded + # build assets, so restore it before invoking the wrapper. + chmod +x ./gradlew + ./gradlew bundleRelease + cp app/build/outputs/bundle/release/app-release.aab "../../{{.BIN_DIR}}/{{.APP_NAME}}.aab" + echo "Release AAB created: {{.BIN_DIR}}/{{.APP_NAME}}.aab" + + generate:android:overlay: + internal: true + summary: Generate Go build overlay that registers the Android main + sources: + - build/config.yml + generates: + - build/android/overlay.json + - build/android/gen/main_android.gen.go + cmds: + - wails3 android overlay:gen -out build/android/overlay.json -config build/config.yml + + generate:android:bindings: + internal: true + summary: Generates bindings for Android + sources: + - "**/*.go" + - go.mod + - go.sum + generates: + - frontend/bindings/**/* + cmds: + # Bindings are generated from the Go AST; CGO is disabled so the NDK + # is not required for this step + - wails3 generate bindings -f '-tags android' -clean=true + env: + GOOS: android + CGO_ENABLED: 0 + + ensure-emulator: + internal: true + summary: Ensure Android Emulator is running + silent: true + cmds: + - | + # Check if an emulator is already running + if "{{.ADB}}" devices | grep -q "emulator"; then + echo "Emulator already running" + exit 0 + fi + + # Get first available AVD + AVD_NAME=$("{{.EMULATOR}}" -list-avds | tail -1) + if [ -z "$AVD_NAME" ]; then + # No AVD yet. Mirror the iOS `ensure-simulator` flow and create one + # automatically — but ONLY from a system image that is already + # installed. We never trigger an sdkmanager download from a `run` + # task (that would be a surprise multi-GB download + license prompt). + # Pick the highest-API installed image matching the host ABI. + SDK_ROOT="{{.SDK_ROOT}}" + ABI="{{.ANDROID_ABI}}" + IMG=$(ls -d "$SDK_ROOT"/system-images/android-*/*/"$ABI" 2>/dev/null | sort -V | tail -1) + AVDMANAGER="{{.AVDMANAGER}}" + if [ -n "$IMG" ] && [ -x "$AVDMANAGER" ]; then + PKG="system-images;$(echo "$IMG" | sed "s|$SDK_ROOT/system-images/||" | tr '/' ';')" + echo "No Android Virtual Devices found. Creating 'wails' from $PKG..." + echo "no" | "$AVDMANAGER" create avd --name wails --package "$PKG" --device pixel_7 --force + AVD_NAME=wails + else + echo "No Android Virtual Devices found, and no system image is installed to create one from." + echo "Install a system image and create an AVD, e.g.:" + echo " sdkmanager 'system-images;android-35;google_apis;$ABI'" + echo " avdmanager create avd --name wails --package 'system-images;android-35;google_apis;$ABI' --device pixel_7" + exit 1 + fi + fi + + echo "Starting emulator: $AVD_NAME" + # Start the emulator daemonized so it outlives this task step. go-task's + # shell tracks background jobs by PID and reaps them when the command's + # interpreter finishes (which nohup/setsid alone don't prevent — the kill + # is direct), so a bare `emulator &` is gone before the later + # install/launch steps run. Launch it from a short-lived child shell that + # backgrounds the emulator and exits immediately: the emulator is then + # reparented to init/launchd and go-task's shell has no handle to reap it. + nohup sh -c "'{{.EMULATOR}}' -avd '$AVD_NAME' -no-snapshot-load /dev/null 2>&1 &" >/dev/null 2>&1 + + # Wait for emulator to boot (max 120 seconds) + echo "Waiting for emulator to boot..." + "{{.ADB}}" wait-for-device + + for i in $(seq 1 120); do + BOOT_COMPLETED=$("{{.ADB}}" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') + if [ "$BOOT_COMPLETED" = "1" ]; then + echo "Emulator booted successfully" + exit 0 + fi + sleep 1 + done + + echo "Emulator boot timeout" + exit 1 + preconditions: + - sh: '[ -x "{{.ADB}}" ] || command -v adb' + msg: "adb not found. Install the Android SDK platform-tools (or set ANDROID_HOME)" + - sh: '[ -x "{{.EMULATOR}}" ] || command -v emulator' + msg: "emulator not found. Install the Android SDK emulator package (or set ANDROID_HOME)" + + deploy-emulator: + summary: Deploy the packaged release APK to the Android Emulator + deps: + - task: package + vars: + ARCH: '{{.ARCH | default .HOST_ARCH}}' + cmds: + - task: ensure-emulator + - '"{{.ADB}}" uninstall {{.APP_ID}} 2>/dev/null || true' + - '"{{.ADB}}" install "{{.BIN_DIR}}/{{.APP_NAME}}.apk"' + - '"{{.ADB}}" shell am start -n {{.APP_ID}}/com.wails.app.MainActivity' + + run: + summary: Build, install and launch a debug build in the Android Emulator + deps: + - task: ensure-emulator + - task: build + cmds: + - task: assemble:apk + - '"{{.ADB}}" uninstall {{.APP_ID}} 2>/dev/null || true' + - '"{{.ADB}}" install "{{.BIN_DIR}}/{{.APP_NAME}}.apk"' + - '"{{.ADB}}" shell am start -n {{.APP_ID}}/com.wails.app.MainActivity' + + device:list: + summary: Lists connected Android devices and emulators (serials) + cmds: + - '"{{.ADB}}" devices -l' + + run:device: + summary: Build, install and launch a debug build on a connected physical Android device + deps: + - task: build + vars: + ARCH: arm64 + cmds: + - task: assemble:apk + - | + DEVICE='{{.DEVICE_ID | default ""}}' + if [ -z "$DEVICE" ]; then + DEVICE="${DEVICE_ID:-}" + fi + if [ -z "$DEVICE" ]; then + DEVICE=$("{{.ADB}}" devices | awk 'NR > 1 && $2 == "device" && $1 !~ /^emulator-/ { print $1; exit }') + fi + if [ -z "$DEVICE" ]; then + echo "Error: no connected physical Android device found." + echo "Pass DEVICE_ID= to target a device explicitly." + echo "Find connected device serials with: {{.ADB}} devices" + exit 1 + fi + + echo "Deploying {{.BIN_DIR}}/{{.APP_NAME}}.apk to device $DEVICE..." + "{{.ADB}}" -s "$DEVICE" uninstall {{.APP_ID}} 2>/dev/null || true + "{{.ADB}}" -s "$DEVICE" install "{{.BIN_DIR}}/{{.APP_NAME}}.apk" + "{{.ADB}}" -s "$DEVICE" shell am start -n {{.APP_ID}}/com.wails.app.MainActivity + preconditions: + - sh: '[ -x "{{.ADB}}" ] || command -v adb' + msg: "adb not found. Install the Android SDK platform-tools (or set ANDROID_HOME)" + + deploy-device: + summary: Deploy the packaged release APK to a connected physical Android device + deps: + - task: package + vars: + ARCH: arm64 + cmds: + - | + DEVICE='{{.DEVICE_ID | default ""}}' + if [ -z "$DEVICE" ]; then + DEVICE="${DEVICE_ID:-}" + fi + if [ -z "$DEVICE" ]; then + DEVICE=$("{{.ADB}}" devices | awk 'NR > 1 && $2 == "device" && $1 !~ /^emulator-/ { print $1; exit }') + fi + if [ -z "$DEVICE" ]; then + echo "Error: no connected physical Android device found." + echo "Pass DEVICE_ID= to target a device explicitly." + echo "Find connected device serials with: {{.ADB}} devices" + exit 1 + fi + + echo "Deploying {{.BIN_DIR}}/{{.APP_NAME}}.apk to device $DEVICE..." + "{{.ADB}}" -s "$DEVICE" uninstall {{.APP_ID}} 2>/dev/null || true + "{{.ADB}}" -s "$DEVICE" install "{{.BIN_DIR}}/{{.APP_NAME}}.apk" + "{{.ADB}}" -s "$DEVICE" shell am start -n {{.APP_ID}}/com.wails.app.MainActivity + preconditions: + - sh: '[ -x "{{.ADB}}" ] || command -v adb' + msg: "adb not found. Install the Android SDK platform-tools (or set ANDROID_HOME)" + + studio: + summary: Open the generated Android project in Android Studio + cmds: + - | + if command -v studio >/dev/null 2>&1; then + studio build/android + elif [ -d "/Applications/Android Studio.app" ]; then + open -a "Android Studio" build/android + else + echo "Android Studio not found. Install it from https://developer.android.com/studio," + echo "then open the build/android directory." + exit 1 + fi + + logs: + summary: Stream Android logcat filtered to this app + cmds: + - '"{{.ADB}}" logcat -v time | grep -E "(Wails|{{.APP_NAME}})" || true' + + logs:all: + summary: Stream all Android logcat (verbose) + cmds: + - '"{{.ADB}}" logcat -v time' + + clean: + summary: Clean build artifacts + cmds: + - rm -rf {{.BIN_DIR}} + - rm -rf build/android/app/build + - rm -rf build/android/app/src/main/jniLibs/*/libwails.so + - rm -rf build/android/.gradle diff --git a/desktop/spectogram-desktop/build/android/app/build.gradle b/desktop/spectogram-desktop/build/android/app/build.gradle new file mode 100644 index 0000000..9c69943 --- /dev/null +++ b/desktop/spectogram-desktop/build/android/app/build.gradle @@ -0,0 +1,83 @@ +plugins { + id 'com.android.application' +} + +android { + namespace 'com.wails.app' + compileSdk 35 + + buildFeatures { + buildConfig = true + } + + defaultConfig { + applicationId "com.wails.app" + minSdk 21 + targetSdk 35 + versionCode 1 + versionName "1.0" + + // Configure supported ABIs + ndk { + abiFilters 'arm64-v8a', 'x86_64' + } + } + + def keystoreFile = System.getenv("ANDROID_KEYSTORE_FILE") + def hasKeystore = keystoreFile != null && !keystoreFile.trim().isEmpty() + + signingConfigs { + // A real keystore can be provided via environment variables; without + // one, release builds are signed with the debug keystore so they can + // be installed for testing (not suitable for Play Store uploads). + release { + if (hasKeystore) { + storeFile file(keystoreFile) + storePassword System.getenv("ANDROID_KEYSTORE_PASSWORD") + keyAlias System.getenv("ANDROID_KEY_ALIAS") + keyPassword System.getenv("ANDROID_KEY_PASSWORD") + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + signingConfig hasKeystore ? signingConfigs.release : signingConfigs.debug + } + debug { + debuggable true + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + + // Source sets configuration + sourceSets { + main { + // JNI libraries are in jniLibs folder + jniLibs.srcDirs = ['src/main/jniLibs'] + // Assets for the WebView + assets.srcDirs = ['src/main/assets'] + } + } + + // Packaging options + packagingOptions { + // Don't strip Go symbols in debug builds + doNotStrip '*/arm64-v8a/libwails.so' + doNotStrip '*/x86_64/libwails.so' + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'androidx.webkit:webkit:1.9.0' + implementation 'com.google.android.material:material:1.11.0' + implementation 'androidx.biometric:biometric:1.1.0' + implementation 'androidx.security:security-crypto:1.1.0-alpha06' +} diff --git a/desktop/spectogram-desktop/build/android/app/proguard-rules.pro b/desktop/spectogram-desktop/build/android/app/proguard-rules.pro new file mode 100644 index 0000000..8b88c3d --- /dev/null +++ b/desktop/spectogram-desktop/build/android/app/proguard-rules.pro @@ -0,0 +1,12 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. + +# Keep native methods +-keepclasseswithmembernames class * { + native ; +} + +# Keep Wails bridge classes +-keep class com.wails.app.WailsBridge { *; } +-keep class com.wails.app.WailsJSBridge { *; } diff --git a/desktop/spectogram-desktop/build/android/app/src/main/AndroidManifest.xml b/desktop/spectogram-desktop/build/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..e4f6cca --- /dev/null +++ b/desktop/spectogram-desktop/build/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/desktop/spectogram-desktop/build/android/app/src/main/java/com/wails/app/MainActivity.java b/desktop/spectogram-desktop/build/android/app/src/main/java/com/wails/app/MainActivity.java new file mode 100644 index 0000000..13df575 --- /dev/null +++ b/desktop/spectogram-desktop/build/android/app/src/main/java/com/wails/app/MainActivity.java @@ -0,0 +1,935 @@ +package com.wails.app; + +import android.annotation.SuppressLint; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.res.Configuration; +import android.database.Cursor; +import android.net.ConnectivityManager; +import android.net.Network; +import android.net.NetworkCapabilities; +import android.net.Uri; +import android.os.BatteryManager; +import android.os.Build; +import android.os.Bundle; +import android.os.PowerManager; +import android.content.pm.PackageManager; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.provider.MediaStore; +import android.provider.OpenableColumns; +import android.util.Base64; +import android.util.Log; +import android.webkit.ConsoleMessage; +import android.webkit.ValueCallback; +import android.webkit.WebChromeClient; +import android.webkit.WebChromeClient.FileChooserParams; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; + +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.content.FileProvider; +import androidx.webkit.WebViewAssetLoader; + +import org.json.JSONObject; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * MainActivity hosts the WebView and manages the Wails application lifecycle. + * It uses WebViewAssetLoader to serve assets from the Go library without + * requiring a network server. + */ +public class MainActivity extends AppCompatActivity { + private static final String TAG = "WailsActivity"; + private static final boolean DEBUG = BuildConfig.DEBUG; + private static final String WAILS_SCHEME = "https"; + private static final String WAILS_HOST = "wails.localhost"; + private static final int FILE_PICKER_REQUEST = 7001; + + private WebView webView; + private WailsBridge bridge; + // Battery: system-event receivers are registered only while the activity is + // in the foreground (onStart) and torn down in onStop, so background battery/ + // network/screen broadcasts don't wake the app. + private boolean systemReceiversRegistered = false; + private WebViewAssetLoader assetLoader; + + // The Go-side dialog ID of the in-flight file picker (-1 when idle) + private int pendingFilePickerCallbackID = -1; + private static final int PHOTO_CAPTURE_REQUEST = 7002; + private static final int VIDEO_CAPTURE_REQUEST = 7003; + private static final int CAMERA_PERMISSION_REQUEST = 7010; + + // In-flight callback for an HTML chooser opened by the + // WebView's WebChromeClient (null when idle). + private static final int WEBVIEW_FILE_CHOOSER_REQUEST = 7004; + private ValueCallback webViewFileChooserCallback; + private File pendingCaptureFile; + private boolean pendingCaptureIsVideo; + + // System-event sources (battery/power, screen lock, network). Registered in + // onCreate, torn down in onDestroy. Each forwards a "system:*" event to JS + // via the bridge. + private BroadcastReceiver batteryReceiver; + private BroadcastReceiver screenReceiver; + private BroadcastReceiver powerSaveReceiver; + private ConnectivityManager connectivityManager; + private ConnectivityManager.NetworkCallback networkCallback; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + // Initialize the native Go library + bridge = new WailsBridge(this); + bridge.initialize(); + + // Set up WebView + setupWebView(); + + // Load the application + loadApplication(); + } + + @SuppressLint("SetJavaScriptEnabled") + private void setupWebView() { + webView = findViewById(R.id.webview); + bridge.setWebView(webView); + + // Configure WebView settings + WebSettings settings = webView.getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setDatabaseEnabled(true); + settings.setAllowFileAccess(false); + settings.setAllowContentAccess(false); + settings.setMediaPlaybackRequiresUserGesture(false); + settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW); + + // Enable debugging in debug builds + if (DEBUG) { + WebView.setWebContentsDebuggingEnabled(true); + } + + // Set up asset loader for serving local assets + assetLoader = new WebViewAssetLoader.Builder() + .setDomain(WAILS_HOST) + .addPathHandler("/", new WailsPathHandler(bridge)) + .build(); + + // Set up WebView client to intercept requests + webView.setWebViewClient(new WebViewClient() { + @Nullable + @Override + public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { + // Handle wails.localhost requests + if (request.getUrl().getHost() != null && + request.getUrl().getHost().equals(WAILS_HOST)) { + + // For wails API calls (runtime, capabilities, etc.) pass the + // full URL including the query string, because + // WebViewAssetLoader.PathHandler strips query params + String path = request.getUrl().getPath(); + if (path != null && path.startsWith("/wails/")) { + String fullPath = path; + String query = request.getUrl().getQuery(); + if (query != null && !query.isEmpty()) { + fullPath = path + "?" + query; + } + if (DEBUG) Log.d(TAG, "Wails API call: " + fullPath); + + byte[] data = bridge.serveAsset(fullPath, request.getMethod(), "{}"); + if (data != null && data.length > 0) { + java.io.InputStream inputStream = new java.io.ByteArrayInputStream(data); + java.util.Map headers = new java.util.HashMap<>(); + headers.put("Access-Control-Allow-Origin", "*"); + headers.put("Cache-Control", "no-cache"); + headers.put("Content-Type", "application/json"); + + // Detect error envelopes: if the body starts with + // {"ok":false, return HTTP 500 so the fallback + // transport's fetch() rejects the promise. + int status = 200; + String reason = "OK"; + if (data.length > 12) { + String prefix = new String(data, 0, Math.min(data.length, 20), + java.nio.charset.StandardCharsets.UTF_8); + if (prefix.contains("\"ok\":false")) { + status = 500; + reason = "Internal Error"; + } + } + + return new WebResourceResponse( + "application/json", + "UTF-8", + status, + reason, + headers, + inputStream + ); + } + // Return error response if data is null + return new WebResourceResponse( + "application/json", + "UTF-8", + 500, + "Internal Error", + new java.util.HashMap<>(), + new java.io.ByteArrayInputStream("{}".getBytes()) + ); + } + + // Stream captured photos/videos from the cache with HTTP Range + // support so