diff --git a/.gitignore b/.gitignore index 7f16709..77c517f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,26 +1,20 @@ # 编译产物 bin/ +build/ -# 可执行文件 +# 可执行文件(含 resources/ 下预编译的 watchdog.exe) *.exe *.dll -# 图标嵌入资源(构建时生成) -**/rsrc.syso - # 本地配置与日志(运行时生成) config.json *.bak logs/ -# 前端依赖与构建产物(设置进程) -node_modules/ -dist/ -*.tmp - # 其他工具的本地状态 .reasonix/ .workbuddy/ +.tmp/ # 编辑器 .vscode/ diff --git a/AGENTS.md b/AGENTS.md index 3764739..6168627 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,39 +1,212 @@ # ZerOriginToolBox(零源工具箱) -Windows 轻量自动化工具箱:Go 托盘常驻主进程 + 触发器/规则/动作引擎 + Wails v3 设置进程。 +Windows 轻量自动化工具箱:**单个 mygo 进程**(托盘常驻 + 原生 UI 设置窗口 + 触发器/规则/动作引擎) ++ watchdog 监督进程。mygo v0.9.0,Go 1.27.3,模块名 `zerorigin`。 -## 架构约束(架构基线 docs/zero-origin-toolbox-architecture.md,不得违背) +## 架构约束(基线 docs/zero-origin-toolbox-architecture.md,不得违背) -- 主进程(cmd/zerorigin)**零 WebView/Wails 依赖**,常驻低占用(目标:空闲 CPU≈0%,Working Set < 30MB); -- 设置进程(cmd/settings)是**独立 Go module**(module 名 `zerorigin-settings`),按需启动、关闭即退出; -- 监督进程(cmd/watchdog)`-supervise` 模式:捕获子进程退出码/stderr,异常死亡自动重启,`clean-quit.flag` 区分用户主动退出,崩溃循环退避(运行 <30s → 重启间隔 10s); -- 配置在 `%LOCALAPPDATA%\ZerOriginTool\config.json`(便携模式:exe 同目录 config.json 优先);原子保存 + 1s mtime 轮询热重载,损坏时生成 .bak 保留旧快照; +- **单进程**:没有独立设置进程、没有 WebView/Wails/Vue、没有 IPC。设置窗口用 + `internal/settings` 的 mygo 原生 UI,按需创建、关闭即销毁; +- 主进程(`cmd/zerorigin`)只组装;生命周期在 `internal/app`; +- 监督进程(`cmd/watchdog`)`-supervise`:捕获子进程退出码/stderr,异常死亡自动重启, + `clean-quit.flag` 区分用户主动退出,运行 <30s 的崩溃按 10s 退避; +- 配置在 `%LOCALAPPDATA%\ZerOriginTool\config.json`(便携模式:exe 同目录 config.json 优先); + 原子保存 + 1s mtime 轮询热重载,损坏时生成 .bak 保留旧快照;版本迁移走 + `internal/config/migrate_*.go` 的 `RegisterMigration`(v1→v2:滚轮音量按格、冷却清零、补底部亮度规则;v2→v3:补 + `global.notify=true`,避免旧配置缺字段被零值静音;v3→v4:每条规则补 `notify=true`,与 global.notify 成 + “与”关系;v4→v5:补 `global.osd`(提示条位置,默认底部居中、距边 64 DIP,避免零值把胶囊贴到底边)); - Windows API 封装**只允许**在 `internal/platform/windows/`,其他包不得直接加载 DLL; - 触发器只产生事件,动作不读 UI 状态,引擎不依赖 Win32 具体实现; -- 默认不要求管理员权限,不写 HKLM,不使用固定 TCP 端口做本地通信(后续 IPC 用 Named Pipe)。 +- 默认不要求管理员权限,不写 HKLM,不使用固定 TCP 端口做本地通信; +- mygo 的 `App.Run` 必须在 main goroutine;`init` 已 `LockOSThread`;窗口/托盘/菜单在 + `WhenReady` 之后创建,后台线程改 UI 用 `mygo.RunOnMain`; +- 自更新用 `plugins/updater/native`(原生窗口),**不得用 `updater.Plugin`**(WebView2 网页窗口); + 便携版就地替换 exe 所在目录内的文件,替换清单来自构建产物里的 `.mygo-files`。 ## 代码布局 -- `cmd/zerorigin` 主进程入口(仅组装,不承载业务);`cmd/settings` Wails v3 设置进程(前端 Vue3+TS+Vite 在 cmd/settings/frontend);`cmd/watchdog` 监督进程; -- `internal/app` 运行时组装;`internal/trigger`(mouse_corner / mouse_edge_wheel / hotkey);`internal/rule` 规则引擎(优先级/冷却/全屏抑制);`internal/action` 动作注册表;`internal/config` 配置模型+校验+迁移;`internal/tray` 托盘;`internal/platform/windows` Win32 集中封装;`internal/logging` slog;`internal/version` ldflags 注入; -- `docs/` 架构与 MVP 计划;`deploy/` NSIS 安装脚本与验收记录;`bin/` 编译产物(gitignore);`portable/` 便携版。 +- `cmd/zerorigin` 主进程入口(日志、SetCrashOutput、`-version`、clean-quit.flag); + `cmd/watchdog` 监督进程;`cmd/diag-volume` 音量 COM 诊断、`cmd/diag-brightness` 亮度 + DDC/CI 诊断(开发用,不随包发布); +- `internal/app` 运行时组装(单实例、配置、快照、触发器差量重建、托盘、设置窗口、退出清理; + `update.go` 注册 updater 插件并提供托盘「检查更新…」菜单项); +- `internal/settings` 设置窗口:`settings.go`(Window/Options/保存/校验)、`draft.go`(编辑副本与 + 参数转换)、`view.go`(每帧重建的原生视图); +- `internal/trigger`(mouse_corner / mouse_edge_wheel / hotkey + schema.go;滚轮按 120 的 + 整数倍按格上报,无去抖窗口); + `internal/rule` 规则引擎(优先级/冷却/全屏抑制/快照);`internal/action` 动作注册表 + (音量/亮度调节都是快进快出,慢 IO 交给内部队列/goroutine); + `internal/osd` 调节提示条(位置由 `global.osd.position/margin` 决定:上/下/左/右四选一, + 上下水平居中、左右垂直居中,边距是该边距屏幕边缘的 DIP,最后钳制进工作区;mygo 无材质透明胶囊窗口,Panel 置顶;显示前截屏 + `glass.Blur` + 自绘毛玻璃;音量/静音/亮度共用;无中文文案,图标+进度条+百分比;不受通知开关影响); + `internal/config` 配置模型+校验+迁移+热重载;`internal/platform/windows` Win32/COM 集中封装 + (含亮度 DDC/CI + gamma 兜底); + `internal/assets` 托盘 PNG(go:embed);`internal/logging` slog;`internal/version` ldflags; +- `resources/windows-amd64/` 随 exe 复制的平台资源(build.bat 编译出 watchdog.exe); + `assets/` 图标源文件;`mygo.json` mygo 应用清单;`bin/` 产物(gitignore);`portable/` 便携版。 ## 构建与验证 -- 一键构建:`build.bat`(rsrc 图标嵌入 → 主进程 → wails3 设置进程 → 便携版 → NSIS 安装包);wails3/rsrc 在 `C:\Users\AlwaysTrue\go\bin`(不在 PATH 时先 export); -- 主进程:`go build ./...`、`go test ./...`(全部包有单测,含真实 SendInput/钩子冒烟); -- 设置进程:`cd cmd/settings && wails3 build`(产物 bin/settings.exe);测试 `go test .`;**不要** `go build ./...`(build/ios 等跨平台模板无 main,报错属正常); -- 修改配置模型时必须同步 cmd/settings(config.go 校验/往返有单测保障格式兼容)。 +- 一键构建:`build.bat`(watchdog → `go tool mygo build`(含 NSIS 安装包)→ 便携版); + `build.bat quick` 跳过安装包(首次生成安装包时 mygo 会下载 NSIS); +- 签名自更新:`mygo.json` 的 `updates.publicKey` 是 Ed25519 公钥,私钥在 + `%APPDATA%\mygo\update-keys\mygo-update.key`(**绝不进仓库**,用户需自行备份;`build.bat` 会读进 + `MYGO_UPDATER_PRIVATE_KEY` 环境变量)。私钥缺失时 `go tool mygo build` 只构建、不产出更新包且不报错, + 容易误以为已经发版(构建日志里有「已加载更新签名私钥」才是有签名的构建); +- 发版顺序:改 `mygo.json` 的 `version` → 在 `CHANGELOG.md` 加同名 `## ` 小节(缺失时 mygo 报 + no notes)→ `build.bat quick` → `scripts/publish-gitea.ps1 -Owner zerorigin -Repo zerorigin-toolbox`; +- 发布脚本为什么自己写:`go tool mygo build -upload` 只支持 GitHub Release(依赖 gh CLI)或 S3 桶, + 自建 Gitea 没有内置支持。脚本用 Gitea REST API 把归档、delta、SHA256SUMS 传到**固定的 `latest` + Release**,同名 manifest **先删旧附件再传、并且最后传**(客户端一旦看到新 manifest,它指向的归档 + 必须已经存在);客户端只读 `/update-windows-amd64.json`; +- 工具链:go 与 mygo 在 `C:\Users\AlwaysTrue\go\bin`(不在 PATH 时先 export); +- `go build ./...`、`go test ./...`(action/config/rule/trigger/platform/settings 均有单测); +- `go vet ./...` 只应有 crashguard.go / win32.go 的 3 条 unsafe 警告; +- **不要**用旧 Wails/rsrc 命令;`mygo.json` 的 `name` 决定 exe 名(ZerOriginTool.exe), + 改 `name`/`identifier` 会改变自启值与单实例键,需同步迁移; +- 修改配置模型时必须同步 `internal/settings`(编辑副本/参数 Schema 有单测保障往返); +- 全局设置的合法性统一走 `config.Validate()`(返回中文问题描述),设置窗口保存前 + `validateConfig` 会把它排在规则问题前面;主进程加载/热重载先经 `config.Normalize()` + 就地修正(非法位置→bottom、空值→bottom、越界边距钳制)再记 Warn,不拒绝加载。 ## 已知坑(改相关代码前必读) -- `enumDisplayMonitors` 回调必须用**包级单例** `syscall.NewCallback`(每次新建会耗尽 2000 槽回调表 → fatal "too many callback functions",曾致主进程 10 分钟静默死亡); -- 钩子/hotkey 消息循环与 COM 操作必须 `runtime.LockOSThread`;hook Start 同步等待安装结果时先释放互斥锁(防自死锁); -- 虚拟桌面切换用 COM 直调(ImmersiveShell → IVirtualDesktopManagerInternal),**不要缓存 COM 管理器**(CoUninitialize 后 RPC 代理失效 → 0xc0000005),每次调用完整重建; +- `enumDisplayMonitors` 回调必须用**包级单例** `syscall.NewCallback`(每次新建会耗尽 2000 槽 + 回调表 → fatal "too many callback functions",曾致主进程 10 分钟静默死亡); +- 钩子消息循环与 COM 操作必须 `runtime.LockOSThread`;hook Start 同步等待安装结果时先释放互斥锁; +- 虚拟桌面切换用 COM 直调(ImmersiveShell → IVirtualDesktopManagerInternal),**不要缓存 COM 管理器** + (CoUninitialize 后 RPC 代理失效 → 0xc0000005),每次调用完整重建; - SendInput 的 INPUT 结构在 x64 下 40 字节(union 对齐),cbSize 不对会被拒绝; -- `-H windowsgui` 下 stderr 无处可去:panic 取证靠 SetCrashOutput(go-crash.log)+ VEH(crash.log)+ heartbeat.json 三件套,别破坏; -- 全屏检测(foregroundFullscreen)必须排除 Shell 桌面窗口类(Progman/WorkerW/#32769/SHELLDLL_DefView/SysListView32):空桌面时前台窗口是它们,矩形全屏且无 WS_MAXIMIZE,会被覆盖率≥95% 误判为全屏 → 所有规则被抑制(曾致空虚拟桌面切桌面/调音量失效); -- vet 对 crashguard.go / win32.go 的 unsafe.Pointer 警告是有意为之(VEH 结构解引用、回调参数恢复),不要"修复"。 +- `-H windowsgui` 下 stderr 无处可去:崩溃取证靠 crash.log(VEH)+ go-crash.log(SetCrashOutput) + + heartbeat.json 三件套,别破坏; +- 全屏检测必须排除 Shell 桌面与覆盖层窗口类(Progman/WorkerW/#32769/SHELLDLL_DefView/ + SysListView32,以及任务视图 `XamlExplorerHostIslandWindow`);否则空桌面或任务视图打开时 + 所有规则被抑制(曾表现为音量滚轮完全无反应); +- 单桌面时 `SwitchDesktopCOM` 返回 `ErrNotEnoughDesktops`,动作层**不得**回退任务视图 + (任务视图会留在前台并触发上一条全屏误判);`taskview_delay_ms <= 0` 归一化为 400ms, + 否则方向键/Enter 会在动画前发出;`method=taskview/hotkey` 在单桌面时直接返回该错误; +- 设置窗口的 `OnClose` 在主线程同步执行,禁止在其中调用 `Dialog.Message`(postMain+await 会阻塞 + 主线程);关闭即丢弃未保存修改,未保存提示只放状态行; +- mygo 原生 UI 视图每帧重建:持久状态放 `Window` 字段、控件绑定 `*string` 指针,不要绑定局部变量; + 重绘用 `c.Invalidate()`,窗口本身没有 Invalidate 方法; +- 触发器参数里空字符串有语义(如 mouse_edge_wheel 的 direction 空=任意方向),编辑副本必须把 + 「任意方向」映射为空选项而**不是**写入空字符串,否则事件匹配永远不成立; +- `mouse_edge_wheel` **没有去抖窗口**:`wheelNotcher` 以 ±120 为步进,每滚一格立刻上报一次; + 连滚 3-4 格就是 3-4 次事件,不要重新引入“同向合并”或“冷却压制”,否则手感立刻变回卡顿; +- 通知有两层开关:`global.notify`(通用设置里的总开关)与每条规则的 `notify`(规则编辑页), + 二者是**与**关系;`action.SetToastEnabled` 在 `applyConfig` 时同步总开关,规则级开关通过 + `action.WithRuleNotify(ctx, r.Notify)` 传给动作。右下角系统 Toast、`show_notification` 都受这两层控制 + (异步动作必须在启动 goroutine 前捕获 `NotificationsAllowed(ctx)`);调节提示条**不受** + 通知开关影响,始终显示。音量/静音动作的 `toast` 参数仍为**默认 false**,不额外叠桌面通知; +- 音量步进是**百分比**:媒体键每次约 2%,所以奇数步进(如 1%)会自动改用 COM 精确 + 调节,避免把 1% 调成 2%;显式 com 路径失败时回退媒体键。COM 调节不会触发 Shell 音量 OSD, + 因此音量/静音 COM 路径读回状态后调用 `osd.ShowVolume/ShowMute`;媒体键路径自带系统 OSD, + 不叠自绘提示条(避免双层提示); +- 音量/亮度动作必须立即返回:媒体键路径发完键就返回(读回/通知放 goroutine),亮度走 + `brightnessQueue` 累加合并,DDC/CI 的阻塞 IO 绝不能跑在事件循环的同步路径上; +- 亮度显示器枚举回调必须是**包级单例**(`enumMonitorHandlesCB` + 包级缓冲),不要用 + `syscall.NewCallback` 每次重建或 unsafe 转 lParam,否则会耗尽回调槽或触发 vet 警告; +- OSD 窗口必须用 `WindowOptions{X,Y}` 在创建时定位:mygo v0.9.0 的 `SetPosition` 对已创建/已显示的 + 透明提示条窗口实测无效(窗口停在首次创建位置)。目标位置(鼠标所在显示器工作区)变化时销毁旧窗再建新窗; + 窗口设 `Panel:true`,浮于全屏应用之上并跨虚拟桌面。显示用 `ShowInactive`,再 + `SetIgnoreMouseEvents(true)`,不抢焦点、鼠标穿透。隐藏用 2.2s 计时器(`displayDuration`),连续调节只重置计时不重建窗口; + 鼠标停在提示条上、或停在胶囊外 120 DIP 容差内(`reachMargin`,给"伸手去够"的时间)时改为每 150ms 复查 + (`hideWhenIdle` → `rescheduleHover`,最多续 20 次),悬停期间不消失,移开后最迟一个复查周期(150ms)内隐藏; + 穿透窗口收不到鼠标消息,悬停与滚轮都靠屏幕坐标判断(`osd.PointerInsideAt` + `pwin.CursorPos`), + `internal/app/osdwheel.go` 用独立全局鼠标钩子接管提示条上的交互:`MouseHook.SetFilter` 在钩子线程 + 判定并标记 `Blocked`,回调 `return 1` 不再 `CallNextHookEx`,系统就不会把滚轮/点击派发给底下的应用 + (否则在胶囊上滚动会带着背景应用一起滚);过滤器必须立即返回,只做坐标判断与原子读取。 + **拖动状态机必须跑在钩子回调线程里**:down/move/up 在过滤器内同步更新原子量(`osdDrag.active/percent`), + 只把非阻塞通知(1 槽 channel)丢给后台协程去做平台调用和提示条重绘。早期版本把拖动判定放在 + `hook.Events()` 的消费协程,64 槽缓冲被 1000Hz 的真实鼠标移动灌满后 down/up 被丢弃, + 表现为"真实鼠标拖拽完全失效"(注入的稀疏事件看不出来);`osd` 的几何因此也改成原子快照 + `geomX/geomW/geomVisible`(钩子线程不能持锁)。 + 滚轮按 `osd.CurrentKind()` 沿用配置里音量/亮度动作的步进继续调节,且不弹通知(提示条本身就是反馈); + 左键按下开始拖动,`osd.PercentAt(x, y)` 按朝向选轴:上下位置用横坐标(`PercentAtX`,`trackLeft=42`/ + `trackWidth=152`),左右位置用纵坐标(`PercentAtY`,`trackTop=54`/`trackHeight=152`,从下往上增长), + 这些常量必须与 `horizontalView`/`verticalView` 的布局一致,并按实际窗口尺寸折算 DPI;拖动期间 + `osd.SetDragging(true)` 阻止隐藏、吞掉按下/抬起, + 目标值用「有界通知 + 原子最新值」合并后调 `pwin.SetMasterVolumePercent`/`pwin.SetBrightness`; + 绝对设置不要做「与上次相同就跳过」的去重(外部改过音量后拖到相同百分比会失效); +- **不要用 DWM 的 Acrylic/Mica 做提示条材质**:透明窗口使用 WS_EX_NOREDIRECTIONBITMAP, + `ShowInactive` 时 Acrylic 会退化成实心深灰(白底实测仍是 RGB 45,45,47),单设 `Panel:true` 不够。 + **也不能只靠 `plugins/glass` 换材质**:glass 的 backdrop 只采样同一窗口帧里此前绘制的内容 + (`internal/scene/effect.go` 的 Backdrop 语义 + `plugins/glass/effect.go` 的 `Effect{Backdrop:true}`), + 不采样窗口外的桌面,独立透明覆盖窗必须自己截屏铺底图。现在在窗口隐藏时用 `pwin.WindowRect` + + `pwin.CaptureRect` 截取窗口下方桌面,存成**未模糊**的 `ui.Bitmap`(`shot`),视图按三层叠: + ① 截屏层 `Draw` 里 `p.Clip(胶囊圆角)` → `p.Image(shot, r, ui.Cover)`;② 模糊层 `Absolute` 四边贴齐 + + `.Radius(胶囊圆角)` + `.Material(glass.Blur{Radius: backdropBlurDIP})`(半径是 DIP,插件内部乘渲染缩放); + ③ 面板层 `Draw` 画 `p.Fill` 半透明底 → 顶部高光/底部暗部 → 内外描边。三层顺序不能变:模糊层 + 必须在截屏层之后、面板层之前,顺序反了只剩一片空白模糊。**不要用 `glass.Glass`(Liquid Glass)当 + 提示条材质**:它的色调映射会把桌面压成深色实体玻璃,260×52 又低于 Clarity 的最小窗格尺寸,细节全丢。 + **不要设置 `WindowOptions.BackgroundColor`**:mygo 的 + `SetBackgroundColor` 用 `CreateSolidBrush` 且忽略 alpha,`"#00000000"` 会变成不透明黑底, + 胶囊外露出一圈黑框。截屏失败时 `shot=nil`,退化为纯深色半透明面板; +- **鼠标光感(hover glow)**:光标进入胶囊时点亮一层跟随指针的径向柔光。位置来源是钩子线程写的 + 原子量 `osd.SetHover(x, y)`/`osd.ClearHover()`(`internal/app/osdwheel.go` 的 `WmMouseMove` 分支, + 只做坐标判断 + 原子写,过滤器必须立即返回);**绝不能在钩子回调里调 `mygo.RunOnMain`**, + 它内部 `onMain` post 后 `<-done` 同步等待(loop.go),会把全系统鼠标拖慢; + `osd` 用 1 槽 channel `hoverCh` + 常驻 `redrawLoop` 协程把重绘投回主线程(`win.Invalidate()`), + 并用 `lastHoverPaint` 做 16ms 节流(1000Hz 鼠标不能每帧重绘)。光效层是 `backdropLayers` 的 + 第 4 层(`Draw(drawHover)`,在面板层之后、内容层之前,避免冲淡图标与百分比): + `p.Clip(胶囊圆角)` 内两次 `p.FillRadialGradient`,Center 用 `hoverCenter()` 把屏幕像素换算成 + 窗口内 0-1 坐标(`clamp01` 钳制,拖动时光标会移出胶囊),大柔光半径 `hoverGlowRadius=62` + 白 0.20→0、小亮核 `hoverCoreRadius=18` 白 0.26→0(半径一开始取 170/54 会整块发亮、看不出跟随); + `drawPanel` 同时读 `hoverOn` 提亮(顶部高光 0.24→0.34、内侧 0.10→0.22、外描边 0.18→0.38), + `panelColorFor(lit)` 把底色压淡到 0.22——玻璃"被照亮"靠更透 + 柔光,不是盖一层白。 + **`hoverOn.Store(false)` 只能放在新建窗口的分支里**:滚轮/拖动每调一格都会走 show→showOnMain, + 放在那里会把光效反复熄灭(鼠标不动只滚轮时彻底灭掉); +- **提示条背景必须跟随屏幕变化**:底图只在创建时截一次,切到别的窗口/黑界面后胶囊里还是旧背景。 + 重截必须在窗口**隐藏**时做(显示时 BitBlt 会把胶囊自己截进底图,形成鬼影);而 + `SetWindowDisplayAffinity(WDA_EXCLUDEFROMCAPTURE)` 救不了——实测排除后 BitBlt(GetDC(NULL)+SRCCOPY) + 得到的是**纯黑**而不是下层窗口内容,不能用它做"显示期间重截"。现在的做法:常驻 `backdropLoop` + 每 150ms(`backdropWatchInterval`)用 `pwin.ScreenPixel` 采样胶囊**四角透明区**(窗口内、圆角 + 之外,`inset=4` 的四个点取平均——透明窗口不参与合成,读到的是 DWM 合成后的真实背景), + 与 `backdropBase` 比:`backdropDelta`(三通道平均差)≥ `backdropColorDelta`(24) 且距上次重截 + ≥ `backdropReshotGap`(600ms) 时执行 `win.Hide() → pwin.FlushDwm() → refreshShot() → ShowInactive()`; + **`FlushDwm` 不能省**:不等"没有胶囊"的那一帧合成完,BitBlt 读到的还是旧画面。 + 连续调节/悬停/拖动(背景没变)只做 4 次 GetPixel,不重绘也不闪烁;`backdropBase` 在显示与隐藏时 + 都重置为 `{-1,-1,-1}`,重截后的第一次采样只建立基准、不再触发重截; +- 提示条窗口尺寸即胶囊尺寸(横向 260×52、竖向 52×260 DIP,**没有投影留白**),窗口圆角与面板半径 + 都是短边的一半(26 DIP),**两端必须是完整半圆**;定位直接用胶囊坐标; + **左右两侧(`position` 为 left/right)时胶囊竖起来**:窗口变 52×260(`sizeFor` 决定尺寸,`positionIn` + 依旧按位置贴边、另一方向居中),视图走 `verticalView`:图标在上、4px 竖向进度条(`trackThickness`)在中、 + 百分比文字在最下且**保持正向横排**(不旋转,避免歪头看);竖向进度条必须从下往上增长(下面填充 Box + 权重 = 百分比、上面透明 Box 权重 = 剩余); + **界面里不要放中文标题或「音/亮/静」方块**:左侧 18px SVG 图标(喇叭/静音叉/太阳)、中间 4px 进度条、 + 右侧 14px 百分比;读屏名称用根 `Label`(如「音量 60%」),不参与绘制。面板底色 + `ui.RGBA(14,14,18,0.30)`、外描边白色 0.18、内侧反光边白色 0.10,文字白色带 + `TextShadow(0,1,4,0.50)`;立体感只靠顶部 0.24→0 的高光渐变 + 底部 0.22→0 的暗部渐变, + **不要加外投影**(投影需要在窗口内留透明空间,用户明确要求去掉阴影);根视图必须 + `c.Root().Background(ui.Transparent)`,否则根背景会盖住自绘的桌面模糊; +- mygo 会给 `Panel` / `Frameless+CornerRadius` 窗口设置 `DWMWCP_ROUND`,Windows 11 于是沿窗口的 + 8px 圆角画系统边框并在窗口外投阴影,在 26px 胶囊外露出一圈**圆角矩形**。窗口创建后必须调用 + `pwin.PrepareOverlayWindow(hwnd)`:`DWMWA_WINDOW_CORNER_PREFERENCE(33)=DWMWCP_DONOTROUND(1)` + + `DWMWA_BORDER_COLOR(34)=DWMWA_COLOR_NONE(0xFFFFFFFE)`。**必须同时关圆角**:只关边框实测仍有 + 轮廓,关掉圆角后窗口变直角、四角透明,窗口外非背景像素为 0;旧系统不支持时静默忽略; +- DDC/CI 的百分比读回按 min/max 量化,标称 +5% 实测可能只 +4%,这是硬件取整不是 bug; +- OSD 进度条的轨道是 `ui.Row`:只放一个 `Grow(pct)` 填充 Box 会让唯一子节点独占整条轨道, + 进度条永远 100%;必须同时放透明剩余 Box `Grow(100-pct)`,两者权重合计 100(`barWeights` 有单测); +- 亮度百分比是**多台物理显示器 DDC/CI 读数的平均值**。某台显示器 `SetMonitorBrightness` 返回成功 + 但读回不变(DDC/CI 被关闭或只读)时,平均值会停在低于 100 的上限(本机 Panda 75 + Philips 100 = 87); + 调试亮度必须逐显示器读 min/cur/max,别拿平均值判断成败;提示条百分比显示的是请求值,可调的屏会精确跟随; + 这是硬件/DDC 限制,不要伪造读数或强行用 gamma 凑 100; +- 便携模式下 mygo 的 window-state.json 也写在 exe 同目录,与 config.json 一起构成便携数据; +- 自更新有三条硬前提,缺一条就**静默不做后台检查**:`updates.publicKey` 非空、构建时注入了 feed + (`updates.github` 或 `updates.url`,二者互斥)、`!IsDev()`,并且 exe 所在目录可写(`mygo.Updater.Enabled()`); +- 发布源是自建 Gitea:`updates.url` = `https://git.zerorigin.cn/zerorigin/zerorigin-toolbox/releases/download/latest` + (2026-11-16 实测:TLS 正常、匿名可下载、单附件上限 100MB、`allowed_types` 含 `.gz`/`.json` 但**不含 + `.delta`**,所以 delta 上传会被拒、脚本直接跳过)。`updates.github` 天然写死 github.com + (`cmd/mygo/updates.go:126`),国内网络常连接超时(实测 `dial tcp 20.6.7.17:443`),不要换回去; +- 固定 tag `latest` 是 URL 的一部分:**改名等于换渠道**,已发出去的 exe 不会跟过来;Release `latest` + 里的附件不能删,删了客户端就再也检查不到更新; +- 更新重启**不写** `clean-quit.flag`:watchdog 发现同名的重启后进程要用 `waitForRelaunch` + (`cmd/watchdog/main.go`)判成更新重启并继续被动监视,否则会当成崩溃抓快照 + 再拉起一次; +- 更新只替换 `.mygo-files` 列出的文件(ZerOriginTool.exe、watchdog.exe),便携数据(config.json、 + window-state.json、updater.json)自然保留;被替换的旧文件先改名成 `..old-`,由下次启动的 + `cleanUpdateLeftovers` 清掉; +- 插件窗口语言固定 `updater.Options{Language: "zh"}`(`internal/app/update.go`),不要依赖系统语言; +- vet 对 crashguard.go / win32.go 的 unsafe.Pointer 警告是有意为之,不要"修复"。 ## 风格 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f4db333 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +# 更新日志 + +mygo 构建会用 `## ` 段落作为更新窗口里的发布说明:发新版本时先把 +`mygo.json` 的 `version` 改掉,再在下面加一段同名小节,否则 `mygo build` 会报 +“CHANGELOG.md has no notes for ”。 + +## 0.2.0 - 2026-11-16 + +首个 mygo 单进程版本。 + +- 单进程常驻托盘:mygo 原生设置窗口、触发器/规则/动作引擎、watchdog 监督进程 +- 触发器:鼠标角落、鼠标边缘滚轮(按格上报,无去抖)、全局热键;支持优先级、冷却与全屏抑制 +- 调节提示条:截屏 + glass.Blur 自绘毛玻璃胶囊,音量/静音/亮度共用,左右位时可竖排, + 背景跟随屏幕变化,支持按住拖动与悬停不消失 +- 亮度走 DDC/CI(多屏取平均,失败回退 gamma),音量走 Core Audio COM(奇数步进也精确) +- 配置热重载、便携模式、崩溃取证三件套(crash.log / go-crash.log / heartbeat.json) +- 支持签名自更新:托盘「检查更新…」,装完可立即重启,便携数据不受影响 diff --git a/README.md b/README.md new file mode 100644 index 0000000..e2a776e --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# ZerOriginToolBox(零源工具箱) + +Windows 轻量自动化工具箱:**单个 mygo 进程**(托盘常驻 + 原生设置窗口 + 触发器/规则/动作引擎) ++ watchdog 监督进程。无 WebView、无 IPC、默认不需要管理员权限。 + +- 鼠标角落 / 屏幕边缘滚轮 / 全局热键 三类触发器,支持优先级、冷却与全屏抑制; +- 音量走 Core Audio COM、亮度走 DDC/CI,调节时弹出截图 + `glass.Blur` 自绘毛玻璃提示条; +- 配置热重载、便携模式、崩溃取证三件套(crash.log / go-crash.log / heartbeat.json); +- 托盘「检查更新…」,便携版可**签名自更新**(Ed25519,就地替换 exe 与 watchdog.exe)。 + +架构与踩坑记录见 [`AGENTS.md`](AGENTS.md) 与 [`docs/zero-origin-toolbox-architecture.md`](docs/zero-origin-toolbox-architecture.md)。 + +## 这个仓库同时承担两件事 + +1. **源码**:`cmd/`(zerorigin 主进程、watchdog、诊断工具)、`internal/`、`docs/`。 +2. **自更新分发**:**请不要删除或改名 Release `latest` 里的附件**。那是便携版客户端检查更新用的 + `updates.url`,URL 已经写死进每一个已发布的 exe,删掉就等于让所有用户断更。 + +## 发版流程 + +1. 改 `mygo.json` 的 `version`; +2. 在 `CHANGELOG.md` 里加 `## <版本号>` 段(mygo 用它做更新窗口的发布说明); +3. `build.bat quick`(需要 `%APPDATA%\mygo\update-keys\mygo-update.key` 才会签名并产出更新包); +4. 发布: + + ```powershell + $env:GITEA_TOKEN = "<个人访问令牌>" + ./scripts/publish-gitea.ps1 -Owner zerorigin -Repo zerorigin-toolbox + ``` + +脚本会先传归档与 delta,最后传 manifest,并先删除同名的旧 manifest 附件。 diff --git a/app.manifest b/app.manifest deleted file mode 100644 index d234394..0000000 --- a/app.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - PerMonitorV2 - - - diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000..5fe0690 Binary files /dev/null and b/assets/icon.png differ diff --git a/assets/tray.png b/assets/tray.png new file mode 100644 index 0000000..23ebd09 Binary files /dev/null and b/assets/tray.png differ diff --git a/build.bat b/build.bat index ac2ab61..cbc0fdc 100644 --- a/build.bat +++ b/build.bat @@ -1,57 +1,62 @@ @echo off chcp 65001 >nul cd /d "%~dp0" +setlocal -rem 防止外部环境(如 NODE_ENV=production)导致 npm 跳过 devDependencies -rem (vite/vue-tsc 不装 → wails3 build 报 'vue-tsc' is not recognized) -set NODE_ENV=development -set NPM_CONFIG_PRODUCTION=false +rem 构建 ZerOriginToolBox(mygo 单进程版) +rem build.bat 完整构建:watchdog + 应用 + 便携版 + NSIS 安装包 +rem build.bat quick 快速构建:跳过安装包 + +set SKIP_INSTALLER= +if /i "%~1"=="quick" set SKIP_INSTALLER=-skip-installer echo [build] 终止旧进程... -taskkill /f /im zerorigin.exe >nul 2>&1 -taskkill /f /im ZerOriginTool-Settings.exe >nul 2>&1 +taskkill /f /im ZerOriginTool.exe >nul 2>&1 +taskkill /f /im watchdog.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) +rem Go 工具链与 mygo 插件都在 GOPATH\bin,确保可直接调用。 +set "GOPATH=" +for /f "tokens=*" %%i in ('go env GOPATH 2^>nul') do set "GOPATH=%%i" +if not defined GOPATH set "GOPATH=%USERPROFILE%\go" +set "PATH=%GOPATH%\bin;%PATH%" -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 +rem 自更新签名私钥:不进仓库,默认读 mygo keygen 的默认位置。 +rem 带私钥构建会额外产出 --.tar.gz、delta 与 update-.json; +rem 没有私钥时只构建应用,不产出更新文件(mygo 只是警告,不报错)。 +if not defined MYGO_UPDATER_PRIVATE_KEY ( + if exist "%APPDATA%\mygo\update-keys\mygo-update.key" ( + set /p MYGO_UPDATER_PRIVATE_KEY=<"%APPDATA%\mygo\update-keys\mygo-update.key" + ) +) +if defined MYGO_UPDATER_PRIVATE_KEY ( + echo [build] 已加载更新签名私钥,将产出签名更新包 +) else ( + echo [build] 未找到更新签名私钥(%APPDATA%\mygo\update-keys\mygo-update.key),只构建不签名 +) -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... +if not exist resources\windows-amd64 mkdir resources\windows-amd64 +go build -trimpath -ldflags="-s -w -H windowsgui" -o resources\windows-amd64\watchdog.exe .\cmd\watchdog +if errorlevel 1 goto fail_watchdog -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] 打包应用(mygo:可执行文件 + 资源 + 安装包)... +go tool mygo build -platform windows/amd64 %SKIP_INSTALLER% +if errorlevel 1 goto fail_mygo 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 +copy /y bin\windows-amd64\ZerOriginTool.exe portable\ZerOriginTool.exe >nul +copy /y bin\windows-amd64\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\windows-amd64\*.exe +echo 便携版:portable\ +exit /b 0 -echo [build] 完成: -dir /b bin\*.exe -echo 便携版:portable\(含两个 exe 与说明) +:fail_watchdog +echo [build] watchdog 编译失败! +exit /b 1 + +:fail_mygo +echo [build] mygo 打包失败! +exit /b 1 diff --git a/cmd/diag-brightness/main.go b/cmd/diag-brightness/main.go new file mode 100644 index 0000000..5c4032a --- /dev/null +++ b/cmd/diag-brightness/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + + pwin "zerorigin/internal/platform/windows" +) + +// diag-brightness 打印屏幕亮度能力与调节结果,用于排查 DDC/CI 支持情况。 +func main() { + info, err := pwin.GetBrightness() + fmt.Printf("get: percent=%d monitors=%d total=%d gamma=%v err=%v\n", + info.Percent, info.Monitors, info.Total, info.Gamma, err) + + info, err = pwin.AdjustBrightness(0) + fmt.Printf("adjust(0): percent=%d monitors=%d total=%d gamma=%v err=%v\n", + info.Percent, info.Monitors, info.Total, info.Gamma, err) +} diff --git a/cmd/diag-volume/main.go b/cmd/diag-volume/main.go index 605f6e4..2cf36ab 100644 --- a/cmd/diag-volume/main.go +++ b/cmd/diag-volume/main.go @@ -3,13 +3,13 @@ // 目标:确认"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 +// 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 形态。 @@ -51,14 +51,14 @@ func guidFromString(s string) comGUID { } 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") + 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 ( @@ -70,17 +70,17 @@ var ( ) const ( - eRender = 0 - eConsole = 0 - eMultimedia = 1 - eCommunications = 2 - deviceStateMaskAll = 0x0F // ACTIVE|DISABLED|NOTPRESENT|UNPLUGGED - clsctxAll = 0x17 + 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" + stgmRead = 0 + vtLPWSTR = 31 + friendlyNamePID = 14 + friendlyNameFmtID = "A45C254E-DF1C-4EFD-8020-67D146A850E0" ) // comCallDiag 调用 COM 接口 vtable 方法,返回 HRESULT。 diff --git a/cmd/settings/.gitignore b/cmd/settings/.gitignore deleted file mode 100644 index 5d7826e..0000000 --- a/cmd/settings/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.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 deleted file mode 100644 index ad12c3f..0000000 --- a/cmd/settings/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# 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 deleted file mode 100644 index ff537fb..0000000 --- a/cmd/settings/Taskfile.yml +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index b0a813e..0000000 Binary files a/cmd/settings/appicon.png and /dev/null differ diff --git a/cmd/settings/assets/logo.ico b/cmd/settings/assets/logo.ico deleted file mode 100644 index 828974e..0000000 Binary files a/cmd/settings/assets/logo.ico and /dev/null differ diff --git a/cmd/settings/build/Taskfile.yml b/cmd/settings/build/Taskfile.yml deleted file mode 100644 index 9714b9e..0000000 --- a/cmd/settings/build/Taskfile.yml +++ /dev/null @@ -1,398 +0,0 @@ -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 deleted file mode 100644 index cd0eb4f..0000000 --- a/cmd/settings/build/android/Taskfile.yml +++ /dev/null @@ -1,455 +0,0 @@ -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 deleted file mode 100644 index 9c69943..0000000 --- a/cmd/settings/build/android/app/build.gradle +++ /dev/null @@ -1,83 +0,0 @@ -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 deleted file mode 100644 index 8b88c3d..0000000 --- a/cmd/settings/build/android/app/proguard-rules.pro +++ /dev/null @@ -1,12 +0,0 @@ -# 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 deleted file mode 100644 index 03d343a..0000000 --- a/cmd/settings/build/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 deleted file mode 100644 index 7b71d3c..0000000 --- a/cmd/settings/build/android/app/src/main/java/com/wails/app/MainActivity.java +++ /dev/null @@ -1,821 +0,0 @@ -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