迁移到 mygo 单进程架构并接入签名自更新

- 单进程:托盘常驻 + 原生设置窗口(internal/settings),移除 Wails 前端与 IPC
- 触发器(鼠标角落 / 边缘滚轮 / 热键)+ 规则引擎 + 动作注册表
- 调节提示条:截屏 + glass.Blur 三层毛玻璃、背景跟随屏幕变化、悬停光感与拖动
- 音量 Core Audio COM、亮度 DDC/CI(gamma 兜底)、多显示器求平均
- 配置热重载 + 版本迁移 v1→v5、便携模式、崩溃取证三件套
- updater/native 插件 + 托盘「检查更新…」,watchdog 识别更新重启
- 自建 Gitea 发布:scripts/publish-gitea.ps1(updates.url 指向 latest Release)
This commit is contained in:
zerorigin committed 2026-11-16 10:31:44 +08:00
1 parent 814012ec52
commit 0b8b9b0775
202 files changed
+7254 -13572

No files matched your search

+3 -9
View File
@@ -1,26 +1,20 @@
# 编译产物 # 编译产物
bin/ bin/
build/
# 可执行文件 # 可执行文件(含 resources/ 下预编译的 watchdog.exe)
*.exe *.exe
*.dll *.dll
# 图标嵌入资源(构建时生成)
**/rsrc.syso
# 本地配置与日志(运行时生成) # 本地配置与日志(运行时生成)
config.json config.json
*.bak *.bak
logs/ logs/
# 前端依赖与构建产物(设置进程)
node_modules/
dist/
*.tmp
# 其他工具的本地状态 # 其他工具的本地状态
.reasonix/ .reasonix/
.workbuddy/ .workbuddy/
.tmp/
# 编辑器 # 编辑器
.vscode/ .vscode/
+193 -20
View File
@@ -1,39 +1,212 @@
# ZerOriginToolBox(零源工具箱) # 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); - **单进程**:没有独立设置进程、没有 WebView/Wails/Vue、没有 IPC。设置窗口用
- 设置进程(cmd/settings)是**独立 Go module**(module 名 `zerorigin-settings`),按需启动、关闭即退出; `internal/settings` 的 mygo 原生 UI,按需创建、关闭即销毁;
- 监督进程(cmd/watchdog)`-supervise` 模式:捕获子进程退出码/stderr,异常死亡自动重启,`clean-quit.flag` 区分用户主动退出,崩溃循环退避(运行 <30s → 重启间隔 10s); - 主进程(`cmd/zerorigin`)只组装;生命周期在 `internal/app`;
- 配置在 `%LOCALAPPDATA%\ZerOriginTool\config.json`(便携模式:exe 同目录 config.json 优先);原子保存 + 1s mtime 轮询热重载,损坏时生成 .bak 保留旧快照; - 监督进程(`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; - Windows API 封装**只允许**在 `internal/platform/windows/`,其他包不得直接加载 DLL;
- 触发器只产生事件,动作不读 UI 状态,引擎不依赖 Win32 具体实现; - 触发器只产生事件,动作不读 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` 监督进程; - `cmd/zerorigin` 主进程入口(日志、SetCrashOutput、`-version`、clean-quit.flag);
- `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 注入; `cmd/watchdog` 监督进程;`cmd/diag-volume` 音量 COM 诊断、`cmd/diag-brightness` 亮度
- `docs/` 架构与 MVP 计划;`deploy/` NSIS 安装脚本与验收记录;`bin/` 编译产物(gitignore);`portable/` 便携版。 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); - 一键构建:`build.bat`(watchdog → `go tool mygo build`(含 NSIS 安装包)→ 便携版);
- 主进程:`go build ./...`、`go test ./...`(全部包有单测,含真实 SendInput/钩子冒烟); `build.bat quick` 跳过安装包(首次生成安装包时 mygo 会下载 NSIS);
- 设置进程:`cd cmd/settings && wails3 build`(产物 bin/settings.exe);测试 `go test .`;**不要** `go build ./...`(build/ios 等跨平台模板无 main,报错属正常); - 签名自更新:`mygo.json` 的 `updates.publicKey` 是 Ed25519 公钥,私钥在
- 修改配置模型时必须同步 cmd/settings(config.go 校验/往返有单测保障格式兼容)。 `%APPDATA%\mygo\update-keys\mygo-update.key`(**绝不进仓库**,用户需自行备份;`build.bat` 会读进
`MYGO_UPDATER_PRIVATE_KEY` 环境变量)。私钥缺失时 `go tool mygo build` 只构建、不产出更新包且不报错,
容易误以为已经发版(构建日志里有「已加载更新签名私钥」才是有签名的构建);
- 发版顺序:改 `mygo.json` 的 `version` → 在 `CHANGELOG.md` 加同名 `## <version>` 小节(缺失时 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,它指向的归档
必须已经存在);客户端只读 `<updates.url>/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 分钟静默死亡); - `enumDisplayMonitors` 回调必须用**包级单例** `syscall.NewCallback`(每次新建会耗尽 2000 槽
- 钩子/hotkey 消息循环与 COM 操作必须 `runtime.LockOSThread`;hook Start 同步等待安装结果时先释放互斥锁(防自死锁); 回调表 → fatal "too many callback functions",曾致主进程 10 分钟静默死亡);
- 虚拟桌面切换用 COM 直调(ImmersiveShell → IVirtualDesktopManagerInternal),**不要缓存 COM 管理器**(CoUninitialize 后 RPC 代理失效 → 0xc0000005),每次调用完整重建; - 钩子消息循环与 COM 操作必须 `runtime.LockOSThread`;hook Start 同步等待安装结果时先释放互斥锁;
- 虚拟桌面切换用 COM 直调(ImmersiveShell → IVirtualDesktopManagerInternal),**不要缓存 COM 管理器**
(CoUninitialize 后 RPC 代理失效 → 0xc0000005),每次调用完整重建;
- SendInput 的 INPUT 结构在 x64 下 40 字节(union 对齐),cbSize 不对会被拒绝; - SendInput 的 INPUT 结构在 x64 下 40 字节(union 对齐),cbSize 不对会被拒绝;
- `-H windowsgui` 下 stderr 无处可去:panic 取证靠 SetCrashOutput(go-crash.log)+ VEH(crash.log)+ heartbeat.json 三件套,别破坏; - `-H windowsgui` 下 stderr 无处可去:崩溃取证靠 crash.log(VEH)+ go-crash.log(SetCrashOutput)
- 全屏检测(foregroundFullscreen)必须排除 Shell 桌面窗口类(Progman/WorkerW/#32769/SHELLDLL_DefView/SysListView32):空桌面时前台窗口是它们,矩形全屏且无 WS_MAXIMIZE,会被覆盖率≥95% 误判为全屏 → 所有规则被抑制(曾致空虚拟桌面切桌面/调音量失效); + heartbeat.json 三件套,别破坏;
- vet 对 crashguard.go / win32.go 的 unsafe.Pointer 警告是有意为之(VEH 结构解引用、回调参数恢复),不要"修复"。 - 全屏检测必须排除 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)自然保留;被替换的旧文件先改名成 `.<name>.old-<pid>`,由下次启动的
`cleanUpdateLeftovers` 清掉;
- 插件窗口语言固定 `updater.Options{Language: "zh"}`(`internal/app/update.go`),不要依赖系统语言;
- vet 对 crashguard.go / win32.go 的 unsafe.Pointer 警告是有意为之,不要"修复"。
## 风格 ## 风格
+17
View File
@@ -0,0 +1,17 @@
# 更新日志
mygo 构建会用 `## <version>` 段落作为更新窗口里的发布说明:发新版本时先把
`mygo.json` 的 `version` 改掉,再在下面加一段同名小节,否则 `mygo build` 会报
“CHANGELOG.md has no notes for <version>”。
## 0.2.0 - 2026-11-16
首个 mygo 单进程版本。
- 单进程常驻托盘:mygo 原生设置窗口、触发器/规则/动作引擎、watchdog 监督进程
- 触发器:鼠标角落、鼠标边缘滚轮(按格上报,无去抖)、全局热键;支持优先级、冷却与全屏抑制
- 调节提示条:截屏 + glass.Blur 自绘毛玻璃胶囊,音量/静音/亮度共用,左右位时可竖排,
背景跟随屏幕变化,支持按住拖动与悬停不消失
- 亮度走 DDC/CI(多屏取平均,失败回退 gamma),音量走 Core Audio COM(奇数步进也精确)
- 配置热重载、便携模式、崩溃取证三件套(crash.log / go-crash.log / heartbeat.json)
- 支持签名自更新:托盘「检查更新…」,装完可立即重启,便携数据不受影响
+31
View File
@@ -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 附件。
-20
View File
@@ -1,20 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

