1
0

main.go 34 KB

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