1
0

main.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. // ============================================================================
  2. //go:build !service
  3. // main.go — 应用入口(GUI)
  4. //
  5. // 创建 Wails 应用、主窗口与系统托盘,注册服务与窗口事件;
  6. // 启动每秒时间广播与待办提醒调度协程,随后进入事件循环。
  7. // 独立服务模式入口见 main_service.go(-tags service)。
  8. // ============================================================================
  9. package main
  10. import (
  11. "bytes" // 托盘菜单图标:PNG 编码缓冲区
  12. "embed" // Go 内嵌资源包:将前端静态文件打包进可执行文件
  13. "fmt" // 格式化 I/O:用于控制台打印调试信息
  14. "image" // 托盘菜单图标:RGBA 画布
  15. "image/color"
  16. "image/png" // 托盘菜单图标:将 RGBA 编码为 PNG 字节
  17. "log" // 日志:记录并输出错误
  18. "os" // 操作系统:服务模式退出码
  19. "strconv" // 数字转换:解析自定义 Tab 序号
  20. "strings" // 字符串处理:Tab id 折叠标记解析
  21. "sync" // 窗口尺寸保存防抖
  22. "time" // 时间处理:用于每秒定时发送事件
  23. "github.com/wailsapp/wails/v3/pkg/application" // Wails3 核心:应用/窗口/菜单/对话框/事件/托盘
  24. "github.com/wailsapp/wails/v3/pkg/events" // Wails3 事件常量:窗口关闭、文件拖放等
  25. "github.com/wailsapp/wails/v3/pkg/services/dock"
  26. )
  27. // ============================================================================
  28. // 前端资源嵌入
  29. // ============================================================================
  30. // Wails 使用 Go 的 `embed` 包将前端文件嵌入到二进制文件中。
  31. // frontend/dist 目录下的所有文件都会被嵌入到可执行文件里,
  32. // 并由 Wails 内置的资源服务器(Asset Server)提供给 WebView 前端访问。
  33. //go:embed all:frontend/dist
  34. var assets embed.FS // assets 持有 frontend/dist 下全部前端文件的只读文件系统
  35. //go:embed frontend/public/wails.png
  36. var trayIcon []byte // 嵌入系统托盘图标(PNG 格式)
  37. // 全局运行时对象:服务、API、托盘菜单都要用到应用实例与主窗口
  38. var (
  39. app *application.App // 应用实例
  40. mainWindow *application.WebviewWindow // 主窗口
  41. tray *application.SystemTray // 系统托盘(导入快捷配置后需重建菜单)
  42. // 快捷启动 ContextMenu:右键收拢圆点/句柄时弹出,用主窗口句柄作宿主,
  43. // 在光标位置显示(OpenContextMenu),不受收拢后 32x32 小窗口尺寸限制。
  44. quickContextMenu *application.ContextMenu
  45. // 窗口隐藏前的位置,恢复显示时还原
  46. savedX, savedY int
  47. hasSavedPos bool
  48. // explorerSvc 资源管理器悬停监听服务(全局引用,供「配置→系统」启停标签功能)。
  49. // 在 main 中创建并 Start;SaveSettings 切换 TagMenuEnabled 时启停。
  50. explorerSvc *explorerService
  51. // startupRunSvc 启动时运行服务(工具页「启动时运行」):应用启动时运行
  52. // 配置好的程序/脚本,支持循环间隔运行。
  53. startupRunSvc *StartupRunService
  54. )
  55. // showMainWindow 统一显示入口:先还原位置,再显示并聚焦。
  56. // 托盘、热键、API 接口都通过它唤出窗口。
  57. func showMainWindow() {
  58. if mainWindow == nil {
  59. return
  60. }
  61. // 热键/托盘呼出时,即使窗口已收拢为圆点,也先还原到收拢前的尺寸。
  62. compactMu.Lock()
  63. wasCompact := compactActive
  64. compactMu.Unlock()
  65. if wasCompact {
  66. (&SettingsService{}).ToggleWindowCompact()
  67. }
  68. if hasSavedPos {
  69. mainWindow.SetPosition(savedX, savedY) // 还原隐藏前的窗口坐标
  70. }
  71. mainWindow.Show() // 显示窗口
  72. mainWindow.Focus() // 聚焦到前台
  73. if wasCompact && app != nil {
  74. app.Event.Emit("windowCompact", false) // 通知前端移除圆点收拢样式
  75. }
  76. }
  77. // showQuickMenuAtCursor 「快捷」菜单全局热键回调:显示窗口(若收拢先还原),
  78. // 获取当前鼠标位置,向前端发射 showQuickMenuAt 事件(带屏幕坐标),前端据此在鼠标位置弹出快捷菜单。
  79. func showQuickMenuAtCursor() {
  80. if mainWindow == nil {
  81. return
  82. }
  83. // 若窗口收拢为圆点,先还原到收拢前尺寸(菜单需要完整的可视区域)
  84. compactMu.Lock()
  85. wasCompact := compactActive
  86. compactMu.Unlock()
  87. if wasCompact {
  88. (&SettingsService{}).ToggleWindowCompact()
  89. if app != nil {
  90. app.Event.Emit("windowCompact", false)
  91. }
  92. }
  93. mainWindow.Show()
  94. mainWindow.Focus()
  95. // 读取鼠标屏幕坐标,通知前端在鼠标处弹菜单
  96. x, y := cursorScreenPos()
  97. if app != nil {
  98. app.Event.Emit("showQuickMenuAt", map[string]int{"x": x, "y": y})
  99. }
  100. }
  101. // toggleProxyByHotkey 「网络代理」开关全局热键回调:切换系统代理启用/禁用,
  102. // 并向前端发射 proxyChanged 事件刷新工具页「网络代理」卡片状态。
  103. // 同时在鼠标位置弹出提示文字:网络代理已启动/关闭。
  104. func toggleProxyByHotkey() {
  105. if app == nil {
  106. return
  107. }
  108. st, err := NewProxyService().ToggleProxy()
  109. if err != nil {
  110. log.Printf("toggle proxy by hotkey failed: %v", err)
  111. return
  112. }
  113. app.Event.Emit("proxyChanged", map[string]any{
  114. "enabled": st.Enabled,
  115. "server": st.Server,
  116. "configured": st.Configured,
  117. })
  118. // 鼠标光标下方提示:网络代理已启动/已关闭
  119. if st.Enabled {
  120. triggerMouseAlert("网络代理已启动")
  121. } else {
  122. triggerMouseAlert("网络代理已关闭")
  123. }
  124. }
  125. var (
  126. windowSizeSaveMu sync.Mutex
  127. windowSizeSaveTimer *time.Timer
  128. )
  129. // rememberWindowSize 延迟保存窗口尺寸,避免拖动边框时频繁写配置文件。
  130. func rememberWindowSize(width, height int) {
  131. if width <= 0 || height <= 0 {
  132. return
  133. }
  134. windowSizeSaveMu.Lock()
  135. defer windowSizeSaveMu.Unlock()
  136. if windowSizeSaveTimer != nil {
  137. windowSizeSaveTimer.Stop()
  138. }
  139. windowSizeSaveTimer = time.AfterFunc(500*time.Millisecond, func() {
  140. windowSizeSaveMu.Lock()
  141. defer windowSizeSaveMu.Unlock()
  142. settings := loadSettings()
  143. if settings.WindowWidth == width && settings.WindowHeight == height {
  144. return
  145. }
  146. settings.WindowWidth, settings.WindowHeight = width, height
  147. if err := saveSettings(settings); err != nil {
  148. log.Printf("保存窗口尺寸失败:%v", err)
  149. }
  150. })
  151. }
  152. // init 在 main 函数之前自动执行,用于应用启动前的注册工作。
  153. func init() {
  154. application.RegisterEvent[string]("time") // 注册 string 类型的自定义事件,绑定生成器据此为前端生成强类型事件 API
  155. application.RegisterEvent[string]("apilog") // Gin 日志行实时推送(「主机」页订阅)
  156. application.RegisterEvent[string]("todoReminder") // 待办提醒:到点时向前端广播提醒内容
  157. application.RegisterEvent[string]("ntfyChat") // ntfy 聊天室:订阅主题后收到消息广播给前端
  158. application.RegisterEvent[int]("handleFlash") // 拖动手柄圆点闪烁:API 触发,前端播放颜色+大小动画
  159. application.RegisterEvent[bool]("windowCompact") // 后端呼出窗口时同步圆点收拢/还原状态
  160. application.RegisterEvent[string]("switchTab") // 托盘菜单点击 Tab:前端切换到对应页面
  161. application.RegisterEvent[PhoneDevicesPayload]("phone:devices") // 手机工具:adb devices 轮询结果广播给前端
  162. // 升级状态由 Wails 内置升级框架自行推给前端(wails:updater:* 系列事件),无需在此注册
  163. }
  164. // trayTabItem 托盘菜单里的一个 Tab 入口(显示名 + 前端 tabId)
  165. type trayTabItem struct {
  166. name string // 菜单显示文字(与 Tab 按钮同名)
  167. id string // 前端 tabId(内置 id 或 custom-N)
  168. }
  169. // trayTabItems 按已保存配置的 Tab 顺序生成托盘菜单项(「设置」除外,托盘里单独固定一项)。
  170. // 前端同名逻辑:内置 Tab 用固定中文名,自定义 Tab 用配置里的名字。
  171. func trayTabItems() []trayTabItem {
  172. settings := loadSettings()
  173. // 内置 Tab 名称(与前端 TAB_NAMES 保持一致)
  174. builtin := map[string]string{
  175. "links": "网址", "news": "新闻", "github": "Github", "stock": "股市",
  176. "todo": "待办", "record": "记录", "tools": "工具", "locals": "本地",
  177. "control": "控制", "host": "服务", "update": "更新", "settings": "设置",
  178. }
  179. nameFor := func(id string) (string, bool) {
  180. if n, ok := builtin[id]; ok {
  181. return n, true
  182. }
  183. // 自定义 Tab:id 形如 custom-3
  184. if i, err := strconv.Atoi(strings.TrimPrefix(id, "custom-")); err == nil {
  185. if i >= 0 && i < len(settings.CustomTabs) && settings.CustomTabs[i].Name != "" {
  186. return settings.CustomTabs[i].Name, true
  187. }
  188. }
  189. return "", false
  190. }
  191. items := make([]trayTabItem, 0, len(settings.TabOrder))
  192. seen := make(map[string]bool, len(settings.TabOrder))
  193. add := func(id, name string) {
  194. if seen[id] {
  195. return
  196. }
  197. seen[id] = true
  198. items = append(items, trayTabItem{name: name, id: id})
  199. }
  200. for _, raw := range settings.TabOrder {
  201. id := strings.TrimSpace(raw)
  202. wrapped := strings.HasPrefix(id, "[") && strings.HasSuffix(id, "]")
  203. if wrapped {
  204. id = strings.TrimSpace(id[1 : len(id)-1]) // 去掉「更多」折叠标记
  205. }
  206. if id == "settings" {
  207. continue // 「设置」在托盘里固定在分隔线下方单独一项
  208. }
  209. if name, ok := nameFor(id); ok {
  210. add(id, name)
  211. }
  212. }
  213. return items
  214. }
  215. // ============================================================================
  216. // 托盘菜单图标:用 image/png 程序化生成 16×16 图标,无需随仓库附带素材文件。
  217. // SetBitmap 只接收 PNG 字节,因此这里现画现编码。
  218. // ============================================================================
  219. // drawMenuIcon 在 16×16 画布上执行 draw,再把画布编码为 PNG 字节。
  220. func drawMenuIcon(draw func(img *image.RGBA)) []byte {
  221. img := image.NewRGBA(image.Rect(0, 0, 16, 16))
  222. draw(img)
  223. var buf bytes.Buffer
  224. _ = png.Encode(&buf, img) // 固定 16×16 RGBA 编码不会失败
  225. return buf.Bytes()
  226. }
  227. // trayIconLight 浅色托盘菜单图标配色
  228. var trayIconLight = color.RGBA{226, 232, 240, 255}
  229. // iconWindow 窗口图标:表示「显示主窗口」
  230. func iconWindow() []byte {
  231. return drawMenuIcon(func(img *image.RGBA) {
  232. c := trayIconLight
  233. for y := 2; y <= 13; y++ {
  234. for x := 2; x <= 13; x++ {
  235. if y == 2 || y == 13 || x == 2 || x == 13 || y == 5 {
  236. img.Set(x, y, c)
  237. }
  238. }
  239. }
  240. d := color.RGBA{120, 170, 255, 255}
  241. for y := 7; y <= 12; y++ {
  242. for x := 4; x <= 11; x++ {
  243. if x <= y+2 {
  244. img.Set(x, y, d)
  245. }
  246. }
  247. }
  248. })
  249. }
  250. // iconGear 齿轮图标:表示「设置」
  251. func iconGear() []byte {
  252. return drawMenuIcon(func(img *image.RGBA) {
  253. c := trayIconLight
  254. for x := 0; x <= 15; x++ {
  255. for y := 0; y <= 15; y++ {
  256. dx, dy := x-7, y-7
  257. r := dx*dx + dy*dy
  258. if r <= 25 && r >= 9 {
  259. img.Set(x, y, c)
  260. }
  261. }
  262. }
  263. })
  264. }
  265. // iconPower 电源图标(圆环 + 顶部竖线):表示「关机」
  266. func iconPower() []byte {
  267. return drawMenuIcon(func(img *image.RGBA) {
  268. c := color.RGBA{255, 200, 120, 255}
  269. // 圆环:半径约 6,中心 (7, 8)
  270. for x := 0; x <= 15; x++ {
  271. for y := 0; y <= 15; y++ {
  272. dx, dy := x-7, y-8
  273. r := dx*dx + dy*dy
  274. if r >= 28 && r <= 42 { // 环带
  275. img.Set(x, y, c)
  276. }
  277. }
  278. }
  279. // 顶部竖线(电源键柄),覆盖圆环缺口
  280. for y := 1; y <= 8; y++ {
  281. img.Set(7, y, c)
  282. img.Set(8, y, c)
  283. }
  284. })
  285. }
  286. // iconExit 叉号图标:表示「退出」
  287. func iconExit() []byte {
  288. return drawMenuIcon(func(img *image.RGBA) {
  289. c := color.RGBA{255, 138, 138, 255}
  290. put := func(x, y int) {
  291. if x >= 0 && x <= 15 && y >= 0 && y <= 15 { // 防止对角线端点越界
  292. img.Set(x, y, c)
  293. }
  294. }
  295. for x := 3; x <= 12; x++ {
  296. put(x, x+3) // 主对角线
  297. put(x, 21-x) // 副对角线
  298. }
  299. })
  300. }
  301. // hasQuickItems 判断是否配置了任何快捷启动项(任一分组含非空条目)。
  302. // 托盘菜单据此决定是否显示「快捷」子菜单:未配置任何快捷项则不显示。
  303. func hasQuickItems() bool {
  304. for _, g := range loadSettings().QuickGroups {
  305. if len(g.Items) > 0 {
  306. return true
  307. }
  308. }
  309. return false
  310. }
  311. // buildQuickTrayMenu 把「快捷」启动分组构建为托盘子菜单。
  312. // 复用 buildQuickMenu 的通用构建逻辑(分组子菜单 + 条目图标 + 点击启动)。
  313. func buildQuickTrayMenu(menu *application.Menu) {
  314. buildQuickMenu(menu)
  315. }
  316. // buildQuickMenu 把「快捷」启动分组构建为指定 Menu 的项:
  317. // 每个命名分组生成一个子菜单,未分组条目直接放在顶层;条目点击即启动应用,
  318. // 并尽量挂上 16x16 程序图标(quickIconCachedPNG 缓存)。托盘菜单与
  319. // 快捷 ContextMenu 共用此构建逻辑,保证两处菜单项一致。
  320. func buildQuickMenu(menu *application.Menu) {
  321. groups := loadSettings().QuickGroups
  322. added := false
  323. for _, g := range groups {
  324. if len(g.Items) == 0 {
  325. continue
  326. }
  327. if g.Name != "" {
  328. // 有分组名:生成一个子菜单,组内条目作为菜单项
  329. sub := menu.AddSubmenu(g.Name)
  330. for _, it := range g.Items {
  331. item := it // 闭包捕获当前条目
  332. mi := sub.Add(item.Title)
  333. if item.Desc != "" {
  334. mi.SetTooltip(item.Desc)
  335. }
  336. if icon, ok := quickIconCachedPNG(item.Path); ok {
  337. mi.SetBitmap(icon) // 缓存 16x16 PNG,显示程序图标
  338. }
  339. mi.OnClick(func(_ *application.Context) {
  340. if _, err := (&LocalService{}).Launch(item.Title, item.Path); err != nil {
  341. log.Printf("quick launch %q failed: %v", item.Title, err)
  342. }
  343. })
  344. }
  345. added = true
  346. } else {
  347. // 未分组条目:直接放在菜单顶层
  348. for _, it := range g.Items {
  349. item := it // 闭包捕获当前条目
  350. mi := menu.Add(item.Title)
  351. if item.Desc != "" {
  352. mi.SetTooltip(item.Desc)
  353. }
  354. if icon, ok := quickIconCachedPNG(item.Path); ok {
  355. mi.SetBitmap(icon) // 缓存 16x16 PNG,显示程序图标
  356. }
  357. mi.OnClick(func(_ *application.Context) {
  358. if _, err := (&LocalService{}).Launch(item.Title, item.Path); err != nil {
  359. log.Printf("quick launch %q failed: %v", item.Title, err)
  360. }
  361. })
  362. added = true
  363. }
  364. }
  365. }
  366. if !added {
  367. // 无任何快捷项时给出提示(禁用项),避免空白菜单
  368. menu.Add("(未配置快捷项,请在 设置-快捷 中添加)").SetEnabled(false)
  369. }
  370. }
  371. // buildTrayMenu 构建托盘右键菜单:
  372. // 显示主窗口 → 「快捷」子菜单(仅配置了快捷项时显示)→ Tab 列表 → 设置/退出。
  373. // 每次调用都会重建 ContextMenu 与托盘菜单,保证「快捷」项与最新设置一致
  374. // (导入 Biniware Run 配置后调用 refreshQuickMenus 刷新)。
  375. func buildTrayMenu() {
  376. if tray == nil {
  377. return
  378. }
  379. trayMenu := application.NewMenu()
  380. // 菜单项图标:运行时程序化生成 16×16 PNG(SetBitmap 支持,官方系统托盘文档标注 Windows/macOS/Linux 均支持)
  381. trayMenu.Add("显示主窗口").SetBitmap(iconWindow()).OnClick(func(_ *application.Context) {
  382. showMainWindow() // 显示窗口到隐藏前的位置并聚焦
  383. })
  384. trayMenu.AddSeparator() // 「显示主窗口」与「快捷」之间的分隔线
  385. // 「快捷」子菜单(第二个位置):直接列出各个应用的快捷启动项(点击即启动),
  386. // 按设置的快捷分组组织;未分组条目放在「快捷」菜单顶层。
  387. // 仅当配置了快捷项时才显示该子菜单(未配置则不出现)。
  388. if hasQuickItems() {
  389. buildQuickTrayMenu(trayMenu.AddSubmenu("快捷"))
  390. }
  391. // 为每个 Tab 生成同名菜单项:点击后显示窗口并切到对应页面
  392. for _, tab := range trayTabItems() {
  393. id := tab.id // 闭包捕获当前 Tab id
  394. trayMenu.Add(tab.name).OnClick(func(_ *application.Context) {
  395. showMainWindow()
  396. if app != nil {
  397. app.Event.Emit("switchTab", id) // 前端收到后切换到该 Tab
  398. }
  399. })
  400. }
  401. // 快捷启动 ContextMenu(右键收拢圆点/句柄时弹出):
  402. // 与托盘菜单共用 buildQuickMenu 构建逻辑。OpenContextMenu 用主窗口句柄作宿主,
  403. // 在光标位置弹出,不受收拢后 32x32 小窗口尺寸限制(修复收拢态右键不弹菜单)。
  404. quickContextMenu = application.NewContextMenu("quickmenu")
  405. buildQuickMenu(quickContextMenu.Menu)
  406. trayMenu.AddSeparator() // Tab 列表与「设置 / 退出」之间的分隔线
  407. trayMenu.Add("设置").SetBitmap(iconGear()).OnClick(func(_ *application.Context) {
  408. showMainWindow()
  409. if app != nil {
  410. app.Event.Emit("switchTab", "settings")
  411. }
  412. })
  413. // 「关机」:设置与退出之间。点击后由前端弹出确认框(showConfirm),
  414. // 用户确认才调用 SettingsService.PoweroffNow 立即关机。
  415. trayMenu.Add("关机").SetBitmap(iconPower()).OnClick(func(_ *application.Context) {
  416. if app != nil {
  417. app.Event.Emit("trayPoweroff") // 前端监听后弹出确认框
  418. }
  419. })
  420. trayMenu.Add("退出").SetBitmap(iconExit()).OnClick(func(_ *application.Context) {
  421. app.Quit() // 彻底退出应用
  422. })
  423. tray.SetMenu(trayMenu) // 设置托盘右键菜单
  424. }
  425. // refreshQuickMenus 在快捷配置变更后重建托盘菜单与快捷 ContextMenu,
  426. // 使「快捷」子菜单(第二个位置)与右键菜单立即反映最新配置。
  427. func refreshQuickMenus() {
  428. if tray != nil {
  429. buildTrayMenu() // 重建托盘菜单(含「快捷」子菜单显隐与条目)
  430. }
  431. if quickContextMenu != nil {
  432. quickContextMenu.Menu.Clear()
  433. buildQuickMenu(quickContextMenu.Menu)
  434. quickContextMenu.Update()
  435. }
  436. }
  437. // main 是应用程序的入口,整体流程如下:
  438. // 1. 创建 Wails 应用实例(注册服务、配置资源服务器)
  439. // 2. 创建主窗口
  440. // 3. 应用已保存的配置(热键、置顶、开机启动、API 服务、滚动条窗口)
  441. // 4. 创建系统托盘(关闭时隐藏到托盘,双击恢复显示)
  442. // 5. 注册窗口事件(文件拖放、关闭→隐藏托盘、显示时还原位置)
  443. // 6. 启动后台协程,运行应用(阻塞直到退出)
  444. func main() {
  445. // 升级的下载、校验、原子替换与重启全部交给 Wails v3 内置升级框架(app.Updater),
  446. // 它通过环境变量派生 helper 子进程完成二进制交换,无需在本进程里处理文件锁。
  447. // 这里只处理两件自研的事:
  448. // 1. --rollback 角色:回滚子进程,在主程序退出后用备份覆盖并重启旧版;
  449. // 2. 启动时判定是否要自动回滚(新版本反复异常启动则退回上一版)。
  450. // 两条路径都已派生子进程完成替换,本进程直接退出,不再初始化应用。
  451. if rollbackModeRequested() {
  452. if err := runRollbackRole(); err != nil {
  453. log.Printf("回滚执行失败:%v", err)
  454. }
  455. return
  456. }
  457. if maybeAutoRollback() {
  458. os.Exit(0)
  459. }
  460. // 服务模式:由 Windows 服务管理器带 --service 启动,无界面、仅提供电源类 API
  461. // (关机/重启/休眠/取消/状态),无人登录时也可调用;登录后仍由界面程序提供完整功能。
  462. if serviceModeRequested() {
  463. if err := runPlatformService(); err != nil {
  464. fmt.Fprintln(os.Stderr, "服务模式启动失败:", err)
  465. os.Exit(1)
  466. }
  467. return
  468. }
  469. // 注册表右键菜单「标签」:本程序 -tag <路径>。
  470. // 若已有实例在运行,把路径转发给其实例的 /api/tag/open 接口后本进程退出
  471. // (保持原程序运行);无运行实例则本进程作为主实例继续启动并弹窗。
  472. if handleTagCommandIfNeeded() {
  473. return // 已转发给运行中的实例,本进程直接退出
  474. }
  475. // 提权写入注册表右键菜单:`-install-tagmenu` 由 maybeWriteTagMenu 检测到
  476. // 权限不足时用 runas 提权启动的本进程(子进程),完成写入后立即退出,
  477. // 不再初始化应用界面。放在 handleTagCommandIfNeeded 之后,二者互斥。
  478. if handleInstallTagMenu() {
  479. return
  480. }
  481. // 提权删除注册表右键菜单:`-remove-tagmenu` 由 maybeRemoveTagMenu 检测到
  482. // 权限不足时用 runas 提权启动的本进程(子进程),完成删除后立即退出。
  483. if handleRemoveTagMenu() {
  484. return
  485. }
  486. // ------------------------------------------------------------------------
  487. // 单实例互斥:GUI 全局唯一,禁止重复启动(用户要求「只有一个实例」)。
  488. // 放在提权子进程处理之后:提权子进程(runas)是独立进程,不应受单实例锁影响。
  489. // 若已有实例在运行:
  490. // 普通启动 → 通知已有实例显示主窗口(/api/window/show),本进程退出;
  491. // 带 -tag → 不在此退出,交给 handleTagCommandIfNeeded 转发(已执行,无实例时本进程为主实例)。
  492. // 若本进程为主实例 → 注册退出时释放单实例锁。
  493. // ------------------------------------------------------------------------
  494. if !acquireSingleInstanceLock() {
  495. if tagPathFromArgs() == "" {
  496. notifyExistingToShow()
  497. return // 已有实例已接管,本进程退出
  498. }
  499. // 带 -tag 且已有实例:handleTagCommandIfNeeded 已转发并退出,不会到达此处;
  500. // 若到达说明转发失败(API 未运行),此时已有实例仍占用锁,本进程也应退出,
  501. // 避免出现第二个界面实例。
  502. return
  503. }
  504. defer releaseSingleInstanceLock()
  505. // 创建 dock service 实例,自定义 badge 选项
  506. dockService := dock.NewWithOptions(dock.BadgeOptions{
  507. TextColour: color.RGBA{255, 255, 255, 255}, // 白色文字
  508. BackgroundColour: color.RGBA{0, 0, 255, 255}, // 蓝色背景
  509. FontName: "consolab.ttf", // 粗体 Consolas 字体
  510. FontSize: 20, // 单字符字号
  511. SmallFontSize: 14, // 多字符字号
  512. })
  513. // ------------------------------------------------------------------------
  514. // 读取配置(提前到创建 explorerService 之前:决定是否启动标签功能监听)。
  515. // ------------------------------------------------------------------------
  516. ensureSettingsFile() // 首次运行:自动生成默认配置文件(已存在则不覆盖)
  517. settings := loadSettings() // 读取用户配置,首次运行返回默认值(开机启动默认开启)
  518. // 创建 explorerService:后台轮询前台资源管理器的选中项并缓存,
  519. // 供 Wails 窗口获得焦点时把最近一次选中的文件/文件夹显示到鼠标提示。
  520. // 是否启动由「配置→系统→启用标签功能」开关决定:
  521. // 启用(默认)→ 启动后台监听,鼠标悬停文件/文件夹时读取标签并提示;
  522. // 关闭 → 不启动(也避免不必要的 COM 轮询干扰资源管理器)。
  523. explorerSvc = newExplorerService()
  524. if settings.TagMenuEnabled {
  525. explorerSvc.Start()
  526. }
  527. // 安装资源管理器右键菜单「标签」钩子(Windows 专用;非 Windows 为空实现)。
  528. // 钩子在独立线程监听右键点击,向系统右键菜单注入「标签(&T)」项。
  529. // 同样受「启用标签功能」开关控制:关闭时不安装钩子(右键不注入菜单)。
  530. if settings.TagMenuEnabled {
  531. startTagContextHook()
  532. }
  533. // 「启动时运行」服务:提前创建实例,便于注册到 Wails 服务并在启动后触发 StartAll。
  534. startupRunSvc = NewStartupRunService()
  535. // ------------------------------------------------------------------------
  536. // 第 1 步:创建 Wails 应用实例
  537. // ------------------------------------------------------------------------
  538. app = application.New(application.Options{
  539. Name: "TengTu Toolbox",
  540. Description: "TengTu Toolbox for OS",
  541. Services: []application.Service{
  542. application.NewService(&GreetService{}), // 注册 GreetService,前端可通过 bindings 直接调用其 Greet 方法
  543. application.NewService(&SettingsService{}), // 注册 SettingsService,供设置页读写配置、拉取行情
  544. application.NewService(&LocalSendService{}), // 注册 LocalSendService,供 LocalSend 页控制发现/接收
  545. application.NewService(NewCrocService()), // 注册 CrocService,供 Croc 传送工具发送/接收文件
  546. application.NewService(NewYTDLPService()), // 注册 YTDLPService,供视频下载工具调用 yt-dlp
  547. application.NewService(NewMemosService()), // 注册 MemosService,供 Memos 速记工具调用 REST API
  548. application.NewService(NewBrightnessService()), // 注册 BrightnessService,供显示器亮度工具调光
  549. application.NewService(&LocalService{}), // 注册 LocalService,供「本地」页启动配置的程序/脚本
  550. application.NewService(&QuickService{}), // 注册 QuickService,供「快捷」页启动程序并提取图标
  551. application.NewService(NewUDPService()), // 注册 UDPService,供工具页 UDP 键值服务器启停/发送
  552. application.NewService(NewProxyService()), // 注册 ProxyService,供工具页「网络代理」设置/启用/禁用系统代理
  553. application.NewService(dockService), // 注册 dockService,前端可通过 bindings 直接调用其 SetBadge 方法
  554. application.NewService(explorerSvc), // 注册 explorerService,供前端读取资源管理器选中项
  555. application.NewService(&TagService{}), // 注册 TagService,供资源管理器右键「标签」/悬停标签提示读写文件标签
  556. application.NewService(NewRenamerService()), // 注册 RenamerService,供工具页「智能重命名」调用
  557. application.NewService(NewResourcesService()), // 注册 ResourcesService,供设置页「资源」栏下载 ffmpeg/croc 等工具
  558. application.NewService(NewPhoneService()), // 注册 PhoneService,供工具页「手机」检测 adb、轮询设备、截图
  559. application.NewService(NewMeituService()), // 注册 MeituService,供工具页「美图」抓取煎蛋图片列表
  560. application.NewService(NewWebClientService()), // 注册 WebClientService,供工具页「Web客户」POST 信息/循环发送
  561. application.NewService(startupRunSvc), // 注册 StartupRunService,供工具页「启动时运行」自动运行程序/脚本
  562. },
  563. Assets: application.AssetOptions{
  564. Handler: application.AssetFileServerFS(assets), // 使用嵌入的前端文件作为资源服务器处理器
  565. },
  566. Mac: application.MacOptions{
  567. ApplicationShouldTerminateAfterLastWindowClosed: false, // 最后一个窗口关闭后不退出应用(托盘常驻)
  568. },
  569. })
  570. // ------------------------------------------------------------------------
  571. // 第 2 步:创建主窗口(使用上次保存的窗口尺寸)
  572. // ------------------------------------------------------------------------
  573. win := app.Window.NewWithOptions(application.WebviewWindowOptions{
  574. Title: "腾图工具箱", // 窗口标题
  575. Width: settings.WindowWidth,
  576. Height: settings.WindowHeight,
  577. Mac: application.MacWindow{
  578. InvisibleTitleBarHeight: 50, // 顶部 50px 为不可见但可拖拽的标题栏区域
  579. Backdrop: application.MacBackdropTranslucent, // 半透明背景材质
  580. TitleBar: application.MacTitleBarHiddenInset, // 隐藏标题栏但保留红绿灯按钮
  581. },
  582. Windows: application.WindowsWindow{
  583. DisableFramelessWindowDecorations: false, // 禁用无边框窗口装饰(标题栏、边框等)
  584. },
  585. BackgroundColour: application.NewRGB(6, 7, 15), // 窗口背景色(深色)
  586. URL: "/", // WebView 加载的页面路径("/" 即前端首页 index.html)
  587. DevToolsEnabled: false, // 关闭开发者工具(生产环境不开放)
  588. DefaultContextMenuDisabled: true, // 禁用默认上下文菜单,防止右键点击打开菜单
  589. UseApplicationMenu: true, // 启用应用菜单
  590. EnableFileDrop: true, // 启用文件拖拽,需在 HTML 中添加 data-file-drop-target 标签
  591. ContentProtectionEnabled: false, // 关闭内容保护,允许截取窗口内容(否则整个屏幕截图看不到本窗口)
  592. Permissions: map[application.PermissionType]application.Permission{
  593. application.PermissionMicrophone: application.PermissionAllow,
  594. application.PermissionNotifications: application.PermissionAllow,
  595. application.PermissionCamera: application.PermissionAllow,
  596. application.PermissionGeolocation: application.PermissionAllow,
  597. application.PermissionClipboardRead: application.PermissionAllow,
  598. },
  599. Frameless: true, // 无边框窗口
  600. BackgroundType: application.BackgroundTypeTransparent, // 透明背景
  601. })
  602. mainWindow = win // 暴露给热键、托盘、API 使用
  603. // ------------------------------------------------------------------------
  604. // 第 3 步:应用已保存的配置(热键、置顶、开机启动)
  605. // ------------------------------------------------------------------------
  606. applySettings(settings) // 注册热键、设置置顶、同步开机启动
  607. startUIRegistration() // 向服务模式登记界面 API 地址(服务转发未实现接口时使用)
  608. // 写入(或修复)资源管理器右键菜单「标签」:文件与文件夹均添加,
  609. // 命令为本程序 -tag "%1",由 -tag 命令行逻辑弹出标签编辑窗口。
  610. // 仅发布构建(production 标签)写入,dev 构建跳过以免覆盖正式版菜单。
  611. // 受「启用标签功能」开关控制:关闭时不写入(也不弹 UAC 提权)。
  612. if settings.TagMenuEnabled {
  613. maybeWriteTagMenu()
  614. }
  615. if settings.Brightness.RestoreOnStart {
  616. restoreBrightness(settings.Brightness.Levels) // 启动时恢复上次各显示器亮度
  617. }
  618. // 初始化内置升级框架并检查一次新版本(私有仓库,地址来自设置页)。
  619. // 结果经 wails:updater:* 事件推给「更新」Tab,这里不再单独广播。
  620. if err := initAppUpdater(); err != nil {
  621. log.Printf("内置升级框架初始化失败:%v", err)
  622. } else {
  623. go func() {
  624. time.Sleep(2 * time.Second) // 等窗口与前端就绪
  625. // 上次选了「下次运行时更新」:本次启动直接自动后台完成升级,跳过启动弹窗。
  626. if maybeApplyPendingUpdate() {
  627. return
  628. }
  629. // 启动时检查一次更新:发现新版本则弹原生对话框(立即升级/后台更新/暂时跳过/此版不再提示),
  630. // 已最新或检查失败则静默不打扰。
  631. if _, err := PromptUpdateIfAvailable(); err != nil {
  632. log.Printf("启动检查新版本失败:%v", err)
  633. }
  634. }()
  635. }
  636. // 新版本存活判定:窗口创建后持续运行一小段时间即视为正常,清除升级待确认标记。
  637. // 只有进程在这之前就退出(崩溃/白屏循环)才会累计 failCount 并触发自动回滚。
  638. go func() {
  639. time.Sleep(8 * time.Second)
  640. MarkUpdateOK()
  641. }()
  642. // ------------------------------------------------------------------------
  643. // 第 4 步:创建系统托盘
  644. // ------------------------------------------------------------------------
  645. // 关闭窗口时隐藏到托盘;双击托盘图标恢复窗口显示
  646. // 托盘菜单提供「显示 / 退出」两个入口
  647. tray = app.SystemTray.New()
  648. tray.SetIcon(trayIcon) // 设置托盘图标(嵌入的 wails.png)
  649. tray.SetTooltip("腾图工具箱") // 设置鼠标悬停提示
  650. tray.AttachWindow(win) // 绑定窗口:点击托盘图标自动切换窗口显隐
  651. buildTrayMenu() // 构建托盘右键菜单(含「快捷」子菜单与各 Tab 入口)
  652. // ------------------------------------------------------------------------
  653. // 第 5 步:注册窗口事件处理
  654. // ------------------------------------------------------------------------
  655. // 资源管理器选中项提示已改为:后台轮询检测选中项变化时,由 explorerService
  656. // 直接调用系统级 mousealert 置顶气泡显示(无需窗口焦点/前端事件)。
  657. // 故不再监听 WindowFocus 发 explorerSelection 事件。
  658. // 监听「文件拖放完成」事件,打印拖放目标详情与所有被拖入的文件
  659. win.OnWindowEvent(events.Common.WindowFilesDropped, func(event *application.WindowEvent) {
  660. files := event.Context().DroppedFiles() // 获取拖入的文件路径列表
  661. details := event.Context().DropTargetDetails() // 获取拖放目标位置等详情
  662. fmt.Println("Drop target details:", details)
  663. // 遍历并打印每个被拖入的文件
  664. for _, file := range files {
  665. fmt.Println("Dropped:", file)
  666. }
  667. })
  668. // 记住窗口尺寸供下次启动使用;收拢为圆点时的 32×32 不保存,
  669. // 圆点还原产生的尺寸变化则正常记录。
  670. win.OnWindowEvent(events.Common.WindowDidResize, func(_ *application.WindowEvent) {
  671. compactMu.Lock()
  672. isCompact := compactActive
  673. compactMu.Unlock()
  674. if isCompact {
  675. return
  676. }
  677. width, height := win.Size()
  678. rememberWindowSize(width, height)
  679. })
  680. // 注册「窗口关闭前」勾子:记录位置后取消关闭,改为隐藏到托盘
  681. win.RegisterHook(events.Common.WindowClosing, func(event *application.WindowEvent) {
  682. savedX, savedY = win.Position() // 记录隐藏前的窗口坐标
  683. hasSavedPos = true // 标记位置已记录
  684. event.Cancel() // 拦截关闭事件,阻止窗口被系统销毁
  685. win.Hide() // 隐藏窗口到托盘
  686. })
  687. // 窗口重新显示时(含托盘图标点击恢复),还原到隐藏前的位置
  688. win.OnWindowEvent(events.Common.WindowShow, func(_ *application.WindowEvent) {
  689. if hasSavedPos {
  690. win.SetPosition(savedX, savedY) // 还原窗口位置
  691. }
  692. })
  693. // 监听「窗口正在关闭」事件,执行清理逻辑
  694. win.OnWindowEvent(events.Common.WindowClosing, func(event *application.WindowEvent) {
  695. fmt.Printf("Window %s is closing\n", win.Name()) // 清理代码写在这里,此处仅打印关闭日志
  696. })
  697. // API 服务与滚动条窗口已在 applySettings(第 3 步)中按配置启动
  698. // 时间事件:footer 只需显示到分,故仅在分钟变化时广播,避免每秒唤醒前端
  699. lastMinute := ""
  700. go func() {
  701. for {
  702. now := time.Now().Format(time.DateTime) // 格式化为 DateTime 时间字符串
  703. minute := now[:len(now)-3] // 去掉 ":SS" 秒部分,取到分
  704. if minute != lastMinute { // 仅跨分钟时发送一次
  705. app.Event.Emit("time", now) // 向所有前端窗口广播 "time" 事件
  706. lastMinute = minute
  707. }
  708. time.Sleep(time.Second) // 每秒检查一次分钟边界
  709. }
  710. }()
  711. // 待办提醒调度:每 15 秒扫描一次待办文件,到点的提醒通过事件广播给前端弹窗。
  712. // 放在后台协程,即使窗口隐藏/最小化也能触发。
  713. go startTodoReminderLoop()
  714. // 本进程作为主实例且带 -tag 参数:界面已就绪,打开标签编辑窗口。
  715. // (转发给运行实例的情况已在 handleTagCommandIfNeeded 中返回退出。)
  716. if pendingTagPath != "" {
  717. path := pendingTagPath
  718. pendingTagPath = ""
  719. go openTagEditor(path)
  720. }
  721. // 启动时运行:触发「启动时运行」工具配置的程序/脚本(异步,不阻塞应用启动)。
  722. if startupRunSvc != nil {
  723. go startupRunSvc.StartAll()
  724. }
  725. // 运行应用(阻塞,直到退出)
  726. if err := app.Run(); err != nil {
  727. log.Fatal(err) // 运行过程中发生错误则记录日志并退出进程
  728. }
  729. }