-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathwebview_window_windows.go
More file actions
2455 lines (2150 loc) · 72.9 KB
/
Copy pathwebview_window_windows.go
File metadata and controls
2455 lines (2150 loc) · 72.9 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
//go:build windows
package application
import (
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/bep/debounce"
"github.com/wailsapp/go-webview2/webviewloader"
"github.com/wailsapp/wails/v3/internal/assetserver"
"github.com/wailsapp/wails/v3/internal/assetserver/webview"
"github.com/wailsapp/wails/v3/internal/capabilities"
"github.com/wailsapp/wails/v3/internal/runtime"
"github.com/wailsapp/wails/v3/internal/sliceutil"
"github.com/wailsapp/go-webview2/pkg/edge"
"github.com/wailsapp/wails/v3/pkg/events"
"github.com/wailsapp/wails/v3/pkg/w32"
)
var edgeMap = map[string]uintptr{
"n-resize": w32.HTTOP,
"ne-resize": w32.HTTOPRIGHT,
"e-resize": w32.HTRIGHT,
"se-resize": w32.HTBOTTOMRIGHT,
"s-resize": w32.HTBOTTOM,
"sw-resize": w32.HTBOTTOMLEFT,
"w-resize": w32.HTLEFT,
"nw-resize": w32.HTTOPLEFT,
}
type windowsWebviewWindow struct {
windowImpl unsafe.Pointer
parent *WebviewWindow
hwnd w32.HWND
menu *Win32Menu
currentlyOpenContextMenu *Win32Menu
ignoreDPIChangeResizing bool
// Fullscreen flags
isCurrentlyFullscreen bool
previousWindowStyle uint32
previousWindowExStyle uint32
previousWindowPlacement w32.WINDOWPLACEMENT
// Webview
chromium *edge.Chromium
webviewNavigationCompleted bool
// Window visibility management - robust fallback for issue #2861
showRequested bool // Track if show() was called before navigation completed
visibilityTimeout *time.Timer // Timeout to show window if navigation is delayed
windowShown bool // Track if window container has been shown
// Track whether content protection has been applied to the native window yet
contentProtectionApplied bool
// resizeBorder* is the width/height of the resize border in pixels.
resizeBorderWidth int32
resizeBorderHeight int32
focusingChromium bool
onceDo sync.Once
// Window move debouncer
moveDebouncer func(func())
resizeDebouncer func(func())
// isMinimizing indicates whether the window is currently being minimized
// Used to prevent unnecessary redraws during minimize/restore operations
isMinimizing bool
// menubarTheme is the theme for the menubar
menubarTheme *w32.MenuBarTheme
}
func (w *windowsWebviewWindow) setMenu(menu *Menu) {
menu.Update()
w.menu = NewApplicationMenu(w, menu)
w.menu.parentWindow = w
w32.SetMenu(w.hwnd, w.menu.menu)
// Set menu background if theme is active
if w.menubarTheme != nil {
globalApplication.debug("Applying menubar theme in setMenu", "window", w.parent.id)
w.menubarTheme.SetMenuBackground(w.menu.menu)
w32.DrawMenuBar(w.hwnd)
// Force a repaint of the menu area
w32.InvalidateRect(w.hwnd, nil, true)
} else {
globalApplication.debug("No menubar theme to apply in setMenu", "window", w.parent.id)
}
// Check if using translucent background with Mica - this makes menubars invisible
if w.parent.options.BackgroundType == BackgroundTypeTranslucent &&
(w.parent.options.Windows.BackdropType == Mica ||
w.parent.options.Windows.BackdropType == Acrylic ||
w.parent.options.Windows.BackdropType == Tabbed) {
// Log warning about menubar visibility issue
globalApplication.debug("Warning: Menubars may be invisible when using translucent backgrounds with Mica/Acrylic/Tabbed effects", "window", w.parent.id)
}
}
func (w *windowsWebviewWindow) cut() {
w.execJS("document.execCommand('cut')")
}
func (w *windowsWebviewWindow) paste() {
w.execJS(`
(async () => {
try {
// Try to read all available formats
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
// Check for image types
for (const type of clipboardItem.types) {
if (type.startsWith('image/')) {
const blob = await clipboardItem.getType(type);
const url = URL.createObjectURL(blob);
document.execCommand('insertHTML', false, '<img src="' + url + '">');
return;
}
}
// If no image found, try text
if (clipboardItem.types.includes('text/plain')) {
const text = await navigator.clipboard.readText();
document.execCommand('insertText', false, text);
return;
}
}
} catch(err) {
// Fallback to text-only paste if clipboard access fails
try {
const text = await navigator.clipboard.readText();
document.execCommand('insertText', false, text);
} catch(fallbackErr) {
console.error('Failed to paste:', err, fallbackErr);
}
}
})()
`)
}
func (w *windowsWebviewWindow) copy() {
w.execJS(`
(async () => {
try {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const container = document.createElement('div');
container.appendChild(range.cloneContents());
// Check if we have any images in the selection
const images = container.getElementsByTagName('img');
if (images.length > 0) {
// Handle image copy
const img = images[0]; // Take the first image
const response = await fetch(img.src);
const blob = await response.blob();
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob
})
]);
} else {
// Handle text copy
const text = selection.toString();
if (text) {
await navigator.clipboard.writeText(text);
}
}
} catch(err) {
console.error('Failed to copy:', err);
}
})()
`)
}
func (w *windowsWebviewWindow) selectAll() {
w.execJS("document.execCommand('selectAll')")
}
func (w *windowsWebviewWindow) undo() {
w.execJS("document.execCommand('undo')")
}
func (w *windowsWebviewWindow) redo() {
w.execJS("document.execCommand('redo')")
}
func (w *windowsWebviewWindow) delete() {
w.execJS("document.execCommand('delete')")
}
func (w *windowsWebviewWindow) handleKeyEvent(_ string) {
// Unused on windows
}
func (w *windowsWebviewWindow) setEnabled(enabled bool) {
w32.EnableWindow(w.hwnd, enabled)
}
func (w *windowsWebviewWindow) print() error {
w.execJS("window.print();")
return nil
}
func (w *windowsWebviewWindow) startResize(border string) error {
if !w32.ReleaseCapture() {
return errors.New("unable to release mouse capture")
}
// Use PostMessage because we don't want to block the caller until resizing has been finished.
w32.PostMessage(w.hwnd, w32.WM_NCLBUTTONDOWN, edgeMap[border], 0)
return nil
}
func (w *windowsWebviewWindow) startDrag() error {
if !w32.ReleaseCapture() {
return errors.New("unable to release mouse capture")
}
// Use PostMessage because we don't want to block the caller until dragging has been finished.
w32.PostMessage(w.hwnd, w32.WM_NCLBUTTONDOWN, w32.HTCAPTION, 0)
return nil
}
func (w *windowsWebviewWindow) nativeWindow() unsafe.Pointer {
return unsafe.Pointer(w.hwnd)
}
func (w *windowsWebviewWindow) setTitle(title string) {
w32.SetWindowText(w.hwnd, title)
}
func (w *windowsWebviewWindow) setAlwaysOnTop(alwaysOnTop bool) {
var hwndInsertAfter uintptr
if alwaysOnTop {
hwndInsertAfter = w32.HWND_TOPMOST
} else {
hwndInsertAfter = w32.HWND_NOTOPMOST
}
w32.SetWindowPos(w.hwnd,
hwndInsertAfter,
0,
0,
0,
0,
uint(w32.SWP_NOMOVE|w32.SWP_NOSIZE))
}
func (w *windowsWebviewWindow) setURL(url string) {
// Navigate to the given URL in the webview
w.webviewNavigationCompleted = false
w.chromium.Navigate(url)
}
func (w *windowsWebviewWindow) setResizable(resizable bool) {
w.setStyle(resizable, w32.WS_THICKFRAME)
w.execJS(fmt.Sprintf("window._wails.setResizable(%v);", resizable))
}
func (w *windowsWebviewWindow) setMinSize(width, height int) {
w.parent.options.MinWidth = width
w.parent.options.MinHeight = height
}
func (w *windowsWebviewWindow) setMaxSize(width, height int) {
w.parent.options.MaxWidth = width
w.parent.options.MaxHeight = height
}
func (w *windowsWebviewWindow) execJS(js string) {
if w.chromium == nil {
return
}
globalApplication.dispatchOnMainThread(func() {
w.chromium.Eval(js)
})
}
func (w *windowsWebviewWindow) setBackgroundColour(color RGBA) {
switch w.parent.options.BackgroundType {
case BackgroundTypeSolid:
w32.SetBackgroundColour(w.hwnd, color.Red, color.Green, color.Blue)
w.chromium.SetBackgroundColour(color.Red, color.Green, color.Blue, color.Alpha)
case BackgroundTypeTransparent, BackgroundTypeTranslucent:
w.chromium.SetBackgroundColour(0, 0, 0, 0)
}
}
func (w *windowsWebviewWindow) framelessWithDecorations() bool {
return w.parent.options.Frameless && !w.parent.options.Windows.DisableFramelessWindowDecorations
}
func (w *windowsWebviewWindow) run() {
options := w.parent.options
// Initialize showRequested based on whether window should be hidden
// Non-hidden windows should be shown by default
w.showRequested = !options.Hidden
w.chromium = edge.NewChromium()
if globalApplication.options.ErrorHandler != nil {
w.chromium.SetErrorCallback(globalApplication.options.ErrorHandler)
}
exStyle := w32.WS_EX_CONTROLPARENT
if options.BackgroundType != BackgroundTypeSolid {
if (options.Frameless && options.BackgroundType == BackgroundTypeTransparent) ||
w.parent.options.IgnoreMouseEvents {
// Always if transparent and frameless
exStyle |= w32.WS_EX_TRANSPARENT | w32.WS_EX_LAYERED
} else {
// Only WS_EX_NOREDIRECTIONBITMAP if not (and not solid)
exStyle |= w32.WS_EX_NOREDIRECTIONBITMAP
}
}
if options.AlwaysOnTop {
exStyle |= w32.WS_EX_TOPMOST
}
// If we're frameless, we need to add the WS_EX_TOOLWINDOW style to hide the window from the taskbar
if options.Windows.HiddenOnTaskbar {
//exStyle |= w32.WS_EX_TOOLWINDOW
exStyle |= w32.WS_EX_NOACTIVATE
} else {
exStyle |= w32.WS_EX_APPWINDOW
}
if options.Windows.ExStyle != 0 {
exStyle = options.Windows.ExStyle
}
bounds := Rect{
X: options.X,
Y: options.Y,
Width: options.Width,
Height: options.Height,
}
initialScreen := ScreenNearestDipRect(bounds)
physicalBounds := initialScreen.dipToPhysicalRect(bounds)
// Default window position applied by the system
// TODO: provide a way to set (0,0) as an initial position?
if options.X == 0 && options.Y == 0 {
physicalBounds.X = w32.CW_USEDEFAULT
physicalBounds.Y = w32.CW_USEDEFAULT
}
var appMenu w32.HMENU
// Process Menu
if !options.Frameless {
userMenu := w.parent.options.Windows.Menu
if userMenu != nil {
userMenu.Update()
w.menu = NewApplicationMenu(w, userMenu)
w.menu.parentWindow = w
appMenu = w.menu.menu
}
}
var parent w32.HWND
var style uint = w32.WS_OVERLAPPEDWINDOW
// If the window should be hidden initially, exclude WS_VISIBLE from the style
// This prevents the white window flash reported in issue #4611
if options.Hidden {
style = style &^ uint(w32.WS_VISIBLE)
}
w.hwnd = w32.CreateWindowEx(
uint(exStyle),
w32.MustStringToUTF16Ptr(globalApplication.options.Windows.WndClass),
w32.MustStringToUTF16Ptr(options.Title),
style,
physicalBounds.X,
physicalBounds.Y,
physicalBounds.Width,
physicalBounds.Height,
parent,
appMenu,
w32.GetModuleHandle(""),
nil)
if w.hwnd == 0 {
globalApplication.fatal("unable to create window")
}
// Ensure correct window size in case the scale factor of current screen is different from the initial one.
// This could happen when using the default window position and the window launches on a secondary monitor.
currentScreen, _ := w.getScreen()
if currentScreen.ScaleFactor != initialScreen.ScaleFactor {
w.setSize(options.Width, options.Height)
}
w.setupChromium()
if options.Windows.WindowDidMoveDebounceMS == 0 {
options.Windows.WindowDidMoveDebounceMS = 50
}
w.moveDebouncer = debounce.New(
time.Duration(options.Windows.WindowDidMoveDebounceMS) * time.Millisecond,
)
if options.Windows.ResizeDebounceMS > 0 {
w.resizeDebouncer = debounce.New(
time.Duration(options.Windows.ResizeDebounceMS) * time.Millisecond,
)
}
// Initialise the window buttons
w.setMinimiseButtonState(options.MinimiseButtonState)
w.setMaximiseButtonState(options.MaximiseButtonState)
w.setCloseButtonState(options.CloseButtonState)
// Register the window with the application
getNativeApplication().registerWindow(w)
w.setResizable(!options.DisableResize)
w.setIgnoreMouseEvents(options.IgnoreMouseEvents)
if options.Frameless {
// Inform the application of the frame change this is needed to trigger the WM_NCCALCSIZE event.
// => https://learn.microsoft.com/en-us/windows/win32/dwm/customframe#removing-the-standard-frame
// This is normally done in WM_CREATE but we can't handle that there because that is emitted during CreateWindowEx
// and at that time we can't yet register the window for calling our WndProc method.
// This must be called after setResizable above!
rcClient := w32.GetWindowRect(w.hwnd)
w32.SetWindowPos(w.hwnd,
0,
int(rcClient.Left),
int(rcClient.Top),
int(rcClient.Right-rcClient.Left),
int(rcClient.Bottom-rcClient.Top),
w32.SWP_FRAMECHANGED)
}
// Icon
if !options.Windows.DisableIcon {
// App icon ID is 3
icon, err := NewIconFromResource(w32.GetModuleHandle(""), uint16(3))
if err != nil {
// Try loading from the given icon
if globalApplication.options.Icon != nil {
icon, _ = w32.CreateLargeHIconFromImage(globalApplication.options.Icon)
}
}
if icon != 0 {
w.setIcon(icon)
}
} else {
w.disableIcon()
}
// Process the theme
switch options.Windows.Theme {
case SystemDefault:
isDark := w32.IsCurrentlyDarkMode()
if isDark {
w32.AllowDarkModeForWindow(w.hwnd, true)
}
w.updateTheme(isDark)
// Don't initialize default dark theme here if custom theme might be set
// The updateTheme call above will handle both default and custom themes
w.parent.onApplicationEvent(events.Windows.SystemThemeChanged, func(*ApplicationEvent) {
InvokeAsync(func() {
w.updateTheme(w32.IsCurrentlyDarkMode())
})
})
case Light:
w.updateTheme(false)
case Dark:
w32.AllowDarkModeForWindow(w.hwnd, true)
w.updateTheme(true)
// Don't initialize default dark theme here if custom theme might be set
// The updateTheme call above will handle custom themes
}
w.setBackgroundColour(options.BackgroundColour)
if options.BackgroundType == BackgroundTypeTranslucent {
w.setBackdropType(w.parent.options.Windows.BackdropType)
}
// Process StartState
switch options.StartState {
case WindowStateMaximised:
if w.parent.Resizable() {
w.maximise()
}
case WindowStateMinimised:
w.minimise()
case WindowStateFullscreen:
w.fullscreen()
case WindowStateNormal:
}
// Process window mask
if options.Windows.WindowMask != nil {
w.setWindowMask(options.Windows.WindowMask)
}
if options.InitialPosition == WindowCentered {
w.center()
} else {
w.setPosition(options.X, options.Y)
}
if options.Frameless {
// Trigger a resize to ensure the window is sized correctly
w.chromium.Resize()
}
}
func (w *windowsWebviewWindow) center() {
w32.CenterWindow(w.hwnd)
}
func (w *windowsWebviewWindow) disableSizeConstraints() {
w.setMaxSize(0, 0)
w.setMinSize(0, 0)
}
func (w *windowsWebviewWindow) enableSizeConstraints() {
options := w.parent.options
if options.MinWidth > 0 || options.MinHeight > 0 {
w.setMinSize(options.MinWidth, options.MinHeight)
}
if options.MaxWidth > 0 || options.MaxHeight > 0 {
w.setMaxSize(options.MaxWidth, options.MaxHeight)
}
}
func (w *windowsWebviewWindow) update() {
w32.UpdateWindow(w.hwnd)
}
// getBorderSizes returns the extended border size for the window
func (w *windowsWebviewWindow) getBorderSizes() *LRTB {
var result LRTB
var frame w32.RECT
w32.DwmGetWindowAttribute(
w.hwnd,
w32.DWMWA_EXTENDED_FRAME_BOUNDS,
unsafe.Pointer(&frame),
unsafe.Sizeof(frame),
)
rect := w32.GetWindowRect(w.hwnd)
result.Left = int(frame.Left - rect.Left)
result.Top = int(frame.Top - rect.Top)
result.Right = int(rect.Right - frame.Right)
result.Bottom = int(rect.Bottom - frame.Bottom)
return &result
}
// convertWindowToWebviewCoordinates converts window-relative coordinates to webview-relative coordinates
func (w *windowsWebviewWindow) convertWindowToWebviewCoordinates(windowX, windowY int) (int, int) {
// Get the client area of the window (this excludes borders, title bar, etc.)
clientRect := w32.GetClientRect(w.hwnd)
if clientRect == nil {
// Fallback: return coordinates as-is if we can't get client rect
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Failed to get client rect, returning original coordinates", "windowX", windowX, "windowY", windowY)
return windowX, windowY
}
// Get the window rect to calculate the offset
windowRect := w32.GetWindowRect(w.hwnd)
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Input window coordinates", "windowX", windowX, "windowY", windowY)
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Window rect",
"left", windowRect.Left, "top", windowRect.Top, "right", windowRect.Right, "bottom", windowRect.Bottom,
"width", windowRect.Right-windowRect.Left, "height", windowRect.Bottom-windowRect.Top)
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Client rect",
"left", clientRect.Left, "top", clientRect.Top, "right", clientRect.Right, "bottom", clientRect.Bottom,
"width", clientRect.Right-clientRect.Left, "height", clientRect.Bottom-clientRect.Top)
// Convert client (0,0) to screen coordinates to find where the client area starts
var point w32.POINT
point.X = 0
point.Y = 0
// Convert client (0,0) to screen coordinates
clientX, clientY := w32.ClientToScreen(w.hwnd, int(point.X), int(point.Y))
// The window coordinates from drag drop are relative to the window's top-left
// But we need them relative to the client area's top-left
// So we need to subtract the difference between window origin and client origin
windowOriginX := int(windowRect.Left)
windowOriginY := int(windowRect.Top)
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Client (0,0) in screen coordinates", "clientX", clientX, "clientY", clientY)
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Window origin in screen coordinates", "windowOriginX", windowOriginX, "windowOriginY", windowOriginY)
// Calculate the offset from window origin to client origin
offsetX := clientX - windowOriginX
offsetY := clientY - windowOriginY
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Calculated offset", "offsetX", offsetX, "offsetY", offsetY)
// Convert window-relative coordinates to webview-relative coordinates
webviewX := windowX - offsetX
webviewY := windowY - offsetY
globalApplication.debug("[DragDropDebug] convertWindowToWebviewCoordinates: Final webview coordinates", "webviewX", webviewX, "webviewY", webviewY)
return webviewX, webviewY
}
func (w *windowsWebviewWindow) physicalBounds() Rect {
// var rect w32.RECT
// // Get the extended frame bounds instead of the window rect to offset the invisible borders in Windows 10
// w32.DwmGetWindowAttribute(w.hwnd, w32.DWMWA_EXTENDED_FRAME_BOUNDS, unsafe.Pointer(&rect), unsafe.Sizeof(rect))
rect := w32.GetWindowRect(w.hwnd)
return Rect{
X: int(rect.Left),
Y: int(rect.Top),
Width: int(rect.Right - rect.Left),
Height: int(rect.Bottom - rect.Top),
}
}
func (w *windowsWebviewWindow) setPhysicalBounds(physicalBounds Rect) {
// // Offset invisible borders
// borderSize := w.getBorderSizes()
// physicalBounds.X -= borderSize.Left
// physicalBounds.Y -= borderSize.Top
// physicalBounds.Width += borderSize.Left + borderSize.Right
// physicalBounds.Height += borderSize.Top + borderSize.Bottom
// Set flag to ignore resizing the window with DPI change because we already calculated the correct size
// for the target position, this prevents double resizing issue when the window is moved between screens
previousFlag := w.ignoreDPIChangeResizing
w.ignoreDPIChangeResizing = true
w32.SetWindowPos(
w.hwnd,
0,
physicalBounds.X,
physicalBounds.Y,
physicalBounds.Width,
physicalBounds.Height,
w32.SWP_NOZORDER|w32.SWP_NOACTIVATE,
)
w.ignoreDPIChangeResizing = previousFlag
}
// Get window dip bounds
func (w *windowsWebviewWindow) bounds() Rect {
return PhysicalToDipRect(w.physicalBounds())
}
// Set window dip bounds
func (w *windowsWebviewWindow) setBounds(bounds Rect) {
w.setPhysicalBounds(DipToPhysicalRect(bounds))
}
func (w *windowsWebviewWindow) size() (int, int) {
bounds := w.bounds()
return bounds.Width, bounds.Height
}
func (w *windowsWebviewWindow) width() int {
return w.bounds().Width
}
func (w *windowsWebviewWindow) height() int {
return w.bounds().Height
}
func (w *windowsWebviewWindow) setSize(width, height int) {
bounds := w.bounds()
bounds.Width = width
bounds.Height = height
w.setBounds(bounds)
}
func (w *windowsWebviewWindow) position() (int, int) {
bounds := w.bounds()
return bounds.X, bounds.Y
}
func (w *windowsWebviewWindow) setPosition(x int, y int) {
bounds := w.bounds()
bounds.X = x
bounds.Y = y
w.setBounds(bounds)
}
// Get window position relative to the screen WorkArea on which it is
func (w *windowsWebviewWindow) relativePosition() (int, int) {
screen, _ := w.getScreen()
pos := screen.absoluteToRelativeDipPoint(w.bounds().Origin())
// Relative to WorkArea origin
pos.X -= (screen.WorkArea.X - screen.X)
pos.Y -= (screen.WorkArea.Y - screen.Y)
return pos.X, pos.Y
}
// Set window position relative to the screen WorkArea on which it is
func (w *windowsWebviewWindow) setRelativePosition(x int, y int) {
screen, _ := w.getScreen()
pos := screen.relativeToAbsoluteDipPoint(Point{X: x, Y: y})
// Relative to WorkArea origin
pos.X += (screen.WorkArea.X - screen.X)
pos.Y += (screen.WorkArea.Y - screen.Y)
w.setPosition(pos.X, pos.Y)
}
func (w *windowsWebviewWindow) destroy() {
w.parent.markAsDestroyed()
// destroy the window
w32.DestroyWindow(w.hwnd)
}
func (w *windowsWebviewWindow) reload() {
w.execJS("window.location.reload();")
}
func (w *windowsWebviewWindow) forceReload() {
// noop
}
func (w *windowsWebviewWindow) zoomReset() {
w.setZoom(1.0)
}
func (w *windowsWebviewWindow) zoomIn() {
// Increase the zoom level by 0.05
currentZoom := w.getZoom()
if currentZoom == -1 {
return
}
w.setZoom(currentZoom + 0.05)
}
func (w *windowsWebviewWindow) zoomOut() {
// Decrease the zoom level by 0.05
currentZoom := w.getZoom()
if currentZoom == -1 {
return
}
if currentZoom > 1.05 {
// Decrease the zoom level by 0.05
w.setZoom(currentZoom - 0.05)
} else {
// Set the zoom level to 1.0
w.setZoom(1.0)
}
}
func (w *windowsWebviewWindow) getZoom() float64 {
controller := w.chromium.GetController()
factor, err := controller.GetZoomFactor()
if err != nil {
return -1
}
return factor
}
func (w *windowsWebviewWindow) setZoom(zoom float64) {
w.chromium.PutZoomFactor(zoom)
}
func (w *windowsWebviewWindow) close() {
// Send WM_CLOSE message to trigger the same flow as clicking the X button
w32.SendMessage(w.hwnd, w32.WM_CLOSE, 0, 0)
}
func (w *windowsWebviewWindow) zoom() {
// Noop
}
func (w *windowsWebviewWindow) setHTML(html string) {
// Render the given HTML in the webview window
w.execJS(fmt.Sprintf("document.documentElement.innerHTML = %q;", html))
}
// on is used to indicate that a particular event should be listened for
func (w *windowsWebviewWindow) on(_ uint) {
// We don't need to worry about this in Windows as we do not need
// to optimise cgo calls
}
func (w *windowsWebviewWindow) minimise() {
w32.ShowWindow(w.hwnd, w32.SW_MINIMIZE)
}
func (w *windowsWebviewWindow) unminimise() {
w.restore()
}
func (w *windowsWebviewWindow) maximise() {
w32.ShowWindow(w.hwnd, w32.SW_MAXIMIZE)
w.chromium.Focus()
}
func (w *windowsWebviewWindow) unmaximise() {
w.restore()
w.parent.emit(events.Windows.WindowUnMaximise)
}
func (w *windowsWebviewWindow) restore() {
w32.ShowWindow(w.hwnd, w32.SW_RESTORE)
w.chromium.Focus()
}
func (w *windowsWebviewWindow) fullscreen() {
if w.isFullscreen() {
return
}
if w.framelessWithDecorations() {
err := w32.ExtendFrameIntoClientArea(w.hwnd, false)
if err != nil {
globalApplication.handleFatalError(err)
}
}
w.disableSizeConstraints()
w.previousWindowStyle = uint32(w32.GetWindowLongPtr(w.hwnd, w32.GWL_STYLE))
w.previousWindowExStyle = uint32(w32.GetWindowLong(w.hwnd, w32.GWL_EXSTYLE))
monitor := w32.MonitorFromWindow(w.hwnd, w32.MONITOR_DEFAULTTOPRIMARY)
var monitorInfo w32.MONITORINFO
monitorInfo.CbSize = uint32(unsafe.Sizeof(monitorInfo))
if !w32.GetMonitorInfo(monitor, &monitorInfo) {
return
}
if !w32.GetWindowPlacement(w.hwnd, &w.previousWindowPlacement) {
return
}
// According to https://devblogs.microsoft.com/oldnewthing/20050505-04/?p=35703 one should use w32.WS_POPUP | w32.WS_VISIBLE
w32.SetWindowLong(
w.hwnd,
w32.GWL_STYLE,
w.previousWindowStyle & ^uint32(w32.WS_OVERLAPPEDWINDOW) | (w32.WS_POPUP|w32.WS_VISIBLE),
)
w32.SetWindowLong(
w.hwnd,
w32.GWL_EXSTYLE,
w.previousWindowExStyle & ^uint32(w32.WS_EX_DLGMODALFRAME),
)
w.isCurrentlyFullscreen = true
w32.SetWindowPos(w.hwnd, w32.HWND_TOP,
int(monitorInfo.RcMonitor.Left),
int(monitorInfo.RcMonitor.Top),
int(monitorInfo.RcMonitor.Right-monitorInfo.RcMonitor.Left),
int(monitorInfo.RcMonitor.Bottom-monitorInfo.RcMonitor.Top),
w32.SWP_NOOWNERZORDER|w32.SWP_FRAMECHANGED)
// Hide the menubar in fullscreen mode
w32.SetMenu(w.hwnd, 0)
w.chromium.Focus()
w.parent.emit(events.Windows.WindowFullscreen)
}
func (w *windowsWebviewWindow) unfullscreen() {
if !w.isFullscreen() {
return
}
if w.framelessWithDecorations() {
err := w32.ExtendFrameIntoClientArea(w.hwnd, true)
if err != nil {
globalApplication.handleFatalError(err)
}
}
w32.SetWindowLong(w.hwnd, w32.GWL_STYLE, w.previousWindowStyle)
w32.SetWindowLong(w.hwnd, w32.GWL_EXSTYLE, w.previousWindowExStyle)
w32.SetWindowPlacement(w.hwnd, &w.previousWindowPlacement)
w.isCurrentlyFullscreen = false
// Restore the menubar when exiting fullscreen
if w.menu != nil {
w32.SetMenu(w.hwnd, w.menu.menu)
}
w32.SetWindowPos(w.hwnd, 0, 0, 0, 0, 0,
w32.SWP_NOMOVE|w32.SWP_NOSIZE|w32.SWP_NOZORDER|w32.SWP_NOOWNERZORDER|w32.SWP_FRAMECHANGED)
w.enableSizeConstraints()
w.parent.emit(events.Windows.WindowUnFullscreen)
}
func (w *windowsWebviewWindow) isMinimised() bool {
style := uint32(w32.GetWindowLong(w.hwnd, w32.GWL_STYLE))
return style&w32.WS_MINIMIZE != 0
}
func (w *windowsWebviewWindow) isMaximised() bool {
style := uint32(w32.GetWindowLong(w.hwnd, w32.GWL_STYLE))
return style&w32.WS_MAXIMIZE != 0
}
func (w *windowsWebviewWindow) isFocused() bool {
// Returns true if the window is currently focused
return w32.GetForegroundWindow() == w.hwnd
}
func (w *windowsWebviewWindow) isFullscreen() bool {
// TODO: Actually calculate this based on size of window against screen size
// => stffabi: This flag is essential since it indicates that we are in fullscreen mode even before the native properties
// reflect this, e.g. when needing to know if we are in fullscreen during a wndproc message.
// That's also why this flag is set before SetWindowPos in v2 in fullscreen/unfullscreen.
return w.isCurrentlyFullscreen
}
func (w *windowsWebviewWindow) isNormal() bool {
return !w.isMinimised() && !w.isMaximised() && !w.isFullscreen()
}
func (w *windowsWebviewWindow) isVisible() bool {
style := uint32(w32.GetWindowLong(w.hwnd, w32.GWL_STYLE))
return style&w32.WS_VISIBLE != 0
}
func (w *windowsWebviewWindow) focus() {
w32.SetForegroundWindow(w.hwnd)
if w.isDisabled() {
return
}
if w.isMinimised() {
w.unminimise()
}
w.focusingChromium = true
w.chromium.Focus()
w.focusingChromium = false
}
// printStyle takes a windows style and prints it in a human-readable format
// This is for debugging window style issues
func (w *windowsWebviewWindow) printStyle() {
style := uint32(w32.GetWindowLong(w.hwnd, w32.GWL_STYLE))
fmt.Printf("Style: ")
if style&w32.WS_BORDER != 0 {
fmt.Printf("WS_BORDER ")
}
if style&w32.WS_CAPTION != 0 {
fmt.Printf("WS_CAPTION ")
}
if style&w32.WS_CHILD != 0 {
fmt.Printf("WS_CHILD ")
}
if style&w32.WS_CLIPCHILDREN != 0 {
fmt.Printf("WS_CLIPCHILDREN ")
}
if style&w32.WS_CLIPSIBLINGS != 0 {
fmt.Printf("WS_CLIPSIBLINGS ")
}
if style&w32.WS_DISABLED != 0 {
fmt.Printf("WS_DISABLED ")
}
if style&w32.WS_DLGFRAME != 0 {
fmt.Printf("WS_DLGFRAME ")
}
if style&w32.WS_GROUP != 0 {
fmt.Printf("WS_GROUP ")
}
if style&w32.WS_HSCROLL != 0 {
fmt.Printf("WS_HSCROLL ")
}
if style&w32.WS_MAXIMIZE != 0 {
fmt.Printf("WS_MAXIMIZE ")
}
if style&w32.WS_MAXIMIZEBOX != 0 {
fmt.Printf("WS_MAXIMIZEBOX ")
}
if style&w32.WS_MINIMIZE != 0 {
fmt.Printf("WS_MINIMIZE ")
}
if style&w32.WS_MINIMIZEBOX != 0 {
fmt.Printf("WS_MINIMIZEBOX ")
}
if style&w32.WS_OVERLAPPED != 0 {
fmt.Printf("WS_OVERLAPPED ")
}
if style&w32.WS_POPUP != 0 {
fmt.Printf("WS_POPUP ")
}
if style&w32.WS_SYSMENU != 0 {
fmt.Printf("WS_SYSMENU ")
}
if style&w32.WS_TABSTOP != 0 {
fmt.Printf("WS_TABSTOP ")
}
if style&w32.WS_THICKFRAME != 0 {
fmt.Printf("WS_THICKFRAME ")
}
if style&w32.WS_VISIBLE != 0 {
fmt.Printf("WS_VISIBLE ")
}