commit 0a1c1e82eac3f6222293350049965d0db4265ba0 Author: zerorigin2019 Date: Wed Aug 5 00:42:45 2026 +0800 chore: 初始化仓库(零源工具箱 0.1.0 基线) - Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎) - Wails v3 设置进程 cmd/settings(独立 module) - 监督进程 cmd/watchdog(-supervise 异常重启) - 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/ - 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f8eabd1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,25 @@ +# 行尾规范:源码统一 LF,Windows 脚本 CRLF +* text=auto + +*.go text eol=lf +*.md text eol=lf +*.json text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.ts text eol=lf +*.vue text eol=lf +*.css text eol=lf +*.html text eol=lf +*.toml text eol=lf +*.nsi text eol=lf + +*.bat text eol=crlf +*.cmd text eol=crlf + +# 二进制 +*.ico binary +*.png binary +*.icns binary +*.jar binary +*.car binary +*.pbxproj text eol=lf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7f16709 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# 编译产物 +bin/ + +# 可执行文件 +*.exe +*.dll + +# 图标嵌入资源(构建时生成) +**/rsrc.syso + +# 本地配置与日志(运行时生成) +config.json +*.bak +logs/ + +# 前端依赖与构建产物(设置进程) +node_modules/ +dist/ +*.tmp + +# 其他工具的本地状态 +.reasonix/ +.workbuddy/ + +# 编辑器 +.vscode/ +.idea/ diff --git a/app.manifest b/app.manifest new file mode 100644 index 0000000..d234394 --- /dev/null +++ b/app.manifest @@ -0,0 +1,20 @@ + + + + + + + + + + PerMonitorV2 + + + diff --git a/assets/logo.ico b/assets/logo.ico new file mode 100644 index 0000000..828974e Binary files /dev/null and b/assets/logo.ico differ diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..b0a813e Binary files /dev/null and b/assets/logo.png differ diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..b602293 --- /dev/null +++ b/build.bat @@ -0,0 +1,52 @@ +@echo off +chcp 65001 >nul +cd /d "%~dp0" + +echo [build] 终止旧进程... +taskkill /f /im zerorigin.exe >nul 2>&1 +taskkill /f /im ZerOriginTool-Settings.exe >nul 2>&1 + +echo [build] 生成主进程图标资源 (rsrc.syso)... +for /f "tokens=*" %%i in ('go env GOPATH') do set "GOPATH=%%i" +"%GOPATH%\bin\rsrc.exe" -ico assets\logo.ico -manifest app.manifest -o cmd\zerorigin\rsrc.syso +if %errorlevel% neq 0 (echo [build] rsrc 失败! && exit /b 1) + +echo [build] 编译主进程... +go build -ldflags="-s -w -H windowsgui -X zerorigin/internal/version.Version=0.1.0" -o bin\ZerOriginTool.exe .\cmd\zerorigin +if %errorlevel% neq 0 (del cmd\zerorigin\rsrc.syso 2>nul && echo [build] 编译失败! && exit /b 1) +del cmd\zerorigin\rsrc.syso 2>nul + +echo [build] 构建设置进程(前端 + Wails)... +set PATH=%GOPATH%\bin;%PATH% +pushd cmd\settings +call wails3 build +popd +if not exist cmd\settings\bin\settings.exe (echo [build] 设置进程构建失败! && exit /b 1) +copy /y cmd\settings\bin\settings.exe bin\ZerOriginTool-Settings.exe >nul + +echo [build] 编译监督进程 (watchdog)... +go build -ldflags="-s -w -H windowsgui" -o bin\watchdog.exe .\cmd\watchdog +if %errorlevel% neq 0 (echo [build] watchdog 编译失败! && exit /b 1) + +echo [build] 生成便携版... +if not exist portable mkdir portable +copy /y bin\ZerOriginTool.exe portable\ZerOriginTool.exe >nul +copy /y bin\ZerOriginTool-Settings.exe portable\ZerOriginTool-Settings.exe >nul +copy /y bin\watchdog.exe portable\watchdog.exe >nul + +echo [build] 编译安装包 (NSIS)... +if exist "C:\Program Files (x86)\NSIS\makensis.exe" ( + pushd deploy + "C:\Program Files (x86)\NSIS\makensis.exe" -INPUTCHARSET UTF8 installer.nsi + popd + if exist deploy\ZerOriginTool_Setup.exe ( + copy /y deploy\ZerOriginTool_Setup.exe bin\ZerOriginTool_Setup.exe >nul + del deploy\ZerOriginTool_Setup.exe + ) +) else ( + echo [build] 未找到 NSIS,跳过安装包。 +) + +echo [build] 完成: +dir /b bin\*.exe +echo 便携版:portable\(含两个 exe 与说明) diff --git a/cmd/diag-volume/main.go b/cmd/diag-volume/main.go new file mode 100644 index 0000000..605f6e4 --- /dev/null +++ b/cmd/diag-volume/main.go @@ -0,0 +1,562 @@ +// ZerOriginToolBox 音量诊断工具(临时诊断,不入生产构建)。 +// +// 目标:确认"COM 直调音量返回 S_OK + 读回验证通过,但 Win11 音量 OSD 简化 / +// 实际听感无变化"的根因。输出: +// +// 1. 所有渲染端点:名称 + ID(GUID) + 状态(ACTIVE/DISABLED/NOTPRESENT/UNPLUGGED) +// 2. 三种 ERole(eConsole/eMultimedia/eCommunications)默认端点 GUID 对比 +// 3. 生产路径 GetMasterVolumePercent 读到的音量 +// 4. IAudioEndpointVolume:音量范围(dB)、步进信息、静音状态 +// 5. 注册 IAudioEndpointVolumeCallback,经生产路径 VolumeAdjustPercent(+1) 调节, +// 观察系统音频通知是否送达(OnNotify 是否被调用) +// 6. SendInput 媒体键 VolumeStep(+1):由系统 Shell 处理 → 应显示完整 OSD +// +// 构建:go build ./cmd/diag-volume +// 运行:在 Win11 有声卡桌面上运行,调节过程中留意屏幕右下角 OSD 形态。 +package main + +import ( + "fmt" + "math" + "os" + "runtime" + "sync/atomic" + "syscall" + "time" + "unicode/utf16" + "unsafe" + + "zerorigin/internal/platform/windows" +) + +// ---------- COM 基础设施(自包含,与 internal/platform/windows 同构) ---------- + +type comGUID struct { + Data1 uint32 + Data2 uint16 + Data3 uint16 + Data4 [8]byte +} + +func guidFromString(s string) comGUID { + var g comGUID + var d1, d2, d3, d4, d5, d6, d7, d8 uint32 + n, _ := fmt.Sscanf(s, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + &g.Data1, &g.Data2, &g.Data3, &d1, &d2, &d3, &d4, &d5, &d6, &d7, &d8) + if n != 11 { + panic("invalid GUID string: " + s) + } + g.Data4 = [8]byte{byte(d1), byte(d2), byte(d3), byte(d4), byte(d5), byte(d6), byte(d7), byte(d8)} + return g +} + +var ( + ole32Diag = syscall.NewLazyDLL("ole32.dll") + procCoInitializeEx = ole32Diag.NewProc("CoInitializeEx") + procCoUninitialize = ole32Diag.NewProc("CoUninitialize") + procCoCreateInstance = ole32Diag.NewProc("CoCreateInstance") + procCoTaskMemFree = ole32Diag.NewProc("CoTaskMemFree") + procPropVariantClear = ole32Diag.NewProc("PropVariantClear") + user32Diag = syscall.NewLazyDLL("user32.dll") + procSendInputDiag = user32Diag.NewProc("SendInput") +) + +var ( + guidMMDeviceEnumeratorDiag = guidFromString("BCDE0395-E52F-467C-8E3D-C4579291692E") + iidIMMDeviceEnumeratorDiag = guidFromString("A95664D2-9614-4F35-A746-DE8DB63617E6") + iidIMMDeviceDiag = guidFromString("D666063F-1587-4E43-81F1-B948E807363F") + iidAudioEndpointVolumeDiag = guidFromString("5CDF2C82-841E-4546-9722-0CF74078229A") + iidIPropertyStoreDiag = guidFromString("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99") +) + +const ( + eRender = 0 + eConsole = 0 + eMultimedia = 1 + eCommunications = 2 + deviceStateMaskAll = 0x0F // ACTIVE|DISABLED|NOTPRESENT|UNPLUGGED + clsctxAll = 0x17 + coinitMultithreaded = 0x0 + stgmRead = 0 + vtLPWSTR = 31 + friendlyNamePID = 14 + friendlyNameFmtID = "A45C254E-DF1C-4EFD-8020-67D146A850E0" +) + +// comCallDiag 调用 COM 接口 vtable 方法,返回 HRESULT。 +func comCallDiag(iface uintptr, slot uint32, args ...uintptr) uintptr { + p := *(*unsafe.Pointer)(unsafe.Pointer(&iface)) + vtable := *(*unsafe.Pointer)(p) + fn := *(*uintptr)(unsafe.Pointer(uintptr(vtable) + uintptr(slot)*8)) + r, _, _ := syscall.SyscallN(fn, append([]uintptr{iface}, args...)...) + return r +} + +func comReleaseDiag(iface uintptr) { + if iface != 0 { + comCallDiag(iface, 2) + } +} + +// ---------- 端点描述 ---------- + +type endpointInfo struct { + name string + id string + state uint32 +} + +func stateName(s uint32) string { + switch s { + case 1: + return "ACTIVE" + case 2: + return "DISABLED" + case 4: + return "NOTPRESENT" + case 8: + return "UNPLUGGED" + } + return fmt.Sprintf("0x%X", s) +} + +func utf16PtrToString(p *uint16) string { + if p == nil { + return "" + } + var buf []uint16 + for *p != 0 { + buf = append(buf, *p) + p = (*uint16)(unsafe.Add(unsafe.Pointer(p), 2)) + } + return string(utf16.Decode(buf)) +} + +type propVariant struct { + vt uint16 + w1 uint16 + w2 uint16 + w3 uint16 + pwszVal *uint16 // VT_LPWSTR:offset 8 起存字符串指针(x64) + _ [8]byte // union 补齐至 DECIMAL 大小,使 sizeof == 24(x64) +} + +func pvString(pv *propVariant) string { + if pv.vt != vtLPWSTR || pv.pwszVal == nil { + return "" + } + return utf16PtrToString(pv.pwszVal) +} + +type propertyKey struct { + fmtid comGUID + pid uint32 +} + +// deviceFriendlyName 通过 IPropertyStore::GetValue(PKEY_Device_FriendlyName) 读名称。 +func deviceFriendlyName(dev uintptr) string { + var store uintptr + if hr := comCallDiag(dev, 4, stgmRead, uintptr(unsafe.Pointer(&store))); hr != 0 || store == 0 { + return "" + } + defer comReleaseDiag(store) + key := propertyKey{fmtid: guidFromString(friendlyNameFmtID), pid: friendlyNamePID} + var pv propVariant + if hr := comCallDiag(store, 5, uintptr(unsafe.Pointer(&key)), uintptr(unsafe.Pointer(&pv))); hr != 0 { + return "" + } + defer procPropVariantClear.Call(uintptr(unsafe.Pointer(&pv))) + return pvString(&pv) +} + +func deviceID(dev uintptr) string { + var idp *uint16 // COM 返回的 LPWSTR,直接以指针接收,避免 uintptr→指针转换 + if hr := comCallDiag(dev, 5, uintptr(unsafe.Pointer(&idp))); hr != 0 || idp == nil { + return "" + } + defer procCoTaskMemFree.Call(uintptr(unsafe.Pointer(idp))) + return utf16PtrToString(idp) +} + +func describeDevice(dev uintptr) endpointInfo { + var state uintptr + comCallDiag(dev, 6, uintptr(unsafe.Pointer(&state))) + return endpointInfo{name: deviceFriendlyName(dev), id: deviceID(dev), state: uint32(state)} +} + +// enumRenderEndpoints 枚举所有渲染端点(含非活动)。 +func enumRenderEndpoints(enumerator uintptr) []endpointInfo { + var coll uintptr + if hr := comCallDiag(enumerator, 3, eRender, deviceStateMaskAll, uintptr(unsafe.Pointer(&coll))); hr != 0 || coll == 0 { + fmt.Printf("[!] EnumAudioEndpoints 失败: hr=0x%08x\n", hr) + return nil + } + defer comReleaseDiag(coll) + var count uintptr + if hr := comCallDiag(coll, 3, uintptr(unsafe.Pointer(&count))); hr != 0 { + fmt.Printf("[!] GetCount 失败: hr=0x%08x\n", hr) + return nil + } + out := make([]endpointInfo, 0, count) + for i := uintptr(0); i < count; i++ { + var dev uintptr + if hr := comCallDiag(coll, 4, i, uintptr(unsafe.Pointer(&dev))); hr != 0 || dev == 0 { + continue + } + out = append(out, describeDevice(dev)) + comReleaseDiag(dev) + } + return out +} + +// defaultEndpointID 获取指定 ERole 的默认渲染端点 ID。 +func defaultEndpointID(enumerator uintptr, role uintptr) (string, error) { + var dev uintptr + if hr := comCallDiag(enumerator, 4, eRender, role, uintptr(unsafe.Pointer(&dev))); hr != 0 || dev == 0 { + return "", fmt.Errorf("GetDefaultAudioEndpoint(role=%d): hr=0x%08x", role, hr) + } + defer comReleaseDiag(dev) + id := deviceID(dev) + if id == "" { + return "", fmt.Errorf("GetId 返回空") + } + return id, nil +} + +// openMultimediaEndpointVolume 打开 eMultimedia 默认端点的 IAudioEndpointVolume。 +func openMultimediaEndpointVolume(enumerator uintptr) (uintptr, error) { + var dev uintptr + if hr := comCallDiag(enumerator, 4, eRender, eMultimedia, uintptr(unsafe.Pointer(&dev))); hr != 0 || dev == 0 { + return 0, fmt.Errorf("GetDefaultAudioEndpoint(multimedia): hr=0x%08x", hr) + } + defer comReleaseDiag(dev) + var vol uintptr + if hr := comCallDiag(dev, 3, uintptr(unsafe.Pointer(&iidAudioEndpointVolumeDiag)), clsctxAll, 0, uintptr(unsafe.Pointer(&vol))); hr != 0 || vol == 0 { + return 0, fmt.Errorf("Activate(IAudioEndpointVolume): hr=0x%08x", hr) + } + return vol, nil +} + +// ---------- IAudioEndpointVolume 查询 ---------- + +func getVolumeRange(vol uintptr) (mindB, maxdB, incdB float32, err error) { + if hr := comCallDiag(vol, 20, + uintptr(unsafe.Pointer(&mindB)), + uintptr(unsafe.Pointer(&maxdB)), + uintptr(unsafe.Pointer(&incdB))); hr != 0 { + return 0, 0, 0, fmt.Errorf("GetVolumeRange: hr=0x%08x", hr) + } + return mindB, maxdB, incdB, nil +} + +func getVolumeStepInfo(vol uintptr) (step, stepCount uint32, err error) { + if hr := comCallDiag(vol, 16, + uintptr(unsafe.Pointer(&step)), + uintptr(unsafe.Pointer(&stepCount))); hr != 0 { + return 0, 0, fmt.Errorf("GetVolumeStepInfo: hr=0x%08x", hr) + } + return step, stepCount, nil +} + +func getScalar(vol uintptr) (float32, error) { + var s float32 + if hr := comCallDiag(vol, 9, uintptr(unsafe.Pointer(&s))); hr != 0 { + return 0, fmt.Errorf("GetMasterVolumeLevelScalar: hr=0x%08x", hr) + } + return s, nil +} + +func getMuted(vol uintptr) (bool, error) { + var m int32 + if hr := comCallDiag(vol, 15, uintptr(unsafe.Pointer(&m))); hr != 0 { + return false, fmt.Errorf("GetMute: hr=0x%08x", hr) + } + return m != 0, nil +} + +// ---------- IAudioEndpointVolumeCallback(观察系统通知) ---------- + +type volumeCallbackVtbl struct { + queryInterface uintptr + addRef uintptr + release uintptr + onNotify uintptr +} + +// volumeCallback 用原子字段记录 OnNotify 是否被调用(回调可能运行在其他线程)。 +type volumeCallback struct { + vtbl *volumeCallbackVtbl + notified int32 + mutedBits int32 + volumeBits uint32 +} + +func cbQueryInterface(this, riid, ppv uintptr) uintptr { return 0x80004001 } // E_NOINTERFACE +func cbAddRef(this uintptr) uintptr { return 1 } +func cbRelease(this uintptr) uintptr { return 1 } + +// audioVolumeNotificationData 对应 AUDIO_VOLUME_NOTIFICATION_DATA: +// +// GUID guidEventContext(16) | BOOL bMuted(4) | float fMasterVolume(4) | UINT nChannels(4) +type audioVolumeNotificationData struct { + eventContext comGUID + muted int32 + fMasterVolume float32 + nChannels uint32 +} + +// cbOnNotify 观察系统音量通知。注意:可能运行在任意 MTA 线程, +// 因此只用原子字段记录,不调用任何可能阻塞的 Go 代码。 +func cbOnNotify(this uintptr, pData uintptr) uintptr { + // this 参数即回调对象指针;通过 &this 取地址再转二级指针,避免 uintptr→指针转换。 + cb := *(**volumeCallback)(unsafe.Pointer(&this)) + atomic.StoreInt32(&cb.notified, 1) + if pData != 0 { + data := *(**audioVolumeNotificationData)(unsafe.Pointer(&pData)) + atomic.StoreInt32(&cb.mutedBits, data.muted) + atomic.StoreUint32(&cb.volumeBits, math.Float32bits(data.fMasterVolume)) + } + return 0 // S_OK +} + +var diagCallbackVtbl = &volumeCallbackVtbl{ + queryInterface: syscall.NewCallback(cbQueryInterface), + addRef: syscall.NewCallback(cbAddRef), + release: syscall.NewCallback(cbRelease), + onNotify: syscall.NewCallback(cbOnNotify), +} + +// ---------- SendInput 媒体键(观察完整 OSD) ---------- + +const ( + inputKeyboard = 1 + keyeventfKeyUp = 0x0002 + vkVolUp = 0xAF + vkVolDown = 0xAE +) + +type keybdInput struct { + wVk uint16 + wScan uint16 + dwFlags uint32 + time uint32 + dwExtraInfo uintptr +} + +type inputStruct struct { + Type uint32 + _ uint32 + Ki keybdInput + _ [8]byte +} + +// sendMediaVolumeKey 发送一次媒体音量键(系统 Shell 处理 → 完整 OSD)。 +func sendMediaVolumeKey(up bool) error { + vk := uint16(vkVolDown) + if up { + vk = vkVolUp + } + ins := []inputStruct{ + {Type: inputKeyboard, Ki: keybdInput{wVk: vk}}, + {Type: inputKeyboard, Ki: keybdInput{wVk: vk, dwFlags: keyeventfKeyUp}}, + } + r, _, err := procSendInputDiag.Call( + uintptr(len(ins)), + uintptr(unsafe.Pointer(&ins[0])), + unsafe.Sizeof(inputStruct{}), + ) + if r != uintptr(len(ins)) { + return fmt.Errorf("SendInput: injected %d of %d: %v", r, len(ins), err) + } + return nil +} + +// ---------- 主流程 ---------- + +func createEnumerator() (uintptr, error) { + var enumerator uintptr + hr, _, _ := procCoCreateInstance.Call( + uintptr(unsafe.Pointer(&guidMMDeviceEnumeratorDiag)), 0, clsctxAll, + uintptr(unsafe.Pointer(&iidIMMDeviceEnumeratorDiag)), + uintptr(unsafe.Pointer(&enumerator))) + if enumerator == 0 { + return 0, fmt.Errorf("CoCreateInstance(IMMDeviceEnumerator): hr=0x%08x", hr) + } + return enumerator, nil +} + +func findName(infos []endpointInfo, id string) string { + for _, info := range infos { + if info.id == id { + return info.name + } + } + return "(未在枚举列表)" +} + +func main() { + fmt.Println("===== ZerOriginToolBox 音量诊断 =====") + fmt.Printf("时间: %s\n", time.Now().Format("2006-01-02 15:04:05")) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + procCoInitializeEx.Call(0, coinitMultithreaded) + defer procCoUninitialize.Call() + + enumerator, err := createEnumerator() + if err != nil { + fmt.Printf("[!] %v\n", err) + os.Exit(1) + } + defer comReleaseDiag(enumerator) + + fmt.Println("\n=== 1. 所有渲染端点(含非活动) ===") + infos := enumRenderEndpoints(enumerator) + for i, info := range infos { + fmt.Printf(" [%d] %-40s state=%-10s id=%s\n", i, truncate(info.name, 40), stateName(info.state), info.id) + } + if len(infos) == 0 { + fmt.Println(" (无渲染端点)") + } + + fmt.Println("\n=== 2. 三种 ERole 默认渲染端点 ===") + roles := []struct { + name string + role uintptr + }{ + {"eConsole", eConsole}, + {"eMultimedia", eMultimedia}, + {"eCommunications", eCommunications}, + } + ids := make(map[string]string) + for _, r := range roles { + id, err := defaultEndpointID(enumerator, r.role) + if err != nil { + fmt.Printf(" %-16s ERROR: %v\n", r.name, err) + continue + } + ids[r.name] = id + fmt.Printf(" %-16s %s [%s]\n", r.name, id, findName(infos, id)) + } + if ids["eConsole"] != "" && ids["eConsole"] == ids["eMultimedia"] { + fmt.Println(" → eConsole 与 eMultimedia 默认端点一致(典型系统)") + } else if ids["eConsole"] != "" && ids["eMultimedia"] != "" { + fmt.Println(" → ⚠ eConsole 与 eMultimedia 默认端点不同!") + } + + fmt.Println("\n=== 3. 生产路径 GetMasterVolumePercent ===") + pct, err := windows.GetMasterVolumePercent() + if err != nil { + fmt.Printf(" [!] %v\n", err) + } else { + fmt.Printf(" 当前音量 = %d%%(此值来自 eMultimedia 默认端点,见第 2 节对应设备)\n", pct) + } + + fmt.Println("\n=== 4. IAudioEndpointVolume(eMultimedia 默认端点)===") + vol, err := openMultimediaEndpointVolume(enumerator) + if err != nil { + fmt.Printf(" [!] %v(无法继续回调/范围测试)\n", err) + } else { + defer comReleaseDiag(vol) + mindB, maxdB, incdB, err := getVolumeRange(vol) + if err != nil { + fmt.Printf(" [!] GetVolumeRange 失败: %v ← 设备可能不支持端点级音量控制(HDMI/数字输出常见)\n", err) + } else { + fmt.Printf(" GetVolumeRange: mindB=%.1f maxdB=%.1f incdB=%.1f(范围有效 → 端点支持音量控制)\n", mindB, maxdB, incdB) + } + step, stepCount, err := getVolumeStepInfo(vol) + if err != nil { + fmt.Printf(" [!] GetVolumeStepInfo 失败: %v\n", err) + } else { + fmt.Printf(" GetVolumeStepInfo: 每步 %d/%d(媒体键一次 = 1 步)\n", step, stepCount) + } + scalar, err := getScalar(vol) + if err != nil { + fmt.Printf(" [!] GetMasterVolumeLevelScalar 失败: %v\n", err) + } else { + fmt.Printf(" 当前 scalar = %.3f (%.0f%%)\n", scalar, scalar*100) + } + muted, err := getMuted(vol) + if err != nil { + fmt.Printf(" [!] GetMute 失败: %v\n", err) + } else { + fmt.Printf(" 静音 = %v\n", muted) + } + } + + fmt.Println("\n=== 5. 注册 IAudioEndpointVolumeCallback + 生产路径 COM 调节 ===") + fmt.Println(" >>> 注意:接下来会自动调节音量(+1 后恢复),请留意屏幕右下角 OSD 形态 <<<") + if vol == 0 { + fmt.Println(" [!] 无可用端点音量接口,跳过") + } else { + cb := &volumeCallback{vtbl: diagCallbackVtbl} + cbPtr := uintptr(unsafe.Pointer(cb)) + if hr := comCallDiag(vol, 3, cbPtr); hr != 0 { + fmt.Printf(" [!] RegisterControlChangeNotify 失败: hr=0x%08x\n", hr) + } else { + fmt.Println(" [i] 已注册回调(等待系统通知)") + defer comCallDiag(vol, 4, cbPtr) // UnregisterControlChangeNotify + + before := pct + upFirst := before < 99 + if upFirst { + fmt.Printf(" >>> VolumeAdjustPercent(+1) 当前 %d%%\n", before) + if err := windows.VolumeAdjustPercent(1); err != nil { + fmt.Printf(" [!] +1 失败: %v\n", err) + } + } else { + fmt.Printf(" >>> VolumeAdjustPercent(-1) 当前 %d%%(已在上限,先降后升)\n", before) + if err := windows.VolumeAdjustPercent(-1); err != nil { + fmt.Printf(" [!] -1 失败: %v\n", err) + } + } + time.Sleep(2 * time.Second) // 等待异步 OnNotify + notified := atomic.LoadInt32(&cb.notified) != 0 + cbVol := math.Float32frombits(atomic.LoadUint32(&cb.volumeBits)) + cbMuted := atomic.LoadInt32(&cb.mutedBits) != 0 + fmt.Printf(" [i] 回调 OnNotify 被调用 = %v;回调报告 volume=%.0f%% muted=%v\n", notified, cbVol*100, cbMuted) + if !notified { + fmt.Println(" [i] 未收到通知:可能是回调线程模型限制(MTA 回调可能不投递),不代表音频服务一定未广播;") + fmt.Println(" 更可靠的判据是下方第 6 步 OSD 是否完整。") + } + // 恢复 + if upFirst { + if err := windows.VolumeAdjustPercent(-1); err != nil { + fmt.Printf(" [!] 恢复 -1 失败: %v\n", err) + } + } else { + if err := windows.VolumeAdjustPercent(1); err != nil { + fmt.Printf(" [!] 恢复 +1 失败: %v\n", err) + } + } + } + } + + fmt.Println("\n=== 6. SendInput 媒体键调节(系统 Shell 处理) ===") + fmt.Println(" >>> 即将发送 VK_VOLUME_UP 一次(随后恢复),请观察 OSD 是否显示:设备名 + 滑块 + 数字 + 应用入口 <<<") + if err := sendMediaVolumeKey(true); err != nil { + fmt.Printf(" [!] 媒体键 + 失败: %v\n", err) + } else { + time.Sleep(1200 * time.Millisecond) + fmt.Println(" [i] 已发送音量+媒体键;若看到完整 OSD(含设备名/应用入口)→ 媒体键路径正确。") + if err := sendMediaVolumeKey(false); err != nil { + fmt.Printf(" [!] 媒体键 - 恢复失败: %v\n", err) + } + time.Sleep(300 * time.Millisecond) + } + + fmt.Println("\n=== 7. 结论提示 ===") + fmt.Println(" 若第 5 步 OSD 简化(仅图标+滑块+数字)而第 6 步完整:") + fmt.Println(" → 确认根因:COM 直调不经过系统 Shell 的 OSD 路径;") + fmt.Println(" → 修复方向:默认走媒体键(SendInput VK_VOLUME_*),COM 仅作精确百分比可选。") + after, _ := windows.GetMasterVolumePercent() + fmt.Printf(" 最终音量 = %d%%(应与诊断前一致或相差 1 步内)\n", after) + fmt.Println("===== 诊断结束 =====") +} + +func truncate(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n-1]) + "…" +} diff --git a/cmd/settings/.gitignore b/cmd/settings/.gitignore new file mode 100644 index 0000000..5d7826e --- /dev/null +++ b/cmd/settings/.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/cmd/settings/README.md b/cmd/settings/README.md new file mode 100644 index 0000000..ad12c3f --- /dev/null +++ b/cmd/settings/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/cmd/settings/Taskfile.yml b/cmd/settings/Taskfile.yml new file mode 100644 index 0000000..ff537fb --- /dev/null +++ b/cmd/settings/Taskfile.yml @@ -0,0 +1,65 @@ +version: '3' + +vars: + APP_NAME: "settings" + 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}} + + 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/cmd/settings/appicon.png b/cmd/settings/appicon.png new file mode 100644 index 0000000..b0a813e Binary files /dev/null and b/cmd/settings/appicon.png differ diff --git a/cmd/settings/assets/logo.ico b/cmd/settings/assets/logo.ico new file mode 100644 index 0000000..828974e Binary files /dev/null and b/cmd/settings/assets/logo.ico differ diff --git a/cmd/settings/build/Taskfile.yml b/cmd/settings/build/Taskfile.yml new file mode 100644 index 0000000..9714b9e --- /dev/null +++ b/cmd/settings/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/cmd/settings/build/android/Taskfile.yml b/cmd/settings/build/android/Taskfile.yml new file mode 100644 index 0000000..cd0eb4f --- /dev/null +++ b/cmd/settings/build/android/Taskfile.yml @@ -0,0 +1,455 @@ +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 + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: '{{.ARCH | default .HOST_ARCH}}' + 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 + deps: + - task: build + vars: + PRODUCTION: "true" + ARCH: '{{.ARCH | default .HOST_ARCH}}' + 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: [package] + 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/cmd/settings/build/android/app/build.gradle b/cmd/settings/build/android/app/build.gradle new file mode 100644 index 0000000..9c69943 --- /dev/null +++ b/cmd/settings/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/cmd/settings/build/android/app/proguard-rules.pro b/cmd/settings/build/android/app/proguard-rules.pro new file mode 100644 index 0000000..8b88c3d --- /dev/null +++ b/cmd/settings/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/cmd/settings/build/android/app/src/main/AndroidManifest.xml b/cmd/settings/build/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..03d343a --- /dev/null +++ b/cmd/settings/build/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cmd/settings/build/android/app/src/main/java/com/wails/app/MainActivity.java b/cmd/settings/build/android/app/src/main/java/com/wails/app/MainActivity.java new file mode 100644 index 0000000..7b71d3c --- /dev/null +++ b/cmd/settings/build/android/app/src/main/java/com/wails/app/MainActivity.java @@ -0,0 +1,821 @@ +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.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; + 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"); + + return new WebResourceResponse( + "application/json", + "UTF-8", + 200, + "OK", + 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