tageditor_windows.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. //go:build windows && !service
  2. // ============================================================================
  3. // tageditor_windows.go — 标签编辑输入窗口(难点2)
  4. //
  5. // 右键菜单点「标签(&T)」后弹出的小窗口:输入「标签」和「备注」两栏,
  6. // 确定时写入标签数据库(SaveTag),取消/关闭则不写。
  7. //
  8. // 实现:仿 mouseAlertLoop 的窗口线程模式(runtime.LockOSThread + RegisterClassExW
  9. // + CreateWindowExW + GetMessage 消息循环 + 自有 WndProc)。不用 Wails 前端模态
  10. // 是因为右键场景前台是 explorer,切到 Wails 窗口体验割裂且需新增前端 UI+事件通道。
  11. // ============================================================================
  12. package main
  13. import (
  14. "fmt"
  15. "os"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "sync"
  20. "syscall"
  21. "unsafe"
  22. )
  23. // 标签编辑窗口控件 ID
  24. const (
  25. tagEditID = 1001 // 标签 EDIT
  26. noteEditID = 1002 // 备注 EDIT(多行)
  27. btnOKID = 1003 // 确定
  28. btnCancelID = 1004 // 取消
  29. tagEditorWidth = 400 // 逻辑宽度(px @96DPI),创建时按 DPI 缩放
  30. tagEditorHeight = 260 // 逻辑高度(px @96DPI),创建时按 DPI 缩放
  31. )
  32. // wmAppRefreshTagEditor:自定义窗口消息,取 WM_APP(0x8000 私有范围)的值,
  33. // 请求「窗口线程」刷新输入框(回填新路径的标签/备注)。
  34. // 用于复用分支:菜单线程不能直接 SetWindowText(跨线程操作控件),
  35. // 改为投递消息,由本窗口消息循环处理,天然串行安全。
  36. const wmAppRefreshTagEditor = 0x8000
  37. // 标准控件样式
  38. const (
  39. wsChild = 0x40000000
  40. wsVisible = 0x10000000
  41. wsTabStop = 0x00010000
  42. wsGroup = 0x00020000
  43. wsBorder = 0x00800000
  44. wsCaption = 0x00C00000
  45. wsSysMenu = 0x00080000
  46. wsThickFrame = 0x00040000
  47. wsOverlapped = 0x00000000
  48. wsExDlgModal = 0x00000001
  49. wsExTopMost = 0x00000008
  50. wsExAppWindow = 0x00040000
  51. esMultiLine = 0x0004
  52. esAutoHScroll = 0x0080
  53. esAutoVScroll = 0x0040
  54. bsDefPushButton = 0x0001
  55. )
  56. // 本文件用到的 user32 过程(procCreateWindowEx/procGetMessage/procRegisterClassEx/
  57. // procDefWindowProc/procDestroyWindow/procShowWindow/procSetForegroundWindow/
  58. // procGetSystemMetrics/procGetModuleHandleW 等已在其它文件定义,此处不复用)。
  59. var (
  60. procGetWindowTextW = user32.NewProc("GetWindowTextW")
  61. procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
  62. procSetWindowTextW = user32.NewProc("SetWindowTextW")
  63. procGetDlgItem = user32.NewProc("GetDlgItem")
  64. procSetFocus = user32.NewProc("SetFocus")
  65. procPostQuitMessage = user32.NewProc("PostQuitMessage")
  66. procGetClientRect = user32.NewProc("GetClientRect")
  67. )
  68. // tagEditor 标签编辑窗口状态(单实例,包级)。
  69. var tagEditor struct {
  70. mu sync.Mutex
  71. hwnd uintptr
  72. path string
  73. cb uintptr // WndProc 回调地址(保持引用防 GC)
  74. classOK bool
  75. started bool
  76. }
  77. // loadTagForEdit 读取 path 当前已保存的标签与备注,用于编辑窗口回填输入框。
  78. // 未找到(尚未打过标签)时返回两个空串,用户可重新填写。
  79. // 出错(数据库占用等)仅记日志并返回空串,不阻塞窗口打开。
  80. func loadTagForEdit(path string) (tag, note string) {
  81. if path == "" {
  82. return "", ""
  83. }
  84. t, found, err := getTagSvc().GetTag(path) // GetTag 内部会规范化路径键
  85. if err != nil {
  86. logTagErr("读取已有标签", err)
  87. return "", ""
  88. }
  89. if !found {
  90. return "", ""
  91. }
  92. return strings.TrimSpace(t.Tag), strings.TrimSpace(t.Note)
  93. }
  94. // refreshTagEditorTexts 用 path 已有的标签/备注刷新编辑窗口的两个输入框,
  95. // 并在窗口标题后附文件名(连续为不同文件打标签时可辨识)。
  96. // 只在编辑窗口的窗口线程内调用(首次创建后 / 切换路径时)。
  97. func refreshTagEditorTexts(hwnd uintptr, path string) {
  98. if hwnd == 0 {
  99. return
  100. }
  101. tag, note := loadTagForEdit(path)
  102. if ctrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID); ctrl != 0 {
  103. procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(tag))))
  104. }
  105. if ctrl, _, _ := procGetDlgItem.Call(hwnd, noteEditID); ctrl != 0 {
  106. procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(note))))
  107. }
  108. // 窗口标题:「标签:文件名」,便于区分当前正在为哪个文件打标签
  109. procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("标签 / 备注 - "+filepath.Base(filepath.Clean(path))))))
  110. }
  111. // openTagEditor 弹出标签编辑窗口(由右键菜单回调异步调用)。
  112. // 会启动一个 LockOSThread 的窗口线程。path 为规范化前的完整路径(显示用原始,
  113. // 写入库时由 SaveTag 再规范化)。
  114. func openTagEditor(path string) {
  115. if path == "" {
  116. return
  117. }
  118. tagEditor.mu.Lock()
  119. if tagEditor.started {
  120. // 已有一个编辑窗口:把新路径切过去(复用窗口,避免多实例),
  121. // 并请求窗口线程把该路径已有的标签/备注回填到输入框,供用户在其上修改。
  122. // 菜单线程不能直接 SetWindowText(跨线程操作控件),改为投递自定义消息,
  123. // 由本窗口的消息循环处理,天然串行安全。
  124. hwnd := tagEditor.hwnd
  125. tagEditor.path = path
  126. tagEditor.mu.Unlock()
  127. if hwnd != 0 {
  128. procSetForegroundWindow.Call(hwnd)
  129. procPostMessage.Call(hwnd, wmAppRefreshTagEditor, 0, 0)
  130. }
  131. return
  132. }
  133. tagEditor.started = true
  134. tagEditor.path = path
  135. tagEditor.mu.Unlock()
  136. go tagEditorLoop(path)
  137. }
  138. // tagEditorLoop 标签编辑窗口线程。path 为本次要编辑的文件/文件夹路径,
  139. // 供创建窗口后回填已有标签/备注使用(避免与复用分支的并发写产生数据竞争)。
  140. func tagEditorLoop(path string) {
  141. runtime.LockOSThread()
  142. defer runtime.UnlockOSThread()
  143. hInst, _, _ := procGetModuleHandleW.Call(0)
  144. className, _ := syscall.UTF16PtrFromString("TengTuTagEditor")
  145. // 注册窗口类(WndProc 是 Go 回调,须保持地址)。
  146. tagEditor.mu.Lock()
  147. tagEditor.cb = syscall.NewCallback(tagEditorWndProc)
  148. wc := wndclassex{
  149. CbSize: uint32(unsafe.Sizeof(wndclassex{})),
  150. LpfnWndProc: tagEditor.cb,
  151. HInstance: hInst,
  152. LpszClassName: className,
  153. HCursor: 0,
  154. }
  155. atom, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
  156. if atom == 0 {
  157. // RegisterClassEx 返回 0 可能是「类已注册」(ERROR_CLASS_ALREADY_EXISTS=1410),
  158. // 此时窗口类定义仍有效,可继续创建窗口。第一次正常关闭后,窗口虽销毁但类定义
  159. // 保留在系统里;再次点击「标签」时若仍把 0 当失败提前 return,会导致 started
  160. // 卡在 true、后续永远无法弹窗。
  161. // 注意:必须用 Call 的第三个返回值(syscall.Errno,API 调用后立即捕获)判断,
  162. // 不能单独再调 GetLastError——Go 运行时在两次 syscall 间会改写线程 last-error,
  163. // 导致读到 0(日志曾出现 "RegisterClassEx failed: 0"),从而误判为真失败。
  164. errno, _ := callErr.(syscall.Errno)
  165. if errno != 1410 { // ERROR_CLASS_ALREADY_EXISTS
  166. fmt.Fprintf(os.Stderr, "[tageditor] RegisterClassEx failed: %d\n", errno)
  167. tagEditor.classOK = false
  168. tagEditor.mu.Unlock()
  169. tagEditor.mu.Lock()
  170. tagEditor.started = false
  171. tagEditor.mu.Unlock()
  172. return
  173. }
  174. // 类已存在:视为注册成功,继续创建窗口
  175. }
  176. tagEditor.classOK = true
  177. tagEditor.mu.Unlock()
  178. // 按 DPI 缩放窗口尺寸:manifest permonitorv2 下窗口按物理像素创建,
  179. // 高 DPI 屏幕(125%/150%/200%)上 380x220 物理像素显得过小(用户反馈
  180. // 「窗口小,看不到按钮/输入框」)。这里把逻辑尺寸乘上缩放因子。
  181. scale := dpiScale()
  182. winW := scaleInt(tagEditorWidth, scale)
  183. winH := scaleInt(tagEditorHeight, scale)
  184. // 屏幕中心定位
  185. sw, _, _ := procGetSystemMetrics.Call(0) // SM_CXSCREEN
  186. sh, _, _ := procGetSystemMetrics.Call(1) // SM_CYSCREEN
  187. x := int(sw)/2 - winW/2
  188. y := int(sh)/2 - winH/2
  189. // 创建主窗口(带标题栏、系统菜单;模态于 explorer 之上)
  190. hwnd, _, _ := procCreateWindowEx.Call(
  191. uintptr(wsExTopMost|wsExAppWindow), // 置顶 + 应用窗口
  192. uintptr(unsafe.Pointer(className)),
  193. strPtr("添加标签 / 备注"),
  194. uintptr(wsOverlapped|wsCaption|wsSysMenu|wsThickFrame),
  195. uintptr(x), uintptr(y),
  196. uintptr(winW), uintptr(winH),
  197. 0, 0, hInst, 0,
  198. )
  199. if hwnd == 0 {
  200. fmt.Fprintf(os.Stderr, "[tageditor] CreateWindowEx failed\n")
  201. tagEditor.mu.Lock()
  202. tagEditor.started = false
  203. tagEditor.mu.Unlock()
  204. return
  205. }
  206. tagEditor.mu.Lock()
  207. tagEditor.hwnd = hwnd
  208. tagEditor.mu.Unlock()
  209. // 创建控件:标签标签+输入框、备注标签+多行输入框、确定/取消按钮
  210. createTagEditorControls(hwnd, hInst)
  211. procShowWindow.Call(hwnd, 1) // SW_SHOWNORMAL
  212. procSetForegroundWindow.Call(hwnd)
  213. // 回填该路径已有的标签/备注(再次为同一文件打标签时,输入框显示上次内容供修改)。
  214. // 用局部参数 path(不读 tagEditor.path,避免与复用分支的并发写产生数据竞争)。
  215. refreshTagEditorTexts(hwnd, path)
  216. // procGetDlgItem.Call 返回 (hwnd, r2, err);Go 不允许对多返回值直接下标,
  217. // 先取第一值(控件句柄)再 SetFocus。
  218. tagEditCtrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID)
  219. procSetFocus.Call(tagEditCtrl)
  220. // 消息循环(直到 WM_QUIT)
  221. var m msg
  222. for {
  223. ret, _, _ := procGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
  224. if ret == 0 {
  225. break
  226. }
  227. procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
  228. procDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
  229. }
  230. // 清理
  231. if hwnd != 0 {
  232. procDestroyWindow.Call(hwnd)
  233. }
  234. tagEditor.mu.Lock()
  235. tagEditor.hwnd = 0
  236. tagEditor.started = false
  237. tagEditor.mu.Unlock()
  238. }
  239. // createTagEditorControls 创建标签编辑窗口内的控件。
  240. func createTagEditorControls(hwnd, hInst uintptr) {
  241. // mk 创建静态标签文本控件(class="STATIC",text 为显示文字)。
  242. // procCreateWindowEx.Call 返回 (hwnd, r2, err),此处只关心句柄,故取 [0]。
  243. // 坐标/尺寸用 int(DPI 缩放后计算),内部转 uintptr。
  244. mk := func(text string, x, y, w, h int) {
  245. ts, _ := syscall.UTF16PtrFromString(text)
  246. procCreateWindowEx.Call(0,
  247. uintptr(unsafe.Pointer(utf16("STATIC"))),
  248. uintptr(unsafe.Pointer(ts)),
  249. uintptr(wsChild|wsVisible|wsGroup),
  250. uintptr(x), uintptr(y), uintptr(w), uintptr(h), hwnd, 0, hInst, 0)
  251. }
  252. // 按 DPI 缩放控件尺寸与坐标(与窗口同比例),否则高 DPI 屏上输入框/按钮
  253. // 仍按物理像素创建而显得过小、且放不进被放大的窗口。
  254. scale := dpiScale()
  255. pad := scaleInt(12, scale)
  256. labelH := scaleInt(18, scale)
  257. inputH := scaleInt(26, scale)
  258. btnW := scaleInt(80, scale)
  259. btnH := scaleInt(30, scale)
  260. gap := scaleInt(12, scale) // 行间距
  261. labelX := pad
  262. labelW := scaleInt(64, scale)
  263. inputX := pad + labelW
  264. noteH := scaleInt(80, scale) // 备注输入框高度(多行)
  265. // 客户区实际尺寸:外层窗口含标题栏+边框,CreateWindowEx 传入的是外层宽高,
  266. // 若按外层高度布局按钮会超出客户区被裁切(用户反馈「按钮/输入框显示不全」)。
  267. // 这里用 GetClientRect 取真实客户区,按钮贴客户区底边、备注框贴按钮上方。
  268. var cr rect
  269. procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&cr)))
  270. clientW := int(cr.Right - cr.Left)
  271. clientH := int(cr.Bottom - cr.Top)
  272. if clientW <= 0 || clientH <= 0 { // 兜底:取外层尺寸(几乎不会发生)
  273. clientW = scaleInt(tagEditorWidth, scale)
  274. clientH = scaleInt(tagEditorHeight, scale)
  275. }
  276. btnY := clientH - pad - btnH // 按钮底边贴客户区底边(留 pad)
  277. editW := clientW - inputX - pad // 输入框右缘贴客户区右边(留 pad)
  278. noteY := pad + inputH + gap // 备注框在标签输入框下方 gap
  279. // 备注框高度:按钮上方到备注框顶部之间全部利用(若剩余空间不足则用 noteH)
  280. if btnY-noteY-gap < noteH {
  281. noteH = btnY - noteY - gap
  282. if noteH < scaleInt(40, scale) {
  283. noteH = scaleInt(40, scale) // 保底 40px,避免极端情况挤压
  284. }
  285. }
  286. // 标签
  287. mk("标签:", labelX, pad, labelW, labelH)
  288. procCreateWindowEx.Call(0,
  289. uintptr(unsafe.Pointer(utf16("EDIT"))),
  290. 0,
  291. uintptr(wsChild|wsVisible|wsTabStop|wsBorder),
  292. uintptr(inputX), uintptr(pad-scaleInt(1, scale)), uintptr(editW), uintptr(inputH), hwnd,
  293. tagEditID, hInst, 0)
  294. // 备注
  295. mk("备注:", labelX, noteY, labelW, labelH)
  296. procCreateWindowEx.Call(0,
  297. uintptr(unsafe.Pointer(utf16("EDIT"))),
  298. 0,
  299. uintptr(wsChild|wsVisible|wsTabStop|wsBorder|esMultiLine|esAutoVScroll|esAutoHScroll),
  300. uintptr(inputX), uintptr(noteY-scaleInt(1, scale)), uintptr(editW), uintptr(noteH), hwnd,
  301. noteEditID, hInst, 0)
  302. // 按钮:取消(左)、确定(右),底边贴客户区底边
  303. procCreateWindowEx.Call(0,
  304. uintptr(unsafe.Pointer(utf16("BUTTON"))),
  305. uintptr(unsafe.Pointer(utf16("取消"))),
  306. uintptr(wsChild|wsVisible|wsTabStop),
  307. uintptr(clientW-btnW*2-pad*2), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
  308. btnCancelID, hInst, 0)
  309. procCreateWindowEx.Call(0,
  310. uintptr(unsafe.Pointer(utf16("BUTTON"))),
  311. uintptr(unsafe.Pointer(utf16("确定"))),
  312. uintptr(wsChild|wsVisible|wsTabStop|bsDefPushButton),
  313. uintptr(clientW-btnW-pad), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
  314. btnOKID, hInst, 0)
  315. }
  316. // utf16 快捷转 UTF16 指针(临时,须立即使用)。
  317. func utf16(s string) *uint16 {
  318. p, _ := syscall.UTF16PtrFromString(s)
  319. return p
  320. }
  321. // tagEditorWndProc 标签编辑窗口消息处理。
  322. func tagEditorWndProc(hwnd uintptr, msgID uint32, wParam uintptr, lParam uintptr) uintptr {
  323. switch msgID {
  324. case 0x0111: // WM_COMMAND:控件通知
  325. id := uint32(wParam & 0xffff)
  326. switch id {
  327. case btnOKID:
  328. // 读控件文本 → 写库 → 关闭
  329. tagEditor.mu.Lock()
  330. path := tagEditor.path
  331. tagEditor.mu.Unlock()
  332. tagText := getControlText(hwnd, tagEditID)
  333. noteText := getControlText(hwnd, noteEditID)
  334. // 两个输入框都清空:视为取消打标签,删除该记录(否则留空记录,
  335. // 悬停提示与右键「标签」都会把它当成有标签)。
  336. if strings.TrimSpace(tagText) == "" && strings.TrimSpace(noteText) == "" {
  337. if err := getTagSvc().DeleteTag(path); err != nil {
  338. logTagErr("DeleteTag", err)
  339. okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
  340. procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
  341. } else {
  342. procPostQuitMessage.Call(0)
  343. }
  344. break
  345. }
  346. if err := getTagSvc().SaveTag(path, tagText, noteText); err != nil {
  347. logTagErr("SaveTag", err)
  348. // 写库失败:提示并保持窗口打开(先取确定按钮句柄)
  349. okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
  350. procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
  351. } else {
  352. procPostQuitMessage.Call(0)
  353. }
  354. case btnCancelID:
  355. procPostQuitMessage.Call(0)
  356. }
  357. case 0x0010: // WM_CLOSE:用户点标题栏关闭 → 视为取消
  358. procPostQuitMessage.Call(0)
  359. case wmAppRefreshTagEditor: // 复用窗口切换到新路径:回填该路径已有的标签/备注
  360. tagEditor.mu.Lock()
  361. path := tagEditor.path
  362. tagEditor.mu.Unlock()
  363. refreshTagEditorTexts(hwnd, path)
  364. case 0x0002: // WM_DESTROY:窗口已销毁
  365. // 立即复位单实例状态,避免竞态:窗口销毁后、消息循环线程清理前,
  366. // 用户再次点击「标签」时 started 仍为 true 且 hwnd=0,走复用分支
  367. // SetForegroundWindow(0) 无效,窗口永远不弹(用户反馈「第二次无法弹出」)。
  368. tagEditor.mu.Lock()
  369. tagEditor.hwnd = 0
  370. tagEditor.started = false
  371. tagEditor.mu.Unlock()
  372. procPostQuitMessage.Call(0)
  373. }
  374. // msgID 是 uint32,转 uintptr 传入 DefWindowProc;
  375. // procDefWindowProc.Call 返回 (ret, r2, err),只需取第一值。
  376. ret, _, _ := procDefWindowProc.Call(hwnd, uintptr(msgID), wParam, lParam)
  377. return ret
  378. }
  379. // getControlText 读取 EDIT 控件文本。
  380. func getControlText(parent, id uintptr) string {
  381. edit, _, _ := procGetDlgItem.Call(parent, id)
  382. if edit == 0 {
  383. return ""
  384. }
  385. // 先查长度,再读
  386. n, _, _ := procGetWindowTextLengthW.Call(edit)
  387. if n == 0 {
  388. return ""
  389. }
  390. buf := make([]uint16, n+1)
  391. procGetWindowTextW.Call(edit, uintptr(unsafe.Pointer(&buf[0])), n+1)
  392. return syscall.UTF16ToString(buf)
  393. }