zenity/util_windows.go

491 lines
12 KiB
Go
Raw Normal View History

package zenity
import (
2022-05-19 08:47:38 -04:00
"bytes"
2020-01-30 09:14:42 -05:00
"context"
2021-01-05 10:20:42 -05:00
"os"
2021-03-10 09:49:09 -05:00
"reflect"
2021-03-26 08:40:24 -04:00
"runtime"
2021-04-08 20:05:48 -04:00
"strconv"
"sync"
2021-03-26 08:40:24 -04:00
"sync/atomic"
"syscall"
"unsafe"
2021-09-09 20:32:20 -04:00
2022-06-17 22:45:49 -04:00
"github.com/ncruces/zenity/internal/win"
2021-09-09 20:32:20 -04:00
"golang.org/x/sys/windows"
)
var (
2021-09-09 20:32:20 -04:00
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
user32 = windows.NewLazySystemDLL("user32.dll")
2022-06-18 19:48:38 -04:00
activateActCtx = kernel32.NewProc("ActivateActCtx")
createActCtx = kernel32.NewProc("CreateActCtxW")
deactivateActCtx = kernel32.NewProc("DeactivateActCtx")
getModuleHandle = kernel32.NewProc("GetModuleHandleW")
2022-06-19 21:14:08 -04:00
callNextHookEx = user32.NewProc("CallNextHookEx")
createIconFromResource = user32.NewProc("CreateIconFromResource")
createWindowEx = user32.NewProc("CreateWindowExW")
defWindowProc = user32.NewProc("DefWindowProcW")
destroyIcon = user32.NewProc("DestroyIcon")
destroyWindow = user32.NewProc("DestroyWindow")
enableWindow = user32.NewProc("EnableWindow")
getDpiForWindow = user32.NewProc("GetDpiForWindow")
getSystemMetrics = user32.NewProc("GetSystemMetrics")
getWindowDC = user32.NewProc("GetWindowDC")
getWindowRect = user32.NewProc("GetWindowRect")
getWindowText = user32.NewProc("GetWindowTextW")
getWindowTextLength = user32.NewProc("GetWindowTextLengthW")
loadIcon = user32.NewProc("LoadIconW")
loadImage = user32.NewProc("LoadImageW")
postQuitMessage = user32.NewProc("PostQuitMessage")
registerClassEx = user32.NewProc("RegisterClassExW")
releaseDC = user32.NewProc("ReleaseDC")
sendMessage = user32.NewProc("SendMessageW")
setFocus = user32.NewProc("SetFocus")
setWindowLong = user32.NewProc("SetWindowLongW")
setWindowPos = user32.NewProc("SetWindowPos")
setWindowsHookEx = user32.NewProc("SetWindowsHookExW")
setWindowText = user32.NewProc("SetWindowTextW")
showWindow = user32.NewProc("ShowWindow")
systemParametersInfo = user32.NewProc("SystemParametersInfoW")
unhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
unregisterClass = user32.NewProc("UnregisterClassW")
)
2021-04-08 19:55:49 -04:00
func intptr(i int64) uintptr {
return uintptr(i)
}
func strptr(s string) uintptr {
return uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(s)))
}
2022-06-18 07:37:39 -04:00
func hwnd(i uint64) win.HWND { return win.HWND(uintptr(i)) }
2021-03-26 08:40:24 -04:00
func setup() context.CancelFunc {
2022-06-18 19:48:38 -04:00
var wnd win.HWND
2022-06-19 21:14:08 -04:00
win.EnumWindows(syscall.NewCallback(setupEnumCallback), unsafe.Pointer(&wnd))
if wnd == 0 {
2022-06-18 19:48:38 -04:00
wnd = win.GetConsoleWindow()
2021-01-05 10:20:42 -05:00
}
if wnd != 0 {
2022-06-19 21:14:08 -04:00
win.SetForegroundWindow(wnd)
2021-01-05 10:20:42 -05:00
}
2021-03-26 08:40:24 -04:00
runtime.LockOSThread()
2021-04-27 20:27:28 -04:00
var restore uintptr
cookie := enableVisualStyles()
2022-06-19 21:14:08 -04:00
for dpi := win.DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2; dpi <= win.DPI_AWARENESS_CONTEXT_SYSTEM_AWARE; dpi++ {
var err error
restore, err = win.SetThreadDpiAwarenessContext(dpi)
if restore != 0 || err != nil {
break
2021-03-26 08:40:24 -04:00
}
}
2022-06-17 22:45:49 -04:00
var icc win.INITCOMMONCONTROLSEX
2021-04-27 09:05:04 -04:00
icc.Size = uint32(unsafe.Sizeof(icc))
icc.ICC = 0x00004020 // ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS
2022-06-17 22:45:49 -04:00
win.InitCommonControlsEx(&icc)
2021-04-27 09:05:04 -04:00
2021-03-26 08:40:24 -04:00
return func() {
2021-04-27 20:27:28 -04:00
if restore != 0 {
2022-06-19 21:14:08 -04:00
win.SetThreadDpiAwarenessContext(restore)
2021-04-27 20:27:28 -04:00
}
if cookie != 0 {
2021-09-09 15:43:01 -04:00
deactivateActCtx.Call(0, cookie)
2021-03-26 08:40:24 -04:00
}
2021-04-09 08:39:15 -04:00
runtime.UnlockOSThread()
2021-03-26 08:40:24 -04:00
}
2021-01-05 10:20:42 -05:00
}
2022-06-18 19:48:38 -04:00
func setupEnumCallback(wnd win.HWND, lparam *win.HWND) uintptr {
var pid uint32
win.GetWindowThreadProcessId(wnd, &pid)
if int(pid) == os.Getpid() {
*lparam = wnd
return 0 // stop enumeration
}
return 1 // continue enumeration
}
2022-06-18 19:48:38 -04:00
func hookDialog(ctx context.Context, icon any, title *string, init func(wnd win.HWND)) (unhook context.CancelFunc, err error) {
2020-01-30 09:14:42 -05:00
if ctx != nil && ctx.Err() != nil {
return nil, ctx.Err()
}
2022-05-19 18:39:21 -04:00
hook, err := newDialogHook(ctx, icon, title, init)
if err != nil {
return nil, err
}
return hook.unhook, nil
}
2020-01-30 09:14:42 -05:00
type dialogHook struct {
2022-05-19 18:39:21 -04:00
ctx context.Context
2022-06-18 19:48:38 -04:00
tid uint32
2022-05-19 18:39:21 -04:00
wnd uintptr
hook uintptr
done chan struct{}
icon any
title *string
2022-06-18 19:48:38 -04:00
init func(wnd win.HWND)
}
2020-01-30 09:14:42 -05:00
2022-06-18 19:48:38 -04:00
func newDialogHook(ctx context.Context, icon any, title *string, init func(wnd win.HWND)) (*dialogHook, error) {
2022-06-18 19:48:38 -04:00
tid := win.GetCurrentThreadId()
2022-05-23 19:12:38 -04:00
hk, _, err := setWindowsHookEx.Call(12, // WH_CALLWNDPROCRET
2022-06-18 19:48:38 -04:00
syscall.NewCallback(dialogHookProc), 0, uintptr(tid))
if hk == 0 {
2020-01-30 09:14:42 -05:00
return nil, err
}
hook := dialogHook{
2022-05-19 18:39:21 -04:00
ctx: ctx,
tid: tid,
hook: hk,
icon: icon,
title: title,
init: init,
}
if ctx != nil {
hook.done = make(chan struct{})
go hook.wait()
2020-01-30 09:14:42 -05:00
}
2022-06-18 19:48:38 -04:00
saveBackRef(uintptr(tid), unsafe.Pointer(&hook))
return &hook, nil
}
2022-05-23 19:12:38 -04:00
func dialogHookProc(code int32, wparam uintptr, lparam *_CWPRETSTRUCT) uintptr {
if lparam.Message == 0x0110 { // WM_INITDIALOG
2022-06-18 19:48:38 -04:00
tid := win.GetCurrentThreadId()
hook := (*dialogHook)(loadBackRef(uintptr(tid)))
2022-06-18 19:48:38 -04:00
atomic.StoreUintptr(&hook.wnd, uintptr(lparam.Wnd))
2022-05-09 10:49:32 -04:00
if hook.ctx != nil && hook.ctx.Err() != nil {
2022-06-18 19:48:38 -04:00
win.SendMessage(lparam.Wnd, win.WM_SYSCOMMAND, _SC_CLOSE, 0)
2022-05-19 18:39:21 -04:00
} else {
if hook.icon != nil {
icon := getIcon(hook.icon)
if icon.handle != 0 {
defer icon.delete()
2022-06-18 19:48:38 -04:00
win.SendMessage(lparam.Wnd, win.WM_SETICON, 0, icon.handle)
2022-05-19 18:39:21 -04:00
}
}
if hook.title != nil {
2022-06-18 19:48:38 -04:00
win.SetWindowText(lparam.Wnd, syscall.StringToUTF16Ptr(*hook.title))
2022-05-19 18:39:21 -04:00
}
if hook.init != nil {
2022-05-23 19:12:38 -04:00
hook.init(lparam.Wnd)
2022-05-19 18:39:21 -04:00
}
2022-03-23 09:24:02 -04:00
}
}
2022-03-23 09:24:02 -04:00
next, _, _ := callNextHookEx.Call(
2022-05-23 19:12:38 -04:00
0, uintptr(code), wparam, uintptr(unsafe.Pointer(lparam)))
2022-03-23 09:24:02 -04:00
return next
}
func (h *dialogHook) unhook() {
2022-06-18 19:48:38 -04:00
deleteBackRef(uintptr(h.tid))
if h.done != nil {
close(h.done)
}
unhookWindowsHookEx.Call(h.hook)
}
func (h *dialogHook) wait() {
select {
case <-h.ctx.Done():
if wnd := atomic.LoadUintptr(&h.wnd); wnd != 0 {
2022-06-18 19:48:38 -04:00
win.SendMessage(win.HWND(wnd), win.WM_SYSCOMMAND, _SC_CLOSE, 0)
2020-01-30 09:14:42 -05:00
}
case <-h.done:
}
}
2022-03-23 09:24:02 -04:00
var backRefs struct {
sync.Mutex
2022-03-23 09:24:02 -04:00
m map[uintptr]unsafe.Pointer
}
2022-03-23 09:24:02 -04:00
func saveBackRef(id uintptr, ptr unsafe.Pointer) {
backRefs.Lock()
defer backRefs.Unlock()
if backRefs.m == nil {
backRefs.m = map[uintptr]unsafe.Pointer{}
2022-05-10 05:30:52 -04:00
} else if _, ok := backRefs.m[id]; ok {
panic("saveBackRef")
}
2022-03-23 09:24:02 -04:00
backRefs.m[id] = ptr
}
2022-03-23 09:24:02 -04:00
func loadBackRef(id uintptr) unsafe.Pointer {
backRefs.Lock()
defer backRefs.Unlock()
return backRefs.m[id]
2020-01-30 09:14:42 -05:00
}
2022-03-23 09:24:02 -04:00
func deleteBackRef(id uintptr) {
backRefs.Lock()
defer backRefs.Unlock()
delete(backRefs.m, id)
2020-01-24 08:59:03 -05:00
}
2021-04-08 19:55:49 -04:00
type dpi uintptr
func getDPI(wnd uintptr) dpi {
var res uintptr
if wnd != 0 && getDpiForWindow.Find() == nil {
res, _, _ = getDpiForWindow.Call(wnd)
} else if dc, _, _ := getWindowDC.Call(wnd); dc != 0 {
2022-06-18 11:12:03 -04:00
res = uintptr(win.GetDeviceCaps(win.Handle(dc), win.LOGPIXELSY))
2021-04-08 19:55:49 -04:00
releaseDC.Call(0, dc)
}
if res == 0 {
return 96 // USER_DEFAULT_SCREEN_DPI
}
return dpi(res)
2021-04-05 12:54:46 -04:00
}
2022-03-23 09:52:52 -04:00
func (d dpi) scale(dim uintptr) uintptr {
2021-04-08 19:55:49 -04:00
if d == 0 {
return dim
}
return dim * uintptr(d) / 96 // USER_DEFAULT_SCREEN_DPI
}
type font struct {
2022-06-18 07:37:39 -04:00
handle win.Handle
logical win.LOGFONT
2021-04-08 19:55:49 -04:00
}
func getFont() font {
var metrics _NONCLIENTMETRICS
metrics.Size = uint32(unsafe.Sizeof(metrics))
systemParametersInfo.Call(0x29, // SPI_GETNONCLIENTMETRICS
unsafe.Sizeof(metrics), uintptr(unsafe.Pointer(&metrics)), 0)
return font{logical: metrics.MessageFont}
}
2022-03-23 09:52:52 -04:00
func (f *font) forDPI(dpi dpi) uintptr {
if h := -int32(dpi.scale(12)); f.handle == 0 || f.logical.Height != h {
f.delete()
2021-04-08 19:55:49 -04:00
f.logical.Height = h
2022-06-18 07:37:39 -04:00
f.handle = win.CreateFontIndirect(&f.logical)
2021-04-08 19:55:49 -04:00
}
2022-06-18 07:37:39 -04:00
return uintptr(f.handle)
2021-04-08 19:55:49 -04:00
}
2022-03-23 09:52:52 -04:00
func (f *font) delete() {
2021-04-08 19:55:49 -04:00
if f.handle != 0 {
2022-06-18 07:37:39 -04:00
win.DeleteObject(f.handle)
2021-04-08 19:55:49 -04:00
f.handle = 0
}
}
2022-05-19 08:47:38 -04:00
type icon struct {
handle uintptr
destroy bool
}
func getIcon(i any) icon {
var res icon
var resource uintptr
switch i {
case ErrorIcon:
resource = 32513 // IDI_ERROR
case QuestionIcon:
resource = 32514 // IDI_QUESTION
case WarningIcon:
resource = 32515 // IDI_WARNING
case InfoIcon:
resource = 32516 // IDI_INFORMATION
}
if resource != 0 {
res.handle, _, _ = loadIcon.Call(0, resource)
return res
}
path, ok := i.(string)
if !ok {
return res
}
data, err := os.ReadFile(path)
if err != nil {
return res
}
switch {
case bytes.HasPrefix(data, []byte("\x00\x00\x01\x00")):
res.handle, _, _ = loadImage.Call(0,
strptr(path),
1, /*IMAGE_ICON*/
0, 0,
0x00008050 /*LR_LOADFROMFILE|LR_DEFAULTSIZE|LR_SHARED*/)
case bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")):
res.handle, _, _ = createIconFromResource.Call(
uintptr(unsafe.Pointer(&data[0])),
uintptr(len(data)),
1, 0x00030000)
res.destroy = true
}
return res
}
func (i *icon) delete() {
if i.handle != 0 {
destroyIcon.Call(i.handle)
i.handle = 0
}
}
2021-04-08 20:05:48 -04:00
func centerWindow(wnd uintptr) {
getMetric := func(i uintptr) int32 {
2021-04-29 11:38:59 -04:00
n, _, _ := getSystemMetrics.Call(i)
return int32(n)
2021-04-08 20:05:48 -04:00
}
var rect _RECT
getWindowRect.Call(wnd, uintptr(unsafe.Pointer(&rect)))
x := (getMetric(0 /* SM_CXSCREEN */) - (rect.right - rect.left)) / 2
y := (getMetric(1 /* SM_CYSCREEN */) - (rect.bottom - rect.top)) / 2
setWindowPos.Call(wnd, 0, uintptr(x), uintptr(y), 0, 0, 0x5) // SWP_NOZORDER|SWP_NOSIZE
}
func getWindowString(wnd uintptr) string {
len, _, _ := getWindowTextLength.Call(wnd)
buf := make([]uint16, len+1)
getWindowText.Call(wnd, uintptr(unsafe.Pointer(&buf[0])), len+1)
return syscall.UTF16ToString(buf)
}
2022-05-23 19:12:38 -04:00
func registerClass(instance, icon, proc uintptr) (uintptr, error) {
2021-04-08 20:05:48 -04:00
name := "WC_" + strconv.FormatUint(uint64(proc), 16)
var wcx _WNDCLASSEX
wcx.Size = uint32(unsafe.Sizeof(wcx))
wcx.WndProc = proc
2022-05-23 19:12:38 -04:00
wcx.Icon = icon
2021-04-08 20:05:48 -04:00
wcx.Instance = instance
wcx.Background = 5 // COLOR_WINDOW
wcx.ClassName = syscall.StringToUTF16Ptr(name)
2021-04-29 11:38:59 -04:00
atom, _, err := registerClassEx.Call(uintptr(unsafe.Pointer(&wcx)))
return atom, err
2021-04-08 20:05:48 -04:00
}
2021-04-27 20:27:28 -04:00
// https://stackoverflow.com/questions/4308503/how-to-enable-visual-styles-without-a-manifest
func enableVisualStyles() (cookie uintptr) {
2022-06-18 19:48:38 -04:00
dir, err := win.GetSystemDirectory()
if err != nil {
2021-04-27 20:27:28 -04:00
return
}
var ctx _ACTCTX
ctx.Size = uint32(unsafe.Sizeof(ctx))
ctx.Flags = 0x01c // ACTCTX_FLAG_RESOURCE_NAME_VALID|ACTCTX_FLAG_SET_PROCESS_DEFAULT|ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID
ctx.Source = syscall.StringToUTF16Ptr("shell32.dll")
2022-06-18 19:48:38 -04:00
ctx.AssemblyDirectory = syscall.StringToUTF16Ptr(dir)
2021-04-27 20:27:28 -04:00
ctx.ResourceName = 124
if h, _, _ := createActCtx.Call(uintptr(unsafe.Pointer(&ctx))); h != 0 {
activateActCtx.Call(h, uintptr(unsafe.Pointer(&cookie)))
}
return
}
// https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-actctxw
type _ACTCTX struct {
Size uint32
Flags uint32
Source *uint16
ProcessorArchitecture uint16
LangId uint16
AssemblyDirectory *uint16
ResourceName uintptr
ApplicationName *uint16
Module uintptr
}
2022-05-23 19:12:38 -04:00
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-cwpretstruct
type _CWPRETSTRUCT struct {
Result uintptr
LParam uintptr
WParam uintptr
Message uint32
2022-06-18 19:48:38 -04:00
Wnd win.HWND
2022-05-23 19:12:38 -04:00
}
2021-04-08 19:55:49 -04:00
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-nonclientmetricsw
type _NONCLIENTMETRICS struct {
Size uint32
BorderWidth int32
ScrollWidth int32
ScrollHeight int32
CaptionWidth int32
CaptionHeight int32
2022-06-18 07:37:39 -04:00
CaptionFont win.LOGFONT
2021-04-08 19:55:49 -04:00
SmCaptionWidth int32
SmCaptionHeight int32
2022-06-18 07:37:39 -04:00
SmCaptionFont win.LOGFONT
2021-04-08 19:55:49 -04:00
MenuWidth int32
MenuHeight int32
2022-06-18 07:37:39 -04:00
MenuFont win.LOGFONT
StatusFont win.LOGFONT
MessageFont win.LOGFONT
2021-04-08 19:55:49 -04:00
}
// https://docs.microsoft.com/en-us/windows/win32/api/windef/ns-windef-rect
type _RECT struct {
left int32
top int32
right int32
bottom int32
2021-04-05 13:58:32 -04:00
}
2021-04-08 20:05:48 -04:00
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassexw
type _WNDCLASSEX struct {
Size uint32
Style uint32
WndProc uintptr
ClsExtra int32
WndExtra int32
Instance uintptr
Icon uintptr
Cursor uintptr
Background uintptr
MenuName *uint16
ClassName *uint16
IconSm uintptr
}
2022-03-28 22:05:46 -04:00
// https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime
type _SYSTEMTIME struct {
year uint16
month uint16
dayOfWeek uint16
day uint16
hour uint16
minute uint16
second uint16
milliseconds uint16
}
2021-03-10 09:49:09 -05:00
// https://github.com/wine-mirror/wine/blob/master/include/unknwn.idl
type _IUnknownVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
}
func uuid(s string) uintptr {
return (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
}