| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791 |
- // ============================================================================
- //go:build !service
- // main.go — 应用入口(GUI)
- //
- // 创建 Wails 应用、主窗口与系统托盘,注册服务与窗口事件;
- // 启动每秒时间广播与待办提醒调度协程,随后进入事件循环。
- // 独立服务模式入口见 main_service.go(-tags service)。
- // ============================================================================
- package main
- import (
- "bytes" // 托盘菜单图标:PNG 编码缓冲区
- "embed" // Go 内嵌资源包:将前端静态文件打包进可执行文件
- "fmt" // 格式化 I/O:用于控制台打印调试信息
- "image" // 托盘菜单图标:RGBA 画布
- "image/color"
- "image/png" // 托盘菜单图标:将 RGBA 编码为 PNG 字节
- "log" // 日志:记录并输出错误
- "os" // 操作系统:服务模式退出码
- "strconv" // 数字转换:解析自定义 Tab 序号
- "strings" // 字符串处理:Tab id 折叠标记解析
- "sync" // 窗口尺寸保存防抖
- "time" // 时间处理:用于每秒定时发送事件
- "github.com/wailsapp/wails/v3/pkg/application" // Wails3 核心:应用/窗口/菜单/对话框/事件/托盘
- "github.com/wailsapp/wails/v3/pkg/events" // Wails3 事件常量:窗口关闭、文件拖放等
- "github.com/wailsapp/wails/v3/pkg/services/dock"
- )
- // ============================================================================
- // 前端资源嵌入
- // ============================================================================
- // Wails 使用 Go 的 `embed` 包将前端文件嵌入到二进制文件中。
- // frontend/dist 目录下的所有文件都会被嵌入到可执行文件里,
- // 并由 Wails 内置的资源服务器(Asset Server)提供给 WebView 前端访问。
- //go:embed all:frontend/dist
- var assets embed.FS // assets 持有 frontend/dist 下全部前端文件的只读文件系统
- //go:embed frontend/public/wails.png
- var trayIcon []byte // 嵌入系统托盘图标(PNG 格式)
- // 全局运行时对象:服务、API、托盘菜单都要用到应用实例与主窗口
- var (
- app *application.App // 应用实例
- mainWindow *application.WebviewWindow // 主窗口
- tray *application.SystemTray // 系统托盘(导入快捷配置后需重建菜单)
- // 快捷启动 ContextMenu:右键收拢圆点/句柄时弹出,用主窗口句柄作宿主,
- // 在光标位置显示(OpenContextMenu),不受收拢后 32x32 小窗口尺寸限制。
- quickContextMenu *application.ContextMenu
- // 窗口隐藏前的位置,恢复显示时还原
- savedX, savedY int
- hasSavedPos bool
- // explorerSvc 资源管理器悬停监听服务(全局引用,供「配置→系统」启停标签功能)。
- // 在 main 中创建并 Start;SaveSettings 切换 TagMenuEnabled 时启停。
- explorerSvc *explorerService
- )
- // showMainWindow 统一显示入口:先还原位置,再显示并聚焦。
- // 托盘、热键、API 接口都通过它唤出窗口。
- func showMainWindow() {
- if mainWindow == nil {
- return
- }
- // 热键/托盘呼出时,即使窗口已收拢为圆点,也先还原到收拢前的尺寸。
- compactMu.Lock()
- wasCompact := compactActive
- compactMu.Unlock()
- if wasCompact {
- (&SettingsService{}).ToggleWindowCompact()
- }
- if hasSavedPos {
- mainWindow.SetPosition(savedX, savedY) // 还原隐藏前的窗口坐标
- }
- mainWindow.Show() // 显示窗口
- mainWindow.Focus() // 聚焦到前台
- if wasCompact && app != nil {
- app.Event.Emit("windowCompact", false) // 通知前端移除圆点收拢样式
- }
- }
- // showQuickMenuAtCursor 「快捷」菜单全局热键回调:显示窗口(若收拢先还原),
- // 获取当前鼠标位置,向前端发射 showQuickMenuAt 事件(带屏幕坐标),前端据此在鼠标位置弹出快捷菜单。
- func showQuickMenuAtCursor() {
- if mainWindow == nil {
- return
- }
- // 若窗口收拢为圆点,先还原到收拢前尺寸(菜单需要完整的可视区域)
- compactMu.Lock()
- wasCompact := compactActive
- compactMu.Unlock()
- if wasCompact {
- (&SettingsService{}).ToggleWindowCompact()
- if app != nil {
- app.Event.Emit("windowCompact", false)
- }
- }
- mainWindow.Show()
- mainWindow.Focus()
- // 读取鼠标屏幕坐标,通知前端在鼠标处弹菜单
- x, y := cursorScreenPos()
- if app != nil {
- app.Event.Emit("showQuickMenuAt", map[string]int{"x": x, "y": y})
- }
- }
- // toggleProxyByHotkey 「网络代理」开关全局热键回调:切换系统代理启用/禁用,
- // 并向前端发射 proxyChanged 事件刷新工具页「网络代理」卡片状态。
- // 同时在鼠标位置弹出提示文字:网络代理已启动/关闭。
- func toggleProxyByHotkey() {
- if app == nil {
- return
- }
- st, err := NewProxyService().ToggleProxy()
- if err != nil {
- log.Printf("toggle proxy by hotkey failed: %v", err)
- return
- }
- app.Event.Emit("proxyChanged", map[string]any{
- "enabled": st.Enabled,
- "server": st.Server,
- "configured": st.Configured,
- })
- // 鼠标光标下方提示:网络代理已启动/已关闭
- if st.Enabled {
- triggerMouseAlert("网络代理已启动")
- } else {
- triggerMouseAlert("网络代理已关闭")
- }
- }
- var (
- windowSizeSaveMu sync.Mutex
- windowSizeSaveTimer *time.Timer
- )
- // rememberWindowSize 延迟保存窗口尺寸,避免拖动边框时频繁写配置文件。
- func rememberWindowSize(width, height int) {
- if width <= 0 || height <= 0 {
- return
- }
- windowSizeSaveMu.Lock()
- defer windowSizeSaveMu.Unlock()
- if windowSizeSaveTimer != nil {
- windowSizeSaveTimer.Stop()
- }
- windowSizeSaveTimer = time.AfterFunc(500*time.Millisecond, func() {
- windowSizeSaveMu.Lock()
- defer windowSizeSaveMu.Unlock()
- settings := loadSettings()
- if settings.WindowWidth == width && settings.WindowHeight == height {
- return
- }
- settings.WindowWidth, settings.WindowHeight = width, height
- if err := saveSettings(settings); err != nil {
- log.Printf("保存窗口尺寸失败:%v", err)
- }
- })
- }
- // init 在 main 函数之前自动执行,用于应用启动前的注册工作。
- func init() {
- application.RegisterEvent[string]("time") // 注册 string 类型的自定义事件,绑定生成器据此为前端生成强类型事件 API
- application.RegisterEvent[string]("apilog") // Gin 日志行实时推送(「主机」页订阅)
- application.RegisterEvent[string]("todoReminder") // 待办提醒:到点时向前端广播提醒内容
- application.RegisterEvent[string]("ntfyChat") // ntfy 聊天室:订阅主题后收到消息广播给前端
- application.RegisterEvent[int]("handleFlash") // 拖动手柄圆点闪烁:API 触发,前端播放颜色+大小动画
- application.RegisterEvent[bool]("windowCompact") // 后端呼出窗口时同步圆点收拢/还原状态
- application.RegisterEvent[string]("switchTab") // 托盘菜单点击 Tab:前端切换到对应页面
- application.RegisterEvent[PhoneDevicesPayload]("phone:devices") // 手机工具:adb devices 轮询结果广播给前端
- // 升级状态由 Wails 内置升级框架自行推给前端(wails:updater:* 系列事件),无需在此注册
- }
- // trayTabItem 托盘菜单里的一个 Tab 入口(显示名 + 前端 tabId)
- type trayTabItem struct {
- name string // 菜单显示文字(与 Tab 按钮同名)
- id string // 前端 tabId(内置 id 或 custom-N)
- }
- // trayTabItems 按已保存配置的 Tab 顺序生成托盘菜单项(「设置」除外,托盘里单独固定一项)。
- // 前端同名逻辑:内置 Tab 用固定中文名,自定义 Tab 用配置里的名字。
- func trayTabItems() []trayTabItem {
- settings := loadSettings()
- // 内置 Tab 名称(与前端 TAB_NAMES 保持一致)
- builtin := map[string]string{
- "links": "网址", "news": "新闻", "github": "Github", "stock": "股市",
- "todo": "待办", "record": "记录", "tools": "工具", "locals": "本地",
- "control": "控制", "host": "服务", "update": "更新", "settings": "设置",
- }
- nameFor := func(id string) (string, bool) {
- if n, ok := builtin[id]; ok {
- return n, true
- }
- // 自定义 Tab:id 形如 custom-3
- if i, err := strconv.Atoi(strings.TrimPrefix(id, "custom-")); err == nil {
- if i >= 0 && i < len(settings.CustomTabs) && settings.CustomTabs[i].Name != "" {
- return settings.CustomTabs[i].Name, true
- }
- }
- return "", false
- }
- items := make([]trayTabItem, 0, len(settings.TabOrder))
- seen := make(map[string]bool, len(settings.TabOrder))
- add := func(id, name string) {
- if seen[id] {
- return
- }
- seen[id] = true
- items = append(items, trayTabItem{name: name, id: id})
- }
- for _, raw := range settings.TabOrder {
- id := strings.TrimSpace(raw)
- wrapped := strings.HasPrefix(id, "[") && strings.HasSuffix(id, "]")
- if wrapped {
- id = strings.TrimSpace(id[1 : len(id)-1]) // 去掉「更多」折叠标记
- }
- if id == "settings" {
- continue // 「设置」在托盘里固定在分隔线下方单独一项
- }
- if name, ok := nameFor(id); ok {
- add(id, name)
- }
- }
- return items
- }
- // ============================================================================
- // 托盘菜单图标:用 image/png 程序化生成 16×16 图标,无需随仓库附带素材文件。
- // SetBitmap 只接收 PNG 字节,因此这里现画现编码。
- // ============================================================================
- // drawMenuIcon 在 16×16 画布上执行 draw,再把画布编码为 PNG 字节。
- func drawMenuIcon(draw func(img *image.RGBA)) []byte {
- img := image.NewRGBA(image.Rect(0, 0, 16, 16))
- draw(img)
- var buf bytes.Buffer
- _ = png.Encode(&buf, img) // 固定 16×16 RGBA 编码不会失败
- return buf.Bytes()
- }
- // trayIconLight 浅色托盘菜单图标配色
- var trayIconLight = color.RGBA{226, 232, 240, 255}
- // iconWindow 窗口图标:表示「显示主窗口」
- func iconWindow() []byte {
- return drawMenuIcon(func(img *image.RGBA) {
- c := trayIconLight
- for y := 2; y <= 13; y++ {
- for x := 2; x <= 13; x++ {
- if y == 2 || y == 13 || x == 2 || x == 13 || y == 5 {
- img.Set(x, y, c)
- }
- }
- }
- d := color.RGBA{120, 170, 255, 255}
- for y := 7; y <= 12; y++ {
- for x := 4; x <= 11; x++ {
- if x <= y+2 {
- img.Set(x, y, d)
- }
- }
- }
- })
- }
- // iconGear 齿轮图标:表示「设置」
- func iconGear() []byte {
- return drawMenuIcon(func(img *image.RGBA) {
- c := trayIconLight
- for x := 0; x <= 15; x++ {
- for y := 0; y <= 15; y++ {
- dx, dy := x-7, y-7
- r := dx*dx + dy*dy
- if r <= 25 && r >= 9 {
- img.Set(x, y, c)
- }
- }
- }
- })
- }
- // iconPower 电源图标(圆环 + 顶部竖线):表示「关机」
- func iconPower() []byte {
- return drawMenuIcon(func(img *image.RGBA) {
- c := color.RGBA{255, 200, 120, 255}
- // 圆环:半径约 6,中心 (7, 8)
- for x := 0; x <= 15; x++ {
- for y := 0; y <= 15; y++ {
- dx, dy := x-7, y-8
- r := dx*dx + dy*dy
- if r >= 28 && r <= 42 { // 环带
- img.Set(x, y, c)
- }
- }
- }
- // 顶部竖线(电源键柄),覆盖圆环缺口
- for y := 1; y <= 8; y++ {
- img.Set(7, y, c)
- img.Set(8, y, c)
- }
- })
- }
- // iconExit 叉号图标:表示「退出」
- func iconExit() []byte {
- return drawMenuIcon(func(img *image.RGBA) {
- c := color.RGBA{255, 138, 138, 255}
- put := func(x, y int) {
- if x >= 0 && x <= 15 && y >= 0 && y <= 15 { // 防止对角线端点越界
- img.Set(x, y, c)
- }
- }
- for x := 3; x <= 12; x++ {
- put(x, x+3) // 主对角线
- put(x, 21-x) // 副对角线
- }
- })
- }
- // hasQuickItems 判断是否配置了任何快捷启动项(任一分组含非空条目)。
- // 托盘菜单据此决定是否显示「快捷」子菜单:未配置任何快捷项则不显示。
- func hasQuickItems() bool {
- for _, g := range loadSettings().QuickGroups {
- if len(g.Items) > 0 {
- return true
- }
- }
- return false
- }
- // buildQuickTrayMenu 把「快捷」启动分组构建为托盘子菜单。
- // 复用 buildQuickMenu 的通用构建逻辑(分组子菜单 + 条目图标 + 点击启动)。
- func buildQuickTrayMenu(menu *application.Menu) {
- buildQuickMenu(menu)
- }
- // buildQuickMenu 把「快捷」启动分组构建为指定 Menu 的项:
- // 每个命名分组生成一个子菜单,未分组条目直接放在顶层;条目点击即启动应用,
- // 并尽量挂上 16x16 程序图标(quickIconCachedPNG 缓存)。托盘菜单与
- // 快捷 ContextMenu 共用此构建逻辑,保证两处菜单项一致。
- func buildQuickMenu(menu *application.Menu) {
- groups := loadSettings().QuickGroups
- added := false
- for _, g := range groups {
- if len(g.Items) == 0 {
- continue
- }
- if g.Name != "" {
- // 有分组名:生成一个子菜单,组内条目作为菜单项
- sub := menu.AddSubmenu(g.Name)
- for _, it := range g.Items {
- item := it // 闭包捕获当前条目
- mi := sub.Add(item.Title)
- if item.Desc != "" {
- mi.SetTooltip(item.Desc)
- }
- if icon, ok := quickIconCachedPNG(item.Path); ok {
- mi.SetBitmap(icon) // 缓存 16x16 PNG,显示程序图标
- }
- mi.OnClick(func(_ *application.Context) {
- if _, err := (&LocalService{}).Launch(item.Title, item.Path); err != nil {
- log.Printf("quick launch %q failed: %v", item.Title, err)
- }
- })
- }
- added = true
- } else {
- // 未分组条目:直接放在菜单顶层
- for _, it := range g.Items {
- item := it // 闭包捕获当前条目
- mi := menu.Add(item.Title)
- if item.Desc != "" {
- mi.SetTooltip(item.Desc)
- }
- if icon, ok := quickIconCachedPNG(item.Path); ok {
- mi.SetBitmap(icon) // 缓存 16x16 PNG,显示程序图标
- }
- mi.OnClick(func(_ *application.Context) {
- if _, err := (&LocalService{}).Launch(item.Title, item.Path); err != nil {
- log.Printf("quick launch %q failed: %v", item.Title, err)
- }
- })
- added = true
- }
- }
- }
- if !added {
- // 无任何快捷项时给出提示(禁用项),避免空白菜单
- menu.Add("(未配置快捷项,请在 设置-快捷 中添加)").SetEnabled(false)
- }
- }
- // buildTrayMenu 构建托盘右键菜单:
- // 显示主窗口 → 「快捷」子菜单(仅配置了快捷项时显示)→ Tab 列表 → 设置/退出。
- // 每次调用都会重建 ContextMenu 与托盘菜单,保证「快捷」项与最新设置一致
- // (导入 Biniware Run 配置后调用 refreshQuickMenus 刷新)。
- func buildTrayMenu() {
- if tray == nil {
- return
- }
- trayMenu := application.NewMenu()
- // 菜单项图标:运行时程序化生成 16×16 PNG(SetBitmap 支持,官方系统托盘文档标注 Windows/macOS/Linux 均支持)
- trayMenu.Add("显示主窗口").SetBitmap(iconWindow()).OnClick(func(_ *application.Context) {
- showMainWindow() // 显示窗口到隐藏前的位置并聚焦
- })
- trayMenu.AddSeparator() // 「显示主窗口」与「快捷」之间的分隔线
- // 「快捷」子菜单(第二个位置):直接列出各个应用的快捷启动项(点击即启动),
- // 按设置的快捷分组组织;未分组条目放在「快捷」菜单顶层。
- // 仅当配置了快捷项时才显示该子菜单(未配置则不出现)。
- if hasQuickItems() {
- buildQuickTrayMenu(trayMenu.AddSubmenu("快捷"))
- }
- // 为每个 Tab 生成同名菜单项:点击后显示窗口并切到对应页面
- for _, tab := range trayTabItems() {
- id := tab.id // 闭包捕获当前 Tab id
- trayMenu.Add(tab.name).OnClick(func(_ *application.Context) {
- showMainWindow()
- if app != nil {
- app.Event.Emit("switchTab", id) // 前端收到后切换到该 Tab
- }
- })
- }
- // 快捷启动 ContextMenu(右键收拢圆点/句柄时弹出):
- // 与托盘菜单共用 buildQuickMenu 构建逻辑。OpenContextMenu 用主窗口句柄作宿主,
- // 在光标位置弹出,不受收拢后 32x32 小窗口尺寸限制(修复收拢态右键不弹菜单)。
- quickContextMenu = application.NewContextMenu("quickmenu")
- buildQuickMenu(quickContextMenu.Menu)
- trayMenu.AddSeparator() // Tab 列表与「设置 / 退出」之间的分隔线
- trayMenu.Add("设置").SetBitmap(iconGear()).OnClick(func(_ *application.Context) {
- showMainWindow()
- if app != nil {
- app.Event.Emit("switchTab", "settings")
- }
- })
- // 「关机」:设置与退出之间。点击后由前端弹出确认框(showConfirm),
- // 用户确认才调用 SettingsService.PoweroffNow 立即关机。
- trayMenu.Add("关机").SetBitmap(iconPower()).OnClick(func(_ *application.Context) {
- if app != nil {
- app.Event.Emit("trayPoweroff") // 前端监听后弹出确认框
- }
- })
- trayMenu.Add("退出").SetBitmap(iconExit()).OnClick(func(_ *application.Context) {
- app.Quit() // 彻底退出应用
- })
- tray.SetMenu(trayMenu) // 设置托盘右键菜单
- }
- // refreshQuickMenus 在快捷配置变更后重建托盘菜单与快捷 ContextMenu,
- // 使「快捷」子菜单(第二个位置)与右键菜单立即反映最新配置。
- func refreshQuickMenus() {
- if tray != nil {
- buildTrayMenu() // 重建托盘菜单(含「快捷」子菜单显隐与条目)
- }
- if quickContextMenu != nil {
- quickContextMenu.Menu.Clear()
- buildQuickMenu(quickContextMenu.Menu)
- quickContextMenu.Update()
- }
- }
- // main 是应用程序的入口,整体流程如下:
- // 1. 创建 Wails 应用实例(注册服务、配置资源服务器)
- // 2. 创建主窗口
- // 3. 应用已保存的配置(热键、置顶、开机启动、API 服务、滚动条窗口)
- // 4. 创建系统托盘(关闭时隐藏到托盘,双击恢复显示)
- // 5. 注册窗口事件(文件拖放、关闭→隐藏托盘、显示时还原位置)
- // 6. 启动后台协程,运行应用(阻塞直到退出)
- func main() {
- // 升级的下载、校验、原子替换与重启全部交给 Wails v3 内置升级框架(app.Updater),
- // 它通过环境变量派生 helper 子进程完成二进制交换,无需在本进程里处理文件锁。
- // 这里只处理两件自研的事:
- // 1. --rollback 角色:回滚子进程,在主程序退出后用备份覆盖并重启旧版;
- // 2. 启动时判定是否要自动回滚(新版本反复异常启动则退回上一版)。
- // 两条路径都已派生子进程完成替换,本进程直接退出,不再初始化应用。
- if rollbackModeRequested() {
- if err := runRollbackRole(); err != nil {
- log.Printf("回滚执行失败:%v", err)
- }
- return
- }
- if maybeAutoRollback() {
- os.Exit(0)
- }
- // 服务模式:由 Windows 服务管理器带 --service 启动,无界面、仅提供电源类 API
- // (关机/重启/休眠/取消/状态),无人登录时也可调用;登录后仍由界面程序提供完整功能。
- if serviceModeRequested() {
- if err := runPlatformService(); err != nil {
- fmt.Fprintln(os.Stderr, "服务模式启动失败:", err)
- os.Exit(1)
- }
- return
- }
- // 注册表右键菜单「标签」:本程序 -tag <路径>。
- // 若已有实例在运行,把路径转发给其实例的 /api/tag/open 接口后本进程退出
- // (保持原程序运行);无运行实例则本进程作为主实例继续启动并弹窗。
- if handleTagCommandIfNeeded() {
- return // 已转发给运行中的实例,本进程直接退出
- }
- // 提权写入注册表右键菜单:`-install-tagmenu` 由 maybeWriteTagMenu 检测到
- // 权限不足时用 runas 提权启动的本进程(子进程),完成写入后立即退出,
- // 不再初始化应用界面。放在 handleTagCommandIfNeeded 之后,二者互斥。
- if handleInstallTagMenu() {
- return
- }
- // 提权删除注册表右键菜单:`-remove-tagmenu` 由 maybeRemoveTagMenu 检测到
- // 权限不足时用 runas 提权启动的本进程(子进程),完成删除后立即退出。
- if handleRemoveTagMenu() {
- return
- }
- // ------------------------------------------------------------------------
- // 单实例互斥:GUI 全局唯一,禁止重复启动(用户要求「只有一个实例」)。
- // 放在提权子进程处理之后:提权子进程(runas)是独立进程,不应受单实例锁影响。
- // 若已有实例在运行:
- // 普通启动 → 通知已有实例显示主窗口(/api/window/show),本进程退出;
- // 带 -tag → 不在此退出,交给 handleTagCommandIfNeeded 转发(已执行,无实例时本进程为主实例)。
- // 若本进程为主实例 → 注册退出时释放单实例锁。
- // ------------------------------------------------------------------------
- if !acquireSingleInstanceLock() {
- if tagPathFromArgs() == "" {
- notifyExistingToShow()
- return // 已有实例已接管,本进程退出
- }
- // 带 -tag 且已有实例:handleTagCommandIfNeeded 已转发并退出,不会到达此处;
- // 若到达说明转发失败(API 未运行),此时已有实例仍占用锁,本进程也应退出,
- // 避免出现第二个界面实例。
- return
- }
- defer releaseSingleInstanceLock()
- // 创建 dock service 实例,自定义 badge 选项
- dockService := dock.NewWithOptions(dock.BadgeOptions{
- TextColour: color.RGBA{255, 255, 255, 255}, // 白色文字
- BackgroundColour: color.RGBA{0, 0, 255, 255}, // 蓝色背景
- FontName: "consolab.ttf", // 粗体 Consolas 字体
- FontSize: 20, // 单字符字号
- SmallFontSize: 14, // 多字符字号
- })
- // ------------------------------------------------------------------------
- // 读取配置(提前到创建 explorerService 之前:决定是否启动标签功能监听)。
- // ------------------------------------------------------------------------
- ensureSettingsFile() // 首次运行:自动生成默认配置文件(已存在则不覆盖)
- settings := loadSettings() // 读取用户配置,首次运行返回默认值(开机启动默认开启)
- // 创建 explorerService:后台轮询前台资源管理器的选中项并缓存,
- // 供 Wails 窗口获得焦点时把最近一次选中的文件/文件夹显示到鼠标提示。
- // 是否启动由「配置→系统→启用标签功能」开关决定:
- // 启用(默认)→ 启动后台监听,鼠标悬停文件/文件夹时读取标签并提示;
- // 关闭 → 不启动(也避免不必要的 COM 轮询干扰资源管理器)。
- explorerSvc = newExplorerService()
- if settings.TagMenuEnabled {
- explorerSvc.Start()
- }
- // 安装资源管理器右键菜单「标签」钩子(Windows 专用;非 Windows 为空实现)。
- // 钩子在独立线程监听右键点击,向系统右键菜单注入「标签(&T)」项。
- // 同样受「启用标签功能」开关控制:关闭时不安装钩子(右键不注入菜单)。
- if settings.TagMenuEnabled {
- startTagContextHook()
- }
- // ------------------------------------------------------------------------
- // 第 1 步:创建 Wails 应用实例
- // ------------------------------------------------------------------------
- app = application.New(application.Options{
- Name: "TengTu Toolbox",
- Description: "TengTu Toolbox for OS",
- Services: []application.Service{
- application.NewService(&GreetService{}), // 注册 GreetService,前端可通过 bindings 直接调用其 Greet 方法
- application.NewService(&SettingsService{}), // 注册 SettingsService,供设置页读写配置、拉取行情
- application.NewService(&LocalSendService{}), // 注册 LocalSendService,供 LocalSend 页控制发现/接收
- application.NewService(NewCrocService()), // 注册 CrocService,供 Croc 传送工具发送/接收文件
- application.NewService(NewYTDLPService()), // 注册 YTDLPService,供视频下载工具调用 yt-dlp
- application.NewService(NewMemosService()), // 注册 MemosService,供 Memos 速记工具调用 REST API
- application.NewService(NewBrightnessService()), // 注册 BrightnessService,供显示器亮度工具调光
- application.NewService(&LocalService{}), // 注册 LocalService,供「本地」页启动配置的程序/脚本
- application.NewService(&QuickService{}), // 注册 QuickService,供「快捷」页启动程序并提取图标
- application.NewService(NewUDPService()), // 注册 UDPService,供工具页 UDP 键值服务器启停/发送
- application.NewService(NewProxyService()), // 注册 ProxyService,供工具页「网络代理」设置/启用/禁用系统代理
- application.NewService(dockService), // 注册 dockService,前端可通过 bindings 直接调用其 SetBadge 方法
- application.NewService(explorerSvc), // 注册 explorerService,供前端读取资源管理器选中项
- application.NewService(&TagService{}), // 注册 TagService,供资源管理器右键「标签」/悬停标签提示读写文件标签
- application.NewService(NewRenamerService()), // 注册 RenamerService,供工具页「智能重命名」调用
- application.NewService(NewResourcesService()), // 注册 ResourcesService,供设置页「资源」栏下载 ffmpeg/croc 等工具
- application.NewService(NewPhoneService()), // 注册 PhoneService,供工具页「手机」检测 adb、轮询设备、截图
- application.NewService(NewMeituService()), // 注册 MeituService,供工具页「美图」抓取煎蛋图片列表
- },
- Assets: application.AssetOptions{
- Handler: application.AssetFileServerFS(assets), // 使用嵌入的前端文件作为资源服务器处理器
- },
- Mac: application.MacOptions{
- ApplicationShouldTerminateAfterLastWindowClosed: false, // 最后一个窗口关闭后不退出应用(托盘常驻)
- },
- })
- // ------------------------------------------------------------------------
- // 第 2 步:创建主窗口(使用上次保存的窗口尺寸)
- // ------------------------------------------------------------------------
- win := app.Window.NewWithOptions(application.WebviewWindowOptions{
- Title: "腾图工具箱", // 窗口标题
- Width: settings.WindowWidth,
- Height: settings.WindowHeight,
- Mac: application.MacWindow{
- InvisibleTitleBarHeight: 50, // 顶部 50px 为不可见但可拖拽的标题栏区域
- Backdrop: application.MacBackdropTranslucent, // 半透明背景材质
- TitleBar: application.MacTitleBarHiddenInset, // 隐藏标题栏但保留红绿灯按钮
- },
- Windows: application.WindowsWindow{
- DisableFramelessWindowDecorations: false, // 禁用无边框窗口装饰(标题栏、边框等)
- },
- BackgroundColour: application.NewRGB(6, 7, 15), // 窗口背景色(深色)
- URL: "/", // WebView 加载的页面路径("/" 即前端首页 index.html)
- DevToolsEnabled: false, // 关闭开发者工具(生产环境不开放)
- DefaultContextMenuDisabled: true, // 禁用默认上下文菜单,防止右键点击打开菜单
- UseApplicationMenu: true, // 启用应用菜单
- EnableFileDrop: true, // 启用文件拖拽,需在 HTML 中添加 data-file-drop-target 标签
- ContentProtectionEnabled: false, // 关闭内容保护,允许截取窗口内容(否则整个屏幕截图看不到本窗口)
- Permissions: map[application.PermissionType]application.Permission{
- application.PermissionMicrophone: application.PermissionAllow,
- application.PermissionNotifications: application.PermissionAllow,
- application.PermissionCamera: application.PermissionAllow,
- application.PermissionGeolocation: application.PermissionAllow,
- application.PermissionClipboardRead: application.PermissionAllow,
- },
- Frameless: true, // 无边框窗口
- BackgroundType: application.BackgroundTypeTransparent, // 透明背景
- })
- mainWindow = win // 暴露给热键、托盘、API 使用
- // ------------------------------------------------------------------------
- // 第 3 步:应用已保存的配置(热键、置顶、开机启动)
- // ------------------------------------------------------------------------
- applySettings(settings) // 注册热键、设置置顶、同步开机启动
- startUIRegistration() // 向服务模式登记界面 API 地址(服务转发未实现接口时使用)
- // 写入(或修复)资源管理器右键菜单「标签」:文件与文件夹均添加,
- // 命令为本程序 -tag "%1",由 -tag 命令行逻辑弹出标签编辑窗口。
- // 仅发布构建(production 标签)写入,dev 构建跳过以免覆盖正式版菜单。
- // 受「启用标签功能」开关控制:关闭时不写入(也不弹 UAC 提权)。
- if settings.TagMenuEnabled {
- maybeWriteTagMenu()
- }
- if settings.Brightness.RestoreOnStart {
- restoreBrightness(settings.Brightness.Levels) // 启动时恢复上次各显示器亮度
- }
- // 初始化内置升级框架并检查一次新版本(私有仓库,地址来自设置页)。
- // 结果经 wails:updater:* 事件推给「更新」Tab,这里不再单独广播。
- if err := initAppUpdater(); err != nil {
- log.Printf("内置升级框架初始化失败:%v", err)
- } else {
- go func() {
- time.Sleep(2 * time.Second) // 等窗口与前端就绪
- // 上次选了「下次运行时更新」:本次启动直接自动后台完成升级,跳过启动弹窗。
- if maybeApplyPendingUpdate() {
- return
- }
- // 启动时检查一次更新:发现新版本则弹原生对话框(立即升级/后台更新/暂时跳过/此版不再提示),
- // 已最新或检查失败则静默不打扰。
- if _, err := PromptUpdateIfAvailable(); err != nil {
- log.Printf("启动检查新版本失败:%v", err)
- }
- }()
- }
- // 新版本存活判定:窗口创建后持续运行一小段时间即视为正常,清除升级待确认标记。
- // 只有进程在这之前就退出(崩溃/白屏循环)才会累计 failCount 并触发自动回滚。
- go func() {
- time.Sleep(8 * time.Second)
- MarkUpdateOK()
- }()
- // ------------------------------------------------------------------------
- // 第 4 步:创建系统托盘
- // ------------------------------------------------------------------------
- // 关闭窗口时隐藏到托盘;双击托盘图标恢复窗口显示
- // 托盘菜单提供「显示 / 退出」两个入口
- tray = app.SystemTray.New()
- tray.SetIcon(trayIcon) // 设置托盘图标(嵌入的 wails.png)
- tray.SetTooltip("腾图工具箱") // 设置鼠标悬停提示
- tray.AttachWindow(win) // 绑定窗口:点击托盘图标自动切换窗口显隐
- buildTrayMenu() // 构建托盘右键菜单(含「快捷」子菜单与各 Tab 入口)
- // ------------------------------------------------------------------------
- // 第 5 步:注册窗口事件处理
- // ------------------------------------------------------------------------
- // 资源管理器选中项提示已改为:后台轮询检测选中项变化时,由 explorerService
- // 直接调用系统级 mousealert 置顶气泡显示(无需窗口焦点/前端事件)。
- // 故不再监听 WindowFocus 发 explorerSelection 事件。
- // 监听「文件拖放完成」事件,打印拖放目标详情与所有被拖入的文件
- win.OnWindowEvent(events.Common.WindowFilesDropped, func(event *application.WindowEvent) {
- files := event.Context().DroppedFiles() // 获取拖入的文件路径列表
- details := event.Context().DropTargetDetails() // 获取拖放目标位置等详情
- fmt.Println("Drop target details:", details)
- // 遍历并打印每个被拖入的文件
- for _, file := range files {
- fmt.Println("Dropped:", file)
- }
- })
- // 记住窗口尺寸供下次启动使用;收拢为圆点时的 32×32 不保存,
- // 圆点还原产生的尺寸变化则正常记录。
- win.OnWindowEvent(events.Common.WindowDidResize, func(_ *application.WindowEvent) {
- compactMu.Lock()
- isCompact := compactActive
- compactMu.Unlock()
- if isCompact {
- return
- }
- width, height := win.Size()
- rememberWindowSize(width, height)
- })
- // 注册「窗口关闭前」勾子:记录位置后取消关闭,改为隐藏到托盘
- win.RegisterHook(events.Common.WindowClosing, func(event *application.WindowEvent) {
- savedX, savedY = win.Position() // 记录隐藏前的窗口坐标
- hasSavedPos = true // 标记位置已记录
- event.Cancel() // 拦截关闭事件,阻止窗口被系统销毁
- win.Hide() // 隐藏窗口到托盘
- })
- // 窗口重新显示时(含托盘图标点击恢复),还原到隐藏前的位置
- win.OnWindowEvent(events.Common.WindowShow, func(_ *application.WindowEvent) {
- if hasSavedPos {
- win.SetPosition(savedX, savedY) // 还原窗口位置
- }
- })
- // 监听「窗口正在关闭」事件,执行清理逻辑
- win.OnWindowEvent(events.Common.WindowClosing, func(event *application.WindowEvent) {
- fmt.Printf("Window %s is closing\n", win.Name()) // 清理代码写在这里,此处仅打印关闭日志
- })
- // API 服务与滚动条窗口已在 applySettings(第 3 步)中按配置启动
- // 时间事件:footer 只需显示到分,故仅在分钟变化时广播,避免每秒唤醒前端
- lastMinute := ""
- go func() {
- for {
- now := time.Now().Format(time.DateTime) // 格式化为 DateTime 时间字符串
- minute := now[:len(now)-3] // 去掉 ":SS" 秒部分,取到分
- if minute != lastMinute { // 仅跨分钟时发送一次
- app.Event.Emit("time", now) // 向所有前端窗口广播 "time" 事件
- lastMinute = minute
- }
- time.Sleep(time.Second) // 每秒检查一次分钟边界
- }
- }()
- // 待办提醒调度:每 15 秒扫描一次待办文件,到点的提醒通过事件广播给前端弹窗。
- // 放在后台协程,即使窗口隐藏/最小化也能触发。
- go startTodoReminderLoop()
- // 本进程作为主实例且带 -tag 参数:界面已就绪,打开标签编辑窗口。
- // (转发给运行实例的情况已在 handleTagCommandIfNeeded 中返回退出。)
- if pendingTagPath != "" {
- path := pendingTagPath
- pendingTagPath = ""
- go openTagEditor(path)
- }
- // 运行应用(阻塞,直到退出)
- if err := app.Run(); err != nil {
- log.Fatal(err) // 运行过程中发生错误则记录日志并退出进程
- }
- }
|