zenity/util_windows.go

537 lines
14 KiB
Go
Raw Normal View History

package zenity
import (
2020-01-30 09:14:42 -05:00
"context"
"fmt"
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
"golang.org/x/sys/windows"
)
var (
2021-09-09 20:32:20 -04:00
comctl32 = windows.NewLazySystemDLL("comctl32.dll")
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
gdi32 = windows.NewLazySystemDLL("gdi32.dll")
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
ntdll = windows.NewLazySystemDLL("ntdll.dll")
ole32 = windows.NewLazySystemDLL("ole32.dll")
shell32 = windows.NewLazySystemDLL("shell32.dll")
user32 = windows.NewLazySystemDLL("user32.dll")
wtsapi32 = windows.NewLazySystemDLL("wtsapi32.dll")
2021-04-27 09:05:04 -04:00
initCommonControlsEx = comctl32.NewProc("InitCommonControlsEx")
commDlgExtendedError = comdlg32.NewProc("CommDlgExtendedError")
2021-04-08 19:55:49 -04:00
deleteObject = gdi32.NewProc("DeleteObject")
getDeviceCaps = gdi32.NewProc("GetDeviceCaps")
createFontIndirect = gdi32.NewProc("CreateFontIndirectW")
2021-03-29 14:07:44 -04:00
getModuleHandle = kernel32.NewProc("GetModuleHandleW")
getCurrentThreadId = kernel32.NewProc("GetCurrentThreadId")
2021-01-05 10:20:42 -05:00
getConsoleWindow = kernel32.NewProc("GetConsoleWindow")
2021-04-27 20:27:28 -04:00
getSystemDirectory = kernel32.NewProc("GetSystemDirectoryW")
createActCtx = kernel32.NewProc("CreateActCtxW")
activateActCtx = kernel32.NewProc("ActivateActCtx")
deactivateActCtx = kernel32.NewProc("DeactivateActCtx")
coInitializeEx = ole32.NewProc("CoInitializeEx")
coUninitialize = ole32.NewProc("CoUninitialize")
coCreateInstance = ole32.NewProc("CoCreateInstance")
coTaskMemFree = ole32.NewProc("CoTaskMemFree")
2021-03-26 08:40:24 -04:00
getMessage = user32.NewProc("GetMessageW")
sendMessage = user32.NewProc("SendMessageW")
2021-04-08 20:05:48 -04:00
postQuitMessage = user32.NewProc("PostQuitMessage")
2021-04-08 19:55:49 -04:00
isDialogMessage = user32.NewProc("IsDialogMessageW")
dispatchMessage = user32.NewProc("DispatchMessageW")
translateMessage = user32.NewProc("TranslateMessage")
2021-03-26 08:40:24 -04:00
unhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
2021-04-08 19:55:49 -04:00
setWindowsHookEx = user32.NewProc("SetWindowsHookExW")
2021-03-26 08:40:24 -04:00
callNextHookEx = user32.NewProc("CallNextHookEx")
enumWindows = user32.NewProc("EnumWindows")
enumChildWindows = user32.NewProc("EnumChildWindows")
setWindowText = user32.NewProc("SetWindowTextW")
2021-04-05 12:54:46 -04:00
getWindowText = user32.NewProc("GetWindowTextW")
getWindowTextLength = user32.NewProc("GetWindowTextLengthW")
2021-03-26 08:40:24 -04:00
setForegroundWindow = user32.NewProc("SetForegroundWindow")
getWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId")
setThreadDpiAwarenessContext = user32.NewProc("SetThreadDpiAwarenessContext")
2021-04-08 19:55:49 -04:00
getDpiForWindow = user32.NewProc("GetDpiForWindow")
releaseDC = user32.NewProc("ReleaseDC")
getWindowDC = user32.NewProc("GetWindowDC")
systemParametersInfo = user32.NewProc("SystemParametersInfoW")
2021-04-08 20:05:48 -04:00
setWindowPos = user32.NewProc("SetWindowPos")
getWindowRect = user32.NewProc("GetWindowRect")
2021-08-10 20:26:48 -04:00
setWindowLong = user32.NewProc("SetWindowLongW")
2021-04-08 20:05:48 -04:00
getSystemMetrics = user32.NewProc("GetSystemMetrics")
unregisterClass = user32.NewProc("UnregisterClassW")
registerClassEx = user32.NewProc("RegisterClassExW")
destroyWindow = user32.NewProc("DestroyWindow")
createWindowEx = user32.NewProc("CreateWindowExW")
showWindow = user32.NewProc("ShowWindow")
2021-04-29 11:38:59 -04:00
enableWindow = user32.NewProc("EnableWindow")
2021-04-08 20:05:48 -04:00
setFocus = user32.NewProc("SetFocus")
defWindowProc = user32.NewProc("DefWindowProcW")
)
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)))
}
2021-03-26 08:40:24 -04:00
func setup() context.CancelFunc {
var wnd uintptr
enumWindows.Call(syscall.NewCallback(setupEnumCallback), uintptr(unsafe.Pointer(&wnd)))
if wnd == 0 {
wnd, _, _ = getConsoleWindow.Call()
2021-01-05 10:20:42 -05:00
}
if wnd != 0 {
setForegroundWindow.Call(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()
2021-03-26 08:40:24 -04:00
if setThreadDpiAwarenessContext.Find() == nil {
// try:
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE
// DPI_AWARENESS_CONTEXT_SYSTEM_AWARE
for i := -4; i <= -2; i++ {
2021-04-27 20:27:28 -04:00
restore, _, _ = setThreadDpiAwarenessContext.Call(uintptr(i))
2021-03-26 08:40:24 -04:00
if restore != 0 {
break
}
}
}
2021-04-27 09:05:04 -04:00
var icc _INITCOMMONCONTROLSEX
icc.Size = uint32(unsafe.Sizeof(icc))
icc.ICC = 0x00004020 // ICC_STANDARD_CLASSES|ICC_PROGRESS_CLASS
2021-07-12 20:43:52 -04:00
initCommonControlsEx.Call(uintptr(unsafe.Pointer(&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 {
setThreadDpiAwarenessContext.Call(restore)
}
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
}
func setupEnumCallback(wnd uintptr, lparam *uintptr) uintptr {
var pid uintptr
getWindowThreadProcessId.Call(wnd, uintptr(unsafe.Pointer(&pid)))
if int(pid) == os.Getpid() {
*lparam = wnd
return 0 // stop enumeration
}
return 1 // continue enumeration
}
func commDlgError() error {
2020-01-29 09:15:21 -05:00
s, _, _ := commDlgExtendedError.Call()
if s == 0 {
2021-04-29 11:05:28 -04:00
return ErrCanceled
} else {
2020-01-29 09:15:21 -05:00
return fmt.Errorf("Common Dialog error: %x", s)
}
}
2020-01-30 09:14:42 -05:00
func hookDialog(ctx context.Context, initDialog func(wnd uintptr)) (unhook context.CancelFunc, err error) {
if ctx != nil && ctx.Err() != nil {
return nil, ctx.Err()
}
hook, err := newDialogHook(ctx, initDialog)
if err != nil {
return nil, err
}
return hook.unhook, nil
}
2020-01-30 09:14:42 -05:00
type dialogHook struct {
ctx context.Context
tid uintptr
wnd uintptr
hook uintptr
done chan struct{}
init func(wnd uintptr)
}
2020-01-30 09:14:42 -05:00
func newDialogHook(ctx context.Context, initDialog func(wnd uintptr)) (*dialogHook, error) {
tid, _, _ := getCurrentThreadId.Call()
2022-05-09 10:49:32 -04:00
hk, _, err := setWindowsHookEx.Call(5, // WH_CBT
syscall.NewCallback(dialogHookProc), 0, tid)
if hk == 0 {
2020-01-30 09:14:42 -05:00
return nil, err
}
hook := dialogHook{
ctx: ctx,
tid: tid,
hook: hk,
init: initDialog,
}
if ctx != nil {
hook.done = make(chan struct{})
go hook.wait()
2020-01-30 09:14:42 -05:00
}
2022-03-23 09:24:02 -04:00
saveBackRef(tid, unsafe.Pointer(&hook))
return &hook, nil
}
2022-05-09 10:49:32 -04:00
func dialogHookProc(code int32, wparam, lparam uintptr) uintptr {
if code == 5 { // HCBT_ACTIVATE
tid, _, _ := getCurrentThreadId.Call()
hook := (*dialogHook)(loadBackRef(tid))
atomic.StoreUintptr(&hook.wnd, wparam)
if hook.ctx != nil && hook.ctx.Err() != nil {
sendMessage.Call(wparam, _WM_SYSCOMMAND, _SC_CLOSE, 0)
} else if hook.init != nil {
hook.init(wparam)
2022-03-23 09:24:02 -04:00
}
}
2022-03-23 09:24:02 -04:00
next, _, _ := callNextHookEx.Call(
2022-05-09 10:49:32 -04:00
0, uintptr(code), wparam, lparam)
2022-03-23 09:24:02 -04:00
return next
}
func (h *dialogHook) unhook() {
2022-03-23 09:24:02 -04:00
deleteBackRef(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-03-28 22:05:46 -04:00
sendMessage.Call(wnd, _WM_SYSCOMMAND, _SC_CLOSE, 0)
2020-01-30 09:14:42 -05:00
}
case <-h.done:
}
}
2022-03-23 09:24:02 -04:00
func hookDialogTitle(ctx context.Context, title *string) (unhook context.CancelFunc, err error) {
var init func(wnd uintptr)
if title != nil {
init = func(wnd uintptr) {
setWindowText.Call(wnd, strptr(*title))
}
}
2022-03-23 09:24:02 -04:00
return hookDialog(ctx, init)
}
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 {
res, _, _ = getDeviceCaps.Call(dc, 90) // LOGPIXELSY
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 {
handle uintptr
logical _LOGFONT
}
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
f.handle, _, _ = createFontIndirect.Call(uintptr(unsafe.Pointer(&f.logical)))
}
return f.handle
}
2022-03-23 09:52:52 -04:00
func (f *font) delete() {
2021-04-08 19:55:49 -04:00
if f.handle != 0 {
deleteObject.Call(f.handle)
f.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)
}
func registerClass(instance, proc uintptr) (uintptr, error) {
name := "WC_" + strconv.FormatUint(uint64(proc), 16)
var wcx _WNDCLASSEX
wcx.Size = uint32(unsafe.Sizeof(wcx))
wcx.WndProc = proc
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-08 19:55:49 -04:00
// https://docs.microsoft.com/en-us/windows/win32/winmsg/using-messages-and-message-queues
func messageLoop(wnd uintptr) error {
getMessage := getMessage.Addr()
isDialogMessage := isDialogMessage.Addr()
translateMessage := translateMessage.Addr()
dispatchMessage := dispatchMessage.Addr()
for {
var msg _MSG
2021-04-29 11:38:59 -04:00
s, _, err := syscall.Syscall6(getMessage, 4, uintptr(unsafe.Pointer(&msg)), 0, 0, 0, 0, 0)
if int32(s) == -1 {
2021-04-08 19:55:49 -04:00
return err
}
2021-04-29 11:38:59 -04:00
if s == 0 {
2021-04-08 19:55:49 -04:00
return nil
}
2021-04-29 11:38:59 -04:00
s, _, _ = syscall.Syscall(isDialogMessage, 2, wnd, uintptr(unsafe.Pointer(&msg)), 0)
if s == 0 {
2021-04-08 19:55:49 -04:00
syscall.Syscall(translateMessage, 1, uintptr(unsafe.Pointer(&msg)), 0, 0)
syscall.Syscall(dispatchMessage, 1, uintptr(unsafe.Pointer(&msg)), 0, 0)
}
}
}
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) {
var dir [260]uint16
n, _, _ := getSystemDirectory.Call(uintptr(unsafe.Pointer(&dir[0])), uintptr(len(dir)))
if n == 0 || int(n) >= len(dir) {
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")
ctx.AssemblyDirectory = &dir[0]
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
}
// https://docs.microsoft.com/en-us/windows/win32/api/commctrl/ns-commctrl-initcommoncontrolsex
type _INITCOMMONCONTROLSEX struct {
Size uint32
ICC uint32
}
2021-04-08 19:55:49 -04:00
// https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw
type _LOGFONT struct {
Height int32
Width int32
Escapement int32
Orientation int32
Weight int32
Italic byte
Underline byte
StrikeOut byte
CharSet byte
OutPrecision byte
ClipPrecision byte
Quality byte
PitchAndFamily byte
FaceName [32]uint16
}
// 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
CaptionFont _LOGFONT
SmCaptionWidth int32
SmCaptionHeight int32
SmCaptionFont _LOGFONT
MenuWidth int32
MenuHeight int32
MenuFont _LOGFONT
StatusFont _LOGFONT
MessageFont _LOGFONT
}
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg
type _MSG struct {
Owner syscall.Handle
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt _POINT
}
// https://docs.microsoft.com/en-us/windows/win32/api/windef/ns-windef-point
type _POINT struct {
x, y int32
}
// 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
}
type _COMObject struct{}
2021-09-15 08:54:35 -04:00
//go:uintptrescapes
func (o *_COMObject) Call(trap uintptr, a ...uintptr) (r1, r2 uintptr, lastErr error) {
2021-04-09 10:28:17 -04:00
switch nargs := uintptr(len(a)); nargs {
case 0:
2021-04-09 10:28:17 -04:00
return syscall.Syscall(trap, nargs+1, uintptr(unsafe.Pointer(o)), 0, 0)
case 1:
2021-04-09 10:28:17 -04:00
return syscall.Syscall(trap, nargs+1, uintptr(unsafe.Pointer(o)), a[0], 0)
case 2:
2021-04-09 10:28:17 -04:00
return syscall.Syscall(trap, nargs+1, uintptr(unsafe.Pointer(o)), a[0], a[1])
default:
panic("COM call with too many arguments.")
}
}