| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421 |
- //go:build windows && !service
- // ============================================================================
- // tageditor_windows.go — 标签编辑输入窗口(难点2)
- //
- // 右键菜单点「标签(&T)」后弹出的小窗口:输入「标签」和「备注」两栏,
- // 确定时写入标签数据库(SaveTag),取消/关闭则不写。
- //
- // 实现:仿 mouseAlertLoop 的窗口线程模式(runtime.LockOSThread + RegisterClassExW
- // + CreateWindowExW + GetMessage 消息循环 + 自有 WndProc)。不用 Wails 前端模态
- // 是因为右键场景前台是 explorer,切到 Wails 窗口体验割裂且需新增前端 UI+事件通道。
- // ============================================================================
- package main
- import (
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "sync"
- "syscall"
- "unsafe"
- )
- // 标签编辑窗口控件 ID
- const (
- tagEditID = 1001 // 标签 EDIT
- noteEditID = 1002 // 备注 EDIT(多行)
- btnOKID = 1003 // 确定
- btnCancelID = 1004 // 取消
- tagEditorWidth = 400 // 逻辑宽度(px @96DPI),创建时按 DPI 缩放
- tagEditorHeight = 260 // 逻辑高度(px @96DPI),创建时按 DPI 缩放
- )
- // wmAppRefreshTagEditor:自定义窗口消息,取 WM_APP(0x8000 私有范围)的值,
- // 请求「窗口线程」刷新输入框(回填新路径的标签/备注)。
- // 用于复用分支:菜单线程不能直接 SetWindowText(跨线程操作控件),
- // 改为投递消息,由本窗口消息循环处理,天然串行安全。
- const wmAppRefreshTagEditor = 0x8000
- // 标准控件样式
- const (
- wsChild = 0x40000000
- wsVisible = 0x10000000
- wsTabStop = 0x00010000
- wsGroup = 0x00020000
- wsBorder = 0x00800000
- wsCaption = 0x00C00000
- wsSysMenu = 0x00080000
- wsThickFrame = 0x00040000
- wsOverlapped = 0x00000000
- wsExDlgModal = 0x00000001
- wsExTopMost = 0x00000008
- wsExAppWindow = 0x00040000
- esMultiLine = 0x0004
- esAutoHScroll = 0x0080
- esAutoVScroll = 0x0040
- bsDefPushButton = 0x0001
- )
- // 本文件用到的 user32 过程(procCreateWindowEx/procGetMessage/procRegisterClassEx/
- // procDefWindowProc/procDestroyWindow/procShowWindow/procSetForegroundWindow/
- // procGetSystemMetrics/procGetModuleHandleW 等已在其它文件定义,此处不复用)。
- var (
- procGetWindowTextW = user32.NewProc("GetWindowTextW")
- procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
- procSetWindowTextW = user32.NewProc("SetWindowTextW")
- procGetDlgItem = user32.NewProc("GetDlgItem")
- procSetFocus = user32.NewProc("SetFocus")
- procPostQuitMessage = user32.NewProc("PostQuitMessage")
- procGetClientRect = user32.NewProc("GetClientRect")
- )
- // tagEditor 标签编辑窗口状态(单实例,包级)。
- var tagEditor struct {
- mu sync.Mutex
- hwnd uintptr
- path string
- cb uintptr // WndProc 回调地址(保持引用防 GC)
- classOK bool
- started bool
- }
- // loadTagForEdit 读取 path 当前已保存的标签与备注,用于编辑窗口回填输入框。
- // 未找到(尚未打过标签)时返回两个空串,用户可重新填写。
- // 出错(数据库占用等)仅记日志并返回空串,不阻塞窗口打开。
- func loadTagForEdit(path string) (tag, note string) {
- if path == "" {
- return "", ""
- }
- t, found, err := getTagSvc().GetTag(path) // GetTag 内部会规范化路径键
- if err != nil {
- logTagErr("读取已有标签", err)
- return "", ""
- }
- if !found {
- return "", ""
- }
- return strings.TrimSpace(t.Tag), strings.TrimSpace(t.Note)
- }
- // refreshTagEditorTexts 用 path 已有的标签/备注刷新编辑窗口的两个输入框,
- // 并在窗口标题后附文件名(连续为不同文件打标签时可辨识)。
- // 只在编辑窗口的窗口线程内调用(首次创建后 / 切换路径时)。
- func refreshTagEditorTexts(hwnd uintptr, path string) {
- if hwnd == 0 {
- return
- }
- tag, note := loadTagForEdit(path)
- if ctrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID); ctrl != 0 {
- procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(tag))))
- }
- if ctrl, _, _ := procGetDlgItem.Call(hwnd, noteEditID); ctrl != 0 {
- procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(note))))
- }
- // 窗口标题:「标签:文件名」,便于区分当前正在为哪个文件打标签
- procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("标签 / 备注 - "+filepath.Base(filepath.Clean(path))))))
- }
- // openTagEditor 弹出标签编辑窗口(由右键菜单回调异步调用)。
- // 会启动一个 LockOSThread 的窗口线程。path 为规范化前的完整路径(显示用原始,
- // 写入库时由 SaveTag 再规范化)。
- func openTagEditor(path string) {
- if path == "" {
- return
- }
- tagEditor.mu.Lock()
- if tagEditor.started {
- // 已有一个编辑窗口:把新路径切过去(复用窗口,避免多实例),
- // 并请求窗口线程把该路径已有的标签/备注回填到输入框,供用户在其上修改。
- // 菜单线程不能直接 SetWindowText(跨线程操作控件),改为投递自定义消息,
- // 由本窗口的消息循环处理,天然串行安全。
- hwnd := tagEditor.hwnd
- tagEditor.path = path
- tagEditor.mu.Unlock()
- if hwnd != 0 {
- procSetForegroundWindow.Call(hwnd)
- procPostMessage.Call(hwnd, wmAppRefreshTagEditor, 0, 0)
- }
- return
- }
- tagEditor.started = true
- tagEditor.path = path
- tagEditor.mu.Unlock()
- go tagEditorLoop(path)
- }
- // tagEditorLoop 标签编辑窗口线程。path 为本次要编辑的文件/文件夹路径,
- // 供创建窗口后回填已有标签/备注使用(避免与复用分支的并发写产生数据竞争)。
- func tagEditorLoop(path string) {
- runtime.LockOSThread()
- defer runtime.UnlockOSThread()
- hInst, _, _ := procGetModuleHandleW.Call(0)
- className, _ := syscall.UTF16PtrFromString("TengTuTagEditor")
- // 注册窗口类(WndProc 是 Go 回调,须保持地址)。
- tagEditor.mu.Lock()
- tagEditor.cb = syscall.NewCallback(tagEditorWndProc)
- wc := wndclassex{
- CbSize: uint32(unsafe.Sizeof(wndclassex{})),
- LpfnWndProc: tagEditor.cb,
- HInstance: hInst,
- LpszClassName: className,
- HCursor: 0,
- }
- atom, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
- if atom == 0 {
- // RegisterClassEx 返回 0 可能是「类已注册」(ERROR_CLASS_ALREADY_EXISTS=1410),
- // 此时窗口类定义仍有效,可继续创建窗口。第一次正常关闭后,窗口虽销毁但类定义
- // 保留在系统里;再次点击「标签」时若仍把 0 当失败提前 return,会导致 started
- // 卡在 true、后续永远无法弹窗。
- // 注意:必须用 Call 的第三个返回值(syscall.Errno,API 调用后立即捕获)判断,
- // 不能单独再调 GetLastError——Go 运行时在两次 syscall 间会改写线程 last-error,
- // 导致读到 0(日志曾出现 "RegisterClassEx failed: 0"),从而误判为真失败。
- errno, _ := callErr.(syscall.Errno)
- if errno != 1410 { // ERROR_CLASS_ALREADY_EXISTS
- fmt.Fprintf(os.Stderr, "[tageditor] RegisterClassEx failed: %d\n", errno)
- tagEditor.classOK = false
- tagEditor.mu.Unlock()
- tagEditor.mu.Lock()
- tagEditor.started = false
- tagEditor.mu.Unlock()
- return
- }
- // 类已存在:视为注册成功,继续创建窗口
- }
- tagEditor.classOK = true
- tagEditor.mu.Unlock()
- // 按 DPI 缩放窗口尺寸:manifest permonitorv2 下窗口按物理像素创建,
- // 高 DPI 屏幕(125%/150%/200%)上 380x220 物理像素显得过小(用户反馈
- // 「窗口小,看不到按钮/输入框」)。这里把逻辑尺寸乘上缩放因子。
- scale := dpiScale()
- winW := scaleInt(tagEditorWidth, scale)
- winH := scaleInt(tagEditorHeight, scale)
- // 屏幕中心定位
- sw, _, _ := procGetSystemMetrics.Call(0) // SM_CXSCREEN
- sh, _, _ := procGetSystemMetrics.Call(1) // SM_CYSCREEN
- x := int(sw)/2 - winW/2
- y := int(sh)/2 - winH/2
- // 创建主窗口(带标题栏、系统菜单;模态于 explorer 之上)
- hwnd, _, _ := procCreateWindowEx.Call(
- uintptr(wsExTopMost|wsExAppWindow), // 置顶 + 应用窗口
- uintptr(unsafe.Pointer(className)),
- strPtr("添加标签 / 备注"),
- uintptr(wsOverlapped|wsCaption|wsSysMenu|wsThickFrame),
- uintptr(x), uintptr(y),
- uintptr(winW), uintptr(winH),
- 0, 0, hInst, 0,
- )
- if hwnd == 0 {
- fmt.Fprintf(os.Stderr, "[tageditor] CreateWindowEx failed\n")
- tagEditor.mu.Lock()
- tagEditor.started = false
- tagEditor.mu.Unlock()
- return
- }
- tagEditor.mu.Lock()
- tagEditor.hwnd = hwnd
- tagEditor.mu.Unlock()
- // 创建控件:标签标签+输入框、备注标签+多行输入框、确定/取消按钮
- createTagEditorControls(hwnd, hInst)
- procShowWindow.Call(hwnd, 1) // SW_SHOWNORMAL
- procSetForegroundWindow.Call(hwnd)
- // 回填该路径已有的标签/备注(再次为同一文件打标签时,输入框显示上次内容供修改)。
- // 用局部参数 path(不读 tagEditor.path,避免与复用分支的并发写产生数据竞争)。
- refreshTagEditorTexts(hwnd, path)
- // procGetDlgItem.Call 返回 (hwnd, r2, err);Go 不允许对多返回值直接下标,
- // 先取第一值(控件句柄)再 SetFocus。
- tagEditCtrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID)
- procSetFocus.Call(tagEditCtrl)
- // 消息循环(直到 WM_QUIT)
- var m msg
- for {
- ret, _, _ := procGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
- if ret == 0 {
- break
- }
- procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
- procDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
- }
- // 清理
- if hwnd != 0 {
- procDestroyWindow.Call(hwnd)
- }
- tagEditor.mu.Lock()
- tagEditor.hwnd = 0
- tagEditor.started = false
- tagEditor.mu.Unlock()
- }
- // createTagEditorControls 创建标签编辑窗口内的控件。
- func createTagEditorControls(hwnd, hInst uintptr) {
- // mk 创建静态标签文本控件(class="STATIC",text 为显示文字)。
- // procCreateWindowEx.Call 返回 (hwnd, r2, err),此处只关心句柄,故取 [0]。
- // 坐标/尺寸用 int(DPI 缩放后计算),内部转 uintptr。
- mk := func(text string, x, y, w, h int) {
- ts, _ := syscall.UTF16PtrFromString(text)
- procCreateWindowEx.Call(0,
- uintptr(unsafe.Pointer(utf16("STATIC"))),
- uintptr(unsafe.Pointer(ts)),
- uintptr(wsChild|wsVisible|wsGroup),
- uintptr(x), uintptr(y), uintptr(w), uintptr(h), hwnd, 0, hInst, 0)
- }
- // 按 DPI 缩放控件尺寸与坐标(与窗口同比例),否则高 DPI 屏上输入框/按钮
- // 仍按物理像素创建而显得过小、且放不进被放大的窗口。
- scale := dpiScale()
- pad := scaleInt(12, scale)
- labelH := scaleInt(18, scale)
- inputH := scaleInt(26, scale)
- btnW := scaleInt(80, scale)
- btnH := scaleInt(30, scale)
- gap := scaleInt(12, scale) // 行间距
- labelX := pad
- labelW := scaleInt(64, scale)
- inputX := pad + labelW
- noteH := scaleInt(80, scale) // 备注输入框高度(多行)
- // 客户区实际尺寸:外层窗口含标题栏+边框,CreateWindowEx 传入的是外层宽高,
- // 若按外层高度布局按钮会超出客户区被裁切(用户反馈「按钮/输入框显示不全」)。
- // 这里用 GetClientRect 取真实客户区,按钮贴客户区底边、备注框贴按钮上方。
- var cr rect
- procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&cr)))
- clientW := int(cr.Right - cr.Left)
- clientH := int(cr.Bottom - cr.Top)
- if clientW <= 0 || clientH <= 0 { // 兜底:取外层尺寸(几乎不会发生)
- clientW = scaleInt(tagEditorWidth, scale)
- clientH = scaleInt(tagEditorHeight, scale)
- }
- btnY := clientH - pad - btnH // 按钮底边贴客户区底边(留 pad)
- editW := clientW - inputX - pad // 输入框右缘贴客户区右边(留 pad)
- noteY := pad + inputH + gap // 备注框在标签输入框下方 gap
- // 备注框高度:按钮上方到备注框顶部之间全部利用(若剩余空间不足则用 noteH)
- if btnY-noteY-gap < noteH {
- noteH = btnY - noteY - gap
- if noteH < scaleInt(40, scale) {
- noteH = scaleInt(40, scale) // 保底 40px,避免极端情况挤压
- }
- }
- // 标签
- mk("标签:", labelX, pad, labelW, labelH)
- procCreateWindowEx.Call(0,
- uintptr(unsafe.Pointer(utf16("EDIT"))),
- 0,
- uintptr(wsChild|wsVisible|wsTabStop|wsBorder),
- uintptr(inputX), uintptr(pad-scaleInt(1, scale)), uintptr(editW), uintptr(inputH), hwnd,
- tagEditID, hInst, 0)
- // 备注
- mk("备注:", labelX, noteY, labelW, labelH)
- procCreateWindowEx.Call(0,
- uintptr(unsafe.Pointer(utf16("EDIT"))),
- 0,
- uintptr(wsChild|wsVisible|wsTabStop|wsBorder|esMultiLine|esAutoVScroll|esAutoHScroll),
- uintptr(inputX), uintptr(noteY-scaleInt(1, scale)), uintptr(editW), uintptr(noteH), hwnd,
- noteEditID, hInst, 0)
- // 按钮:取消(左)、确定(右),底边贴客户区底边
- procCreateWindowEx.Call(0,
- uintptr(unsafe.Pointer(utf16("BUTTON"))),
- uintptr(unsafe.Pointer(utf16("取消"))),
- uintptr(wsChild|wsVisible|wsTabStop),
- uintptr(clientW-btnW*2-pad*2), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
- btnCancelID, hInst, 0)
- procCreateWindowEx.Call(0,
- uintptr(unsafe.Pointer(utf16("BUTTON"))),
- uintptr(unsafe.Pointer(utf16("确定"))),
- uintptr(wsChild|wsVisible|wsTabStop|bsDefPushButton),
- uintptr(clientW-btnW-pad), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
- btnOKID, hInst, 0)
- }
- // utf16 快捷转 UTF16 指针(临时,须立即使用)。
- func utf16(s string) *uint16 {
- p, _ := syscall.UTF16PtrFromString(s)
- return p
- }
- // tagEditorWndProc 标签编辑窗口消息处理。
- func tagEditorWndProc(hwnd uintptr, msgID uint32, wParam uintptr, lParam uintptr) uintptr {
- switch msgID {
- case 0x0111: // WM_COMMAND:控件通知
- id := uint32(wParam & 0xffff)
- switch id {
- case btnOKID:
- // 读控件文本 → 写库 → 关闭
- tagEditor.mu.Lock()
- path := tagEditor.path
- tagEditor.mu.Unlock()
- tagText := getControlText(hwnd, tagEditID)
- noteText := getControlText(hwnd, noteEditID)
- // 两个输入框都清空:视为取消打标签,删除该记录(否则留空记录,
- // 悬停提示与右键「标签」都会把它当成有标签)。
- if strings.TrimSpace(tagText) == "" && strings.TrimSpace(noteText) == "" {
- if err := getTagSvc().DeleteTag(path); err != nil {
- logTagErr("DeleteTag", err)
- okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
- procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
- } else {
- procPostQuitMessage.Call(0)
- }
- break
- }
- if err := getTagSvc().SaveTag(path, tagText, noteText); err != nil {
- logTagErr("SaveTag", err)
- // 写库失败:提示并保持窗口打开(先取确定按钮句柄)
- okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
- procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
- } else {
- procPostQuitMessage.Call(0)
- }
- case btnCancelID:
- procPostQuitMessage.Call(0)
- }
- case 0x0010: // WM_CLOSE:用户点标题栏关闭 → 视为取消
- procPostQuitMessage.Call(0)
- case wmAppRefreshTagEditor: // 复用窗口切换到新路径:回填该路径已有的标签/备注
- tagEditor.mu.Lock()
- path := tagEditor.path
- tagEditor.mu.Unlock()
- refreshTagEditorTexts(hwnd, path)
- case 0x0002: // WM_DESTROY:窗口已销毁
- // 立即复位单实例状态,避免竞态:窗口销毁后、消息循环线程清理前,
- // 用户再次点击「标签」时 started 仍为 true 且 hwnd=0,走复用分支
- // SetForegroundWindow(0) 无效,窗口永远不弹(用户反馈「第二次无法弹出」)。
- tagEditor.mu.Lock()
- tagEditor.hwnd = 0
- tagEditor.started = false
- tagEditor.mu.Unlock()
- procPostQuitMessage.Call(0)
- }
- // msgID 是 uint32,转 uintptr 传入 DefWindowProc;
- // procDefWindowProc.Call 返回 (ret, r2, err),只需取第一值。
- ret, _, _ := procDefWindowProc.Call(hwnd, uintptr(msgID), wParam, lParam)
- return ret
- }
- // getControlText 读取 EDIT 控件文本。
- func getControlText(parent, id uintptr) string {
- edit, _, _ := procGetDlgItem.Call(parent, id)
- if edit == 0 {
- return ""
- }
- // 先查长度,再读
- n, _, _ := procGetWindowTextLengthW.Call(edit)
- if n == 0 {
- return ""
- }
- buf := make([]uint16, n+1)
- procGetWindowTextW.Call(edit, uintptr(unsafe.Pointer(&buf[0])), n+1)
- return syscall.UTF16ToString(buf)
- }
|