//go:build windows && !service // ============================================================================ // quickservice_windows.go — 「快捷」页程序图标提取(Windows) // // x/sys/windows 未封装 SHGetFileInfo/GetIconInfo/GetDIBits 等 Win32 图标符号, // 故通过 syscall.NewLazyDLL 动态调用 shell32/user32/gdi32 提取 exe 图标为 PNG // data URI(含 alpha),供前端 展示;提取失败返回空串由前端回退。 // ============================================================================ package main import ( "bytes" "crypto/sha256" "encoding/base64" "encoding/hex" "image" "image/color" "image/png" "log" "os" "path/filepath" "syscall" "unsafe" ) // SHGetFileInfo 标志 const ( shgfiIcon = 0x000000100 // SHGFI_ICON:返回 hIcon shgfiLargeicon = 0x000000000 // SHGFI_LARGEICON:32x32 ) const ( dibRgbColors = 0 // DIB_RGB_COLORS biRgb = 0 // BI_RGB ) // gdi32 过程变量(DeleteObject/CreateCompatibleDC/DeleteDC/SelectObject 与 // mousealert_windows.go 共用同名全局,此处不再重复声明,直接复用)。 var ( shell32DLL = syscall.NewLazyDLL("shell32.dll") user32DLL = syscall.NewLazyDLL("user32.dll") procSHGetFileInfoW = shell32DLL.NewProc("SHGetFileInfoW") procDestroyIcon = user32DLL.NewProc("DestroyIcon") procGetIconInfo = user32DLL.NewProc("GetIconInfo") procGetObjectW = gdi32.NewProc("GetObjectW") procGetDIBits = gdi32.NewProc("GetDIBits") procCreateBitmap = gdi32.NewProc("CreateBitmap") procSetDIBits = gdi32.NewProc("SetDIBits") ) // 原生弹出菜单(收拢后 Webview 太小,HTML 菜单被裁剪,改用 TrackPopupMenu 显示在屏幕上) var ( procCreatePopupMenu = user32DLL.NewProc("CreatePopupMenu") procAppendMenuW = user32DLL.NewProc("AppendMenuW") procTrackPopupMenu = user32DLL.NewProc("TrackPopupMenu") procDestroyMenu = user32DLL.NewProc("DestroyMenu") procSetMenuItemBitmaps = user32DLL.NewProc("SetMenuItemBitmaps") procCopyImage = user32DLL.NewProc("CopyImage") procGetSystemMetrics = user32DLL.NewProc("GetSystemMetrics") procSetForegroundWindow = user32DLL.NewProc("SetForegroundWindow") ) // AppendMenuW 标志 const ( mfString = 0x00000000 // MF_STRING mfPopup = 0x00000010 // MF_POPUP mfBitmap = 0x00000004 // MF_BITMAP mfSeparator = 0x00000800 // MF_SEPARATOR tpmRightButto = 0x00000002 // TPM_RIGHTBUTTON tpmReturnCmd = 0x00000100 // TPM_RETURNCMD:同步返回被选命令 ID smCxsmicon = 49 // SM_CXSMICON smCysmicon = 50 // SM_CYSMICON imageBitmap = 0 // IMAGE_BITMAP lrCopyfromRgba = 0x00001000 // LR_COPYFROMRGBA ) // quickMenuItem 原生菜单命令 ID -> 启动条目的映射(命令 ID 从 1 起) type quickMenuItem struct { title string path string } // showNativeQuickMenu 在屏幕坐标 (x,y) 处弹出原生快捷菜单(分组子菜单 + 条目图标)。 // owner 为宿主窗口句柄(可用 0);非 0 时先前台化该窗口,避免收拢态小窗口失活导致 // TrackPopupMenu 不显示。TrackPopupMenu 用 TPM_RETURNCMD 同步返回被选条目的命令 ID。 func showNativeQuickMenu(groups []QuickGroup, x, y int, owner uintptr) { menu, _, _ := procCreatePopupMenu.Call() if menu == 0 { return } defer procDestroyMenu.Call(menu) var items []quickMenuItem cmdID := uintptr(1) for _, g := range groups { if g.Name != "" { // 命名分组:子菜单 sub, _, _ := procCreatePopupMenu.Call() if sub == 0 { continue } for _, it := range g.Items { procAppendMenuW.Call(sub, mfString, cmdID, strPtr(it.Title)) attachMenuIcon(sub, cmdID, it.Path) items = append(items, quickMenuItem{title: it.Title, path: it.Path}) cmdID++ } procAppendMenuW.Call(menu, mfPopup|mfString, sub, strPtr(g.Name)) } else { // 未分组条目:直接平铺在顶层 for _, it := range g.Items { procAppendMenuW.Call(menu, mfString, cmdID, strPtr(it.Title)) attachMenuIcon(menu, cmdID, it.Path) items = append(items, quickMenuItem{title: it.Title, path: it.Path}) cmdID++ } } } if len(items) == 0 { return // 无条目:不弹空菜单 } // 前台化宿主窗口:收拢态小窗口可能失去激活,TrackPopupMenu 需要前台窗口才可靠显示 if owner != 0 { procSetForegroundWindow.Call(owner) } // TPM_RETURNCMD:TrackPopupMenu 阻塞直到菜单关闭,返回被选命令 ID(0=未选) selected, _, _ := procTrackPopupMenu.Call( menu, tpmRightButto|tpmReturnCmd, uintptr(int32(x)), uintptr(int32(y)), owner, // 宿主窗口(TPM_RETURNCMD 依赖其消息循环) 0, 0, ) if selected < 1 || int(selected-1) >= len(items) { return } it := items[selected-1] if it.path != "" { if _, err := (&LocalService{}).Launch(it.title, it.path); err != nil { log.Printf("快捷菜单启动失败 [%s]: %v", it.title, err) } } } // strPtr 返回 UTF-16 指针(AppendMenuW 的 lpNewItem 参数;空串返回 nil) func strPtr(s string) uintptr { u, err := syscall.UTF16PtrFromString(s) if err != nil || u == nil { return 0 } return uintptr(unsafe.Pointer(u)) } // attachMenuIcon 提取 exe 图标并挂到菜单项(16x16 位图)。 // 图标提取失败或非文件时静默跳过(菜单仍显示文字)。 func attachMenuIcon(menu uintptr, cmdID uintptr, path string) { bgra, w, h, ok := iconBGRA(path) if !ok || w <= 0 || h <= 0 { return } // 缩放到菜单图标尺寸(16x16),并转为带 alpha 的 32bpp 位图 cx, _, _ := procGetSystemMetrics.Call(smCxsmicon) cy, _, _ := procGetSystemMetrics.Call(smCysmicon) if cx == 0 || cy == 0 { cx, cy = 16, 16 } hbm := bgraToBitmap(bgra, w, h, int(cx), int(cy)) if hbm == 0 { return } // 菜单项挂位图;菜单关闭后由 DestroyMenu 释放挂载的位图资源 procSetMenuItemBitmaps.Call(menu, cmdID, mfBitmap, hbm, 0) } // bgraToBitmap 把 BGRA 像素缩放为 (dw x dh) 的 32bpp 设备无关位图(顶向下、含 alpha)。 // 源为全透明 alpha(旧式图标无 alpha 通道)时按不透明处理。返回 HBITMAP,失败为 0。 func bgraToBitmap(bgra []byte, sw, sh, dw, dh int) uintptr { if sw <= 0 || sh <= 0 || dw <= 0 || dh <= 0 || len(bgra) < sw*sh*4 { return 0 } allAlphaZero := true for i := 0; i < sw*sh; i++ { if bgra[i*4+3] != 0 { allAlphaZero = false break } } bi := bitmapInfo{} bi.bmiHeader.biSize = uint32(unsafe.Sizeof(bitmapInfoHeader{})) bi.bmiHeader.biWidth = int32(dw) bi.bmiHeader.biHeight = -int32(dh) // 负值:自顶向下 bi.bmiHeader.biPlanes = 1 bi.bmiHeader.biBitCount = 32 bi.bmiHeader.biCompression = biRgb hdc, _, _ := procCreateCompatibleDC.Call(0) if hdc == 0 { return 0 } defer procDeleteDC.Call(hdc) // CreateDIBSection 不存在于过程表,用 CreateBitmap + SetDIBits 兜底 hbm, _, _ := procCreateBitmap.Call(uintptr(dw), uintptr(dh), 1, 32, 0) if hbm == 0 { return 0 } procSelectObject.Call(hdc, hbm) // 最近邻缩放写入像素缓冲 buf := make([]byte, dw*dh*4) for y := 0; y < dh; y++ { sy := y * sh / dh if sy >= sh { sy = sh - 1 } for x := 0; x < dw; x++ { sx := x * sw / dw if sx >= sw { sx = sw - 1 } si := (sy*sw + sx) * 4 di := (y*dw + x) * 4 a := bgra[si+3] if allAlphaZero { a = 255 } buf[di+0] = bgra[si+0] // B buf[di+1] = bgra[si+1] // G buf[di+2] = bgra[si+2] // R buf[di+3] = a // A } } procSetDIBits.Call(hdc, hbm, 0, uintptr(dh), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&bi)), dibRgbColors) return hbm } // SHFILEINFOW:SHGetFileInfoW 输出结构(hIcon 为首字段) type shfileinfow struct { hIcon uintptr iIcon int32 dwAttributes uint32 szDisplayName [260]uint16 szTypeName [80]uint16 } // ICONINFO:GetIconInfo 输出结构 type iconinfo struct { fIcon int32 xHotspot int32 yHotspot int32 hbmMask uintptr // HBITMAP 掩码 hbmColor uintptr // HBITMAP 颜色 } // BITMAP:GetObjectW 对位图返回的结构 type bitmap struct { bmType int32 bmWidth int32 bmHeight int32 bmWidthBytes int32 bmPlanes uint16 bmBitsPixel uint16 bmBits uintptr } // BITMAPINFOHEADER:位图信息头 type bitmapInfoHeader struct { biSize uint32 biWidth int32 biHeight int32 biPlanes uint16 biBitCount uint16 biCompression uint32 biSizeImage uint32 biXPelsPerMeter int32 biYPelsPerMeter int32 biClrUsed uint32 biClrImportant uint32 } // BITMAPINFO:位图信息(32bpp 无调色板,bmiColors 足够大即可) type bitmapInfo struct { bmiHeader bitmapInfoHeader bmiColors [4]uint32 } // extractFileIcon 提取文件关联图标为 PNG data URI。 // 路径不存在、非文件或无图标时返回空串(不报错,前端回退通用图标)。 func extractFileIcon(path string) (string, error) { bgra, w, h, ok := iconBGRA(path) if !ok { return "", nil } return encodeIconPNG(bgra, w, h), nil } // iconBGRA 提取文件关联图标像素(强制 32bpp 自顶向下 BGRA)。 // 返回 (bgra, 宽, 高, ok);失败或路径无效时 ok=false。 // 与 attachMenuIcon 共用,保证原生菜单与 HTML 图标一致(都能处理无 alpha 旧图标)。 func iconBGRA(path string) ([]byte, int, int, bool) { if path == "" { return nil, 0, 0, false } u16, err := syscall.UTF16PtrFromString(path) if err != nil { return nil, 0, 0, false } var sfi shfileinfow ret, _, _ := procSHGetFileInfoW.Call( uintptr(unsafe.Pointer(u16)), 0, uintptr(unsafe.Pointer(&sfi)), uintptr(unsafe.Sizeof(sfi)), uintptr(shgfiIcon|shgfiLargeicon), ) if ret == 0 || sfi.hIcon == 0 { return nil, 0, 0, false // 无图标(如目录占位),交给前端回退 } defer procDestroyIcon.Call(sfi.hIcon) // 用完即销毁 HICON // 从 HICON 取位图句柄 var ii iconinfo if r, _, _ := procGetIconInfo.Call(sfi.hIcon, uintptr(unsafe.Pointer(&ii))); r == 0 { return nil, 0, 0, false } defer procDeleteObject.Call(ii.hbmMask) defer procDeleteObject.Call(ii.hbmColor) hbm := ii.hbmColor if hbm == 0 { hbm = ii.hbmMask // 无颜色位图(单色图标)时用掩码 } if hbm == 0 { return nil, 0, 0, false } // 查询位图尺寸与位深 var bmp bitmap if r, _, _ := procGetObjectW.Call(hbm, uintptr(unsafe.Sizeof(bmp)), uintptr(unsafe.Pointer(&bmp))); r == 0 { return nil, 0, 0, false } w, h := int(bmp.bmWidth), int(bmp.bmHeight) if w <= 0 || h <= 0 { return nil, 0, 0, false } // 32bpp 顶下行(负高度),逐像素 BGRA bi := bitmapInfo{} bi.bmiHeader.biSize = uint32(unsafe.Sizeof(bitmapInfoHeader{})) bi.bmiHeader.biWidth = int32(w) bi.bmiHeader.biHeight = -int32(h) // 负值:自顶向下 bi.bmiHeader.biPlanes = 1 bi.bmiHeader.biBitCount = 32 bi.bmiHeader.biCompression = biRgb hdc, _, _ := procCreateCompatibleDC.Call(0) if hdc == 0 { return nil, 0, 0, false } defer procDeleteDC.Call(hdc) procSelectObject.Call(hdc, hbm) // 选择到位图,GetDIBits 需要兼容 DC // 分配像素缓冲(每像素 4 字节) buf := make([]byte, w*h*4) if r, _, _ := procGetDIBits.Call(hdc, hbm, 0, uintptr(h), uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&bi)), dibRgbColors); r == 0 { return nil, 0, 0, false } return buf, w, h, true } // encodeIconPNG 把 BGRA 像素编码为 PNG data URI。 // 全透明 alpha(旧式 32bpp 图标无 alpha 通道)时按不透明处理,避免图标隐形。 func encodeIconPNG(bgra []byte, w, h int) string { img := image.NewNRGBA(image.Rect(0, 0, w, h)) allAlphaZero := true for i := 0; i < w*h; i++ { if bgra[i*4+3] != 0 { allAlphaZero = false break } } for y := 0; y < h; y++ { for x := 0; x < w; x++ { i := (y*w + x) * 4 a := bgra[i+3] if allAlphaZero { a = 255 // 无 alpha 信息:视为不透明 } img.SetNRGBA(x, y, color.NRGBA{ R: bgra[i+2], G: bgra[i+1], B: bgra[i+0], A: a, }) } } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { return "" } return "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()) } // ============================================================================ // 快捷项图标缓存:供系统托盘「快捷」菜单项显示程序图标。 // // 建立快捷(设置保存 / 托盘菜单构建)时,把各程序路径的关联图标提取为 // 16x16 PNG 字节,缓存到 <用户配置目录>/TengTuToolbox/quickicons/ 子目录, // 之后直接读取缓存给托盘菜单项 SetBitmap 使用,避免每次启动重复走 // SHGetFileInfo/GetDIBits。缓存文件名为路径 SHA-256 前 32 位 + .png, // 不依赖路径中的非法文件名字符,路径变化(文件移动)自动重新生成。 // ============================================================================ // iconCacheDir 返回图标缓存子目录:<配置目录>/quickicons func iconCacheDir() (string, error) { dir, err := os.UserConfigDir() if err != nil { return "", err } return filepath.Join(dir, "TengTuToolbox", "quickicons"), nil } // quickIconCachePath 计算程序路径对应的缓存 PNG 文件路径。 // 返回 (路径, 是否可用);路径为空表示无法定位缓存目录。 func quickIconCachePath(path string) (string, bool) { if path == "" { return "", false } dir, err := iconCacheDir() if err != nil { return "", false } sum := sha256.Sum256([]byte(path)) name := hex.EncodeToString(sum[:16]) + ".png" // 前 16 字节(32 位十六进制)足够区分 return filepath.Join(dir, name), true } // quickIconCachedPNG 返回程序路径的 16x16 PNG 字节(供托盘菜单项 SetBitmap)。 // 优先读磁盘缓存;缓存缺失/损坏时重新提取并写回缓存。提取失败返回 (nil,false)。 func quickIconCachedPNG(path string) ([]byte, bool) { cachePath, ok := quickIconCachePath(path) if !ok { return fileIconPNG16(path) // 无法定位缓存目录:直接提取,不缓存 } if data, err := os.ReadFile(cachePath); err == nil && len(data) > 0 { // 校验是合法 PNG,损坏则回退重新提取 if _, err := png.Decode(bytes.NewReader(data)); err == nil { return data, true } } pngBytes, ok := fileIconPNG16(path) if !ok { return nil, false } // 写回缓存(目录不存在时自动创建;失败不影响本次使用) if err := os.MkdirAll(filepath.Dir(cachePath), 0o755); err == nil { _ = os.WriteFile(cachePath, pngBytes, 0o644) } return pngBytes, true } // fileIconPNG16 提取程序关联图标为 16x16 PNG 原始字节(顶向下、含 alpha)。 // 复用 iconBGRA 提取原尺寸(32x32),最近邻缩放到 16x16 后编码 PNG。 func fileIconPNG16(path string) ([]byte, bool) { bgra, w, h, ok := iconBGRA(path) if !ok || w <= 0 || h <= 0 { return nil, false } const size = 16 img := image.NewNRGBA(image.Rect(0, 0, size, size)) allAlphaZero := true for i := 0; i < w*h; i++ { if bgra[i*4+3] != 0 { allAlphaZero = false break } } for y := 0; y < size; y++ { sy := y * h / size if sy >= h { sy = h - 1 } for x := 0; x < size; x++ { sx := x * w / size if sx >= w { sx = w - 1 } si := (sy*w + sx) * 4 a := bgra[si+3] if allAlphaZero { a = 255 } img.SetNRGBA(x, y, color.NRGBA{R: bgra[si+2], G: bgra[si+1], B: bgra[si+0], A: a}) } } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { return nil, false } return buf.Bytes(), true }