-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1585 lines (1337 loc) · 44.5 KB
/
Copy pathmain.go
File metadata and controls
1585 lines (1337 loc) · 44.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"fullscreen-monitor-manager/internal/autostart"
"fullscreen-monitor-manager/internal/config"
"fullscreen-monitor-manager/internal/ui"
"github.com/getlantern/systray"
"golang.org/x/sys/windows"
)
// State represents the global application state
type State struct {
configMgr *config.Manager
monitorsDisabled bool
autoPaused bool
disabledMonitors []string
fullscreenMonitor string // name of monitor with fullscreen window
originalPrimary string // save original primary monitor
monitors []MonitorData // list of monitors from MMT
settingsWindowOpen bool
savedWindowPos []SavedWindow // saved window positions
mu sync.RWMutex
stopChan chan bool
logger *log.Logger
logLevel string // "debug" or "info"
}
// SavedWindow stores window position information
type SavedWindow struct {
Hwnd windows.HWND
ProcessName string
Title string
Rect RECT
MonitorName string
IsVisible bool
IsMaximized bool
WasSuccessful bool // track if restoration was successful
}
// MonitorData contains information about a monitor from MMT
type MonitorData struct {
Name string // \\.\DISPLAY1
LeftTop RECT // coordinates
RightBottom RECT
Active bool
Primary bool
MonitorModel string // e.g. "DELL P2421D"
MonitorName string // e.g. "Generic PnP Monitor"
Resolution string // e.g. "2560 X 1440"
}
// RECT represents a rectangle structure
type RECT struct {
Left int32
Top int32
Right int32
Bottom int32
}
// MONITORINFO contains monitor information
type MONITORINFO struct {
CbSize uint32
RcMonitor RECT
RcWork RECT
DwFlags uint32
}
// MONITORINFOEX extends MONITORINFO with device name
type MONITORINFOEX struct {
CbSize uint32
RcMonitor RECT
RcWork RECT
DwFlags uint32
SzDevice [32]uint16 // CCHDEVICENAME = 32
}
const (
MONITOR_DEFAULTTONEAREST = 2
SW_MAXIMIZE = 3
SW_RESTORE = 9
SWP_NOSIZE = 0x0001
SWP_NOZORDER = 0x0004
SWP_NOACTIVATE = 0x0010
GWL_STYLE = -16
WS_VISIBLE = 0x10000000
WS_MAXIMIZE = 0x01000000
)
var (
state *State
// Windows API functions
user32 = windows.NewLazySystemDLL("user32.dll")
procGetForegroundWindow = user32.NewProc("GetForegroundWindow")
procGetWindowRect = user32.NewProc("GetWindowRect")
procMonitorFromWindow = user32.NewProc("MonitorFromWindow")
procGetMonitorInfo = user32.NewProc("GetMonitorInfoW")
procGetWindowThreadProcessId = user32.NewProc("GetWindowThreadProcessId")
procEnumWindows = user32.NewProc("EnumWindows")
procIsWindowVisible = user32.NewProc("IsWindowVisible")
procGetWindowTextW = user32.NewProc("GetWindowTextW")
procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
procSetWindowPos = user32.NewProc("SetWindowPos")
procGetWindowLongW = user32.NewProc("GetWindowLongW")
procShowWindow = user32.NewProc("ShowWindow")
)
// getForegroundWindow retrieves the active window
func getForegroundWindow() windows.HWND {
r, _, _ := procGetForegroundWindow.Call()
return windows.HWND(r)
}
// setMonitorPrimary sets the monitor as primary using MultiMonitorTool
func setMonitorPrimary(monitorName string) error {
if monitorName == "" {
state.logger.Printf("[Primary] Skipping empty monitor name")
return nil
}
cfg := state.configMgr.GetConfig()
state.logger.Printf("[Primary] Setting %s as primary monitor...", monitorName)
args := []string{"/SetPrimary", monitorName}
cmd := createMMTCommand(cfg.MMTPath, args...)
if err := cmd.Run(); err != nil {
state.logger.Printf("[Primary] ❌ Failed to set as primary: %v", err)
return err
}
state.logger.Printf("[Primary] ✅ %s set as primary", monitorName)
// Give the system time to process
time.Sleep(200 * time.Millisecond)
// Verify by reloading monitors
if err := loadMonitorsFromMMT(); err == nil {
state.mu.RLock()
for _, m := range state.monitors {
if m.Primary {
if state.configMgr.GetConfig().LogLevel == "debug" {
state.logger.Printf("[DEBUG][Primary] Verified: %s is now primary", m.Name)
}
break
}
}
state.mu.RUnlock()
}
return nil
}
// getWindowRect retrieves the window dimensions
func getWindowRect(hwnd windows.HWND) (RECT, error) {
var rect RECT
r, _, err := procGetWindowRect.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&rect)))
if r == 0 {
return rect, fmt.Errorf("GetWindowRect failed: %v", err)
}
return rect, nil
}
// monitorFromWindow retrieves the monitor for a window
func monitorFromWindow(hwnd windows.HWND, dwFlags uint32) windows.Handle {
r, _, _ := procMonitorFromWindow.Call(uintptr(hwnd), uintptr(dwFlags))
return windows.Handle(r)
}
// getMonitorInfo retrieves monitor information
func getMonitorInfo(hMonitor windows.Handle) (MONITORINFO, error) {
var mi MONITORINFO
mi.CbSize = uint32(unsafe.Sizeof(mi))
r, _, err := procGetMonitorInfo.Call(uintptr(hMonitor), uintptr(unsafe.Pointer(&mi)))
if r == 0 {
return mi, fmt.Errorf("GetMonitorInfo failed: %v", err)
}
return mi, nil
}
// getMonitorDeviceName retrieves the device name for a monitor (e.g., \\.\DISPLAY1)
func getMonitorDeviceName(hMonitor windows.Handle) (string, error) {
var miex MONITORINFOEX
miex.CbSize = uint32(unsafe.Sizeof(miex))
r, _, err := procGetMonitorInfo.Call(uintptr(hMonitor), uintptr(unsafe.Pointer(&miex)))
if r == 0 {
return "", fmt.Errorf("GetMonitorInfo failed: %v", err)
}
// Convert UTF-16 to string
deviceName := windows.UTF16ToString(miex.SzDevice[:])
return deviceName, nil
}
// isFullscreen checks if a window is in fullscreen mode
func isFullscreen(hwnd windows.HWND) (bool, error) {
if hwnd == 0 {
return false, nil
}
rect, err := getWindowRect(hwnd)
if err != nil {
return false, err
}
hMon := monitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)
if hMon == 0 {
return false, fmt.Errorf("MonitorFromWindow failed")
}
mi, err := getMonitorInfo(hMon)
if err != nil {
return false, err
}
cfg := state.configMgr.GetConfig()
tolerance := int32(cfg.FullscreenTolerancePx)
fullscreen := (rect.Left <= mi.RcMonitor.Left+tolerance &&
rect.Top <= mi.RcMonitor.Top+tolerance &&
rect.Right >= mi.RcMonitor.Right-tolerance &&
rect.Bottom >= mi.RcMonitor.Bottom-tolerance)
return fullscreen, nil
}
// getProcessName retrieves the process name for a window
func getProcessName(hwnd windows.HWND) (string, error) {
var processID uint32
procGetWindowThreadProcessId.Call(
uintptr(hwnd),
uintptr(unsafe.Pointer(&processID)),
)
if processID == 0 {
return "", fmt.Errorf("failed to get process ID")
}
// Open the process
kernel32 := windows.NewLazySystemDLL("kernel32.dll")
procOpenProcess := kernel32.NewProc("OpenProcess")
procQueryFullProcessImageName := kernel32.NewProc("QueryFullProcessImageNameW")
procCloseHandle := kernel32.NewProc("CloseHandle")
const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
hProcess, _, _ := procOpenProcess.Call(
uintptr(PROCESS_QUERY_LIMITED_INFORMATION),
0,
uintptr(processID),
)
if hProcess == 0 {
return "", fmt.Errorf("failed to open process")
}
defer procCloseHandle.Call(hProcess)
// Get the full path
var buf [windows.MAX_PATH]uint16
size := uint32(len(buf))
procQueryFullProcessImageName.Call(
hProcess,
0,
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&size)),
)
fullPath := windows.UTF16ToString(buf[:])
// Extract only the filename
parts := strings.Split(fullPath, "\\")
if len(parts) > 0 {
return parts[len(parts)-1], nil
}
return fullPath, nil
}
// createMMTCommand creates a command to run MMT with a hidden window
func createMMTCommand(mmtPath string, args ...string) *exec.Cmd {
// If it's just a filename - search for it in the current directory
if !strings.Contains(mmtPath, "/") && !strings.Contains(mmtPath, "\\") {
// Try to find the absolute path
if path, err := os.Executable(); err == nil {
baseDir := filepath.Dir(path)
fullPath := filepath.Join(baseDir, mmtPath)
if _, err := os.Stat(fullPath); err == nil {
mmtPath = fullPath
}
}
}
// Add parameters to hide the window (move it offscreen)
fullArgs := append([]string{"/WindowLeft", "-32000", "/WindowTop", "-32000"}, args...)
// Direct execution - simpler and more reliable
cmd := exec.Command(mmtPath, fullArgs...)
// Hide window using Windows API
cmd.SysProcAttr = &windows.SysProcAttr{
HideWindow: true,
CreationFlags: 0x08000000, // CREATE_NO_WINDOW
}
// Redirect stdout/stderr to null
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
return cmd
}
func loadMonitorsFromMMT() error {
state.logger.Printf("Loading monitors from MultiMonitorTool...")
mmtPath := state.configMgr.GetConfig().MMTPath
monitorsFile := filepath.Join("config_files", "monitors.txt")
cmd := createMMTCommand(mmtPath, "/scomma", monitorsFile)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to run MultiMonitorTool: %w", err)
}
file, err := os.Open(monitorsFile)
if err != nil {
return fmt.Errorf("failed to open monitors file: %w", err)
}
defer file.Close()
// Read file - MMT /scomma generates UTF-8, not UTF-16
data, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("failed to read monitors file: %w", err)
}
// Parse the output
monitors := parseMMTOutput(string(data))
state.mu.Lock()
state.monitors = monitors
state.mu.Unlock()
state.logger.Printf("Loaded %d monitors from MultiMonitorTool", len(monitors))
if state.configMgr.GetConfig().LogLevel == "debug" {
for _, m := range monitors {
state.logger.Printf("[DEBUG] %s: (%d,%d)-(%d,%d) Active:%v Primary:%v",
m.Name, m.LeftTop.Left, m.LeftTop.Top,
m.RightBottom.Right, m.RightBottom.Bottom, m.Active, m.Primary)
}
}
return nil
}
// saveMonitorConfig saves current monitor configuration to file
func saveMonitorConfig() error {
state.logger.Printf("Saving monitor configuration...")
mmtPath := state.configMgr.GetConfig().MMTPath
configPath := filepath.Join("config_files", "monitors_config.cfg")
// Ensure config_files directory exists
if err := os.MkdirAll("config_files", 0755); err != nil {
return fmt.Errorf("failed to create config_files directory: %w", err)
}
cmd := createMMTCommand(mmtPath, "/SaveConfig", configPath)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to save monitor config: %w", err)
}
state.logger.Printf("Monitor configuration saved to %s", configPath)
return nil
}
// restoreMonitorConfig restores monitor configuration from file
func restoreMonitorConfig() error {
configPath := filepath.Join("config_files", "monitors_config.cfg")
// Check if config file exists
if _, err := os.Stat(configPath); os.IsNotExist(err) {
state.logger.Printf("Monitor config file not found, skipping restore")
return nil
}
state.logger.Printf("Restoring monitor configuration from %s...", configPath)
mmtPath := state.configMgr.GetConfig().MMTPath
cmd := createMMTCommand(mmtPath, "/LoadConfig", configPath)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to restore monitor config: %w", err)
}
// Wait for monitors to settle
time.Sleep(500 * time.Millisecond)
state.logger.Printf("Monitor configuration restored")
return nil
}
// parseMMTOutput parses the output from MultiMonitorTool
func parseMMTOutput(data string) []MonitorData {
data = strings.TrimSpace(data)
if data == "" {
return nil
}
// CSV output from /scomma
if strings.HasPrefix(data, "Resolution,") && strings.Contains(data, "Left-Top") {
return parseMMTCSV(data)
}
var monitors []MonitorData
lines := strings.Split(data, "\n")
var current MonitorData
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "Left-Top") {
var left, top int32
fmt.Sscanf(line, "Left-Top : %d, %d", &left, &top)
current.LeftTop = RECT{Left: left, Top: top}
} else if strings.HasPrefix(line, "Right-Bottom") {
var right, bottom int32
fmt.Sscanf(line, "Right-Bottom : %d, %d", &right, &bottom)
current.RightBottom = RECT{Right: right, Bottom: bottom}
} else if strings.HasPrefix(line, "Active") {
current.Active = strings.Contains(line, "Yes")
} else if strings.HasPrefix(line, "Primary") {
current.Primary = strings.Contains(line, "Yes")
} else if strings.HasPrefix(line, "Name") && strings.Contains(line, "DISPLAY") {
// Name comes last - now we have all data, save and store
parts := strings.SplitN(line, ":", 2)
if len(parts) == 2 {
current.Name = strings.TrimSpace(parts[1])
// Store the current monitor
if current.Name != "" {
monitors = append(monitors, current)
}
// Start a new one
current = MonitorData{}
}
}
}
return monitors
}
func parseMMTCSV(data string) []MonitorData {
var monitors []MonitorData
reader := csv.NewReader(strings.NewReader(data))
reader.TrimLeadingSpace = true
records, err := reader.ReadAll()
if err != nil {
state.logger.Printf("CSV parsing error: %v", err)
return monitors
}
if len(records) < 2 {
state.logger.Printf("CSV has no data rows (only %d records)", len(records))
return monitors
}
header := records[0]
cfg := state.configMgr.GetConfig()
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG] CSV headers: %v", header)
}
idx := func(name string) int {
for i, h := range header {
if strings.EqualFold(strings.TrimSpace(h), name) {
return i
}
}
return -1
}
idxLeftTop := idx("Left-Top")
idxRightBottom := idx("Right-Bottom")
idxActive := idx("Active")
idxPrimary := idx("Primary")
idxName := idx("Name")
idxMonitorString := idx("Monitor String")
idxMonitorName := idx("Monitor Name")
idxResolution := idx("Resolution")
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG] Column indices - LeftTop:%d, RightBottom:%d, Active:%d, Primary:%d, Name:%d",
idxLeftTop, idxRightBottom, idxActive, idxPrimary, idxName)
}
for i, row := range records[1:] {
if idxName < 0 || idxName >= len(row) {
state.logger.Printf("Row %d: Name column not found or out of bounds", i+1)
continue
}
name := strings.TrimSpace(row[idxName])
if name == "" {
state.logger.Printf("Row %d: Name is empty", i+1)
continue
}
var m MonitorData
m.Name = name
if idxLeftTop >= 0 && idxLeftTop < len(row) {
m.LeftTop = parseCSVLeftTop(row[idxLeftTop])
}
if idxRightBottom >= 0 && idxRightBottom < len(row) {
m.RightBottom = parseCSVRightBottom(row[idxRightBottom])
}
if idxActive >= 0 && idxActive < len(row) {
m.Active = strings.EqualFold(strings.TrimSpace(row[idxActive]), "Yes")
}
if idxPrimary >= 0 && idxPrimary < len(row) {
m.Primary = strings.EqualFold(strings.TrimSpace(row[idxPrimary]), "Yes")
}
if idxMonitorString >= 0 && idxMonitorString < len(row) {
m.MonitorName = strings.TrimSpace(row[idxMonitorString]) // "Generic PnP Monitor"
}
if idxMonitorName >= 0 && idxMonitorName < len(row) {
m.MonitorModel = strings.TrimSpace(row[idxMonitorName]) // "DELL P2421D"
}
if idxResolution >= 0 && idxResolution < len(row) {
m.Resolution = strings.TrimSpace(row[idxResolution])
}
if state.configMgr.GetConfig().LogLevel == "debug" {
state.logger.Printf("[DEBUG] Parsed monitor: %s (Active:%v, Primary:%v, Model:%s)", name, m.Active, m.Primary, m.MonitorModel)
}
monitors = append(monitors, m)
}
return monitors
}
func parseCSVLeftTop(value string) RECT {
parts := strings.Split(value, ",")
if len(parts) != 2 {
return RECT{}
}
left, _ := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 32)
top, _ := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 32)
return RECT{Left: int32(left), Top: int32(top)}
}
func parseCSVRightBottom(value string) RECT {
parts := strings.Split(value, ",")
if len(parts) != 2 {
return RECT{}
}
right, _ := strconv.ParseInt(strings.TrimSpace(parts[0]), 10, 32)
bottom, _ := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 32)
return RECT{Right: int32(right), Bottom: int32(bottom)}
}
// saveWindowPositions saves positions of all visible windows
func saveWindowPositions() error {
state.logger.Printf("[WindowPos] Saving window positions...")
var savedWindows []SavedWindow
// Callback for EnumWindows
callback := syscall.NewCallback(func(hwnd windows.HWND, lParam uintptr) uintptr {
// Check if window is visible
visible, _, _ := procIsWindowVisible.Call(uintptr(hwnd))
if visible == 0 {
return 1 // Continue enumeration
}
// Get window style to check if maximized
style, _, _ := procGetWindowLongW.Call(uintptr(hwnd), uintptr(^uint(15)))
isMaximized := (style & WS_MAXIMIZE) != 0
// Get window rect
var rect RECT
ret, _, _ := procGetWindowRect.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&rect)))
if ret == 0 {
return 1 // Continue
}
// Skip windows that are too small (likely not user windows)
width := rect.Right - rect.Left
height := rect.Bottom - rect.Top
if width < 100 || height < 100 {
return 1
}
// Get window title
titleLen, _, _ := procGetWindowTextLengthW.Call(uintptr(hwnd))
if titleLen == 0 {
return 1 // Skip windows without title
}
titleBuf := make([]uint16, titleLen+1)
procGetWindowTextW.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&titleBuf[0])), uintptr(titleLen+1))
title := windows.UTF16ToString(titleBuf)
if title == "" {
return 1 // Skip
}
// Get process name
procName, err := getProcessName(hwnd)
if err != nil {
procName = "unknown"
}
// Find which monitor this window is on
hMon := monitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)
monitorName := ""
if hMon != 0 {
mi, err := getMonitorInfo(hMon)
if err == nil {
monitorName = findMonitorByCoordinates(mi.RcMonitor)
}
}
// Save window info
sw := SavedWindow{
Hwnd: hwnd,
ProcessName: procName,
Title: title,
Rect: rect,
MonitorName: monitorName,
IsVisible: true,
IsMaximized: isMaximized,
}
savedWindows = append(savedWindows, sw)
return 1 // Continue enumeration
})
// Enumerate all top-level windows
ret, _, _ := procEnumWindows.Call(callback, 0)
if ret == 0 {
return fmt.Errorf("EnumWindows failed")
}
// Store in state
state.mu.Lock()
state.savedWindowPos = savedWindows
state.mu.Unlock()
state.logger.Printf("[WindowPos] Saved %d window positions", len(savedWindows))
// Log some windows for debugging
if state.configMgr.GetConfig().LogLevel == "debug" {
for i, sw := range savedWindows {
if i < 5 { // Log first 5
state.logger.Printf("[DEBUG][WindowPos] %s - %s (%d,%d) on %s",
sw.ProcessName, sw.Title, sw.Rect.Left, sw.Rect.Top, sw.MonitorName)
}
}
}
return nil
}
// restoreWindowPositions restores saved window positions
func restoreWindowPositions() error {
state.mu.RLock()
savedWindows := make([]SavedWindow, len(state.savedWindowPos))
copy(savedWindows, state.savedWindowPos)
state.mu.RUnlock()
if len(savedWindows) == 0 {
state.logger.Printf("[WindowPos] No saved window positions to restore")
return nil
}
state.logger.Printf("[WindowPos] Restoring %d window positions...", len(savedWindows))
restored := 0
failed := 0
// Restore in reverse order to preserve Z-order (bottom to top)
// EnumWindows gives us top-to-bottom order, so reversing it
// and applying each with HWND_TOP will recreate the original stack
for i := len(savedWindows) - 1; i >= 0; i-- {
sw := savedWindows[i]
// Check if window still exists and is visible
visible, _, _ := procIsWindowVisible.Call(uintptr(sw.Hwnd))
if visible == 0 {
continue
}
// Restore window position with HWND_TOP (each successive window goes on top)
// Since we're going in reverse order, the original top window will be restored last
flags := SWP_NOACTIVATE
ret, _, _ := procSetWindowPos.Call(
uintptr(sw.Hwnd),
0, // HWND_TOP - places window on top of Z-order
uintptr(sw.Rect.Left),
uintptr(sw.Rect.Top),
uintptr(sw.Rect.Right-sw.Rect.Left),
uintptr(sw.Rect.Bottom-sw.Rect.Top),
uintptr(flags),
)
if ret != 0 {
// Restore maximized state if needed
if sw.IsMaximized {
procShowWindow.Call(uintptr(sw.Hwnd), SW_MAXIMIZE)
}
restored++
if state.configMgr.GetConfig().LogLevel == "debug" {
state.logger.Printf("[DEBUG][WindowPos] ✓ %s - %s", sw.ProcessName, sw.Title)
}
} else {
failed++
}
}
state.logger.Printf("[WindowPos] Restored: %d successful, %d failed", restored, failed)
// Clear saved positions
state.mu.Lock()
state.savedWindowPos = nil
state.mu.Unlock()
return nil
}
// findMonitorByCoordinates finds a monitor by coordinates
func findMonitorByCoordinates(monRect RECT) string {
state.mu.RLock()
defer state.mu.RUnlock()
// Find the monitor that contains these coordinates
for _, m := range state.monitors {
if m.Active &&
monRect.Left >= m.LeftTop.Left &&
monRect.Top >= m.LeftTop.Top &&
monRect.Right <= m.RightBottom.Right &&
monRect.Bottom <= m.RightBottom.Bottom {
return m.Name
}
}
return ""
}
// getMonitorNumber returns the monitor number (1, 2, 3) for convenient logging
func getMonitorNumber(monitorName string) int {
state.mu.RLock()
defer state.mu.RUnlock()
for i, m := range state.monitors {
if m.Name == monitorName {
return i + 1
}
}
return 0
}
// getDisabledMonitorIDs returns the IDs of monitors to disable
func getDisabledMonitorIDs(fullscreenMonitorName string) []string {
state.mu.RLock()
defer state.mu.RUnlock()
var disabled []string
for _, m := range state.monitors {
if m.Active && m.Name != "" && m.Name != fullscreenMonitorName {
disabled = append(disabled, m.Name)
}
}
return disabled
}
// disableExcept disables managed monitors except the one in fullscreen mode
func disableExcept(fullscreenMonID string) error {
cfg := state.configMgr.GetConfig()
state.mu.RLock()
var disabled []string
// If no managed monitors configured, don't disable anything
if len(cfg.ManagedMonitors) == 0 {
state.mu.RUnlock()
state.logger.Printf("No managed monitors configured - skipping disable")
return nil
}
for _, m := range state.monitors {
if m.Name == "" || m.Name == fullscreenMonID {
continue
}
// Only disable monitors that are in ManagedMonitors list
isManaged := false
for _, managed := range cfg.ManagedMonitors {
if m.Name == managed {
isManaged = true
break
}
}
if !isManaged {
continue
}
disabled = append(disabled, m.Name)
}
state.mu.RUnlock()
if len(disabled) == 0 {
state.logger.Printf("No managed monitors to disable (fullscreen on %s)", fullscreenMonID)
return nil
}
// Save current monitor configuration before making changes
if err := saveMonitorConfig(); err != nil {
state.logger.Printf("Warning: Failed to save monitor config: %v", err)
}
// Save window positions if enabled
if cfg.RestoreWindowPositions {
if err := saveWindowPositions(); err != nil {
state.logger.Printf("Warning: Failed to save window positions: %v", err)
}
}
state.logger.Printf("Disabling managed monitors (except %s): %v", fullscreenMonID, disabled)
// Set fullscreen monitor as primary (helps Windows manage monitor state better)
if err := setMonitorPrimary(fullscreenMonID); err != nil {
state.logger.Printf("Warning: Could not set primary monitor: %v", err)
}
// Use /disable batch command (primary method)
args := []string{"/disable"}
args = append(args, disabled...)
cmd := createMMTCommand(cfg.MMTPath, args...)
if err := cmd.Run(); err != nil {
state.logger.Printf("Warning: /disable failed: %v", err)
} else {
state.logger.Printf("✅ /disable batch executed successfully")
}
state.mu.Lock()
state.disabledMonitors = disabled
state.fullscreenMonitor = fullscreenMonID
state.mu.Unlock()
return nil
}
// restoreConfig restores the monitor configuration
func restoreConfig() error {
cfg := state.configMgr.GetConfig()
// Check if we should use LoadConfig method
if cfg.UseConfigRestore {
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG][Restore] Using MMT /LoadConfig method")
}
return restoreConfigUsingMMT()
}
// Legacy method: manual enable + setPrimary
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG][Restore] Using legacy /enable method")
}
return restoreConfigLegacy()
}
// restoreConfigUsingMMT restores configuration using MMT /LoadConfig
func restoreConfigUsingMMT() error {
// Simply restore the saved config - it handles everything
if err := restoreMonitorConfig(); err != nil {
state.logger.Printf("[Restore] Failed to restore config: %v", err)
return err
}
// Wait for monitors to stabilize
time.Sleep(500 * time.Millisecond)
// Reload monitor state
if err := loadMonitorsFromMMT(); err != nil {
state.logger.Printf("[Restore] Warning: could not reload monitors: %v", err)
}
// Restore window positions if enabled
cfg := state.configMgr.GetConfig()
if cfg.RestoreWindowPositions {
// Small delay to let monitors stabilize
time.Sleep(500 * time.Millisecond)
if err := restoreWindowPositions(); err != nil {
state.logger.Printf("Warning: Failed to restore window positions: %v", err)
}
}
// Clear state
state.mu.Lock()
state.disabledMonitors = nil
state.fullscreenMonitor = ""
state.mu.Unlock()
state.logger.Printf("[Restore] Configuration restored successfully")
return nil
}
// restoreConfigLegacy restores configuration using manual enable/setPrimary
func restoreConfigLegacy() error {
state.mu.Lock()
fullscreenMon := state.fullscreenMonitor
state.mu.Unlock()
cfg := state.configMgr.GetConfig()
// Enable only managed monitors (or all if no managed list)
state.mu.RLock()
var toEnable []string
for _, m := range state.monitors {
if m.Name == "" || m.Name == fullscreenMon {
continue
}
// Only enable monitors that are in ManagedMonitors list (if list is set)
if len(cfg.ManagedMonitors) > 0 {
isManaged := false
for _, managed := range cfg.ManagedMonitors {
if m.Name == managed {
isManaged = true
break
}
}
if !isManaged {
continue
}
}
toEnable = append(toEnable, m.Name)
}
state.mu.RUnlock()
if len(toEnable) == 0 {
state.logger.Println("No managed monitors to enable")
state.mu.Lock()
state.disabledMonitors = nil
state.fullscreenMonitor = ""
state.mu.Unlock()
return nil
}
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG] Enabling managed monitors: %v", toEnable)
}
// Execute /enable once (like disable)
args := []string{"/enable"}
args = append(args, toEnable...)
cmd := createMMTCommand(cfg.MMTPath, args...)
if err := cmd.Run(); err != nil {
state.logger.Printf("[Enable] Command failed: %v", err)
}
// Wait and verify result
time.Sleep(500 * time.Millisecond)
if err := loadMonitorsFromMMT(); err != nil {
state.logger.Printf("Warning: could not verify monitor state after enable: %v", err)
}
// Restore original primary monitor FIRST (before window positions)
state.mu.RLock()
origPrimary := state.originalPrimary
state.mu.RUnlock()
if origPrimary != "" {
if cfg.LogLevel == "debug" {
state.logger.Printf("[DEBUG][Restore] Restoring primary monitor to: %s", origPrimary)
}