+47 -42
View File
@@ -1,57 +1,62 @@
@echo off @echo off
chcp 65001 >nul chcp 65001 >nul
cd /d "%~dp0" cd /d "%~dp0"
setlocal
rem 防止外部环境(如 NODE_ENV=production)导致 npm 跳过 devDependencies rem 构建 ZerOriginToolBox(mygo 单进程版)
rem (vite/vue-tsc 不装 → wails3 build 报 'vue-tsc' is not recognized) rem build.bat 完整构建:watchdog + 应用 + 便携版 + NSIS 安装包
set NODE_ENV=development rem build.bat quick 快速构建:跳过安装包
set NPM_CONFIG_PRODUCTION=false
set SKIP_INSTALLER=
if /i "%~1"=="quick" set SKIP_INSTALLER=-skip-installer
echo [build] 终止旧进程... echo [build] 终止旧进程...
taskkill /f /im zerorigin.exe >nul 2>&1 taskkill /f /im ZerOriginTool.exe >nul 2>&1
taskkill /f /im ZerOriginTool-Settings.exe >nul 2>&1 taskkill /f /im watchdog.exe >nul 2>&1
echo [build] 生成主进程图标资源 (rsrc.syso)... rem Go 工具链与 mygo 插件都在 GOPATH\bin,确保可直接调用。
for /f "tokens=*" %%i in ('go env GOPATH') do set "GOPATH=%%i" set "GOPATH="
"%GOPATH%\bin\rsrc.exe" -ico assets\logo.ico -manifest app.manifest -o cmd\zerorigin\rsrc.syso for /f "tokens=*" %%i in ('go env GOPATH 2^>nul') do set "GOPATH=%%i"
if %errorlevel% neq 0 (echo [build] rsrc 失败! && exit /b 1) if not defined GOPATH set "GOPATH=%USERPROFILE%\go"
set "PATH=%GOPATH%\bin;%PATH%"
echo [build] 编译主进程... rem 自更新签名私钥:不进仓库,默认读 mygo keygen 的默认位置。
go build -ldflags="-s -w -H windowsgui -X zerorigin/internal/version.Version=0.1.0" -o bin\ZerOriginTool.exe .\cmd\zerorigin rem 带私钥构建会额外产出 <slug>-<version>-<target>.tar.gz、delta 与 update-<target>.json;
if %errorlevel% neq 0 (del cmd\zerorigin\rsrc.syso 2>nul && echo [build] 编译失败! && exit /b 1) rem 没有私钥时只构建应用,不产出更新文件(mygo 只是警告,不报错)。
del cmd\zerorigin\rsrc.syso 2>nul 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)... echo [build] 编译监督进程 watchdog...
set PATH=%GOPATH%\bin;%PATH% if not exist resources\windows-amd64 mkdir resources\windows-amd64
pushd cmd\settings go build -trimpath -ldflags="-s -w -H windowsgui" -o resources\windows-amd64\watchdog.exe .\cmd\watchdog
call wails3 build if errorlevel 1 goto fail_watchdog
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)... echo [build] 打包应用(mygo:可执行文件 + 资源 + 安装包)...
go build -ldflags="-s -w -H windowsgui" -o bin\watchdog.exe .\cmd\watchdog go tool mygo build -platform windows/amd64 %SKIP_INSTALLER%
if %errorlevel% neq 0 (echo [build] watchdog 编译失败! && exit /b 1) if errorlevel 1 goto fail_mygo
echo [build] 生成便携版... echo [build] 生成便携版...
if not exist portable mkdir portable if not exist portable mkdir portable
copy /y bin\ZerOriginTool.exe portable\ZerOriginTool.exe >nul copy /y bin\windows-amd64\ZerOriginTool.exe portable\ZerOriginTool.exe >nul
copy /y bin\ZerOriginTool-Settings.exe portable\ZerOriginTool-Settings.exe >nul copy /y bin\windows-amd64\watchdog.exe portable\watchdog.exe >nul
copy /y bin\watchdog.exe portable\watchdog.exe >nul
echo [build] 编译安装包 (NSIS)... echo [build] 完成,产物:
if exist "C:\Program Files (x86)\NSIS\makensis.exe" ( dir /b bin\windows-amd64\*.exe
pushd deploy echo 便携版:portable\
"C:\Program Files (x86)\NSIS\makensis.exe" -INPUTCHARSET UTF8 installer.nsi exit /b 0
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] 完成: :fail_watchdog
dir /b bin\*.exe echo [build] watchdog 编译失败!
echo 便携版:portable\(含两个 exe 与说明) exit /b 1
:fail_mygo
echo [build] mygo 打包失败!
exit /b 1
+18
View File
@@ -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)
}
+25 -25
View File
@@ -3,13 +3,13 @@
// 目标:确认"COM 直调音量返回 S_OK + 读回验证通过,但 Win11 音量 OSD 简化 / // 目标:确认"COM 直调音量返回 S_OK + 读回验证通过,但 Win11 音量 OSD 简化 /
// 实际听感无变化"的根因。输出: // 实际听感无变化"的根因。输出:
// //
// 1. 所有渲染端点:名称 + ID(GUID) + 状态(ACTIVE/DISABLED/NOTPRESENT/UNPLUGGED) // 1. 所有渲染端点:名称 + ID(GUID) + 状态(ACTIVE/DISABLED/NOTPRESENT/UNPLUGGED)
// 2. 三种 ERole(eConsole/eMultimedia/eCommunications)默认端点 GUID 对比 // 2. 三种 ERole(eConsole/eMultimedia/eCommunications)默认端点 GUID 对比
// 3. 生产路径 GetMasterVolumePercent 读到的音量 // 3. 生产路径 GetMasterVolumePercent 读到的音量
// 4. IAudioEndpointVolume:音量范围(dB)、步进信息、静音状态 // 4. IAudioEndpointVolume:音量范围(dB)、步进信息、静音状态
// 5. 注册 IAudioEndpointVolumeCallback,经生产路径 VolumeAdjustPercent(+1) 调节, // 5. 注册 IAudioEndpointVolumeCallback,经生产路径 VolumeAdjustPercent(+1) 调节,
// 观察系统音频通知是否送达(OnNotify 是否被调用) // 观察系统音频通知是否送达(OnNotify 是否被调用)
// 6. SendInput 媒体键 VolumeStep(+1):由系统 Shell 处理 → 应显示完整 OSD // 6. SendInput 媒体键 VolumeStep(+1):由系统 Shell 处理 → 应显示完整 OSD
// //
// 构建:go build ./cmd/diag-volume // 构建:go build ./cmd/diag-volume
// 运行:在 Win11 有声卡桌面上运行,调节过程中留意屏幕右下角 OSD 形态。 // 运行:在 Win11 有声卡桌面上运行,调节过程中留意屏幕右下角 OSD 形态。
@@ -51,14 +51,14 @@ func guidFromString(s string) comGUID {
} }
var ( var (
ole32Diag = syscall.NewLazyDLL("ole32.dll") ole32Diag = syscall.NewLazyDLL("ole32.dll")
procCoInitializeEx = ole32Diag.NewProc("CoInitializeEx") procCoInitializeEx = ole32Diag.NewProc("CoInitializeEx")
procCoUninitialize = ole32Diag.NewProc("CoUninitialize") procCoUninitialize = ole32Diag.NewProc("CoUninitialize")
procCoCreateInstance = ole32Diag.NewProc("CoCreateInstance") procCoCreateInstance = ole32Diag.NewProc("CoCreateInstance")
procCoTaskMemFree = ole32Diag.NewProc("CoTaskMemFree") procCoTaskMemFree = ole32Diag.NewProc("CoTaskMemFree")
procPropVariantClear = ole32Diag.NewProc("PropVariantClear") procPropVariantClear = ole32Diag.NewProc("PropVariantClear")
user32Diag = syscall.NewLazyDLL("user32.dll") user32Diag = syscall.NewLazyDLL("user32.dll")
procSendInputDiag = user32Diag.NewProc("SendInput") procSendInputDiag = user32Diag.NewProc("SendInput")
) )
var ( var (
@@ -70,17 +70,17 @@ var (
) )
const ( const (
eRender = 0 eRender = 0
eConsole = 0 eConsole = 0
eMultimedia = 1 eMultimedia = 1
eCommunications = 2 eCommunications = 2
deviceStateMaskAll = 0x0F // ACTIVE|DISABLED|NOTPRESENT|UNPLUGGED deviceStateMaskAll = 0x0F // ACTIVE|DISABLED|NOTPRESENT|UNPLUGGED
clsctxAll = 0x17 clsctxAll = 0x17
coinitMultithreaded = 0x0 coinitMultithreaded = 0x0
stgmRead = 0 stgmRead = 0
vtLPWSTR = 31 vtLPWSTR = 31
friendlyNamePID = 14 friendlyNamePID = 14
friendlyNameFmtID = "A45C254E-DF1C-4EFD-8020-67D146A850E0" friendlyNameFmtID = "A45C254E-DF1C-4EFD-8020-67D146A850E0"
) )
// comCallDiag 调用 COM 接口 vtable 方法,返回 HRESULT。 // comCallDiag 调用 COM 接口 vtable 方法,返回 HRESULT。
-11
View File
@@ -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/
-59
View File
@@ -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.
-65
View File
@@ -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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

-398
View File
@@ -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/<pkg>"' (#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 " <link rel=\"stylesheet\" href=\"/puppertino/puppertino.css\"/>"; 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/<YourProject>.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}}"
-455
View File
@@ -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/<version>/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 >/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=<serial> 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=<serial> 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
@@ -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'
}
-12
View File
@@ -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 <methods>;
}
# Keep Wails bridge classes
-keep class com.wails.app.WailsBridge { *; }
-keep class com.wails.app.WailsJSBridge { *; }
@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Internet permission for WebView -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<!-- Observe network connectivity / type for android:NetworkChanged events -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
<intent>
<action android:name="android.media.action.VIDEO_CAPTURE" />
</intent>
</queries>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.WailsApp"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<service
android:name=".WailsForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
@@ -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<String, String> 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 <video> can seek/stream a clip of any length.
if (path != null && path.startsWith("/__capture__/")) {
return serveCaptureFile(path.substring("/__capture__/".length()), request);
}
// For regular assets, use the asset loader
return assetLoader.shouldInterceptRequest(request.getUrl());
}
return super.shouldInterceptRequest(view, request);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (DEBUG) Log.d(TAG, "Page loaded: " + url);
bridge.onPageFinished(url);
// Now that JS listeners are mounted, push a snapshot of the
// current battery / network / theme so the UI starts populated.
emitSystemSnapshot();
}
});
// Add JavaScript interface for Go communication
webView.addJavascriptInterface(new WailsJSBridge(bridge, webView), "wails");
}
private void loadApplication() {
String url = WAILS_SCHEME + "://" + WAILS_HOST + "/";
if (DEBUG) Log.d(TAG, "Loading URL: " + url);
webView.loadUrl(url);
}
/**
* Launch the system camera to capture a photo (video=false) or a video
* (video=true). The capture is written to a FileProvider URI in the cache and
* the result is delivered to JS as a "common:capture" event.
*/
public void launchCameraCapture(boolean video) {
if (checkSelfPermission("android.permission.CAMERA") != PackageManager.PERMISSION_GRANTED) {
pendingCaptureIsVideo = video;
requestPermissions(new String[]{"android.permission.CAMERA"}, CAMERA_PERMISSION_REQUEST);
return;
}
try {
File dir = new File(getCacheDir(), "captures");
if (!dir.exists()) dir.mkdirs();
pendingCaptureFile = new File(dir, "capture_" + System.currentTimeMillis() + (video ? ".mp4" : ".jpg"));
pendingCaptureIsVideo = video;
Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", pendingCaptureFile);
Intent intent = new Intent(video ? MediaStore.ACTION_VIDEO_CAPTURE : MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Don't pre-check with resolveActivity(): Android 11+ package visibility
// hides other apps' intents unless declared in <queries>, so it can
// return null even when a camera app exists. Just launch and handle a miss.
startActivityForResult(intent, video ? VIDEO_CAPTURE_REQUEST : PHOTO_CAPTURE_REQUEST);
} catch (android.content.ActivityNotFoundException e) {
bridge.emitEvent("common:capture", "{\"error\":\"no camera app available\"}");
} catch (Exception e) {
Log.e(TAG, "launchCameraCapture failed", e);
bridge.emitEvent("common:capture", "{\"error\":\"capture failed\"}");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_PERMISSION_REQUEST) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCameraCapture(pendingCaptureIsVideo);
} else {
bridge.emitEvent("common:capture", "{\"error\":\"camera permission denied\"}");
}
return;
}
if (bridge != null) {
bridge.onRequestPermissionsResult(requestCode, grantResults);
}
}
private void handleCaptureResult(int resultCode, @Nullable Intent data) {
File file = pendingCaptureFile;
final boolean video = pendingCaptureIsVideo;
pendingCaptureFile = null;
if (resultCode != RESULT_OK) {
bridge.emitEvent("common:capture", "{\"cancelled\":true}");
return;
}
// Some camera apps (commonly for video) ignore EXTRA_OUTPUT and instead
// return a content URI in the result data; copy that into our cache.
if ((file == null || !file.exists() || file.length() == 0)
&& data != null && data.getData() != null) {
String copied = copyUriToCache(data.getData());
if (copied != null) file = new File(copied);
}
final File f = file;
if (f == null || !f.exists() || f.length() == 0) {
bridge.emitEvent("common:capture", "{\"cancelled\":true}");
return;
}
new Thread(() -> {
try {
JSONObject o = new JSONObject();
o.put("type", video ? "video" : "photo");
o.put("path", f.getAbsolutePath());
o.put("size", f.length());
if (!video) {
String thumb = makePhotoThumbnail(f);
if (thumb != null) o.put("thumb", thumb);
}
// Stream URL works for both: <video>/<img> load it from the cache
// via shouldInterceptRequest (Range-enabled), no size limit.
o.put("streamUrl", captureStreamUrl(f));
bridge.emitEvent("common:capture", o.toString());
} catch (Exception e) {
Log.e(TAG, "handleCaptureResult failed", e);
bridge.emitEvent("common:capture", "{\"error\":\"result processing failed\"}");
}
}).start();
}
/** Downscale a captured photo into a base64 JPEG data URL for display in the webview. */
@Nullable
private String makePhotoThumbnail(File file) {
try {
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), bounds);
int sample = 1;
while (Math.max(bounds.outWidth, bounds.outHeight) / sample > 640) sample *= 2;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = sample;
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
if (bmp == null) return null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos);
bmp.recycle();
return "data:image/jpeg;base64," + Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
} catch (Exception e) {
return null;
}
}
/**
* Build a same-origin URL the webview can stream a capture from. Served by
* serveCaptureFile (via shouldInterceptRequest); the path is relative to the
* cache dir so both camera files (captures/) and copied content URIs
* (wails-picker/) resolve.
*/
private String captureStreamUrl(File file) {
String base = getCacheDir().getAbsolutePath() + File.separator;
String abs = file.getAbsolutePath();
String rel = abs.startsWith(base) ? abs.substring(base.length()) : file.getName();
return "/__capture__/" + Uri.encode(rel, "/");
}
/**
* Serve a captured file (under the app cache) to the webview with HTTP Range
* support, so &lt;video&gt; can stream and seek a clip of any length without
* inlining it as a data URL.
*/
private WebResourceResponse serveCaptureFile(String relPath, WebResourceRequest request) {
try {
File cache = getCacheDir();
File file = new File(cache, Uri.decode(relPath));
// Path-traversal guard: only ever serve files under the cache dir.
if (!file.getCanonicalPath().startsWith(cache.getCanonicalPath() + File.separator)
|| !file.exists() || !file.isFile()) {
return new WebResourceResponse("text/plain", "UTF-8", 404, "Not Found",
new java.util.HashMap<>(), new java.io.ByteArrayInputStream(new byte[0]));
}
String name = file.getName().toLowerCase();
String mime = name.endsWith(".mp4") ? "video/mp4"
: name.endsWith(".mov") ? "video/quicktime"
: name.endsWith(".jpg") || name.endsWith(".jpeg") ? "image/jpeg"
: name.endsWith(".png") ? "image/png" : "application/octet-stream";
long length = file.length();
java.util.Map<String, String> reqHeaders = request.getRequestHeaders();
String range = reqHeaders != null ? reqHeaders.get("Range") : null;
if (range == null && reqHeaders != null) range = reqHeaders.get("range");
java.util.Map<String, String> headers = new java.util.HashMap<>();
headers.put("Accept-Ranges", "bytes");
headers.put("Cache-Control", "no-store");
if (range != null && range.startsWith("bytes=")) {
long start = 0, end = length - 1;
String spec = range.substring(6).trim();
int dash = spec.indexOf('-');
if (dash >= 0) {
try {
if (dash > 0) start = Long.parseLong(spec.substring(0, dash).trim());
String e = spec.substring(dash + 1).trim();
if (!e.isEmpty()) end = Long.parseLong(e);
} catch (NumberFormatException ignored) { }
}
if (start < 0) start = 0;
if (end >= length) end = length - 1;
if (start > end) { start = 0; end = length - 1; }
long count = end - start + 1;
java.io.InputStream in = new java.io.FileInputStream(file);
long toSkip = start;
while (toSkip > 0) {
long s = in.skip(toSkip);
if (s <= 0) break;
toSkip -= s;
}
headers.put("Content-Range", "bytes " + start + "-" + end + "/" + length);
headers.put("Content-Length", String.valueOf(count));
return new WebResourceResponse(mime, null, 206, "Partial Content",
headers, new LimitedInputStream(in, count));
}
headers.put("Content-Length", String.valueOf(length));
return new WebResourceResponse(mime, null, 200, "OK", headers,
new java.io.FileInputStream(file));
} catch (Exception e) {
Log.e(TAG, "serveCaptureFile failed", e);
return new WebResourceResponse("text/plain", "UTF-8", 500, "Error",
new java.util.HashMap<>(), new java.io.ByteArrayInputStream(new byte[0]));
}
}
/** Wraps a stream to yield at most a fixed number of bytes (for Range responses). */
private static final class LimitedInputStream extends java.io.FilterInputStream {
private long remaining;
LimitedInputStream(java.io.InputStream in, long limit) {
super(in);
this.remaining = limit;
}
@Override public int read() throws java.io.IOException {
if (remaining <= 0) return -1;
int b = super.read();
if (b >= 0) remaining--;
return b;
}
@Override public int read(byte[] b, int off, int len) throws java.io.IOException {
if (remaining <= 0) return -1;
int n = super.read(b, off, (int) Math.min(len, remaining));
if (n > 0) remaining -= n;
return n;
}
}
/**
* Launch the system document picker. Results are copied into the app's
* cache directory so Go receives real filesystem paths. Called by
* WailsBridge on the main thread.
*/
public void launchFilePicker(int callbackID, boolean multiple) {
synchronized (this) {
if (pendingFilePickerCallbackID != -1) {
// Only one picker can be in flight
bridge.filePickerDone(callbackID);
return;
}
pendingFilePickerCallbackID = callbackID;
}
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);
try {
startActivityForResult(intent, FILE_PICKER_REQUEST);
} catch (Exception e) {
Log.e(TAG, "Failed to launch file picker", e);
pendingFilePickerCallbackID = -1;
bridge.filePickerDone(callbackID);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_CAPTURE_REQUEST || requestCode == VIDEO_CAPTURE_REQUEST) {
handleCaptureResult(resultCode, data);
return;
}
if (requestCode != FILE_PICKER_REQUEST) {
return;
}
final int callbackID = pendingFilePickerCallbackID;
pendingFilePickerCallbackID = -1;
if (callbackID == -1) {
return;
}
final List<Uri> uris = new ArrayList<>();
if (resultCode == RESULT_OK && data != null) {
if (data.getClipData() != null) {
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
uris.add(data.getClipData().getItemAt(i).getUri());
}
} else if (data.getData() != null) {
uris.add(data.getData());
}
}
// Copy the documents off the main thread, then notify Go
new Thread(() -> {
for (Uri uri : uris) {
String path = copyUriToCache(uri);
if (path != null) {
bridge.filePickerResult(callbackID, path);
}
}
bridge.filePickerDone(callbackID);
}).start();
}
/**
* Copy a content URI into the app cache and return its filesystem path.
*/
@Nullable
private String copyUriToCache(Uri uri) {
String name = "document";
try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
int idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (idx >= 0 && cursor.getString(idx) != null) {
name = new File(cursor.getString(idx)).getName();
}
}
} catch (Exception ignored) {
}
try {
File dir = new File(getCacheDir(), "wails-picker/" + System.nanoTime());
if (!dir.mkdirs()) {
return null;
}
File out = new File(dir, name);
try (InputStream in = getContentResolver().openInputStream(uri);
OutputStream os = new FileOutputStream(out)) {
if (in == null) {
return null;
}
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) > 0) {
os.write(buf, 0, n);
}
}
return out.getAbsolutePath();
} catch (Exception e) {
Log.e(TAG, "Failed to copy picked document", e);
return null;
}
}
/**
* Execute JavaScript in the WebView from the Go side
*/
public void executeJavaScript(final String js) {
runOnUiThread(() -> {
if (webView != null) {
webView.evaluateJavascript(js, null);
}
});
}
// ---- System events ---------------------------------------------------
// Battery/power, screen lock and network connectivity are surfaced to JS as
// "system:*" events. The OS broadcasts used here (ACTION_BATTERY_CHANGED,
// SCREEN_OFF, USER_PRESENT, POWER_SAVE_MODE_CHANGED) are protected system
// broadcasts, so dynamic registration needs no RECEIVER_* export flag.
private void registerSystemEventReceivers() {
// Battery + charging state (sticky broadcast: the current value is
// delivered to the receiver immediately on registration).
batteryReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
emitBattery(intent);
}
};
registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
// Low-power (battery saver) mode toggles → re-emit battery with the flag.
powerSaveReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
emitBattery(registerSticky(Intent.ACTION_BATTERY_CHANGED));
}
};
registerReceiver(powerSaveReceiver,
new IntentFilter(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED));
// Screen lock / unlock. SCREEN_OFF ≈ locked; USER_PRESENT = unlocked.
screenReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
emitLock(true);
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
emitLock(false);
}
}
};
IntentFilter screenFilter = new IntentFilter();
screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
screenFilter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(screenReceiver, screenFilter);
// Network connectivity / transport type / cellular signal strength.
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
networkCallback = new ConnectivityManager.NetworkCallback() {
@Override public void onAvailable(Network network) { emitNetwork(network); }
@Override public void onLost(Network network) { emitNetworkDisconnected(); }
@Override public void onCapabilitiesChanged(Network network, NetworkCapabilities caps) {
emitNetwork(network);
}
};
try {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} catch (Exception e) {
Log.e(TAG, "registerDefaultNetworkCallback failed", e);
}
}
}
private void unregisterSystemEventReceivers() {
safeUnregister(batteryReceiver);
batteryReceiver = null;
safeUnregister(powerSaveReceiver);
powerSaveReceiver = null;
safeUnregister(screenReceiver);
screenReceiver = null;
if (connectivityManager != null && networkCallback != null) {
try {
connectivityManager.unregisterNetworkCallback(networkCallback);
} catch (Exception ignored) {
}
networkCallback = null;
}
}
private void safeUnregister(BroadcastReceiver r) {
if (r != null) {
try {
unregisterReceiver(r);
} catch (Exception ignored) {
}
}
}
/** Read the current sticky value for an action without a standing receiver. */
@Nullable
private Intent registerSticky(String action) {
return registerReceiver(null, new IntentFilter(action));
}
/** Push current battery / network / theme so a freshly-loaded UI is populated. */
private void emitSystemSnapshot() {
emitBattery(registerSticky(Intent.ACTION_BATTERY_CHANGED));
if (connectivityManager != null) {
Network active = connectivityManager.getActiveNetwork();
if (active != null) {
emitNetwork(active);
} else {
emitNetworkDisconnected();
}
}
emitTheme();
}
private void emitBattery(@Nullable Intent batteryStatus) {
try {
float level = -1f;
String state = "unknown";
if (batteryStatus != null) {
int lvl = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (lvl >= 0 && scale > 0) {
level = lvl / (float) scale;
}
switch (batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1)) {
case BatteryManager.BATTERY_STATUS_CHARGING: state = "charging"; break;
case BatteryManager.BATTERY_STATUS_FULL: state = "full"; break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
case BatteryManager.BATTERY_STATUS_NOT_CHARGING: state = "unplugged"; break;
default: state = "unknown"; break;
}
}
boolean lowPower = false;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm != null) {
lowPower = pm.isPowerSaveMode();
}
JSONObject o = new JSONObject();
o.put("level", (double) level);
o.put("state", state);
o.put("lowPowerMode", lowPower);
if (bridge != null) bridge.emitSystemEvent("android:BatteryChanged", o.toString());
} catch (Exception e) {
Log.e(TAG, "emitBattery failed", e);
}
}
private void emitNetwork(@Nullable Network network) {
try {
boolean connected = false;
String type = "none";
boolean metered = false;
Integer signal = null;
if (connectivityManager != null && network != null) {
NetworkCapabilities caps = connectivityManager.getNetworkCapabilities(network);
if (caps != null) {
connected = caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
type = "wifi";
} else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
type = "cellular";
} else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
type = "wired";
} else {
type = "other";
}
metered = !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
int s = caps.getSignalStrength();
if (s != Integer.MIN_VALUE) {
signal = s; // dBm; closer to 0 is a stronger signal
}
}
}
}
JSONObject o = new JSONObject();
o.put("connected", connected);
o.put("type", type);
o.put("metered", metered);
if (signal != null) {
o.put("signal", (int) signal);
}
if (bridge != null) bridge.emitSystemEvent("android:NetworkChanged", o.toString());
} catch (Exception e) {
Log.e(TAG, "emitNetwork failed", e);
}
}
private void emitNetworkDisconnected() {
try {
JSONObject o = new JSONObject();
o.put("connected", false);
o.put("type", "none");
o.put("metered", false);
if (bridge != null) bridge.emitSystemEvent("android:NetworkChanged", o.toString());
} catch (Exception ignored) {
}
}
private void emitLock(boolean locked) {
// Lock/unlock are signals (no payload); name carries the state.
if (bridge != null) {
bridge.emitSystemEvent(locked ? "android:ScreenLocked" : "android:ScreenUnlocked", "{}");
}
}
private void emitTheme() {
try {
int mode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
JSONObject o = new JSONObject();
// "isDarkMode" matches the context key the desktop platforms use.
o.put("isDarkMode", mode == Configuration.UI_MODE_NIGHT_YES);
if (bridge != null) bridge.emitSystemEvent("android:ThemeChanged", o.toString());
} catch (Exception ignored) {
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Fires for light/dark switches because the manifest lists uiMode in
// android:configChanges (otherwise the activity would be recreated).
emitTheme();
}
@Override
protected void onStart() {
super.onStart();
// Battery: only monitor system events while the app is visible.
if (!systemReceiversRegistered) {
registerSystemEventReceivers();
systemReceiversRegistered = true;
}
if (bridge != null) {
bridge.onStart();
}
}
@Override
protected void onResume() {
super.onResume();
if (bridge != null) {
bridge.onResume();
}
}
@Override
protected void onPause() {
super.onPause();
if (bridge != null) {
bridge.onPause();
}
}
@Override
protected void onStop() {
super.onStop();
if (systemReceiversRegistered) {
unregisterSystemEventReceivers();
systemReceiversRegistered = false;
}
if (bridge != null) {
bridge.onStop();
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (bridge != null) {
bridge.onLowMemory();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterSystemEventReceivers();
if (bridge != null) {
bridge.shutdown();
}
if (webView != null) {
webView.destroy();
}
}
@Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,74 +0,0 @@
package com.wails.app;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
/**
* A minimal started foreground service. It does no work of its own — its purpose
* is to keep the app's process alive (with the required ongoing notification) so
* the developer's Go goroutines keep running while the app is backgrounded,
* which Android would otherwise be free to kill. Start it from
* {@link WailsBridge#startForegroundService(String)} and stop it with
* {@link WailsBridge#stopForegroundService()}.
*/
public class WailsForegroundService extends android.app.Service {
public static final String ACTION_START = "com.wails.app.FGS_START";
private static final String CHANNEL_ID = "wails_foreground";
private static final int NOTIFICATION_ID = 0x57A1; // "WAI"
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String title = "Wails";
String text = "Running in the background";
if (intent != null) {
if (intent.getStringExtra("title") != null) title = intent.getStringExtra("title");
if (intent.getStringExtra("text") != null) text = intent.getStringExtra("text");
}
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel ch = new NotificationChannel(
CHANNEL_ID, "Background work", NotificationManager.IMPORTANCE_LOW);
nm.createNotificationChannel(ch);
}
PendingIntent contentIntent = null;
Intent launch = getPackageManager().getLaunchIntentForPackage(getPackageName());
if (launch != null) {
int piFlags = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
? PendingIntent.FLAG_IMMUTABLE : 0;
contentIntent = PendingIntent.getActivity(this, 0, launch, piFlags);
}
Notification n = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_popup_sync)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.setContentIntent(contentIntent)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(NOTIFICATION_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
} else {
startForeground(NOTIFICATION_ID, n);
}
// Restart if the OS kills us while still wanted.
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
@@ -1,151 +0,0 @@
package com.wails.app;
import android.util.Log;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import com.wails.app.BuildConfig;
/**
* WailsJSBridge provides the JavaScript interface that allows the web frontend
* to communicate with the Go backend. This is exposed to JavaScript as the
* `window.wails` object.
*
* Similar to iOS's WKScriptMessageHandler but using Android's addJavascriptInterface.
*/
public class WailsJSBridge {
private static final String TAG = "WailsJSBridge";
private static final boolean DEBUG = BuildConfig.DEBUG;
// Pooled threads avoid unbounded thread creation under high call volume.
private static final ExecutorService executor = Executors.newCachedThreadPool();
private final WailsBridge bridge;
private final WebView webView;
public WailsJSBridge(WailsBridge bridge, WebView webView) {
this.bridge = bridge;
this.webView = webView;
}
/**
* Send a message to Go and return the response synchronously.
* Called from JavaScript: wails.invoke(message)
*
* @param message The message to send (JSON string)
* @return The response from Go (JSON string)
*/
@JavascriptInterface
public String invoke(String message) {
if (DEBUG) Log.d(TAG, "Invoke called: " + message);
return bridge.handleMessage(message);
}
/**
* Send a message to Go asynchronously.
* The response will be sent back via a callback.
* Called from JavaScript: wails.invokeAsync(callbackId, message)
*
* @param callbackId The callback ID to use for the response
* @param message The message to send (JSON string)
*/
@JavascriptInterface
public void invokeAsync(final String callbackId, final String payload) {
if (DEBUG) Log.d(TAG, "InvokeAsync called: " + payload);
// Handle off the JS thread so we don't block the WebView.
executor.execute(() -> {
try {
String response = bridge.handleRuntimeCall(payload);
sendCallback(callbackId, response, null);
} catch (Exception e) {
Log.e(TAG, "Error in async invoke", e);
sendCallback(callbackId, null, e.getMessage());
}
});
}
/**
* Log a message from JavaScript to Android's logcat
* Called from JavaScript: wails.log(level, message)
*
* @param level The log level (debug, info, warn, error)
* @param message The message to log
*/
@JavascriptInterface
public void log(String level, String message) {
switch (level.toLowerCase()) {
case "debug":
Log.d(TAG + "/JS", message);
break;
case "info":
Log.i(TAG + "/JS", message);
break;
case "warn":
Log.w(TAG + "/JS", message);
break;
case "error":
Log.e(TAG + "/JS", message);
break;
default:
Log.v(TAG + "/JS", message);
break;
}
}
/**
* Get the platform name
* Called from JavaScript: wails.platform()
*
* @return "android"
*/
@JavascriptInterface
public String platform() {
return "android";
}
/**
* Check if we're running in debug mode
* Called from JavaScript: wails.isDebug()
*
* @return true if debug build, false otherwise
*/
@JavascriptInterface
public boolean isDebug() {
return BuildConfig.DEBUG;
}
/**
* Send a callback response to JavaScript
*/
private void sendCallback(String callbackId, String result, String error) {
final String js;
if (error != null) {
js = String.format(
"window._wailsAndroidCallback && window._wailsAndroidCallback('%s', null, '%s');",
escapeJsString(callbackId),
escapeJsString(error)
);
} else {
js = String.format(
"window._wailsAndroidCallback && window._wailsAndroidCallback('%s', '%s', null);",
escapeJsString(callbackId),
escapeJsString(result != null ? result : "")
);
}
webView.post(() -> webView.evaluateJavascript(js, null));
}
private String escapeJsString(String str) {
if (str == null) return "";
return str.replace("\\", "\\\\")
.replace("'", "\\'")
.replace("\n", "\\n")
.replace("\r", "\\r")
// JS line terminators (U+2028/U+2029) must be escaped too; built via
// (char) casts so the Java lexer does not reinterpret them as newlines.
.replace(String.valueOf((char) 0x2028), "\\u2028")
.replace(String.valueOf((char) 0x2029), "\\u2029");
}
}
@@ -1,68 +0,0 @@
package com.wails.app;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebResourceResponse;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.webkit.WebViewAssetLoader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* WailsPathHandler implements WebViewAssetLoader.PathHandler to serve assets
* from the Go asset server. This allows the WebView to load assets without
* using a network server, similar to iOS's WKURLSchemeHandler.
*/
public class WailsPathHandler implements WebViewAssetLoader.PathHandler {
private static final String TAG = "WailsPathHandler";
private static final boolean DEBUG = BuildConfig.DEBUG;
private final WailsBridge bridge;
public WailsPathHandler(WailsBridge bridge) {
this.bridge = bridge;
}
@Nullable
@Override
public WebResourceResponse handle(@NonNull String path) {
if (DEBUG) Log.d(TAG, "Handling path: " + path);
// Normalize path
if (path.isEmpty() || path.equals("/")) {
path = "/index.html";
}
// Get asset from Go
byte[] data = bridge.serveAsset(path, "GET", "{}");
if (data == null || data.length == 0) {
Log.w(TAG, "Asset not found: " + path);
return null; // Return null to let WebView handle 404
}
// Determine MIME type
String mimeType = bridge.getAssetMimeType(path);
if (DEBUG) Log.d(TAG, "Serving " + path + " with type " + mimeType + " (" + data.length + " bytes)");
// Create response
InputStream inputStream = new ByteArrayInputStream(data);
Map<String, String> headers = new HashMap<>();
headers.put("Access-Control-Allow-Origin", "*");
headers.put("Cache-Control", "no-cache");
return new WebResourceResponse(
mimeType,
"UTF-8",
200,
"OK",
headers,
inputStream
);
}
}
@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="wails_blue">#3574D4</color>
<color name="wails_blue_dark">#2C5FB8</color>
<color name="wails_background">#1B2636</color>
<color name="white">#FFFFFFFF</color>
<color name="black">#FF000000</color>
</resources>
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Wails App</string>
</resources>
@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.WailsApp" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/wails_blue</item>
<item name="colorPrimaryVariant">@color/wails_blue_dark</item>
<item name="colorOnPrimary">@android:color/white</item>
<!-- Status bar color. -->
<item name="android:statusBarColor">@color/wails_background</item>
<item name="android:navigationBarColor">@color/wails_background</item>
<!-- Window background -->
<item name="android:windowBackground">@color/wails_background</item>
</style>
</resources>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!-- Camera captures are written here and shared with the camera app via the
FileProvider. -->
<cache-path name="captures" path="captures/" />
</paths>
-4
View File
@@ -1,4 +0,0 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '8.7.3' apply false
}
@@ -1,26 +0,0 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/build/optimize-your-build#parallel
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
Binary file not shown.
@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-248
View File
@@ -1,248 +0,0 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
-93
View File
@@ -1,93 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -1,11 +0,0 @@
//go:build android
package main
import "github.com/wailsapp/wails/v3/pkg/application"
func init() {
// Register main function to be called when the Android app initializes
// This is necessary because in c-shared build mode, main() is not automatically called
application.RegisterAndroidMain(main)
}
@@ -1,266 +0,0 @@
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
func main() {
fmt.Println("Checking Android development dependencies...")
fmt.Println()
errors := []string{}
// Check Go
if !checkCommand("go", "version") {
errors = append(errors, "Go is not installed. Install from https://go.dev/dl/")
} else {
fmt.Println("✓ Go is installed")
}
// Check ANDROID_HOME
androidHome := os.Getenv("ANDROID_HOME")
if androidHome == "" {
androidHome = os.Getenv("ANDROID_SDK_ROOT")
}
if androidHome == "" {
// Try common default locations
home, _ := os.UserHomeDir()
possiblePaths := []string{
filepath.Join(home, "Android", "Sdk"),
filepath.Join(home, "Library", "Android", "sdk"),
"/usr/local/share/android-sdk",
}
for _, p := range possiblePaths {
if _, err := os.Stat(p); err == nil {
androidHome = p
break
}
}
}
if androidHome == "" {
errors = append(errors, "ANDROID_HOME not set. Install Android Studio and set ANDROID_HOME environment variable")
} else {
fmt.Printf("✓ ANDROID_HOME: %s\n", androidHome)
}
// Check adb
if !checkCommand("adb", "version") {
if androidHome != "" {
platformTools := filepath.Join(androidHome, "platform-tools")
errors = append(errors, fmt.Sprintf("adb not found. Add %s to PATH", platformTools))
} else {
errors = append(errors, "adb not found. Install Android SDK Platform-Tools")
}
} else {
fmt.Println("✓ adb is installed")
}
// Check emulator
if !checkCommand("emulator", "-list-avds") {
if androidHome != "" {
emulatorPath := filepath.Join(androidHome, "emulator")
errors = append(errors, fmt.Sprintf("emulator not found. Add %s to PATH", emulatorPath))
} else {
errors = append(errors, "emulator not found. Install Android Emulator via SDK Manager")
}
} else {
fmt.Println("✓ Android Emulator is installed")
}
// Check NDK
ndkHome := os.Getenv("ANDROID_NDK_HOME")
if ndkHome == "" && androidHome != "" {
// Look for NDK in default location
ndkDir := filepath.Join(androidHome, "ndk")
if entries, err := os.ReadDir(ndkDir); err == nil {
for _, entry := range entries {
if entry.IsDir() {
ndkHome = filepath.Join(ndkDir, entry.Name())
break
}
}
}
}
if ndkHome == "" {
errors = append(errors, "Android NDK not found. Install NDK via Android Studio > SDK Manager > SDK Tools > NDK (Side by side)")
} else {
fmt.Printf("✓ Android NDK: %s\n", ndkHome)
}
// Check Java
if !checkCommand("java", "-version") {
errors = append(errors, "Java not found. Install JDK 11+ (OpenJDK recommended)")
} else {
fmt.Println("✓ Java is installed")
}
// Check for AVD (Android Virtual Device)
if checkCommand("emulator", "-list-avds") {
cmd := exec.Command("emulator", "-list-avds")
output, err := cmd.Output()
if err == nil && len(strings.TrimSpace(string(output))) > 0 {
avds := strings.Split(strings.TrimSpace(string(output)), "\n")
fmt.Printf("✓ Found %d Android Virtual Device(s)\n", len(avds))
} else {
// Mirror the iOS installer, which offers to create a simulator when
// none exist. Only create from an already-installed system image.
offerCreateAVD(androidHome)
}
}
fmt.Println()
if len(errors) > 0 {
fmt.Println("❌ Missing dependencies:")
for _, err := range errors {
fmt.Printf(" - %s\n", err)
}
fmt.Println()
fmt.Println("Setup instructions:")
fmt.Println("1. Install Android Studio: https://developer.android.com/studio")
fmt.Println("2. Open SDK Manager and install:")
fmt.Println(" - Android SDK Platform (API 35)")
fmt.Println(" - Android SDK Build-Tools")
fmt.Println(" - Android SDK Platform-Tools")
fmt.Println(" - Android Emulator")
fmt.Println(" - NDK (Side by side)")
fmt.Println("3. Set environment variables:")
if runtime.GOOS == "darwin" {
fmt.Println(" export ANDROID_HOME=$HOME/Library/Android/sdk")
} else {
fmt.Println(" export ANDROID_HOME=$HOME/Android/Sdk")
}
fmt.Println(" export PATH=$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator")
fmt.Println("4. Create an AVD via Android Studio > Tools > Device Manager")
os.Exit(1)
}
fmt.Println("✓ All Android development dependencies are installed!")
}
func checkCommand(name string, args ...string) bool {
cmd := exec.Command(name, args...)
cmd.Stdout = nil
cmd.Stderr = nil
return cmd.Run() == nil
}
// offerCreateAVD mirrors the iOS installer's simulator offer: when no AVD
// exists, offer to create one — but ONLY from a system image that is already
// installed. We never run sdkmanager here (a multi-GB download with a license
// prompt is a surprise the user should trigger themselves).
func offerCreateAVD(androidHome string) {
abi := "x86_64"
if runtime.GOARCH == "arm64" {
abi = "arm64-v8a"
}
// Find the highest-API installed system image matching the host ABI.
// The API level must be compared numerically: lexicographic sorting
// would rank android-9 above android-35.
var img string
if androidHome != "" {
matches, _ := filepath.Glob(filepath.Join(androidHome, "system-images", "android-*", "*", abi))
bestAPI := -1
for _, m := range matches {
apiDir := filepath.Base(filepath.Dir(filepath.Dir(m)))
api, err := strconv.Atoi(strings.TrimPrefix(apiDir, "android-"))
if err != nil {
continue // preview/extension images (e.g. android-35-ext14)
}
if api > bestAPI {
bestAPI = api
img = m
}
}
}
avdmanager := findAVDManager(androidHome)
if img == "" || avdmanager == "" {
fmt.Println("⚠ No Android Virtual Devices found.")
fmt.Println(" Install a system image and create an AVD, e.g.:")
fmt.Printf(" sdkmanager 'system-images;android-35;google_apis;%s'\n", abi)
fmt.Printf(" avdmanager create avd --name wails --package 'system-images;android-35;google_apis;%s' --device pixel_7\n", abi)
return
}
// Derive the package path from the installed image directory, e.g.
// <sdk>/system-images/android-35/google_apis/arm64-v8a
// -> system-images;android-35;google_apis;arm64-v8a
rel := strings.TrimPrefix(img, filepath.Join(androidHome, "system-images")+string(os.PathSeparator))
pkg := "system-images;" + strings.ReplaceAll(rel, string(os.PathSeparator), ";")
fmt.Println("⚠ No Android Virtual Devices found.")
fmt.Printf(" Would you like to create a 'wails' AVD from %s?\n", pkg)
if !promptUser("Create AVD?") {
fmt.Println(" Skipping AVD creation.")
fmt.Printf(" Create manually: avdmanager create avd --name wails --package '%s' --device pixel_7\n", pkg)
return
}
cmd := exec.Command(avdmanager, "create", "avd", "--name", "wails", "--package", pkg, "--device", "pixel_7", "--force")
cmd.Stdin = strings.NewReader("no\n") // decline the custom hardware-profile prompt
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Printf(" Failed to create AVD: %v\n", err)
} else {
fmt.Println(" ✅ 'wails' AVD created")
}
}
// findAVDManager returns the avdmanager path from PATH, or from the SDK's
// cmdline-tools (preferring the newest version), or "" if not found.
func findAVDManager(androidHome string) string {
if p, err := exec.LookPath("avdmanager"); err == nil {
return p
}
if androidHome != "" {
matches, _ := filepath.Glob(filepath.Join(androidHome, "cmdline-tools", "*", "bin", "avdmanager"))
// Prefer the "latest" alias; otherwise compare versions numerically
// ("9.0" would lexicographically outrank "11.0").
best := ""
bestVersion := -1.0
for _, m := range matches {
version := filepath.Base(filepath.Dir(filepath.Dir(m)))
if version == "latest" {
return m
}
v, err := strconv.ParseFloat(version, 64)
if err != nil {
v = 0
}
if v > bestVersion {
bestVersion = v
best = m
}
}
return best
}
return ""
}
func promptUser(question string) bool {
if os.Getenv("CI") != "" || os.Getenv("TASK_FORCE_YES") == "true" {
fmt.Printf("%s [y/N]: y (auto-accepted)\n", question)
return true
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s [y/N]: ", question)
response, err := reader.ReadString('\n')
if err != nil {
return false
}
response = strings.ToLower(strings.TrimSpace(response))
return response == "y" || response == "yes"
}
@@ -1,18 +0,0 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "WailsApp"
include ':app'
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 583 533" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1,0,0,1,-246,-251)">
<g id="Ebene1">
<path d="M246,251L265,784L401,784L506,450L507,450L505,784L641,784L829,251L682,251L596,567L595,567L596,251L478,251L378,568L391,251L246,251Z"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 698 B

-51
View File
@@ -1,51 +0,0 @@
{
"fill" : {
"automatic-gradient" : "extended-gray:1.00000,1.00000"
},
"groups" : [
{
"layers" : [
{
"fill-specializations" : [
{
"appearance" : "dark",
"value" : {
"solid" : "srgb:0.92143,0.92145,0.92144,1.00000"
}
},
{
"appearance" : "tinted",
"value" : {
"solid" : "srgb:0.83742,0.83744,0.83743,1.00000"
}
}
],
"image-name" : "wails_icon_vector.svg",
"name" : "wails_icon_vector",
"position" : {
"scale" : 1.5,
"translation-in-points" : [
0.0,
0.0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
},
"specular" : true,
"translucency" : {
"enabled" : true,
"value" : 0.5
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

-79
View File
@@ -1,79 +0,0 @@
# This file contains the configuration for this project.
# When you update `info` or `fileAssociations`, run `wails3 task common:update:build-assets` to update the assets.
# Note that this will overwrite any changes you have made to the assets.
version: '3'
# This information is used to generate the build assets.
info:
companyName: "My Company" # The name of the company
productName: "My Product" # The name of the application
productIdentifier: "com.mycompany.myproduct" # The unique product identifier
description: "A program that does X" # The application description
copyright: "(c) 2025, My Company" # Copyright text
comments: "Some Product Comments" # Comments
version: "0.0.1" # The application version
# cfBundleIconName: "appicon" # The macOS icon name in Assets.car icon bundles (optional)
# # Should match the name of your .icon file without the extension
# # If not set and Assets.car exists, defaults to "appicon"
# iOS build configuration (uncomment to customise iOS project generation)
# Note: Keys under `ios` OVERRIDE values under `info` when set.
# ios:
# # The iOS bundle identifier used in the generated Xcode project (CFBundleIdentifier)
# bundleID: "com.mycompany.myproduct"
# # The display name shown under the app icon (CFBundleDisplayName/CFBundleName)
# displayName: "My Product"
# # The app version to embed in Info.plist (CFBundleShortVersionString/CFBundleVersion)
# version: "0.0.1"
# # The company/organisation name for templates and project settings
# company: "My Company"
# # Additional comments to embed in Info.plist metadata
# comments: "Some Product Comments"
# Dev mode configuration
dev_mode:
root_path: .
log_level: warn
debounce: 1000
ignore:
dir:
- .git
- node_modules
- frontend
- bin
file:
- .DS_Store
- .gitignore
- .gitkeep
- "*_test.go"
watched_extension:
- "*.go"
- "*.js" # Watch for changes to JS/TS files included using the //wails:include directive.
- "*.ts" # The frontend directory will be excluded entirely by the setting above.
git_ignore: true
executes:
- cmd: wails3 build DEV=true
type: blocking
- cmd: wails3 task common:dev:frontend
type: background
- cmd: wails3 task run
type: primary
# File Associations
# More information at: https://v3.wails.io/noit/done/yet
fileAssociations:
# - ext: wails
# name: Wails
# description: Wails Application File
# iconName: wailsFileIcon
# role: Editor
# - ext: jpg
# name: JPEG
# description: Image File
# iconName: jpegFileIcon
# role: Editor
# mimeType: image/jpeg # (optional)
# Other data
other:
- name: My Other Data
Binary file not shown.
-34
View File
@@ -1,34 +0,0 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleName</key>
<string>ZerOriginTool Settings</string>
<key>CFBundleExecutable</key>
<string>settings.exe</string>
<key>CFBundleIdentifier</key>
<string>com.zerorigin.settings</string>
<key>CFBundleVersion</key>
<string>0.1.0</string>
<key>CFBundleGetInfoString</key>
<string>This is a comment</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<key>CFBundleIconFile</key>
<string>icons</string>
<key>CFBundleIconName</key>
<string>appicon</string>
<key>LSMinimumSystemVersion</key>
<string>12.0.0</string>
<key>NSHighResolutionCapable</key>
<string>true</string>
<key>NSHumanReadableCopyright</key>
<string>© 2026, My Company</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
</dict>
</plist>
-29
View File
@@ -1,29 +0,0 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleName</key>
<string>ZerOriginTool Settings</string>
<key>CFBundleExecutable</key>
<string>settings.exe</string>
<key>CFBundleIdentifier</key>
<string>com.zerorigin.settings</string>
<key>CFBundleVersion</key>
<string>0.1.0</string>
<key>CFBundleGetInfoString</key>
<string>This is a comment</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<key>CFBundleIconFile</key>
<string>icons</string>
<key>CFBundleIconName</key>
<string>appicon</string>
<key>LSMinimumSystemVersion</key>
<string>12.0.0</string>
<key>NSHighResolutionCapable</key>
<string>true</string>
<key>NSHumanReadableCopyright</key>
<string>© 2026, My Company</string>
</dict>
</plist>
-193
View File
@@ -1,193 +0,0 @@
version: '3'
includes:
common: ../Taskfile.yml
vars:
# Docker image for cross-compilation (used when building on non-macOS)
CROSS_IMAGE: wails-cross
tasks:
build:
summary: Builds the application
cmds:
- task: '{{if eq OS "darwin"}}build:native{{else}}build:docker{{end}}'
vars:
ARCH: '{{.ARCH}}'
DEV: '{{.DEV}}'
OUTPUT: '{{.OUTPUT}}'
EXTRA_TAGS: '{{.EXTRA_TAGS}}'
OBFUSCATED: '{{.OBFUSCATED}}'
GARBLE_ARGS: '{{.GARBLE_ARGS}}'
vars:
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
build:native:
summary: Builds the application natively on macOS
internal: true
deps:
- task: common:go:mod:tidy
- task: common:build:frontend
vars:
BUILD_FLAGS:
ref: .BUILD_FLAGS
OBFUSCATED:
ref: .OBFUSCATED
DEV:
ref: .DEV
- task: common:generate:icons
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 "{{.OUTPUT}}"'
vars:
BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s"{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
env:
GOOS: darwin
CGO_ENABLED: 1
GOARCH: '{{.ARCH | default ARCH}}'
CGO_CFLAGS: "-mmacosx-version-min=12.0"
CGO_LDFLAGS: "-mmacosx-version-min=12.0"
MACOSX_DEPLOYMENT_TARGET: "12.0"
build:docker:
summary: Cross-compiles for macOS using Docker (for Linux/Windows hosts)
internal: true
deps:
- task: common:build:frontend
vars:
OBFUSCATED:
ref: .OBFUSCATED
- task: common:generate:icons
preconditions:
- sh: docker info > /dev/null 2>&1
msg: "Docker is required for cross-compilation. Please install Docker."
- sh: docker image inspect {{.CROSS_IMAGE}} > /dev/null 2>&1
msg: |
Docker image '{{.CROSS_IMAGE}}' not found.
Build it first: wails3 task setup:docker
cmds:
- docker run --rm -v "{{.ROOT_DIR}}:/app" {{.DOCKER_MOUNTS}} -e APP_NAME="{{.APP_NAME}}" {{if .EXTRA_TAGS}}-e EXTRA_TAGS="{{.EXTRA_TAGS}}"{{end}} {{if eq .OBFUSCATED "true"}}-e OBFUSCATED=true{{end}} {{if .GARBLE_ARGS}}-e GARBLE_ARGS="{{.GARBLE_ARGS}}"{{end}} {{.CROSS_IMAGE}} darwin {{.DOCKER_ARCH}}
- cmd: docker run --rm -v "{{.ROOT_DIR}}:/app" alpine chown -R $(id -u):$(id -g) /app/bin
platforms: [linux, darwin]
- mkdir -p {{.BIN_DIR}}
- mv "bin/{{.APP_NAME}}-darwin-{{.DOCKER_ARCH}}" "{{.OUTPUT}}"
vars:
DOCKER_ARCH: '{{if eq .ARCH "arm64"}}arm64{{else if eq .ARCH "amd64"}}amd64{{else}}arm64{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
# Generate Docker volume mounts: Go module cache + go.mod replace directives
# Uses wails3 tool docker-mounts for cross-platform compatibility (Windows/Linux/macOS)
DOCKER_MOUNTS:
sh: 'wails3 tool docker-mounts'
build:universal:
summary: Builds darwin universal binary (arm64 + amd64)
deps:
- task: build
vars:
ARCH: amd64
OUTPUT: "{{.BIN_DIR}}/{{.APP_NAME}}-amd64"
- task: build
vars:
ARCH: arm64
OUTPUT: "{{.BIN_DIR}}/{{.APP_NAME}}-arm64"
cmds:
- task: '{{if eq OS "darwin"}}build:universal:lipo:native{{else}}build:universal:lipo:go{{end}}'
build:universal:lipo:native:
summary: Creates universal binary using native lipo (macOS)
internal: true
cmds:
- lipo -create -output "{{.BIN_DIR}}/{{.APP_NAME}}" "{{.BIN_DIR}}/{{.APP_NAME}}-amd64" "{{.BIN_DIR}}/{{.APP_NAME}}-arm64"
- rm "{{.BIN_DIR}}/{{.APP_NAME}}-amd64" "{{.BIN_DIR}}/{{.APP_NAME}}-arm64"
build:universal:lipo:go:
summary: Creates universal binary using wails3 tool lipo (Linux/Windows)
internal: true
cmds:
- wails3 tool lipo -output "{{.BIN_DIR}}/{{.APP_NAME}}" -input "{{.BIN_DIR}}/{{.APP_NAME}}-amd64" -input "{{.BIN_DIR}}/{{.APP_NAME}}-arm64"
- rm -f "{{.BIN_DIR}}/{{.APP_NAME}}-amd64" "{{.BIN_DIR}}/{{.APP_NAME}}-arm64"
package:
summary: Packages the application into a `.app` bundle
deps:
- task: build
cmds:
- task: create:app:bundle
package:universal:
summary: Packages darwin universal binary (arm64 + amd64)
deps:
- task: build:universal
cmds:
- task: create:app:bundle
create:app:bundle:
summary: Creates an `.app` bundle
cmds:
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents/MacOS"
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents/Resources"
- cp build/darwin/icons.icns "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents/Resources"
- |
if [ -f build/darwin/Assets.car ]; then
cp build/darwin/Assets.car "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents/Resources"
fi
- cp "{{.BIN_DIR}}/{{.APP_NAME}}" "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents/MacOS"
- cp build/darwin/Info.plist "{{.BIN_DIR}}/{{.APP_NAME}}.app/Contents"
- task: '{{if eq OS "darwin"}}codesign:adhoc{{else}}codesign:skip{{end}}'
codesign:adhoc:
summary: Ad-hoc signs the app bundle (macOS only)
internal: true
cmds:
- codesign --force --deep --sign - "{{.BIN_DIR}}/{{.APP_NAME}}.app"
codesign:skip:
summary: Skips codesigning when cross-compiling
internal: true
cmds:
- 'echo "Skipping codesign (not available on {{OS}}). Sign the .app on macOS before distribution."'
run:
cmds:
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/MacOS"
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/Resources"
- cp build/darwin/icons.icns "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/Resources"
- |
if [ -f build/darwin/Assets.car ]; then
cp build/darwin/Assets.car "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/Resources"
fi
- cp "{{.BIN_DIR}}/{{.APP_NAME}}" "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/MacOS"
- cp "build/darwin/Info.dev.plist" "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/Info.plist"
- codesign --force --deep --sign - "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
- '"{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Contents/MacOS/{{.APP_NAME}}"'
sign:
summary: Signs the application bundle with Developer ID
desc: |
Signs the .app bundle for distribution.
Uses signing identity from `wails3 setup` (stored in ~/.config/wails/defaults.yaml).
Override with: task darwin:sign -- --identity "Developer ID Application: ..."
deps:
- task: package
cmds:
- wails3 tool sign --input "{{.BIN_DIR}}/{{.APP_NAME}}.app" {{.CLI_ARGS}}
sign:notarize:
summary: Signs and notarizes the application bundle
desc: |
Signs the .app bundle and submits it for notarization.
Uses signing identity and keychain profile from `wails3 setup`.
First-time setup:
wails3 setup
deps:
- task: package
cmds:
- wails3 tool sign --input "{{.BIN_DIR}}/{{.APP_NAME}}.app" --notarize {{.CLI_ARGS}}
Binary file not shown.
Binary file not shown.
-220
View File
@@ -1,220 +0,0 @@
# Cross-compile Wails v3 apps to any platform
#
# Darwin: Zig + macOS SDK
# Linux: Native GCC when host matches target, Zig for cross-arch
# Windows: Zig + bundled mingw
#
# Usage:
# docker build -t wails-cross -f Dockerfile.cross .
# docker run --rm -v $(pwd):/app wails-cross darwin arm64
# docker run --rm -v $(pwd):/app wails-cross darwin amd64
# docker run --rm -v $(pwd):/app wails-cross linux amd64
# docker run --rm -v $(pwd):/app wails-cross linux arm64
# docker run --rm -v $(pwd):/app wails-cross windows amd64
# docker run --rm -v $(pwd):/app wails-cross windows arm64
FROM golang:1.26-bookworm
ARG TARGETARCH
ARG GARBLE_VERSION=v0.16.0
# Install base tools, GCC, and GTK/WebKit dev packages
RUN apt-get update && apt-get install -y --no-install-recommends \
curl xz-utils python3 nodejs npm pkg-config gcc libc6-dev \
libgtk-3-dev libwebkit2gtk-4.1-dev \
libgtk-4-dev libwebkitgtk-6.0-dev \
&& rm -rf /var/lib/apt/lists/*
RUN go install mvdan.cc/garble@${GARBLE_VERSION}
# Install Zig - automatically selects correct binary for host architecture.
# The SHA-256 is fetched from Zig's official download manifest and verified
# before extraction to protect against MITM or corrupted downloads.
ARG ZIG_VERSION=0.14.0
RUN ZIG_ARCH=$(case "${TARGETARCH}" in arm64) echo "aarch64" ;; *) echo "x86_64" ;; esac) && \
ZIG_FILE="zig-linux-${ZIG_ARCH}-${ZIG_VERSION}.tar.xz" && \
curl -fSL "https://ziglang.org/download/${ZIG_VERSION}/${ZIG_FILE}" -o "/tmp/${ZIG_FILE}" && \
EXPECTED=$(curl -fsSL "https://ziglang.org/download/index.json" | \
python3 -c "import json,sys; d=json.load(sys.stdin); print(d[sys.argv[1]][sys.argv[2]+'-linux']['shasum'])" \
"${ZIG_VERSION}" "${ZIG_ARCH}") && \
echo "${EXPECTED} /tmp/${ZIG_FILE}" | sha256sum -c - && \
tar -xJ -f "/tmp/${ZIG_FILE}" -C /opt && \
rm "/tmp/${ZIG_FILE}" && \
ln -s /opt/zig-linux-${ZIG_ARCH}-${ZIG_VERSION}/zig /usr/local/bin/zig
# Download macOS SDK (required for darwin targets)
ARG MACOS_SDK_VERSION=14.5
RUN curl -L "https://github.com/joseluisq/macosx-sdks/releases/download/${MACOS_SDK_VERSION}/MacOSX${MACOS_SDK_VERSION}.sdk.tar.xz" \
| tar -xJ -C /opt \
&& mv /opt/MacOSX${MACOS_SDK_VERSION}.sdk /opt/macos-sdk
ENV MACOS_SDK_PATH=/opt/macos-sdk
# Create Zig CC wrappers for cross-compilation targets
# Darwin and Windows use Zig; Linux uses native GCC (run with --platform for cross-arch)
# Darwin arm64
COPY <<'ZIGWRAP' /usr/local/bin/zcc-darwin-arm64
#!/bin/sh
ARGS=""
SKIP_NEXT=0
for arg in "$@"; do
if [ $SKIP_NEXT -eq 1 ]; then
SKIP_NEXT=0
continue
fi
case "$arg" in
-target) SKIP_NEXT=1 ;;
-mmacosx-version-min=*) ;;
*) ARGS="$ARGS $arg" ;;
esac
done
exec zig cc -fno-sanitize=all -target aarch64-macos-none -isysroot /opt/macos-sdk -I/opt/macos-sdk/usr/include -L/opt/macos-sdk/usr/lib -F/opt/macos-sdk/System/Library/Frameworks -w $ARGS
ZIGWRAP
RUN chmod +x /usr/local/bin/zcc-darwin-arm64
# Darwin amd64
COPY <<'ZIGWRAP' /usr/local/bin/zcc-darwin-amd64
#!/bin/sh
ARGS=""
SKIP_NEXT=0
for arg in "$@"; do
if [ $SKIP_NEXT -eq 1 ]; then
SKIP_NEXT=0
continue
fi
case "$arg" in
-target) SKIP_NEXT=1 ;;
-mmacosx-version-min=*) ;;
*) ARGS="$ARGS $arg" ;;
esac
done
exec zig cc -fno-sanitize=all -target x86_64-macos-none -isysroot /opt/macos-sdk -I/opt/macos-sdk/usr/include -L/opt/macos-sdk/usr/lib -F/opt/macos-sdk/System/Library/Frameworks -w $ARGS
ZIGWRAP
RUN chmod +x /usr/local/bin/zcc-darwin-amd64
# Windows amd64 - uses Zig's bundled mingw
COPY <<'ZIGWRAP' /usr/local/bin/zcc-windows-amd64
#!/bin/sh
ARGS=""
SKIP_NEXT=0
for arg in "$@"; do
if [ $SKIP_NEXT -eq 1 ]; then
SKIP_NEXT=0
continue
fi
case "$arg" in
-target) SKIP_NEXT=1 ;;
-Wl,*) ;;
*) ARGS="$ARGS $arg" ;;
esac
done
exec zig cc -target x86_64-windows-gnu $ARGS
ZIGWRAP
RUN chmod +x /usr/local/bin/zcc-windows-amd64
# Windows arm64 - uses Zig's bundled mingw
COPY <<'ZIGWRAP' /usr/local/bin/zcc-windows-arm64
#!/bin/sh
ARGS=""
SKIP_NEXT=0
for arg in "$@"; do
if [ $SKIP_NEXT -eq 1 ]; then
SKIP_NEXT=0
continue
fi
case "$arg" in
-target) SKIP_NEXT=1 ;;
-Wl,*) ;;
*) ARGS="$ARGS $arg" ;;
esac
done
exec zig cc -target aarch64-windows-gnu $ARGS
ZIGWRAP
RUN chmod +x /usr/local/bin/zcc-windows-arm64
# Build script
COPY <<'SCRIPT' /usr/local/bin/build.sh
#!/bin/sh
set -e
OS=${1:-darwin}
ARCH=${2:-arm64}
case "${OS}-${ARCH}" in
darwin-arm64|darwin-aarch64)
export CC=zcc-darwin-arm64
export GOARCH=arm64
export GOOS=darwin
;;
darwin-amd64|darwin-x86_64)
export CC=zcc-darwin-amd64
export GOARCH=amd64
export GOOS=darwin
;;
linux-arm64|linux-aarch64)
export CC=gcc
export GOARCH=arm64
export GOOS=linux
;;
linux-amd64|linux-x86_64)
export CC=gcc
export GOARCH=amd64
export GOOS=linux
;;
windows-arm64|windows-aarch64)
export CC=zcc-windows-arm64
export GOARCH=arm64
export GOOS=windows
;;
windows-amd64|windows-x86_64)
export CC=zcc-windows-amd64
export GOARCH=amd64
export GOOS=windows
;;
*)
echo "Usage: <os> <arch>"
echo " os: darwin, linux, windows"
echo " arch: amd64, arm64"
exit 1
;;
esac
export CGO_ENABLED=1
export CGO_CFLAGS="-w"
# Build frontend if exists and not already built (host may have built it)
if [ -d "frontend" ] && [ -f "frontend/package.json" ] && [ ! -d "frontend/dist" ]; then
(cd frontend && npm install --silent && npm run build --silent)
fi
# Build
APP=${APP_NAME:-$(basename $(pwd))}
mkdir -p bin
EXT=""
LDFLAGS="-s -w"
if [ "$GOOS" = "windows" ]; then
EXT=".exe"
LDFLAGS="-s -w -H windowsgui"
fi
TAGS="production"
if [ -n "$EXTRA_TAGS" ]; then
TAGS="${TAGS},${EXTRA_TAGS}"
fi
COMPILER="go build"
if [ "$OBFUSCATED" = "true" ]; then
COMPILER="garble ${GARBLE_ARGS} build"
TAGS="${TAGS},wails_obfuscated"
fi
${COMPILER} -tags "$TAGS" -trimpath -buildvcs=false -ldflags="$LDFLAGS" -o bin/${APP}-${GOOS}-${GOARCH}${EXT} .
echo "Built: bin/${APP}-${GOOS}-${GOARCH}${EXT}"
SCRIPT
RUN chmod +x /usr/local/bin/build.sh
WORKDIR /app
ENTRYPOINT ["/usr/local/bin/build.sh"]
CMD ["darwin", "arm64"]
@@ -1,67 +0,0 @@
# Wails Server Mode Dockerfile
# Multi-stage build for a minimal image.
#
# Defaults produce a pure-Go, fully static binary on a distroless/static base:
# the smallest, most secure image, and correct for the default (CGO-free) app.
#
# If your app needs CGO, override the build args, e.g.:
# docker build --build-arg CGO_ENABLED=1 \
# --build-arg GO_IMAGE=golang:bookworm \
# --build-arg RUNTIME_IMAGE=gcr.io/distroless/base-debian12 \
# -f build/docker/Dockerfile.server .
# CGO needs a C toolchain in the builder and a libc in the runtime image; keep
# the builder and runtime libc compatible (a glibc builder -> a glibc runtime).
# The Taskfile passes these through: task build:docker CGO_ENABLED=1 GO_IMAGE=... RUNTIME_IMAGE=...
ARG GO_IMAGE=golang:alpine
ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12
ARG CGO_ENABLED=0
# Build stage
FROM ${GO_IMAGE} AS builder
ARG CGO_ENABLED
WORKDIR /app
# Install build dependencies: git always; a C compiler only when CGO is enabled.
# Supports both apk (alpine) and apt (debian/bookworm) base images.
RUN if command -v apk >/dev/null 2>&1; then \
apk add --no-cache git $([ "$CGO_ENABLED" = "1" ] && echo gcc musl-dev); \
else \
apt-get update && apt-get install -y --no-install-recommends git $([ "$CGO_ENABLED" = "1" ] && echo gcc libc6-dev) && rm -rf /var/lib/apt/lists/*; \
fi
# Copy source code
COPY . .
# Remove local replace directive if present (for production builds)
RUN sed -i '/^replace/d' go.mod || true
# Download dependencies
RUN go mod tidy
# Build the production server binary.
# - server,production tags: HTTP server mode with production code paths (no dev
# logger/asset middleware), matching the desktop production build.
# - CGO_ENABLED defaults to 0 for a fully static binary (distroless/static);
# override with --build-arg CGO_ENABLED=1 (see header) for CGO apps.
RUN CGO_ENABLED=${CGO_ENABLED} go build -tags server,production -trimpath -buildvcs=false -ldflags="-s -w" -o server .
# Runtime stage - minimal image
FROM ${RUNTIME_IMAGE}
# Copy the binary
COPY --from=builder /app/server /server
# Copy frontend assets
COPY --from=builder /app/frontend/dist /frontend/dist
# Expose the default port
EXPOSE 8080
# Bind to all interfaces (required for Docker)
# Can be overridden at runtime with -e WAILS_SERVER_HOST=...
ENV WAILS_SERVER_HOST=0.0.0.0
# Run the server
ENTRYPOINT ["/server"]
-116
View File
@@ -1,116 +0,0 @@
{
"info" : {
"author" : "xcode",
"version" : 1
},
"images" : [
{
"filename" : "icon-20@2x.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "icon-20@3x.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"filename" : "icon-29@2x.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "icon-29@3x.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"filename" : "icon-40@2x.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "icon-40@3x.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"filename" : "icon-60@2x.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"filename" : "icon-60@3x.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"filename" : "icon-20.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "20x20"
},
{
"filename" : "icon-20@2x.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "icon-29.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "29x29"
},
{
"filename" : "icon-29@2x.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "icon-40.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "40x40"
},
{
"filename" : "icon-40@2x.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "icon-76.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "76x76"
},
{
"filename" : "icon-76@2x.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "76x76"
},
{
"filename" : "icon-83.5@2x.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "83.5x83.5"
},
{
"filename" : "icon-1024.png",
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
]
}
-61
View File
@@ -1,61 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>settings.exe</string>
<key>CFBundleIdentifier</key>
<string>com.zerorigin.settings.dev</string>
<key>CFBundleName</key>
<string>ZerOriginTool Settings (Dev)</string>
<key>CFBundleDisplayName</key>
<string>ZerOriginTool Settings (Dev)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0-dev</string>
<key>CFBundleVersion</key>
<string>0.1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
<string>15.0</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<!-- Development mode enabled -->
<key>WailsDevelopmentMode</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>© 2026, My Company</string>
<key>CFBundleGetInfoString</key>
<string>This is a comment</string>
</dict>
</plist>
-59
View File
@@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>settings.exe</string>
<key>CFBundleIdentifier</key>
<string>com.zerorigin.settings</string>
<key>CFBundleName</key>
<string>ZerOriginTool Settings</string>
<key>CFBundleDisplayName</key>
<string>ZerOriginTool Settings</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1.0</string>
<key>CFBundleVersion</key>
<string>0.1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MinimumOSVersion</key>
<string>15.0</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSHumanReadableCopyright</key>
<string>© 2026, My Company</string>
<key>CFBundleGetInfoString</key>
<string>This is a comment</string>
</dict>
</plist>
@@ -1,53 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="21701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_12" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="21678"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ZerOriginTool Settings" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="397" width="393" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="A settings application" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
<rect key="frame" x="0.0" y="448" width="393" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/2" constant="-20" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" symbolic="YES" id="x7j-FC-K8j"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="top" secondItem="GJd-Yh-RWb" secondAttribute="bottom" constant="8" symbolic="YES" id="cPy-rs-vsC"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="centerX" secondItem="Bcu-3y-fUS" secondAttribute="centerX" id="OQL-iM-xY6"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" symbolic="YES" id="Dti-5h-tvW"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
-365
View File
@@ -1,365 +0,0 @@
version: '3'
includes:
common: ../Taskfile.yml
# Platform selection:
# task ios:package -> simulator bundle (ad-hoc signed)
# task ios:package IOS_PLATFORM=device CODESIGN_IDENTITY="Apple Development: ..." \
# [PROVISIONING_PROFILE=path.mobileprovision]
# -> device bundle (real signing)
# task ios:package:ipa IOS_PLATFORM=device ... -> .ipa for distribution/install
# For automatically managed signing & provisioning, use `task ios:xcode` and
# build from the generated Xcode project instead.
vars:
BUNDLE_ID: '{{.BUNDLE_ID | default "com.wails.app"}}'
IOS_PLATFORM: '{{.IOS_PLATFORM | default "simulator"}}'
MIN_IOS_VERSION: '{{.MIN_IOS_VERSION | default "15.0"}}'
IOS_SDK: '{{if eq .IOS_PLATFORM "device"}}iphoneos{{else}}iphonesimulator{{end}}'
IOS_TARGET: 'arm64-apple-ios{{.MIN_IOS_VERSION}}{{if ne .IOS_PLATFORM "device"}}-simulator{{end}}'
IOS_VERSION_MIN_FLAG: '{{if eq .IOS_PLATFORM "device"}}-miphoneos-version-min={{.MIN_IOS_VERSION}}{{else}}-mios-simulator-version-min={{.MIN_IOS_VERSION}}{{end}}'
# "-" is ad-hoc signing: fine for the simulator, rejected by real devices.
CODESIGN_IDENTITY: '{{.CODESIGN_IDENTITY | default "-"}}'
# Optional path to a .mobileprovision embedded into device bundles
PROVISIONING_PROFILE: '{{.PROVISIONING_PROFILE | default ""}}'
# Optional entitlements applied at codesign time (generated default below)
ENTITLEMENTS_FILE: '{{.ENTITLEMENTS_FILE | default "build/ios/entitlements.plist"}}'
# SDK_PATH is computed lazily at task-level to avoid errors on non-macOS systems
tasks:
install:deps:
summary: Check and install iOS development dependencies
cmds:
- go run build/ios/scripts/deps/install_deps.go
env:
TASK_FORCE_YES: '{{if .YES}}true{{else}}false{{end}}'
prompt: This will check and install iOS development dependencies. Continue?
# Note: Bindings generation may show CGO warnings for iOS C imports.
# These warnings are harmless and don't affect the generated bindings,
# as the generator only needs to parse Go types, not C implementations.
build:
summary: Creates a build of the application for iOS
deps:
- task: generate:ios:overlay
- task: generate:ios:xcode
- task: common:go:mod:tidy
- task: common:build:frontend
vars:
BUILD_FLAGS:
ref: .BUILD_FLAGS
PRODUCTION:
ref: .PRODUCTION
cmds:
- echo "Building iOS app {{.APP_NAME}} ({{.IOS_PLATFORM}})..."
- go build -buildmode=c-archive -overlay build/ios/xcode/overlay.json {{.BUILD_FLAGS}} -o {{.OUTPUT}}.a
vars:
BUILD_FLAGS: '{{if eq .PRODUCTION "true"}}-tags production,ios -trimpath -buildvcs=false -ldflags="-w -s"{{else}}-tags ios,debug -buildvcs=false -gcflags=all="-l"{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
SDK_PATH:
sh: xcrun --sdk {{.IOS_SDK}} --show-sdk-path
env:
GOOS: ios
CGO_ENABLED: 1
GOARCH: '{{.ARCH | default "arm64"}}'
PRODUCTION: '{{.PRODUCTION | default "false"}}'
CGO_CFLAGS: '-isysroot {{.SDK_PATH}} -target {{.IOS_TARGET}} {{.IOS_VERSION_MIN_FLAG}}'
CGO_LDFLAGS: '-isysroot {{.SDK_PATH}} -target {{.IOS_TARGET}}'
package:
summary: Packages a production build of the application into a `.app` bundle
deps:
- task: build
vars:
PRODUCTION: "true"
cmds:
- task: compile:ios:link
- task: create:app:bundle
package:ipa:
summary: Packages a production build into an .ipa (requires IOS_PLATFORM=device and a real CODESIGN_IDENTITY)
deps:
- task: package
cmds:
- rm -rf "{{.BIN_DIR}}/Payload" "{{.BIN_DIR}}/{{.APP_NAME}}.ipa"
- mkdir -p "{{.BIN_DIR}}/Payload"
- cp -R "{{.BIN_DIR}}/{{.APP_NAME}}.app" "{{.BIN_DIR}}/Payload/"
- cd "{{.BIN_DIR}}" && zip -qry "{{.APP_NAME}}.ipa" Payload
- rm -rf "{{.BIN_DIR}}/Payload"
- echo "Created {{.BIN_DIR}}/{{.APP_NAME}}.ipa"
# Link the Go c-archive with main.m into the final executable.
# Used by both the dev `run` flow and `package`.
compile:ios:link:
internal: true
summary: Link the iOS executable from the Go archive and main.m
vars:
SDK_PATH:
sh: xcrun --sdk {{.IOS_SDK}} --show-sdk-path
cmds:
- |
MAIN_M=build/ios/xcode/main/main.m
if [ ! -f "$MAIN_M" ]; then
MAIN_M=build/ios/main.m
fi
xcrun -sdk {{.IOS_SDK}} clang \
-target {{.IOS_TARGET}} \
-isysroot {{.SDK_PATH}} \
-framework Foundation -framework UIKit -framework WebKit \
-framework Security -framework CoreFoundation \
-framework UniformTypeIdentifiers \
-framework LocalAuthentication -framework UserNotifications \
-framework AVFoundation \
-framework CoreLocation -framework CoreMotion -framework SystemConfiguration \
-lresolv \
-o "{{.BIN_DIR}}/{{.APP_NAME | lower}}" \
"$MAIN_M" -Wl,-force_load,"{{.BIN_DIR}}/{{.APP_NAME}}.a"
create:app:bundle:
summary: Creates an iOS `.app` bundle
cmds:
- rm -rf "{{.BIN_DIR}}/{{.APP_NAME}}.app"
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.app"
- cp "{{.BIN_DIR}}/{{.APP_NAME | lower}}" "{{.BIN_DIR}}/{{.APP_NAME}}.app/"
- cp build/ios/Info.plist "{{.BIN_DIR}}/{{.APP_NAME}}.app/"
- |
# Embed the provisioning profile for device builds when provided
if [ "{{.IOS_PLATFORM}}" = "device" ] && [ -n "{{.PROVISIONING_PROFILE}}" ]; then
cp "{{.PROVISIONING_PROFILE}}" "{{.BIN_DIR}}/{{.APP_NAME}}.app/embedded.mobileprovision"
fi
- |
# Compile asset catalog and embed icons in the app bundle
APP_BUNDLE="{{.BIN_DIR}}/{{.APP_NAME}}.app"
AC_IN="build/ios/xcode/main/Assets.xcassets"
if [ -d "$AC_IN" ]; then
TMP_AC=$(mktemp -d)
xcrun actool \
--compile "$TMP_AC" \
--app-icon AppIcon \
--platform {{.IOS_SDK}} \
--minimum-deployment-target {{.MIN_IOS_VERSION}} \
--product-type com.apple.product-type.application \
--target-device iphone \
--target-device ipad \
--output-partial-info-plist "$APP_BUNDLE/assetcatalog_generated_info.plist" \
"$AC_IN"
if [ -f "$TMP_AC/Assets.car" ]; then
cp -f "$TMP_AC/Assets.car" "$APP_BUNDLE/Assets.car"
fi
rm -rf "$TMP_AC"
if [ -f "$APP_BUNDLE/assetcatalog_generated_info.plist" ]; then
/usr/libexec/PlistBuddy -c "Merge $APP_BUNDLE/assetcatalog_generated_info.plist" "$APP_BUNDLE/Info.plist" || true
fi
fi
- |
# Sign the bundle. Ad-hoc ("-") works on the simulator only; device
# builds need a real identity (and usually entitlements + profile).
# Entitlements are only applied to device builds - simulator bundles
# must not carry them (SpringBoard refuses to launch the app).
if [ "{{.IOS_PLATFORM}}" = "device" ] && [ -f "{{.ENTITLEMENTS_FILE}}" ]; then
codesign --force --sign "{{.CODESIGN_IDENTITY}}" --entitlements "{{.ENTITLEMENTS_FILE}}" "{{.BIN_DIR}}/{{.APP_NAME}}.app"
else
codesign --force --sign "{{.CODESIGN_IDENTITY}}" "{{.BIN_DIR}}/{{.APP_NAME}}.app"
fi
deploy-simulator:
summary: Deploy to iOS Simulator
deps: [package]
cmds:
- |
# Read the real bundle id from the built bundle (it comes from
# build/config.yml, not the BUNDLE_ID var, so it varies per project).
APP="{{.BIN_DIR}}/{{.APP_NAME}}.app"
BUNDLE_ID=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$APP/Info.plist")
xcrun simctl terminate booted "$BUNDLE_ID" 2>/dev/null || true
xcrun simctl uninstall booted "$BUNDLE_ID" 2>/dev/null || true
xcrun simctl install booted "$APP"
xcrun simctl launch booted "$BUNDLE_ID"
deploy-device:
summary: Install and launch on a connected device (requires IOS_PLATFORM=device build and real signing)
cmds:
- |
DEVICE="{{.DEVICE_ID}}"
if [ -z "$DEVICE" ]; then
DEVICE=$(xcrun devicectl list devices --hide-headers 2>/dev/null | awk 'NR==1 {print $3}')
fi
if [ -z "$DEVICE" ]; then
echo "No connected device found. Pass DEVICE_ID=<identifier> (see: xcrun devicectl list devices)"
exit 1
fi
xcrun devicectl device install app --device "$DEVICE" "{{.BIN_DIR}}/{{.APP_NAME}}.app"
BUNDLE_ID=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "{{.BIN_DIR}}/{{.APP_NAME}}.app/Info.plist")
xcrun devicectl device process launch --device "$DEVICE" "$BUNDLE_ID"
compile:ios:
summary: Compile the iOS executable from Go archive and main.m
deps:
- task: build
cmds:
- task: compile:ios:link
generate:ios:bindings:
internal: true
summary: Generates bindings for iOS with proper CGO flags
sources:
- "**/*.go"
- go.mod
- go.sum
generates:
- frontend/bindings/**/*
vars:
SDK_PATH:
sh: xcrun --sdk {{.IOS_SDK}} --show-sdk-path
cmds:
- wails3 generate bindings -f '{{.BUILD_FLAGS}}' -clean=true
env:
GOOS: ios
CGO_ENABLED: 1
GOARCH: '{{.ARCH | default "arm64"}}'
CGO_CFLAGS: '-isysroot {{.SDK_PATH}} -target {{.IOS_TARGET}} {{.IOS_VERSION_MIN_FLAG}}'
CGO_LDFLAGS: '-isysroot {{.SDK_PATH}} -target {{.IOS_TARGET}}'
ensure-simulator:
internal: true
summary: Ensure iOS Simulator is running and booted
silent: true
cmds:
- |
if ! xcrun simctl list devices booted | grep -q "Booted"; then
echo "Starting iOS Simulator..."
# Get first available iPhone device
DEVICE_ID=$(xcrun simctl list devices available | grep "iPhone" | head -1 | grep -o "[A-F0-9-]\{36\}" || true)
if [ -z "$DEVICE_ID" ]; then
echo "No iPhone simulator found. Creating one..."
RUNTIME=$(xcrun simctl list runtimes | grep iOS | tail -1 | awk '{print $NF}')
# Use the newest iPhone device type this Xcode knows about
DEVICE_TYPE=$(xcrun simctl list devicetypes | grep -oE "iPhone [0-9][^(]*" | tail -1 | xargs)
DEVICE_ID=$(xcrun simctl create "Wails iPhone" "${DEVICE_TYPE:-iPhone 15}" "$RUNTIME")
fi
# Boot the device
echo "Booting device $DEVICE_ID..."
xcrun simctl boot "$DEVICE_ID" 2>/dev/null || true
# Open Simulator app
open -a Simulator
# Wait for boot (max 30 seconds)
for i in {1..30}; do
if xcrun simctl list devices booted | grep -q "Booted"; then
echo "Simulator booted successfully"
break
fi
sleep 1
done
# Final check
if ! xcrun simctl list devices booted | grep -q "Booted"; then
echo "Failed to boot simulator after 30 seconds"
exit 1
fi
fi
preconditions:
- sh: command -v xcrun
msg: "xcrun not found. Please run 'wails3 task ios:install:deps' to install iOS development dependencies"
generate:ios:overlay:
internal: true
summary: Generate Go build overlay and iOS shim
sources:
- build/config.yml
generates:
- build/ios/xcode/overlay.json
- build/ios/xcode/gen/main_ios.gen.go
cmds:
- wails3 ios overlay:gen -out build/ios/xcode/overlay.json -config build/config.yml
generate:ios:xcode:
internal: true
summary: Generate iOS Xcode project structure and assets
sources:
- build/config.yml
- build/appicon.png
generates:
- build/ios/xcode/main/main.m
- build/ios/xcode/main/Assets.xcassets/**/*
- build/ios/xcode/project.pbxproj
cmds:
- wails3 ios xcode:gen -outdir build/ios/xcode -config build/config.yml
run:
summary: Run the application in iOS Simulator
deps:
- task: ensure-simulator
- task: compile:ios
cmds:
- rm -rf "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
- mkdir -p "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
- cp "{{.BIN_DIR}}/{{.APP_NAME | lower}}" "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/{{.APP_NAME | lower}}"
- cp build/ios/Info.dev.plist "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app/Info.plist"
- |
# Compile asset catalog and embed icons for dev bundle
APP_BUNDLE="{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
AC_IN="build/ios/xcode/main/Assets.xcassets"
if [ -d "$AC_IN" ]; then
TMP_AC=$(mktemp -d)
xcrun actool \
--compile "$TMP_AC" \
--app-icon AppIcon \
--platform iphonesimulator \
--minimum-deployment-target {{.MIN_IOS_VERSION}} \
--product-type com.apple.product-type.application \
--target-device iphone \
--target-device ipad \
--output-partial-info-plist "$APP_BUNDLE/assetcatalog_generated_info.plist" \
"$AC_IN"
if [ -f "$TMP_AC/Assets.car" ]; then
cp -f "$TMP_AC/Assets.car" "$APP_BUNDLE/Assets.car"
fi
rm -rf "$TMP_AC"
if [ -f "$APP_BUNDLE/assetcatalog_generated_info.plist" ]; then
/usr/libexec/PlistBuddy -c "Merge $APP_BUNDLE/assetcatalog_generated_info.plist" "$APP_BUNDLE/Info.plist" || true
fi
fi
- codesign --force --sign - "{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
- |
# The dev bundle id comes from build/ios/Info.dev.plist (derived from
# build/config.yml), so read it from the built bundle rather than
# assuming a com.wails.* prefix.
DEV_APP="{{.BIN_DIR}}/{{.APP_NAME}}.dev.app"
BUNDLE_ID=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$DEV_APP/Info.plist")
xcrun simctl terminate booted "$BUNDLE_ID" 2>/dev/null || true
xcrun simctl uninstall booted "$BUNDLE_ID" 2>/dev/null || true
xcrun simctl install booted "$DEV_APP"
xcrun simctl launch booted "$BUNDLE_ID"
xcode:
summary: Open the generated Xcode project for this app
cmds:
- task: generate:ios:xcode
- open build/ios/xcode/main.xcodeproj
logs:
summary: Stream iOS Simulator logs filtered to this app
cmds:
- |
xcrun simctl spawn booted log stream \
--level debug \
--style compact \
--predicate 'senderImagePath CONTAINS[c] "{{.APP_NAME | lower}}.app/" OR composedMessage CONTAINS[c] "{{.APP_NAME | lower}}" OR eventMessage CONTAINS[c] "{{.APP_NAME | lower}}" OR process == "{{.APP_NAME | lower}}" OR category CONTAINS[c] "{{.APP_NAME | lower}}"'
logs:dev:
summary: Stream logs for the dev bundle (used by `task ios:run`)
cmds:
- |
xcrun simctl spawn booted log stream \
--level debug \
--style compact \
--predicate 'senderImagePath CONTAINS[c] ".dev.app/" OR subsystem == "com.wails.{{.APP_NAME | lower}}.dev" OR process == "{{.APP_NAME | lower}}"'
logs:wide:
summary: Wide log stream to help discover the exact process/bundle identifiers
cmds:
- |
xcrun simctl spawn booted log stream \
--level debug \
--style compact \
--predicate 'senderImagePath CONTAINS[c] ".app/"'
@@ -1,10 +0,0 @@
//go:build !ios
package main
import "github.com/wailsapp/wails/v3/pkg/application"
// modifyOptionsForIOS is a no-op on non-iOS platforms
func modifyOptionsForIOS(opts *application.Options) {
// No modifications needed for non-iOS platforms
}
-11
View File
@@ -1,11 +0,0 @@
//go:build ios
package main
import "github.com/wailsapp/wails/v3/pkg/application"
// modifyOptionsForIOS adjusts the application options for iOS
func modifyOptionsForIOS(opts *application.Options) {
// Disable signal handlers on iOS to prevent crashes
opts.DisableDefaultSignalHandler = true
}
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- iOS development entitlements. Applied to device builds only
(task ios:package IOS_PLATFORM=device). Add capability keys here
(e.g. aps-environment) as your app needs them. -->
<key>get-task-allow</key>
<true/>
</dict>
</plist>
-3
View File
@@ -1,3 +0,0 @@
# iOS Icon Placeholder
# This file should be replaced with the actual app icon (1024x1024 PNG)
# The build process will generate all required icon sizes from this base icon
-22
View File
@@ -1,22 +0,0 @@
//go:build ios
// Minimal bootstrap: delegate comes from Go archive (WailsAppDelegate)
#import <UIKit/UIKit.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
@autoreleasepool {
// Disable buffering so stdout/stderr from Go log.Printf flush immediately
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
// Call UIApplicationMain IMMEDIATELY and start NOTHING else here. Do not
// start the Go runtime yet: starting it concurrently with UIApplicationMain
// intermittently corrupts the FrontBoard launch handshake on a physical
// device, so the app delegate's didFinishLaunchingWithOptions never fires
// (blank cold launch / 0x8BADF00D). Instead, the WailsAppDelegate (provided
// by the Go archive) starts the Go runtime itself from
// didFinishLaunchingWithOptions — i.e. only AFTER UIKit has delivered the
// launch — so the runtime never races the launch handshake.
return UIApplicationMain(argc, argv, nil, @"WailsAppDelegate");
}
}
-23
View File
@@ -1,23 +0,0 @@
//go:build ios
package main
import (
"C"
)
// For iOS builds we export a function the WailsAppDelegate can call.
// This wrapper keeps the user's main.go unmodified.
// WailsIOSMain runs the user's main() (application.New / app.Run). It is invoked
// by the WailsAppDelegate from didFinishLaunchingWithOptions — i.e. only AFTER
// UIKit has launched — on a BACKGROUND thread, so the Go runtime never starts
// concurrently with UIApplicationMain (that race intermittently corrupts the
// FrontBoard launch handshake on a physical device → blank cold launch /
// scene-create watchdog 0x8BADF00D). Keeping all app setup off the OS main
// thread also leaves UIApplicationMain unobstructed on the main thread.
//
//export WailsIOSMain
func WailsIOSMain() {
main()
}
-222
View File
@@ -1,222 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {};
objectVersion = 56;
objects = {
/* Begin PBXBuildFile section */
C0DEBEEF0000000000000001 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000002 /* main.m */; };
C0DEBEEF00000000000000F1 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000101 /* UIKit.framework */; };
C0DEBEEF00000000000000F2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000102 /* Foundation.framework */; };
C0DEBEEF00000000000000F3 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000103 /* WebKit.framework */; };
C0DEBEEF00000000000000F4 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000104 /* Security.framework */; };
C0DEBEEF00000000000000F5 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000105 /* CoreFoundation.framework */; };
C0DEBEEF00000000000000F6 /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000106 /* libresolv.tbd */; };
C0DEBEEF00000000000000F7 /* ZerOriginTool Settings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C0DEBEEF0000000000000107 /* ZerOriginTool Settings.a */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C0DEBEEF0000000000000002 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
C0DEBEEF0000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C0DEBEEF0000000000000004 /* ZerOriginTool Settings.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ZerOriginTool Settings.app"; sourceTree = BUILT_PRODUCTS_DIR; };
C0DEBEEF0000000000000101 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
C0DEBEEF0000000000000102 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
C0DEBEEF0000000000000103 /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };
C0DEBEEF0000000000000104 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };
C0DEBEEF0000000000000105 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };
C0DEBEEF0000000000000106 /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.text-based-dylib-definition; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
C0DEBEEF0000000000000107 /* ZerOriginTool Settings.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = "ZerOriginTool Settings.a"; path = "../../../bin/ZerOriginTool Settings.a"; sourceTree = SOURCE_ROOT; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
C0DEBEEF0000000000000010 = {
isa = PBXGroup;
children = (
C0DEBEEF0000000000000020 /* Products */,
C0DEBEEF0000000000000045 /* Frameworks */,
C0DEBEEF0000000000000030 /* main */,
);
sourceTree = "<group>";
};
C0DEBEEF0000000000000020 /* Products */ = {
isa = PBXGroup;
children = (
C0DEBEEF0000000000000004 /* ZerOriginTool Settings.app */,
);
name = Products;
sourceTree = "<group>";
};
C0DEBEEF0000000000000030 /* main */ = {
isa = PBXGroup;
children = (
C0DEBEEF0000000000000002 /* main.m */,
C0DEBEEF0000000000000003 /* Info.plist */,
);
path = main;
sourceTree = SOURCE_ROOT;
};
C0DEBEEF0000000000000045 /* Frameworks */ = {
isa = PBXGroup;
children = (
C0DEBEEF0000000000000101 /* UIKit.framework */,
C0DEBEEF0000000000000102 /* Foundation.framework */,
C0DEBEEF0000000000000103 /* WebKit.framework */,
C0DEBEEF0000000000000104 /* Security.framework */,
C0DEBEEF0000000000000105 /* CoreFoundation.framework */,
C0DEBEEF0000000000000106 /* libresolv.tbd */,
C0DEBEEF0000000000000107 /* ZerOriginTool Settings.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C0DEBEEF0000000000000040 /* ZerOriginTool Settings */ = {
isa = PBXNativeTarget;
buildConfigurationList = C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "ZerOriginTool Settings" */;
buildPhases = (
C0DEBEEF0000000000000055 /* Prebuild: Wails Go Archive */,
C0DEBEEF0000000000000050 /* Sources */,
C0DEBEEF0000000000000056 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = "ZerOriginTool Settings";
productName = "ZerOriginTool Settings";
productReference = C0DEBEEF0000000000000004 /* ZerOriginTool Settings.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C0DEBEEF0000000000000060 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1500;
ORGANIZATIONNAME = "My Company";
TargetAttributes = {
C0DEBEEF0000000000000040 = {
CreatedOnToolsVersion = 15.0;
};
};
};
buildConfigurationList = C0DEBEEF0000000000000080 /* Build configuration list for PBXProject "main" */;
compatibilityVersion = "Xcode 15.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = C0DEBEEF0000000000000010;
productRefGroup = C0DEBEEF0000000000000020 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C0DEBEEF0000000000000040 /* ZerOriginTool Settings */,
);
};
/* End PBXProject section */
/* Begin PBXFrameworksBuildPhase section */
C0DEBEEF0000000000000056 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C0DEBEEF00000000000000F7 /* ZerOriginTool Settings.a in Frameworks */,
C0DEBEEF00000000000000F1 /* UIKit.framework in Frameworks */,
C0DEBEEF00000000000000F2 /* Foundation.framework in Frameworks */,
C0DEBEEF00000000000000F3 /* WebKit.framework in Frameworks */,
C0DEBEEF00000000000000F4 /* Security.framework in Frameworks */,
C0DEBEEF00000000000000F5 /* CoreFoundation.framework in Frameworks */,
C0DEBEEF00000000000000F6 /* libresolv.tbd in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
C0DEBEEF0000000000000055 /* Prebuild: Wails Go Archive */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = "Prebuild: Wails Go Archive";
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\nAPP_ROOT=\"${PROJECT_DIR}/../../..\"\nPLATFORM=${PLATFORM_NAME:-iphonesimulator}\nSDK_PATH=${SDKROOT:-$(xcrun --sdk ${PLATFORM} --show-sdk-path)}\nif [ ${PLATFORM} = iphonesimulator ]; then GO_TARGET=arm64-apple-ios15.0-simulator; MIN_FLAG=-mios-simulator-version-min=15.0; else GO_TARGET=arm64-apple-ios15.0; MIN_FLAG=-miphoneos-version-min=15.0; fi\nexport GOOS=ios\nexport GOARCH=arm64\nexport CGO_ENABLED=1\nexport CGO_CFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET} ${MIN_FLAG}\"\nexport CGO_LDFLAGS=\"-isysroot ${SDK_PATH} -target ${GO_TARGET}\"\ncd \"${APP_ROOT}\"\n# Ensure overlay exists\nif [ ! -f build/ios/xcode/overlay.json ]; then\n wails3 ios overlay:gen -out build/ios/xcode/overlay.json -config build/config.yml || true\nfi\n# Always rebuild the Go c-archive; Go's build cache keeps this fast\n# and avoids stale binaries when .go sources change.\necho \"Building Go c-archive...\"\ngo build -buildmode=c-archive -overlay build/ios/xcode/overlay.json -o \"bin/ZerOriginTool Settings.a\"\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C0DEBEEF0000000000000050 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C0DEBEEF0000000000000001 /* main.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C0DEBEEF0000000000000090 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
INFOPLIST_FILE = main/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.zerorigin.settings";
PRODUCT_NAME = "ZerOriginTool Settings";
CODE_SIGNING_ALLOWED = NO;
SDKROOT = iphoneos;
};
name = Debug;
};
C0DEBEEF00000000000000A0 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
INFOPLIST_FILE = main/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = "com.zerorigin.settings";
PRODUCT_NAME = "ZerOriginTool Settings";
CODE_SIGNING_ALLOWED = NO;
SDKROOT = iphoneos;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C0DEBEEF0000000000000070 /* Build configuration list for PBXNativeTarget "ZerOriginTool Settings" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C0DEBEEF0000000000000090 /* Debug */,
C0DEBEEF00000000000000A0 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
C0DEBEEF0000000000000080 /* Build configuration list for PBXProject "main" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C0DEBEEF0000000000000090 /* Debug */,
C0DEBEEF00000000000000A0 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
/* End XCConfigurationList section */
};
rootObject = C0DEBEEF0000000000000060 /* Project object */;
}
@@ -1,319 +0,0 @@
// install_deps.go - iOS development dependency checker
// This script checks for required iOS development tools.
// It's designed to be portable across different shells by using Go instead of shell scripts.
//
// Usage:
// go run install_deps.go # Interactive mode
// TASK_FORCE_YES=true go run install_deps.go # Auto-accept prompts
// CI=true go run install_deps.go # CI mode (auto-accept)
package main
import (
"bufio"
"fmt"
"os"
"os/exec"
"strings"
)
type Dependency struct {
Name string
CheckFunc func() (bool, string) // Returns (success, details)
Required bool
InstallCmd []string
InstallMsg string
SuccessMsg string
FailureMsg string
}
func main() {
fmt.Println("Checking iOS development dependencies...")
fmt.Println("=" + strings.Repeat("=", 50))
fmt.Println()
hasErrors := false
dependencies := []Dependency{
{
Name: "Xcode",
CheckFunc: func() (bool, string) {
// Check if xcodebuild exists
if !checkCommand([]string{"xcodebuild", "-version"}) {
return false, ""
}
// Get version info
out, err := exec.Command("xcodebuild", "-version").Output()
if err != nil {
return false, ""
}
lines := strings.Split(string(out), "\n")
if len(lines) > 0 {
return true, strings.TrimSpace(lines[0])
}
return true, ""
},
Required: true,
InstallMsg: "Please install Xcode from the Mac App Store:\n https://apps.apple.com/app/xcode/id497799835\n Xcode is REQUIRED for iOS development (includes iOS SDKs, simulators, and frameworks)",
SuccessMsg: "✅ Xcode found",
FailureMsg: "❌ Xcode not found (REQUIRED)",
},
{
Name: "Xcode Developer Path",
CheckFunc: func() (bool, string) {
// Check if xcode-select points to a valid Xcode path
out, err := exec.Command("xcode-select", "-p").Output()
if err != nil {
return false, "xcode-select not configured"
}
path := strings.TrimSpace(string(out))
// Check if path exists and is in Xcode.app
if _, err := os.Stat(path); err != nil {
return false, "Invalid Xcode path"
}
// Verify it's pointing to Xcode.app (not just Command Line Tools)
if !strings.Contains(path, "Xcode.app") {
return false, fmt.Sprintf("Points to %s (should be Xcode.app)", path)
}
return true, path
},
Required: true,
InstallCmd: []string{"sudo", "xcode-select", "-s", "/Applications/Xcode.app/Contents/Developer"},
InstallMsg: "Xcode developer path needs to be configured",
SuccessMsg: "✅ Xcode developer path configured",
FailureMsg: "❌ Xcode developer path not configured correctly",
},
{
Name: "iOS SDK",
CheckFunc: func() (bool, string) {
// Get the iOS Simulator SDK path
cmd := exec.Command("xcrun", "--sdk", "iphonesimulator", "--show-sdk-path")
output, err := cmd.Output()
if err != nil {
return false, "Cannot find iOS SDK"
}
sdkPath := strings.TrimSpace(string(output))
// Check if the SDK path exists
if _, err := os.Stat(sdkPath); err != nil {
return false, "iOS SDK path not found"
}
// Check for UIKit framework (essential for iOS development)
uikitPath := fmt.Sprintf("%s/System/Library/Frameworks/UIKit.framework", sdkPath)
if _, err := os.Stat(uikitPath); err != nil {
return false, "UIKit.framework not found"
}
// Get SDK version
versionCmd := exec.Command("xcrun", "--sdk", "iphonesimulator", "--show-sdk-version")
versionOut, _ := versionCmd.Output()
version := strings.TrimSpace(string(versionOut))
return true, fmt.Sprintf("iOS %s SDK", version)
},
Required: true,
InstallMsg: "iOS SDK comes with Xcode. Please ensure Xcode is properly installed.",
SuccessMsg: "✅ iOS SDK found with UIKit framework",
FailureMsg: "❌ iOS SDK not found or incomplete",
},
{
Name: "iOS Simulator Runtime",
CheckFunc: func() (bool, string) {
if !checkCommand([]string{"xcrun", "simctl", "help"}) {
return false, ""
}
// Check if we can list runtimes
out, err := exec.Command("xcrun", "simctl", "list", "runtimes").Output()
if err != nil {
return false, "Cannot access simulator"
}
// Count iOS runtimes
lines := strings.Split(string(out), "\n")
count := 0
var versions []string
for _, line := range lines {
if strings.Contains(line, "iOS") && !strings.Contains(line, "unavailable") {
count++
// Extract version number
if parts := strings.Fields(line); len(parts) > 2 {
for _, part := range parts {
if strings.HasPrefix(part, "(") && strings.HasSuffix(part, ")") {
versions = append(versions, strings.Trim(part, "()"))
break
}
}
}
}
}
if count > 0 {
return true, fmt.Sprintf("%d runtime(s): %s", count, strings.Join(versions, ", "))
}
return false, "No iOS runtimes installed"
},
Required: true,
InstallMsg: "iOS Simulator runtimes come with Xcode. You may need to download them:\n Xcode → Settings → Platforms → iOS",
SuccessMsg: "✅ iOS Simulator runtime available",
FailureMsg: "❌ iOS Simulator runtime not available",
},
}
// Check each dependency
for _, dep := range dependencies {
success, details := dep.CheckFunc()
if success {
msg := dep.SuccessMsg
if details != "" {
msg = fmt.Sprintf("%s (%s)", dep.SuccessMsg, details)
}
fmt.Println(msg)
} else {
fmt.Println(dep.FailureMsg)
if details != "" {
fmt.Printf(" Details: %s\n", details)
}
if dep.Required {
hasErrors = true
if len(dep.InstallCmd) > 0 {
fmt.Println()
fmt.Println(" " + dep.InstallMsg)
fmt.Printf(" Fix command: %s\n", strings.Join(dep.InstallCmd, " "))
if promptUser("Do you want to run this command?") {
fmt.Println("Running command...")
cmd := exec.Command(dep.InstallCmd[0], dep.InstallCmd[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
fmt.Printf("Command failed: %v\n", err)
os.Exit(1)
}
fmt.Println("✅ Command completed. Please run this check again.")
} else {
fmt.Printf(" Please run manually: %s\n", strings.Join(dep.InstallCmd, " "))
}
} else {
fmt.Println(" " + dep.InstallMsg)
}
}
}
}
// Check for iPhone simulators
fmt.Println()
fmt.Println("Checking for iPhone simulator devices...")
if !checkCommand([]string{"xcrun", "simctl", "list", "devices"}) {
fmt.Println("❌ Cannot check for iPhone simulators")
hasErrors = true
} else {
out, err := exec.Command("xcrun", "simctl", "list", "devices").Output()
if err != nil {
fmt.Println("❌ Failed to list simulator devices")
hasErrors = true
} else if !strings.Contains(string(out), "iPhone") {
fmt.Println("⚠️ No iPhone simulator devices found")
fmt.Println()
// Get the latest iOS runtime
runtimeOut, err := exec.Command("xcrun", "simctl", "list", "runtimes").Output()
if err != nil {
fmt.Println(" Failed to get iOS runtimes:", err)
} else {
lines := strings.Split(string(runtimeOut), "\n")
var latestRuntime string
for _, line := range lines {
if strings.Contains(line, "iOS") && !strings.Contains(line, "unavailable") {
// Extract runtime identifier
parts := strings.Fields(line)
if len(parts) > 0 {
latestRuntime = parts[len(parts)-1]
}
}
}
if latestRuntime == "" {
fmt.Println(" No iOS runtime found. Please install iOS simulators in Xcode:")
fmt.Println(" Xcode → Settings → Platforms → iOS")
} else {
fmt.Println(" Would you like to create an iPhone 15 Pro simulator?")
createCmd := []string{"xcrun", "simctl", "create", "iPhone 15 Pro", "iPhone 15 Pro", latestRuntime}
fmt.Printf(" Command: %s\n", strings.Join(createCmd, " "))
if promptUser("Create simulator?") {
cmd := exec.Command(createCmd[0], createCmd[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
fmt.Printf(" Failed to create simulator: %v\n", err)
} else {
fmt.Println(" ✅ iPhone 15 Pro simulator created")
}
} else {
fmt.Println(" Skipping simulator creation")
fmt.Printf(" Create manually: %s\n", strings.Join(createCmd, " "))
}
}
}
} else {
// Count iPhone devices
count := 0
lines := strings.Split(string(out), "\n")
for _, line := range lines {
if strings.Contains(line, "iPhone") && !strings.Contains(line, "unavailable") {
count++
}
}
fmt.Printf("✅ %d iPhone simulator device(s) available\n", count)
}
}
// Final summary
fmt.Println()
fmt.Println("=" + strings.Repeat("=", 50))
if hasErrors {
fmt.Println("❌ Some required dependencies are missing or misconfigured.")
fmt.Println()
fmt.Println("Quick setup guide:")
fmt.Println("1. Install Xcode from Mac App Store (if not installed)")
fmt.Println("2. Open Xcode once and agree to the license")
fmt.Println("3. Install additional components when prompted")
fmt.Println("4. Run: sudo xcode-select -s /Applications/Xcode.app/Contents/Developer")
fmt.Println("5. Download iOS simulators: Xcode → Settings → Platforms → iOS")
fmt.Println("6. Run this check again")
os.Exit(1)
} else {
fmt.Println("✅ All required dependencies are installed!")
fmt.Println(" You're ready for iOS development with Wails!")
}
}
func checkCommand(args []string) bool {
if len(args) == 0 {
return false
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = nil
cmd.Stderr = nil
err := cmd.Run()
return err == nil
}
func promptUser(question string) bool {
// Check if we're in a non-interactive environment
if os.Getenv("CI") != "" || os.Getenv("TASK_FORCE_YES") == "true" {
fmt.Printf("%s [y/N]: y (auto-accepted)\n", question)
return true
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("%s [y/N]: ", question)
response, err := reader.ReadString('\n')
if err != nil {
return false
}
response = strings.ToLower(strings.TrimSpace(response))
return response == "y" || response == "yes"
}
-220
View File
@@ -1,220 +0,0 @@
version: '3'
includes:
common: ../Taskfile.yml
vars:
# Signing configuration - edit these values for your project
# PGP_KEY: "path/to/signing-key.asc"
# SIGN_ROLE: "builder" # Options: origin, maint, archive, builder
#
# Password is stored securely in system keychain. Run: wails3 setup signing
# Docker image for cross-compilation (used when building on non-Linux or no CC available)
CROSS_IMAGE: wails-cross
tasks:
build:
summary: Builds the application for Linux
cmds:
# Linux requires CGO - use Docker when:
# 1. Cross-compiling from non-Linux, OR
# 2. No C compiler is available, OR
# 3. Target architecture differs from host architecture (cross-arch compilation)
- task: '{{if and (eq OS "linux") (eq .HAS_CC "true") (eq .TARGET_ARCH ARCH)}}build:native{{else}}build:docker{{end}}'
vars:
ARCH: '{{.ARCH}}'
DEV: '{{.DEV}}'
OUTPUT: '{{.OUTPUT}}'
EXTRA_TAGS: '{{.EXTRA_TAGS}}'
OBFUSCATED: '{{.OBFUSCATED}}'
GARBLE_ARGS: '{{.GARBLE_ARGS}}'
vars:
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
# Determine target architecture (defaults to host ARCH if not specified)
TARGET_ARCH: '{{.ARCH | default ARCH}}'
# Check if a C compiler is available (gcc or clang) — cross-platform via wails3 tool
HAS_CC:
sh: 'wails3 tool has "gcc|clang"'
build:native:
summary: Builds the application natively on Linux
internal: true
deps:
- task: common:go:mod:tidy
- task: common:build:frontend
vars:
BUILD_FLAGS:
ref: .BUILD_FLAGS
OBFUSCATED:
ref: .OBFUSCATED
DEV:
ref: .DEV
- task: common:generate:icons
- task: generate:dotdesktop
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 {{.OUTPUT}}'
vars:
BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s"{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
env:
GOOS: linux
CGO_ENABLED: 1
GOARCH: '{{.ARCH | default ARCH}}'
build:docker:
summary: Builds for Linux using Docker (for non-Linux hosts or when no C compiler available)
internal: true
deps:
- task: common:build:frontend
vars:
OBFUSCATED:
ref: .OBFUSCATED
- task: common:generate:icons
- task: generate:dotdesktop
preconditions:
- sh: docker info > /dev/null 2>&1
msg: "Docker is required for cross-compilation to Linux. Please install Docker."
- sh: docker image inspect {{.CROSS_IMAGE}} > /dev/null 2>&1
msg: |
Docker image '{{.CROSS_IMAGE}}' not found.
Build it first: wails3 task setup:docker
cmds:
- docker run --rm -v "{{.ROOT_DIR}}:/app" {{.DOCKER_MOUNTS}} -e APP_NAME="{{.APP_NAME}}" {{if .EXTRA_TAGS}}-e EXTRA_TAGS="{{.EXTRA_TAGS}}"{{end}} {{if eq .OBFUSCATED "true"}}-e OBFUSCATED=true{{end}} {{if .GARBLE_ARGS}}-e GARBLE_ARGS="{{.GARBLE_ARGS}}"{{end}} "{{.CROSS_IMAGE}}" linux {{.DOCKER_ARCH}}
- cmd: docker run --rm -v "{{.ROOT_DIR}}:/app" alpine chown -R $(id -u):$(id -g) /app/bin
platforms: [linux, darwin]
- mkdir -p {{.BIN_DIR}}
- mv "bin/{{.APP_NAME}}-linux-{{.DOCKER_ARCH}}" "{{.OUTPUT}}"
vars:
DOCKER_ARCH: '{{.ARCH | default "amd64"}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
# Generate Docker volume mounts: Go module cache + go.mod replace directives
# Uses wails3 tool docker-mounts for cross-platform compatibility (Windows/Linux/macOS)
DOCKER_MOUNTS:
sh: 'wails3 tool docker-mounts'
package:
summary: Packages the application for Linux
deps:
- task: build
cmds:
- task: create:appimage
- task: create:deb
- task: create:rpm
- task: create:aur
create:appimage:
summary: Creates an AppImage
dir: build/linux/appimage
deps:
- task: build
- task: generate:dotdesktop
cmds:
- cp "{{.APP_BINARY}}" "{{.APP_NAME}}"
- cp ../../appicon.png "{{.APP_NAME}}.png"
- wails3 generate appimage -binary "{{.APP_NAME}}" -icon {{.ICON}} -desktopfile {{.DESKTOP_FILE}} -outputdir {{.OUTPUT_DIR}} -builddir {{.ROOT_DIR}}/build/linux/appimage/build
vars:
APP_NAME: '{{.APP_NAME}}'
APP_BINARY: '../../../bin/{{.APP_NAME}}'
ICON: '{{.APP_NAME}}.png'
DESKTOP_FILE: '../{{.APP_NAME}}.desktop'
OUTPUT_DIR: '../../../bin'
create:deb:
summary: Creates a deb package
deps:
- task: build
cmds:
- task: generate:dotdesktop
- task: generate:deb
create:rpm:
summary: Creates a rpm package
deps:
- task: build
cmds:
- task: generate:dotdesktop
- task: generate:rpm
create:aur:
summary: Creates a arch linux packager package
deps:
- task: build
cmds:
- task: generate:dotdesktop
- task: generate:aur
generate:deb:
summary: Creates a deb package
cmds:
- wails3 tool package -name "{{.APP_NAME}}" -format deb -config ./build/linux/nfpm/nfpm.yaml -out {{.ROOT_DIR}}/bin
generate:rpm:
summary: Creates a rpm package
cmds:
- wails3 tool package -name "{{.APP_NAME}}" -format rpm -config ./build/linux/nfpm/nfpm.yaml -out {{.ROOT_DIR}}/bin
generate:aur:
summary: Creates a arch linux packager package
cmds:
- wails3 tool package -name "{{.APP_NAME}}" -format archlinux -config ./build/linux/nfpm/nfpm.yaml -out {{.ROOT_DIR}}/bin
generate:dotdesktop:
summary: Generates a `.desktop` file
dir: build
cmds:
- mkdir -p {{.ROOT_DIR}}/build/linux/appimage
- wails3 generate .desktop -name "{{.APP_NAME}}" -exec "{{.EXEC}}" -icon "{{.ICON}}" -outputfile "{{.ROOT_DIR}}/build/linux/{{.APP_NAME}}.desktop" -categories "{{.CATEGORIES}}"
vars:
APP_NAME: '{{.APP_NAME}}'
EXEC: '{{.APP_NAME}}'
ICON: '{{.APP_NAME}}'
CATEGORIES: 'Development;'
OUTPUTFILE: '{{.ROOT_DIR}}/build/linux/{{.APP_NAME}}.desktop'
run:
cmds:
- '{{.BIN_DIR}}/{{.APP_NAME}}'
sign:deb:
summary: Signs the DEB package
desc: |
Signs the .deb package with a PGP key.
Set PGP_KEY in the vars section to override the key configured globally via
`wails3 setup` (~/.config/wails/defaults.yaml).
Password is retrieved from system keychain (run: wails3 setup signing)
deps:
- task: create:deb
cmds:
# PGP_KEY is optional: if unset, `wails3 tool sign` falls back to the key
# configured globally via `wails3 setup`.
- wails3 tool sign --input "{{.BIN_DIR}}/{{.APP_NAME}}*.deb" {{if .PGP_KEY}}--pgp-key "{{.PGP_KEY}}"{{end}} {{if .SIGN_ROLE}}--role "{{.SIGN_ROLE}}"{{end}}
sign:rpm:
summary: Signs the RPM package
desc: |
Signs the .rpm package with a PGP key.
Set PGP_KEY in the vars section to override the key configured globally via
`wails3 setup` (~/.config/wails/defaults.yaml).
Password is retrieved from system keychain (run: wails3 setup signing)
deps:
- task: create:rpm
cmds:
- wails3 tool sign --input "{{.BIN_DIR}}/{{.APP_NAME}}*.rpm" {{if .PGP_KEY}}--pgp-key "{{.PGP_KEY}}"{{end}}
sign:packages:
summary: Signs all Linux packages (DEB and RPM)
desc: |
Signs both .deb and .rpm packages with a PGP key.
Set PGP_KEY in the vars section to override the key configured globally via
`wails3 setup` (~/.config/wails/defaults.yaml).
Password is retrieved from system keychain (run: wails3 setup signing)
cmds:
- task: sign:deb
- task: sign:rpm
@@ -1,35 +0,0 @@
#!/usr/bin/env bash
# Copyright (c) 2018-Present Lea Anthony
# SPDX-License-Identifier: MIT
# Fail script on any error
set -euxo pipefail
# Define variables
APP_DIR="${APP_NAME}.AppDir"
# Create AppDir structure
mkdir -p "${APP_DIR}/usr/bin"
cp -r "${APP_BINARY}" "${APP_DIR}/usr/bin/"
cp "${ICON_PATH}" "${APP_DIR}/"
cp "${DESKTOP_FILE}" "${APP_DIR}/"
if [[ $(uname -m) == *x86_64* ]]; then
# Download linuxdeploy and make it executable
wget -q -4 -N https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage
chmod +x linuxdeploy-x86_64.AppImage
# Run linuxdeploy to bundle the application
./linuxdeploy-x86_64.AppImage --appdir "${APP_DIR}" --output appimage
else
# Download linuxdeploy and make it executable (arm64)
wget -q -4 -N https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-aarch64.AppImage
chmod +x linuxdeploy-aarch64.AppImage
# Run linuxdeploy to bundle the application (arm64)
./linuxdeploy-aarch64.AppImage --appdir "${APP_DIR}" --output appimage
fi
# Rename the generated AppImage
mv "${APP_NAME}*.AppImage" "${APP_NAME}.AppImage"
-13
View File
@@ -1,13 +0,0 @@
[Desktop Entry]
Version=1.0
Name=ZerOriginTool Settings
Comment=A settings application
# The Exec line includes %u to pass the URL to the application
Exec=/usr/local/bin/settings.exe %u
Terminal=false
Type=Application
Icon=settings.exe
Categories=Utility;
StartupWMClass=settings.exe
-80
View File
@@ -1,80 +0,0 @@
# Feel free to remove those if you don't want/need to use them.
# Make sure to check the documentation at https://nfpm.goreleaser.com
#
# The lines below are called `modelines`. See `:help modeline`
name: "settings.exe"
arch: ${GOARCH}
platform: "linux"
version: "0.1.0"
section: "default"
priority: "extra"
maintainer: ${GIT_COMMITTER_NAME} <${GIT_COMMITTER_EMAIL}>
description: "A settings application"
vendor: "My Company"
homepage: "https://wails.io"
license: "MIT"
release: "1"
contents:
- src: "./bin/settings.exe"
dst: "/usr/local/bin/settings.exe"
- src: "./build/appicon.png"
dst: "/usr/share/icons/hicolor/128x128/apps/settings.exe.png"
- src: "./build/linux/settings.exe.desktop"
dst: "/usr/share/applications/settings.exe.desktop"
# Default dependencies for the GTK4 + WebKitGTK 6.0 stack (Ubuntu 24.04+ / Debian 13+)
depends:
- libgtk-4-1
- libwebkitgtk-6.0-4
# Distribution-specific overrides for different package formats
overrides:
# RPM packages for Fedora / RHEL / AlmaLinux / Rocky Linux
rpm:
depends:
- gtk4
- webkitgtk6.0
# Arch Linux packages
archlinux:
depends:
- gtk4
- webkitgtk-6.0
# scripts section to ensure desktop database is updated after install
scripts:
postinstall: "./build/linux/nfpm/scripts/postinstall.sh"
# You can also add preremove, postremove if needed
# preremove: "./build/linux/nfpm/scripts/preremove.sh"
# postremove: "./build/linux/nfpm/scripts/postremove.sh"
# If you build your app with -tags gtk3 (legacy WebKit2GTK 4.1 stack — supported through v3.0.x, removed in v3.1),
# replace the depends/overrides above with these:
#
# depends:
# - libgtk-3-0
# - libwebkit2gtk-4.1-0
# overrides:
# rpm:
# depends:
# - gtk3
# - webkit2gtk4.1
# archlinux:
# depends:
# - gtk3
# - webkit2gtk-4.1
#
# replaces:
# - foobar
# provides:
# - bar
# recommends:
# - whatever
# suggests:
# - something-else
# conflicts:
# - not-foo
# - not-bar
# changelog: "changelog.yaml"
@@ -1,21 +0,0 @@
#!/bin/sh
# Update desktop database for .desktop file changes
# This makes the application appear in application menus and registers its capabilities.
if command -v update-desktop-database >/dev/null 2>&1; then
echo "Updating desktop database..."
update-desktop-database -q /usr/share/applications
else
echo "Warning: update-desktop-database command not found. Desktop file may not be immediately recognized." >&2
fi
# Update MIME database for custom URL schemes (x-scheme-handler)
# This ensures the system knows how to handle your custom protocols.
if command -v update-mime-database >/dev/null 2>&1; then
echo "Updating MIME database..."
update-mime-database -n /usr/share/mime
else
echo "Warning: update-mime-database command not found. Custom URL schemes may not be immediately recognized." >&2
fi
exit 0
@@ -1 +0,0 @@
#!/bin/bash
@@ -1 +0,0 @@
#!/bin/bash
@@ -1 +0,0 @@
#!/bin/bash
-195
View File
@@ -1,195 +0,0 @@
version: '3'
includes:
common: ../Taskfile.yml
vars:
# Signing configuration - edit these values for your project
# SIGN_CERTIFICATE: "path/to/certificate.pfx"
# SIGN_THUMBPRINT: "certificate-thumbprint" # Alternative to SIGN_CERTIFICATE
# TIMESTAMP_SERVER: "http://timestamp.digicert.com"
#
# Password is stored securely in system keychain. Run: wails3 setup signing
# Docker image for cross-compilation with CGO (used when CGO_ENABLED=1 on non-Windows)
CROSS_IMAGE: wails-cross
tasks:
build:
summary: Builds the application for Windows
cmds:
# Auto-detect CGO: if CGO_ENABLED=1, use Docker; otherwise use native Go cross-compile
- task: '{{if and (ne OS "windows") (eq .CGO_ENABLED "1")}}build:docker{{else}}build:native{{end}}'
vars:
ARCH: '{{.ARCH}}'
DEV: '{{.DEV}}'
EXTRA_TAGS: '{{.EXTRA_TAGS}}'
OBFUSCATED: '{{.OBFUSCATED}}'
GARBLE_ARGS: '{{.GARBLE_ARGS}}'
vars:
# Default to CGO_ENABLED=0 if not explicitly set
CGO_ENABLED: '{{.CGO_ENABLED | default "0"}}'
build:native:
summary: Builds the application using native Go cross-compilation
internal: true
deps:
- task: common:go:mod:tidy
- task: common:build:frontend
vars:
BUILD_FLAGS:
ref: .BUILD_FLAGS
OBFUSCATED:
ref: .OBFUSCATED
DEV:
ref: .DEV
- task: common:generate:icons
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:
- task: generate:syso
vars:
ARCH: '{{.ARCH}}'
- '{{if eq .OBFUSCATED "true"}}garble {{.GARBLE_ARGS}} build{{else}}go build{{end}} {{.BUILD_FLAGS}} -o "{{.BIN_DIR}}/{{.APP_NAME}}.exe"'
- cmd: powershell Remove-item *.syso
platforms: [windows]
- cmd: rm -f *.syso
platforms: [linux, darwin]
vars:
BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s -H windowsgui"{{end}}'
env:
GOOS: windows
CGO_ENABLED: '{{.CGO_ENABLED | default "0"}}'
GOARCH: '{{.ARCH | default ARCH}}'
build:docker:
summary: Cross-compiles for Windows using Docker with Zig (for CGO builds on non-Windows)
internal: true
deps:
- task: common:build:frontend
vars:
OBFUSCATED:
ref: .OBFUSCATED
- task: common:generate:icons
preconditions:
- sh: docker info > /dev/null 2>&1
msg: "Docker is required for CGO cross-compilation. Please install Docker."
- sh: docker image inspect {{.CROSS_IMAGE}} > /dev/null 2>&1
msg: |
Docker image '{{.CROSS_IMAGE}}' not found.
Build it first: wails3 task setup:docker
cmds:
- task: generate:syso
vars:
ARCH: '{{.ARCH}}'
- docker run --rm -v "{{.ROOT_DIR}}:/app" {{.DOCKER_MOUNTS}} -e APP_NAME="{{.APP_NAME}}" {{if .EXTRA_TAGS}}-e EXTRA_TAGS="{{.EXTRA_TAGS}}"{{end}} {{if eq .OBFUSCATED "true"}}-e OBFUSCATED=true{{end}} {{if .GARBLE_ARGS}}-e GARBLE_ARGS="{{.GARBLE_ARGS}}"{{end}} {{.CROSS_IMAGE}} windows {{.DOCKER_ARCH}}
- cmd: docker run --rm -v "{{.ROOT_DIR}}:/app" alpine chown -R $(id -u):$(id -g) /app/bin
platforms: [linux, darwin]
- rm -f *.syso
vars:
DOCKER_ARCH: '{{.ARCH | default "amd64"}}'
# Generate Docker volume mounts: Go module cache + go.mod replace directives
# Uses wails3 tool docker-mounts for cross-platform compatibility (Windows/Linux/macOS)
DOCKER_MOUNTS:
sh: 'wails3 tool docker-mounts'
package:
summary: Packages the application
cmds:
- task: '{{if eq (.FORMAT | default "nsis") "msix"}}create:msix:package{{else}}create:nsis:installer{{end}}'
vars:
INSTALL_SCOPE: '{{.INSTALL_SCOPE | default "machine"}}'
vars:
FORMAT: '{{.FORMAT | default "nsis"}}'
INSTALL_SCOPE: '{{.INSTALL_SCOPE | default "machine"}}'
generate:syso:
summary: Generates Windows `.syso` file
dir: build
cmds:
- wails3 generate syso -arch {{.ARCH}} -icon windows/icon.ico -manifest windows/wails.exe.manifest -info windows/info.json -out ../wails_windows_{{.ARCH}}.syso
vars:
ARCH: '{{.ARCH | default ARCH}}'
create:nsis:installer:
summary: Creates an NSIS installer
dir: build/windows/nsis
deps:
- task: build
preconditions:
- sh: '[ "{{.INSTALL_SCOPE}}" = "user" ] || [ "{{.INSTALL_SCOPE}}" = "machine" ]'
msg: "INSTALL_SCOPE must be 'user' or 'machine', got '{{.INSTALL_SCOPE}}'"
cmds:
# Create the Microsoft WebView2 bootstrapper if it doesn't exist
- wails3 generate webview2bootstrapper -dir "{{.ROOT_DIR}}/build/windows/nsis"
- |
{{if eq OS "windows"}}
makensis {{if eq .INSTALL_SCOPE "user"}}-DWAILS_INSTALL_SCOPE=user -DREQUEST_EXECUTION_LEVEL=user {{end}}-DARG_WAILS_{{.ARG_FLAG}}_BINARY="{{.ROOT_DIR}}\{{.BIN_DIR}}\{{.APP_NAME}}.exe" project.nsi
{{else}}
makensis {{if eq .INSTALL_SCOPE "user"}}-DWAILS_INSTALL_SCOPE=user -DREQUEST_EXECUTION_LEVEL=user {{end}}-DARG_WAILS_{{.ARG_FLAG}}_BINARY="{{.ROOT_DIR}}/{{.BIN_DIR}}/{{.APP_NAME}}.exe" project.nsi
{{end}}
vars:
ARCH: '{{.ARCH | default ARCH}}'
ARG_FLAG: '{{if eq .ARCH "amd64"}}AMD64{{else}}ARM64{{end}}'
INSTALL_SCOPE: '{{.INSTALL_SCOPE | default "machine"}}'
create:msix:package:
summary: Creates an MSIX package
deps:
- task: build
cmds:
- |-
wails3 tool msix \
--config "{{.ROOT_DIR}}/wails.json" \
--name "{{.APP_NAME}}" \
--executable "{{.ROOT_DIR}}/{{.BIN_DIR}}/{{.APP_NAME}}.exe" \
--arch "{{.ARCH}}" \
--out "{{.ROOT_DIR}}/{{.BIN_DIR}}/{{.APP_NAME}}-{{.ARCH}}.msix" \
{{if .CERT_PATH}}--cert "{{.CERT_PATH}}"{{end}} \
{{if .PUBLISHER}}--publisher "{{.PUBLISHER}}"{{end}} \
{{if .USE_MSIX_TOOL}}--use-msix-tool{{else}}--use-makeappx{{end}}
vars:
ARCH: '{{.ARCH | default ARCH}}'
CERT_PATH: '{{.CERT_PATH | default ""}}'
PUBLISHER: '{{.PUBLISHER | default ""}}'
USE_MSIX_TOOL: '{{.USE_MSIX_TOOL | default "false"}}'
install:msix:tools:
summary: Installs tools required for MSIX packaging
cmds:
- wails3 tool msix-install-tools
run:
cmds:
- '{{.BIN_DIR}}/{{.APP_NAME}}.exe'
sign:
summary: Signs the Windows executable
desc: |
Signs the .exe with an Authenticode certificate.
Set SIGN_CERTIFICATE or SIGN_THUMBPRINT to override the certificate
configured globally via `wails3 setup` (~/.config/wails/defaults.yaml).
Password is retrieved from system keychain (run: wails3 setup signing)
deps:
- task: build
cmds:
# Certificate vars are optional: if unset, `wails3 tool sign` falls back to
# the certificate configured globally via `wails3 setup`.
- wails3 tool sign --input "{{.BIN_DIR}}/{{.APP_NAME}}.exe" {{if .SIGN_CERTIFICATE}}--certificate "{{.SIGN_CERTIFICATE}}"{{end}} {{if .SIGN_THUMBPRINT}}--thumbprint "{{.SIGN_THUMBPRINT}}"{{end}} {{if .TIMESTAMP_SERVER}}--timestamp "{{.TIMESTAMP_SERVER}}"{{end}}
sign:installer:
summary: Signs the NSIS installer
desc: |
Creates and signs the NSIS installer.
Set SIGN_CERTIFICATE or SIGN_THUMBPRINT to override the certificate
configured globally via `wails3 setup` (~/.config/wails/defaults.yaml).
Password is retrieved from system keychain (run: wails3 setup signing)
deps:
- task: create:nsis:installer
vars:
INSTALL_SCOPE: '{{.INSTALL_SCOPE | default "machine"}}'
vars:
INSTALL_SCOPE: '{{.INSTALL_SCOPE | default "machine"}}'
cmds:
- wails3 tool sign --input "build/windows/nsis/{{.APP_NAME}}-installer.exe" {{if .SIGN_CERTIFICATE}}--certificate "{{.SIGN_CERTIFICATE}}"{{end}} {{if .SIGN_THUMBPRINT}}--thumbprint "{{.SIGN_THUMBPRINT}}"{{end}} {{if .TIMESTAMP_SERVER}}--timestamp "{{.TIMESTAMP_SERVER}}"{{end}}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

-15
View File
@@ -1,15 +0,0 @@
{
"fixed": {
"file_version": "0.1.0"
},
"info": {
"0000": {
"ProductVersion": "0.1.0",
"CompanyName": "My Company",
"FileDescription": "A settings application",
"LegalCopyright": "© 2026, My Company",
"ProductName": "ZerOriginTool Settings",
"Comments": "This is a comment"
}
}
}
@@ -1,55 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10"
IgnorableNamespaces="uap3">
<Identity
Name="com.zerorigin.settings"
Publisher="CN=My Company"
Version="0.1.0.0"
ProcessorArchitecture="x64" />
<Properties>
<DisplayName>ZerOriginTool Settings</DisplayName>
<PublisherDisplayName>My Company</PublisherDisplayName>
<Description>A settings application</Description>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
</Dependencies>
<Resources>
<Resource Language="en-us" />
</Resources>
<Applications>
<Application Id="com.zerorigin.settings" Executable="settings.exe" EntryPoint="Windows.FullTrustApplication">
<uap:VisualElements
DisplayName="ZerOriginTool Settings"
Description="A settings application"
BackgroundColor="transparent"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
<Extensions>
<desktop:Extension Category="windows.fullTrustProcess" Executable="settings.exe" />
</Extensions>
</Application>
</Applications>
<Capabilities>
<rescap:Capability Name="runFullTrust" />
</Capabilities>
</Package>
@@ -1,54 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<MsixPackagingToolTemplate
xmlns="http://schemas.microsoft.com/msix/packaging/msixpackagingtool/template/2022">
<Settings
AllowTelemetry="false"
ApplyACLsToPackageFiles="true"
GenerateCommandLineFile="true"
AllowPromptForPassword="false">
</Settings>
<Installer
Path="settings.exe"
Arguments=""
InstallLocation="C:\Program Files\My Company\ZerOriginTool Settings">
</Installer>
<PackageInformation
PackageName="ZerOriginTool Settings"
PackageDisplayName="ZerOriginTool Settings"
PublisherName="CN=My Company"
PublisherDisplayName="My Company"
Version="0.1.0.0"
PackageDescription="A settings application">
<Capabilities>
<Capability Name="runFullTrust" />
</Capabilities>
<Applications>
<Application
Id="com.zerorigin.settings"
Description="A settings application"
DisplayName="ZerOriginTool Settings"
ExecutableName="settings.exe"
EntryPoint="Windows.FullTrustApplication">
</Application>
</Applications>
<Resources>
<Resource Language="en-us" />
</Resources>
<Dependencies>
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.19041.0" />
</Dependencies>
<Properties>
<Framework>false</Framework>
<DisplayName>ZerOriginTool Settings</DisplayName>
<PublisherDisplayName>My Company</PublisherDisplayName>
<Description>A settings application</Description>
<Logo>Assets\AppIcon.png</Logo>
</Properties>
</PackageInformation>
<SaveLocation PackagePath="settings.msix" />
<PackageIntegrity>
<CertificatePath></CertificatePath>
</PackageIntegrity>
</MsixPackagingToolTemplate>
-119
View File
@@ -1,119 +0,0 @@
Unicode true
####
## Please note: Template replacements don't work in this file. They are provided with default defines like
## mentioned underneath.
## If the keyword is not defined, "wails_tools.nsh" will populate them.
## If they are defined here, "wails_tools.nsh" will not touch them. This allows you to use this project.nsi manually
## from outside of Wails for debugging and development of the installer.
##
## For development first make a wails nsis build to populate the "wails_tools.nsh":
## > wails build --target windows/amd64 --nsis
## Then you can call makensis on this file with specifying the path to your binary:
## For a AMD64 only installer:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe
## For a ARM64 only installer:
## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe
## For a installer with both architectures:
## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe
####
## The following information is taken from the wails_tools.nsh file, but they can be overwritten here.
####
## !define INFO_PROJECTNAME "my-project" # Default "settings"
## !define INFO_COMPANYNAME "My Company" # Default "My Company"
## !define INFO_PRODUCTNAME "My Product Name" # Default "ZerOriginTool Settings"
## !define INFO_PRODUCTVERSION "1.0.0" # Default "0.1.0"
## !define INFO_COPYRIGHT "(c) Now, My Company" # Default "© 2026, My Company"
###
## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe"
## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
####
## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html
## !define WAILS_INSTALL_SCOPE "user" # Default "machine" - set to "user" for per-user install ($LOCALAPPDATA) without UAC prompt
####
## Include the wails tools
####
!include "wails_tools.nsh"
# The version information for this two must consist of 4 parts
VIProductVersion "${INFO_PRODUCTVERSION}.0"
VIFileVersion "${INFO_PRODUCTVERSION}.0"
VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}"
VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer"
VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}"
VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}"
VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}"
# Enable HiDPI support. https://nsis.sourceforge.io/Reference/ManifestDPIAware
ManifestDPIAware true
!include "MUI.nsh"
!define MUI_ICON "..\icon.ico"
!define MUI_UNICON "..\icon.ico"
# !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314
!define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps
!define MUI_ABORTWARNING # This will warn the user if they exit from the installer.
!insertmacro MUI_PAGE_WELCOME # Welcome to the installer page.
# !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer
!insertmacro MUI_PAGE_DIRECTORY # In which folder install page.
!insertmacro MUI_PAGE_INSTFILES # Installing page.
!insertmacro MUI_PAGE_FINISH # Finished installation page.
!insertmacro MUI_UNPAGE_INSTFILES # Uninstalling page
!insertmacro MUI_LANGUAGE "English" # Set the Language of the installer
## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1
#!uninstfinalize 'signtool --file "%1"'
#!finalize 'signtool --file "%1"'
Name "${INFO_PRODUCTNAME}"
OutFile "..\..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file.
!if "${WAILS_INSTALL_SCOPE}" == "user"
InstallDir "$LOCALAPPDATA\Programs\${INFO_PRODUCTNAME}"
!else
InstallDir "$PROGRAMFILES64\${INFO_COMPANYNAME}\${INFO_PRODUCTNAME}"
!endif
ShowInstDetails show # This will always show the installation details.
Function .onInit
!insertmacro wails.checkArchitecture
FunctionEnd
Section
!insertmacro wails.setShellContext
!insertmacro wails.webview2runtime
SetOutPath $INSTDIR
!insertmacro wails.files
CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}"
!insertmacro wails.associateFiles
!insertmacro wails.associateCustomProtocols
!insertmacro wails.writeUninstaller
SectionEnd
Section "uninstall"
!insertmacro wails.setShellContext
RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath
RMDir /r $INSTDIR
Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk"
Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk"
!insertmacro wails.unassociateFiles
!insertmacro wails.unassociateCustomProtocols
!insertmacro wails.deleteUninstaller
SectionEnd
@@ -1,261 +0,0 @@
# DO NOT EDIT - Generated automatically by `wails build`
!include "x64.nsh"
!include "WinVer.nsh"
!include "FileFunc.nsh"
!ifndef INFO_PROJECTNAME
!define INFO_PROJECTNAME "settings"
!endif
!ifndef INFO_COMPANYNAME
!define INFO_COMPANYNAME "My Company"
!endif
!ifndef INFO_PRODUCTNAME
!define INFO_PRODUCTNAME "ZerOriginTool Settings"
!endif
!ifndef INFO_PRODUCTVERSION
!define INFO_PRODUCTVERSION "0.1.0"
!endif
!ifndef INFO_COPYRIGHT
!define INFO_COPYRIGHT "© 2026, My Company"
!endif
!ifndef PRODUCT_EXECUTABLE
!define PRODUCT_EXECUTABLE "${INFO_PROJECTNAME}.exe"
!endif
!ifndef UNINST_KEY_NAME
!define UNINST_KEY_NAME "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"
!endif
!define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${UNINST_KEY_NAME}"
!ifndef WAILS_INSTALL_SCOPE
!define WAILS_INSTALL_SCOPE "machine"
!endif
!ifndef REQUEST_EXECUTION_LEVEL
!if "${WAILS_INSTALL_SCOPE}" == "user"
!define REQUEST_EXECUTION_LEVEL "user"
!else
!define REQUEST_EXECUTION_LEVEL "admin"
!endif
!endif
RequestExecutionLevel "${REQUEST_EXECUTION_LEVEL}"
!ifdef ARG_WAILS_AMD64_BINARY
!define SUPPORTS_AMD64
!endif
!ifdef ARG_WAILS_ARM64_BINARY
!define SUPPORTS_ARM64
!endif
!ifdef SUPPORTS_AMD64
!ifdef SUPPORTS_ARM64
!define ARCH "amd64_arm64"
!else
!define ARCH "amd64"
!endif
!else
!ifdef SUPPORTS_ARM64
!define ARCH "arm64"
!else
!error "Wails: Undefined ARCH, please provide at least one of ARG_WAILS_AMD64_BINARY or ARG_WAILS_ARM64_BINARY"
!endif
!endif
!macro wails.checkArchitecture
!ifndef WAILS_WIN10_REQUIRED
!define WAILS_WIN10_REQUIRED "This product is only supported on Windows 10 (Server 2016) and later."
!endif
!ifndef WAILS_ARCHITECTURE_NOT_SUPPORTED
!define WAILS_ARCHITECTURE_NOT_SUPPORTED "This product can't be installed on the current Windows architecture. Supports: ${ARCH}"
!endif
${If} ${AtLeastWin10}
!ifdef SUPPORTS_AMD64
${if} ${IsNativeAMD64}
Goto ok
${EndIf}
!endif
!ifdef SUPPORTS_ARM64
${if} ${IsNativeARM64}
Goto ok
${EndIf}
!endif
IfSilent silentArch notSilentArch
silentArch:
SetErrorLevel 65
Abort
notSilentArch:
MessageBox MB_OK "${WAILS_ARCHITECTURE_NOT_SUPPORTED}"
Quit
${else}
IfSilent silentWin notSilentWin
silentWin:
SetErrorLevel 64
Abort
notSilentWin:
MessageBox MB_OK "${WAILS_WIN10_REQUIRED}"
Quit
${EndIf}
ok:
!macroend
!macro wails.files
!ifdef SUPPORTS_AMD64
${if} ${IsNativeAMD64}
File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_AMD64_BINARY}"
${EndIf}
!endif
!ifdef SUPPORTS_ARM64
${if} ${IsNativeARM64}
File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_ARM64_BINARY}"
${EndIf}
!endif
!macroend
!macro wails.writeUninstaller
WriteUninstaller "$INSTDIR\uninstall.exe"
SetRegView 64
!if "${WAILS_INSTALL_SCOPE}" == "user"
WriteRegStr HKCU "${UNINST_KEY}" "Publisher" "${INFO_COMPANYNAME}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayName" "${INFO_PRODUCTNAME}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayVersion" "${INFO_PRODUCTVERSION}"
WriteRegStr HKCU "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\${PRODUCT_EXECUTABLE}"
WriteRegStr HKCU "${UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegStr HKCU "${UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
IntFmt $0 "0x%08X" $0
WriteRegDWORD HKCU "${UNINST_KEY}" "EstimatedSize" "$0"
!else
WriteRegStr HKLM "${UNINST_KEY}" "Publisher" "${INFO_COMPANYNAME}"
WriteRegStr HKLM "${UNINST_KEY}" "DisplayName" "${INFO_PRODUCTNAME}"
WriteRegStr HKLM "${UNINST_KEY}" "DisplayVersion" "${INFO_PRODUCTVERSION}"
WriteRegStr HKLM "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\${PRODUCT_EXECUTABLE}"
WriteRegStr HKLM "${UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
WriteRegStr HKLM "${UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
IntFmt $0 "0x%08X" $0
WriteRegDWORD HKLM "${UNINST_KEY}" "EstimatedSize" "$0"
!endif
!macroend
!macro wails.deleteUninstaller
Delete "$INSTDIR\uninstall.exe"
SetRegView 64
!if "${WAILS_INSTALL_SCOPE}" == "user"
DeleteRegKey HKCU "${UNINST_KEY}"
!else
DeleteRegKey HKLM "${UNINST_KEY}"
!endif
!macroend
!macro wails.setShellContext
${If} ${REQUEST_EXECUTION_LEVEL} == "admin"
SetShellVarContext all
${else}
SetShellVarContext current
${EndIf}
!macroend
# Install webview2 by launching the bootstrapper
# See https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#online-only-deployment
!macro wails.webview2runtime
!ifndef WAILS_INSTALL_WEBVIEW_DETAILPRINT
!define WAILS_INSTALL_WEBVIEW_DETAILPRINT "Installing: WebView2 Runtime"
!endif
SetRegView 64
# If the admin key exists and is not empty then webview2 is already installed
ReadRegStr $0 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
${If} $0 != ""
Goto ok
${EndIf}
${If} ${REQUEST_EXECUTION_LEVEL} == "user"
# If the installer is run in user level, check the user specific key exists and is not empty then webview2 is already installed
ReadRegStr $0 HKCU "Software\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv"
${If} $0 != ""
Goto ok
${EndIf}
${EndIf}
SetDetailsPrint both
DetailPrint "${WAILS_INSTALL_WEBVIEW_DETAILPRINT}"
SetDetailsPrint listonly
InitPluginsDir
CreateDirectory "$pluginsdir\webview2bootstrapper"
SetOutPath "$pluginsdir\webview2bootstrapper"
File "MicrosoftEdgeWebview2Setup.exe"
ExecWait '"$pluginsdir\webview2bootstrapper\MicrosoftEdgeWebview2Setup.exe" /silent /install'
SetDetailsPrint both
ok:
!macroend
# Copy of APP_ASSOCIATE and APP_UNASSOCIATE macros from here https://gist.github.com/nikku/281d0ef126dbc215dd58bfd5b3a5cd5b
!macro APP_ASSOCIATE EXT FILECLASS DESCRIPTION ICON COMMANDTEXT COMMAND
; Backup the previously associated file class
ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" ""
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "${FILECLASS}_backup" "$R0"
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "${FILECLASS}"
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}" "" `${DESCRIPTION}`
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\DefaultIcon" "" `${ICON}`
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell" "" "open"
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open" "" `${COMMANDTEXT}`
WriteRegStr SHELL_CONTEXT "Software\Classes\${FILECLASS}\shell\open\command" "" `${COMMAND}`
!macroend
!macro APP_UNASSOCIATE EXT FILECLASS
; Backup the previously associated file class
ReadRegStr $R0 SHELL_CONTEXT "Software\Classes\.${EXT}" `${FILECLASS}_backup`
WriteRegStr SHELL_CONTEXT "Software\Classes\.${EXT}" "" "$R0"
DeleteRegKey SHELL_CONTEXT `Software\Classes\${FILECLASS}`
!macroend
!macro wails.associateFiles
; Create file associations
!macroend
!macro wails.unassociateFiles
; Delete app associations
!macroend
!macro CUSTOM_PROTOCOL_ASSOCIATE PROTOCOL DESCRIPTION ICON COMMAND
DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}"
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "" "${DESCRIPTION}"
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}" "URL Protocol" ""
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\DefaultIcon" "" "${ICON}"
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell" "" ""
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open" "" ""
WriteRegStr SHELL_CONTEXT "Software\Classes\${PROTOCOL}\shell\open\command" "" "${COMMAND}"
!macroend
!macro CUSTOM_PROTOCOL_UNASSOCIATE PROTOCOL
DeleteRegKey SHELL_CONTEXT "Software\Classes\${PROTOCOL}"
!macroend
!macro wails.associateCustomProtocols
; Create custom protocols associations
!macroend
!macro wails.unassociateCustomProtocols
; Delete app custom protocol associations
!macroend
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<assemblyIdentity type="win32" name="com.zerorigin.settings" version="0.1.0" processorArchitecture="*"/>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
<asmv3:application>
<asmv3:windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware> <!-- fallback for Windows 7 and 8 -->
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness> <!-- falls back to per-monitor if per-monitor v2 is not supported -->
</asmv3:windowsSettings>
</asmv3:application>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
-146
View File
@@ -1,146 +0,0 @@
// 设置进程的配置模型与读写。与主进程(zerorigin/internal/config)的
// JSON 格式完全兼容:trigger 采用扁平形式,action 使用 params 对象。
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// Config 为配置根结构(版本 1),与主进程一致。
type Config struct {
Version int `json:"version"`
Global GlobalConfig `json:"global"`
Rules []Rule `json:"rules"`
}
// GlobalConfig 为全局设置。
type GlobalConfig struct {
Enabled bool `json:"enabled"`
Theme string `json:"theme"`
LogLevel string `json:"log_level"`
}
// Rule 为一条规则。
type Rule struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
Trigger TriggerConfig `json:"trigger"`
Conditions []ConditionConfig `json:"conditions,omitempty"`
Actions []ActionConfig `json:"actions"`
CooldownMs int `json:"cooldown_ms"`
// Fullscreen 全屏行为:"" / "ignore"(默认,全屏前台窗口时忽略)/ "allow"(豁免)。
Fullscreen string `json:"fullscreen,omitempty"`
}
// TriggerConfig 为触发器配置。JSON 采用扁平形式(与主进程一致):
//
// {"type": "mouse_corner", "corner": "bottom_left", "screen": "all"}
type TriggerConfig struct {
Type string `json:"type"`
Params map[string]any `json:"-"`
}
// UnmarshalJSON 将扁平 JSON 拆分为 Type 与 Params。
func (t *TriggerConfig) UnmarshalJSON(b []byte) error {
var raw map[string]json.RawMessage
if err := json.Unmarshal(b, &raw); err != nil {
return err
}
if v, ok := raw["type"]; ok {
if err := json.Unmarshal(v, &t.Type); err != nil {
return err
}
delete(raw, "type")
}
t.Params = make(map[string]any, len(raw))
for k, v := range raw {
var x any
if err := json.Unmarshal(v, &x); err != nil {
return err
}
t.Params[k] = x
}
return nil
}
// MarshalJSON 将 Type 与 Params 展平回写,保证与主进程读写兼容。
func (t TriggerConfig) MarshalJSON() ([]byte, error) {
m := make(map[string]any, len(t.Params)+1)
for k, v := range t.Params {
m[k] = v
}
m["type"] = t.Type
return json.Marshal(m)
}
// ConditionConfig 为条件配置(MVP 仅空列表)。
type ConditionConfig struct {
Type string `json:"type"`
Params map[string]any `json:"params"`
}
// ActionConfig 为动作配置。
type ActionConfig struct {
Type string `json:"type"`
Params map[string]any `json:"params"`
}
// configPath 返回配置文件路径(与主进程一致)。
func configPath() (string, error) {
base := os.Getenv("LOCALAPPDATA")
if base == "" {
return "", fmt.Errorf("LOCALAPPDATA not set")
}
return filepath.Join(base, "ZerOriginTool", "config.json"), nil
}
// LoadConfig 读取配置;文件不存在时返回错误(由前端提示创建默认)。
func LoadConfig() (*Config, error) {
p, err := configPath()
if err != nil {
return nil, err
}
data, err := os.ReadFile(p)
if err != nil {
return nil, err
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return nil, fmt.Errorf("parse config: %w", err)
}
return &cfg, nil
}
// SaveConfig 原子保存配置(临时文件 + 替换),与主进程策略一致。
func SaveConfig(cfg *Config) error {
p, err := configPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(p), "config-*.tmp")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), p)
}
-63
View File
@@ -1,63 +0,0 @@
package main
import (
"encoding/json"
"strings"
"testing"
)
func TestValidateConfig(t *testing.T) {
cfg := &Config{Rules: []Rule{
{ID: "r1", Name: "好规则", Trigger: TriggerConfig{Type: "mouse_corner"}, Actions: []ActionConfig{{Type: "volume_up"}}},
{ID: "r2", Name: "坏触发器", Trigger: TriggerConfig{Type: "nope"}, Actions: []ActionConfig{{Type: "volume_up"}}},
{ID: "r3", Name: "空动作", Trigger: TriggerConfig{Type: "hotkey"}},
{ID: "r1", Name: "重复ID", Trigger: TriggerConfig{Type: "hotkey"}, Actions: []ActionConfig{{Type: "open_url"}}},
{ID: "r5", Name: "坏动作", Trigger: TriggerConfig{Type: "hotkey"}, Actions: []ActionConfig{{Type: "evil"}}},
}}
errs := ValidateConfig(cfg)
if len(errs) != 4 {
t.Fatalf("errs = %d, want 4: %v", len(errs), errs)
}
joined := strings.Join(errs, "\n")
for _, want := range []string{"未知触发器", "至少需要一个动作", "id 重复", "未知动作类型"} {
if !strings.Contains(joined, want) {
t.Errorf("missing error %q in: %s", want, joined)
}
}
}
func TestTriggerConfigRoundTrip(t *testing.T) {
src := `{"type":"mouse_corner","corner":"bottom_left","screen":"all","threshold_px":32}`
var tc TriggerConfig
if err := json.Unmarshal([]byte(src), &tc); err != nil {
t.Fatal(err)
}
if tc.Type != "mouse_corner" || tc.Params["corner"] != "bottom_left" {
t.Fatalf("unmarshal wrong: %+v", tc)
}
out, err := json.Marshal(&tc)
if err != nil {
t.Fatal(err)
}
var back TriggerConfig
if err := json.Unmarshal(out, &back); err != nil {
t.Fatal(err)
}
if back.Type != "mouse_corner" || back.Params["threshold_px"] != float64(32) {
t.Fatalf("round trip lost data: %s", out)
}
}
func TestSanitizeRule(t *testing.T) {
r := &Rule{
Trigger: TriggerConfig{Type: "hotkey", Params: map[string]any{"hotkey": " ctrl+alt+d "}},
Actions: []ActionConfig{{Type: "volume_up"}}, // params nil
}
sanitizeRule(r)
if r.Trigger.Params["hotkey"] != "ctrl+alt+d" {
t.Fatalf("hotkey not trimmed: %v", r.Trigger.Params)
}
if r.Actions[0].Params == nil {
t.Fatal("action params should be initialized")
}
}
-53
View File
@@ -1,53 +0,0 @@
package main
import "fmt"
// ConfigService 为前端提供配置读写能力。
// 通过 Wails 绑定,前端可直接调用其导出方法。
type ConfigService struct{}
// AppConfig 为返回给前端的完整配置视图(含可选元数据)。
type AppConfig struct {
Config *Config `json:"config"`
}
// Meta 为前端下拉与展示所需的静态元数据。
type Meta struct {
TriggerTypes map[string]string `json:"trigger_types"`
ActionTypes map[string]string `json:"action_types"`
}
// Load 读取当前配置。配置文件缺失时返回错误,前端引导用户先运行主程序。
func (s *ConfigService) Load() (*AppConfig, error) {
cfg, err := LoadConfig()
if err != nil {
return nil, fmt.Errorf("读取配置失败(请先运行 ZerOriginTool 生成默认配置): %v", err)
}
return &AppConfig{Config: cfg}, nil
}
// Meta 返回静态元数据(触发器/动作类型清单)。
func (s *ConfigService) Meta() *Meta {
return &Meta{
TriggerTypes: triggerLabels,
ActionTypes: actionLabels,
}
}
// Save 校验并原子保存配置。返回校验警告(不阻塞保存)与错误。
func (s *ConfigService) Save(cfg *Config) ([]string, error) {
if cfg == nil {
return nil, fmt.Errorf("配置为空")
}
if cfg.Version == 0 {
cfg.Version = 1
}
for i := range cfg.Rules {
sanitizeRule(&cfg.Rules[i])
}
warnings := ValidateConfig(cfg)
if err := SaveConfig(cfg); err != nil {
return warnings, fmt.Errorf("保存失败: %v", err)
}
return warnings, nil
}
-5
View File
@@ -1,5 +0,0 @@
# Refuse to install package versions published less than 7 days (10080 minutes)
# ago, reducing exposure to freshly compromised or malicious releases.
# Honoured by pnpm and bun; npm currently has no native support and ignores it,
# so this is harmless today and forward-compatible.
minimum-release-age=10080
@@ -1,93 +0,0 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
-18
View File
@@ -1,18 +0,0 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Type Support For `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin) to make the TypeScript language service aware of `.vue` types.
If the standalone TypeScript plugin doesn't feel fast enough to you, Volar has also implemented a [Take Over Mode](https://github.com/johnsoncodehk/volar/discussions/471#discussioncomment-1361669) that is more performant. You can enable it by the following steps:
1. Disable the built-in TypeScript Extension
1. Run `Extensions: Show Built-in Extensions` from VSCode's command palette
2. Find `TypeScript and JavaScript Language Features`, right click and select `Disable (Workspace)`
2. Reload the VSCode window by running `Developer: Reload Window` from the command palette.
@@ -1,9 +0,0 @@
//@ts-check
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import { Create as $Create } from "@wailsio/runtime";
Object.freeze($Create.Events);
@@ -1,2 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
@@ -1,37 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
/**
* ConfigService 为前端提供配置读写能力。
* 通过 Wails 绑定,前端可直接调用其导出方法。
* @module
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wailsio/runtime";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as $models from "./models.js";
/**
* Load 读取当前配置。配置文件缺失时返回错误,前端引导用户先运行主程序。
*/
export function Load(): $CancellablePromise<$models.AppConfig | null> {
return $Call.ByID(1374598707);
}
/**
* Meta 返回静态元数据(触发器/动作类型清单)。
*/
export function Meta(): $CancellablePromise<$models.Meta | null> {
return $Call.ByID(3472161870);
}
/**
* Save 校验并原子保存配置。返回校验警告(不阻塞保存)与错误。
*/
export function Save(cfg: $models.Config | null): $CancellablePromise<string[] | null> {
return $Call.ByID(2730444782, cfg);
}
@@ -1,18 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
import * as ConfigService from "./configservice.js";
export {
ConfigService
};
export type {
ActionConfig,
AppConfig,
ConditionConfig,
Config,
GlobalConfig,
Meta,
Rule,
TriggerConfig
} from "./models.js";
Loaded 100 of 202 files, more files were not shown because too many files have changed in this diff. Show more