-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
524 lines (432 loc) · 12.5 KB
/
utils.go
File metadata and controls
524 lines (432 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
package main
import (
"bytes"
"encoding/json"
"fmt"
"image"
"image/png"
"os"
"os/exec"
"path/filepath"
"syscall"
"unsafe"
"github.com/AlecAivazis/survey/v2"
"github.com/JamesHovious/w32"
hook "github.com/robotn/gohook"
"golang.design/x/clipboard"
)
func setConfig(key string, value any) {
data := make(map[string]any)
content, err := os.ReadFile(configFilePath)
if err == nil {
_ = json.Unmarshal(content, &data)
}
data[key] = value
updData, err := json.MarshalIndent(data, "", " ")
if err != nil {
panic(err)
}
os.WriteFile(configFilePath, updData, 0644)
initConfig()
if debugMode {
fmt.Println("setConfig called")
fmt.Println(key)
fmt.Println(value)
fmt.Println("New config: ")
fmt.Println(config)
}
}
var (
user32 = syscall.NewLazyDLL("user32.dll")
procEnumWindows = user32.NewProc("EnumWindows")
procGetWindow = user32.NewProc("GetWindow")
)
type RECT struct {
Left int32
Top int32
Right int32
Bottom int32
}
type WindowBounds struct {
X int32
Y int32
Width int32
Height int32
}
func CopyImgToClipboard(img image.Image) {
err := clipboard.Init()
if err != nil {
fmt.Println("Cannot copy image to clipboard.")
return
}
var buf bytes.Buffer
err = png.Encode(&buf, img)
if err != nil {
fmt.Println("Cannot copy image to clipboard.")
if debugMode {
fmt.Println(err)
}
return
}
clipboard.Write(clipboard.FmtImage, buf.Bytes())
fmt.Println("\nScreenshot copied to clipboard")
}
func SetProcessDPIAware() error {
user32 := syscall.NewLazyDLL("user32.dll")
setProcessDpiAwarenessContext := user32.NewProc("SetProcessDpiAwarenessContext")
if setProcessDpiAwarenessContext.Find() == nil {
const DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = ^uintptr(3) + 1 // -4
ret, _, _ := setProcessDpiAwarenessContext.Call(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)
if ret != 0 {
return nil
}
}
shcore := syscall.NewLazyDLL("shcore.dll")
setProcessDpiAwareness := shcore.NewProc("SetProcessDpiAwareness")
if setProcessDpiAwareness.Find() == nil {
const PROCESS_PER_MONITOR_DPI_AWARE = 2
ret, _, _ := setProcessDpiAwareness.Call(PROCESS_PER_MONITOR_DPI_AWARE)
if ret == 0 { // S_OK
return nil
}
}
setProcessDPIAware := user32.NewProc("SetProcessDPIAware")
ret, _, err := setProcessDPIAware.Call()
if ret == 0 {
return fmt.Errorf("SetProcessDPIAware failed: %v", err)
}
return nil
}
func GetSystemDPI() (uint32, uint32) {
user32 := syscall.NewLazyDLL("user32.dll")
getDC := user32.NewProc("GetDC")
releaseDC := user32.NewProc("ReleaseDC")
gdi32 := syscall.NewLazyDLL("gdi32.dll")
getDeviceCaps := gdi32.NewProc("GetDeviceCaps")
hdc, _, _ := getDC.Call(0)
defer releaseDC.Call(0, hdc)
const LOGPIXELSX = 88
const LOGPIXELSY = 90
dpiX, _, _ := getDeviceCaps.Call(hdc, LOGPIXELSX)
dpiY, _, _ := getDeviceCaps.Call(hdc, LOGPIXELSY)
return uint32(dpiX), uint32(dpiY)
}
func GetWindowDPI(hwnd uintptr) (uint32, uint32, error) {
user32 := syscall.NewLazyDLL("user32.dll")
shcore := syscall.NewLazyDLL("shcore.dll")
getDpiForWindow := user32.NewProc("GetDpiForWindow")
if getDpiForWindow.Find() == nil {
dpi, _, _ := getDpiForWindow.Call(hwnd)
if dpi != 0 {
return uint32(dpi), uint32(dpi), nil
}
}
monitorFromWindow := user32.NewProc("MonitorFromWindow")
getDpiForMonitor := shcore.NewProc("GetDpiForMonitor")
if monitorFromWindow.Find() == nil && getDpiForMonitor.Find() == nil {
const MONITOR_DEFAULTTONEAREST = 2
hMonitor, _, _ := monitorFromWindow.Call(hwnd, MONITOR_DEFAULTTONEAREST)
if hMonitor != 0 {
var dpiX, dpiY uint32
const MDT_EFFECTIVE_DPI = 0
ret, _, _ := getDpiForMonitor.Call(
hMonitor,
MDT_EFFECTIVE_DPI,
uintptr(unsafe.Pointer(&dpiX)),
uintptr(unsafe.Pointer(&dpiY)),
)
if ret == 0 { // S_OK
return dpiX, dpiY, nil
}
}
}
dpiX, dpiY := GetSystemDPI()
return dpiX, dpiY, nil
}
func GetWindowBounds(hwnd uintptr) (WindowBounds, error) {
user32 := syscall.NewLazyDLL("user32.dll")
getWindowRect := user32.NewProc("GetWindowRect")
var rect RECT
ret, _, err := getWindowRect.Call(
hwnd,
uintptr(unsafe.Pointer(&rect)),
)
if ret == 0 {
return WindowBounds{}, fmt.Errorf("GetWindowRect failed: %v", err)
}
bounds := WindowBounds{
X: rect.Left,
Y: rect.Top,
Width: rect.Right - rect.Left,
Height: rect.Bottom - rect.Top,
}
return bounds, nil
}
func GetWindowBoundsWithDPIInfo(hwnd uintptr) (WindowBounds, uint32, uint32, error) {
bounds, err := GetWindowBounds(hwnd)
if err != nil {
return WindowBounds{}, 0, 0, err
}
dpiX, dpiY, dpiErr := GetWindowDPI(hwnd)
if dpiErr != nil {
return bounds, 96, 96, nil // Default to 96 DPI
}
return bounds, dpiX, dpiY, nil
}
func isAltTabWindow(hwnd w32.HWND) bool {
if !w32.IsWindowVisible(hwnd) {
return false
}
length := len(w32.GetWindowText(hwnd))
if length == 0 {
return false
}
exStyle := w32.GetWindowLong(hwnd, w32.GWL_EXSTYLE)
if exStyle&w32.WS_EX_TOOLWINDOW != 0 {
return false
}
ret, _, _ := procGetWindow.Call(uintptr(hwnd), uintptr(4))
owner := w32.HWND(ret)
return owner == 0
}
func chooseWindow() w32.HWND {
windows := make(map[string]w32.HWND)
cb := syscall.NewCallback(func(hwnd uintptr, lparam uintptr) uintptr {
h := w32.HWND(hwnd)
if isAltTabWindow(h) {
title := w32.GetWindowText(h)
windows[fmt.Sprintf("%s - 0x%x", title, h)] = h
}
return 1
})
_, _, _ = procEnumWindows.Call(cb, 0)
var result string
err := survey.AskOne(&survey.Select{
Message: "Select Window",
Options: func() []string {
values := []string{}
for k := range windows {
values = append(values, k)
}
return values
}(),
}, &result, survey.WithValidator(survey.Required))
if err != nil {
fmt.Printf("Prompt failed")
os.Exit(0)
}
return windows[result]
}
func AllowSetForegroundWindow(processId uint32) error {
user32 := syscall.NewLazyDLL("user32.dll")
allowSetForegroundWindow := user32.NewProc("AllowSetForegroundWindow")
ret, _, err := allowSetForegroundWindow.Call(uintptr(processId))
if ret == 0 {
return fmt.Errorf("AllowSetForegroundWindow failed: %v", err)
}
return nil
}
// SimulateUserInput simulates minimal user input to allow window activation
func SimulateUserInput() {
user32 := syscall.NewLazyDLL("user32.dll")
setForegroundWindow := user32.NewProc("SetForegroundWindow")
// Get our own window to temporarily focus
getConsoleWindow := syscall.NewLazyDLL("kernel32.dll").NewProc("GetConsoleWindow")
consoleHwnd, _, _ := getConsoleWindow.Call()
if consoleHwnd != 0 {
setForegroundWindow.Call(consoleHwnd)
}
}
// BringWindowToTop brings the specified window to the top and activates it
func BringWindowToTop(hwnd uintptr) error {
user32 := syscall.NewLazyDLL("user32.dll")
kernel32 := syscall.NewLazyDLL("kernel32.dll")
isIconic := user32.NewProc("IsIconic")
showWindow := user32.NewProc("ShowWindow")
setForegroundWindow := user32.NewProc("SetForegroundWindow")
getWindowThreadProcessId := user32.NewProc("GetWindowThreadProcessId")
attachThreadInput := user32.NewProc("AttachThreadInput")
getCurrentThreadId := kernel32.NewProc("GetCurrentThreadId")
setWindowPos := user32.NewProc("SetWindowPos")
bringWindowToTop := user32.NewProc("BringWindowToTop")
var processId uint32
targetThreadId, _, _ := getWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&processId)))
AllowSetForegroundWindow(processId)
ret, _, _ := isIconic.Call(hwnd)
if ret != 0 {
const SW_RESTORE = 9
showWindow.Call(hwnd, SW_RESTORE)
kernel32.NewProc("Sleep").Call(50)
}
currentThreadId, _, _ := getCurrentThreadId.Call()
var attached bool
if targetThreadId != currentThreadId && targetThreadId != 0 {
ret, _, _ := attachThreadInput.Call(currentThreadId, targetThreadId, 1)
attached = (ret != 0)
}
SimulateUserInput()
// Try to bring window to foreground
ret, _, _ = setForegroundWindow.Call(hwnd)
if ret == 0 {
const HWND_TOPMOST = ^uintptr(0) // -1
const HWND_NOTOPMOST = ^uintptr(1) // -2
const SWP_NOMOVE = 0x0002
const SWP_NOSIZE = 0x0001
const SWP_SHOWWINDOW = 0x0040
setWindowPos.Call(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW)
kernel32.NewProc("Sleep").Call(10)
setWindowPos.Call(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW)
setForegroundWindow.Call(hwnd)
bringWindowToTop.Call(hwnd)
}
if attached {
attachThreadInput.Call(currentThreadId, targetThreadId, 0)
}
return nil
}
func ForceWindowToTop(hwnd uintptr) error {
user32 := syscall.NewLazyDLL("user32.dll")
kernel32 := syscall.NewLazyDLL("kernel32.dll")
err := BringWindowToTop(hwnd)
if err == nil {
return nil
}
getWindowThreadProcessId := user32.NewProc("GetWindowThreadProcessId")
var processId uint32
getWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&processId)))
keybd_event := user32.NewProc("keybd_event")
const VK_MENU = 0x12 // Alt key
const VK_TAB = 0x09 // Tab key
const KEYEVENTF_KEYUP = 0x0002
// Simulate Alt+Tab
keybd_event.Call(VK_MENU, 0, 0, 0) // Alt down
keybd_event.Call(VK_TAB, 0, 0, 0) // Tab down
keybd_event.Call(VK_TAB, 0, KEYEVENTF_KEYUP, 0) // Tab up
keybd_event.Call(VK_MENU, 0, KEYEVENTF_KEYUP, 0) // Alt up
kernel32.NewProc("Sleep").Call(100)
// Try to activate the window again
setForegroundWindow := user32.NewProc("SetForegroundWindow")
showWindow := user32.NewProc("ShowWindow")
const SW_SHOW = 5
const SW_RESTORE = 9
showWindow.Call(hwnd, SW_RESTORE)
kernel32.NewProc("Sleep").Call(50)
showWindow.Call(hwnd, SW_SHOW)
setForegroundWindow.Call(hwnd)
return nil
}
func FlashWindowToGetAttention(hwnd uintptr) error {
user32 := syscall.NewLazyDLL("user32.dll")
flashWindowEx := user32.NewProc("FlashWindowEx")
type FLASHWINFO struct {
cbSize uint32
hwnd uintptr
dwFlags uint32
uCount uint32
dwTimeout uint32
}
const FLASHW_STOP = 0
const FLASHW_ALL = 3
const FLASHW_TIMERNOFG = 12
flashInfo := FLASHWINFO{
cbSize: uint32(unsafe.Sizeof(FLASHWINFO{})),
hwnd: hwnd,
dwFlags: FLASHW_ALL | FLASHW_TIMERNOFG,
uCount: 3,
dwTimeout: 0,
}
// Flash the window
ret, _, err := flashWindowEx.Call(uintptr(unsafe.Pointer(&flashInfo)))
if ret == 0 {
return fmt.Errorf("FlashWindowEx failed: %v", err)
}
// Stop flashing after bringing to front
flashInfo.dwFlags = FLASHW_STOP
flashWindowEx.Call(uintptr(unsafe.Pointer(&flashInfo)))
// Try to bring to front after flashing
return BringWindowToTop(hwnd)
}
func ActivateWindowAndGetBounds(hwnd uintptr) (WindowBounds, error) {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
user32 := syscall.NewLazyDLL("user32.dll")
sleep := kernel32.NewProc("Sleep")
getWindowThreadProcessId := user32.NewProc("GetWindowThreadProcessId")
var processId uint32
getWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&processId)))
AllowSetForegroundWindow(processId)
BringWindowToTop(hwnd)
sleep.Call(200)
FlashWindowToGetAttention(hwnd)
sleep.Call(200)
ForceWindowToTop(hwnd)
sleep.Call(300)
bounds, err := GetWindowBounds(hwnd)
if err != nil {
return WindowBounds{}, err
}
return bounds, nil
}
func getFfmpegPath() string {
cmd := exec.Command("ffmpeg", "-version")
if err := cmd.Run(); err == nil {
return "ffmpeg"
}
return filepath.Join(appdataDir, "bin", "ffmpeg.exe")
}
func ternary[T any](cond bool, trueval, falseval T) T {
if cond {
return trueval
}
return falseval
}
func RegisterHotkey() ([]string, string) {
var (
modKeys = map[uint16]string{
29: "ctrl", // LCtrl
3613: "ctrl", // RCtrl
56: "alt", // LAlt
3640: "alt", // RAlt
42: "shift", // LShift
54: "shift", // RShift
}
keyOrder = []string{"ctrl", "alt", "shift"}
keyMap = map[uint16]string{
2: "1", 3: "2", 4: "3", 5: "4", 6: "5",
7: "6", 8: "7", 9: "8", 10: "9", 11: "0",
16: "q", 17: "w", 18: "e", 19: "r", 20: "t",
21: "y", 22: "u", 23: "i", 24: "o", 25: "p",
30: "a", 31: "s", 32: "d", 33: "f", 34: "g",
35: "h", 36: "j", 37: "k", 38: "l",
44: "z", 45: "x", 46: "c", 47: "v", 48: "b",
49: "n", 50: "m",
}
)
fmt.Println("Press your hotkey combo (e.g. ctrl+alt+z)...")
pressedMods := map[string]bool{}
var mainKey string
evChan := hook.Start()
defer hook.End()
for ev := range evChan {
if ev.Kind != hook.KeyDown {
continue
}
if mod, ok := modKeys[ev.Keycode]; ok {
pressedMods[mod] = true
continue
}
if k, ok := keyMap[ev.Keycode]; ok {
mainKey = k
break
} else {
fmt.Println("Invalid key. Only A-Z or 0-9 accepted.")
os.Exit(1)
}
}
var mods []string
for _, mod := range keyOrder {
if pressedMods[mod] {
mods = append(mods, mod)
}
}
return mods, mainKey
}