-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhtmlayout_ui.go
More file actions
1398 lines (1230 loc) · 34 KB
/
htmlayout_ui.go
File metadata and controls
1398 lines (1230 loc) · 34 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 gohl
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"unsafe"
)
func init() {
//take care!
//主goroutine必须锁定在主线程,否则被调度之后(在go的调度度下,主goroutine也不一定总是运行在主线程),会导致HTMLayout崩溃(GUI操作需要在主线程)
runtime.LockOSThread()
// DPI 感知由 manifest 文件设置 (PerMonitorV2)
// 程序需要自己根据 DPI 缩放窗口大小
}
// GetDpiScale 获取当前 DPI 缩放因子(相对于 96 DPI)
func GetDpiScale() float64 {
user32 := syscall.NewLazyDLL("user32.dll")
// 尝试使用 GetDpiForSystem (Windows 10 1607+)
if proc := user32.NewProc("GetDpiForSystem"); proc != nil {
dpi, _, _ := proc.Call()
if dpi != 0 {
log.Printf("[DPI] GetDpiForSystem returned: %d (scale: %.2f)", dpi, float64(dpi)/96.0)
return float64(dpi) / 96.0
}
}
// 回退到 GetDeviceCaps
gdi32 := syscall.NewLazyDLL("gdi32.dll")
procGetDC := user32.NewProc("GetDC")
procReleaseDC := user32.NewProc("ReleaseDC")
procGetDeviceCaps := gdi32.NewProc("GetDeviceCaps")
hdc, _, _ := procGetDC.Call(0)
if hdc != 0 {
defer procReleaseDC.Call(0, hdc)
// LOGPIXELSX = 88
dpi, _, _ := procGetDeviceCaps.Call(hdc, 88)
if dpi != 0 {
log.Printf("[DPI] GetDeviceCaps returned: %d (scale: %.2f)", dpi, float64(dpi)/96.0)
return float64(dpi) / 96.0
}
}
return 1.0
}
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
user32 = syscall.NewLazyDLL("user32.dll")
dwmapi = syscall.NewLazyDLL("dwmapi.dll")
gdi32 = syscall.NewLazyDLL("gdi32.dll")
procLoadIcon = user32.NewProc("LoadIconW")
procIsZoomed = user32.NewProc("IsZoomed")
procGetWindowRect = user32.NewProc("GetWindowRect")
procCreateWindowEx = user32.NewProc("CreateWindowExW")
procDefWindowProc = user32.NewProc("DefWindowProcW")
procRegisterClassEx = user32.NewProc("RegisterClassExW")
procGetMessage = user32.NewProc("GetMessageW")
procTranslateMessage = user32.NewProc("TranslateMessage")
procDispatchMessage = user32.NewProc("DispatchMessageW")
procPostQuitMessage = user32.NewProc("PostQuitMessage")
procDestroyWindow = user32.NewProc("DestroyWindow")
procLoadCursor = user32.NewProc("LoadCursorW")
procShowWindow = user32.NewProc("ShowWindow")
procUpdateWindow = user32.NewProc("UpdateWindow")
procGetModuleHandle = kernel32.NewProc("GetModuleHandleW")
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
procSetWindowPos = user32.NewProc("SetWindowPos")
procSetWindowText = user32.NewProc("SetWindowTextW")
procScreenToClient = user32.NewProc("ScreenToClient")
procDwmSetWindowAttr = dwmapi.NewProc("DwmSetWindowAttribute")
procSetTimer = user32.NewProc("SetTimer")
procKillTimer = user32.NewProc("KillTimer")
procSetLayeredWindowAttributes = user32.NewProc("SetLayeredWindowAttributes")
procUpdateLayeredWindow = user32.NewProc("UpdateLayeredWindow")
procGetDC = user32.NewProc("GetDC")
procReleaseDC = user32.NewProc("ReleaseDC")
procCreateCompatibleDC = gdi32.NewProc("CreateCompatibleDC")
procDeleteDC = gdi32.NewProc("DeleteDC")
procCreateCompatibleBitmap = gdi32.NewProc("CreateCompatibleBitmap")
procDeleteObject = gdi32.NewProc("DeleteObject")
procSelectObject = gdi32.NewProc("SelectObject")
procCreateRoundRectRgn = gdi32.NewProc("CreateRoundRectRgn")
procSetWindowRgn = user32.NewProc("SetWindowRgn")
procGetWindowLong = user32.NewProc("GetWindowLongW")
procSetWindowLong = user32.NewProc("SetWindowLongW")
procPostMessage = user32.NewProc("PostMessageW")
)
const (
WS_OVERLAPPED = 0x00000000
WS_POPUP = 0x80000000
WS_CAPTION = 0x00C00000
WS_SYSMENU = 0x00080000
WS_THICKFRAME = 0x00040000
WS_MINIMIZEBOX = 0x00020000
WS_MAXIMIZEBOX = 0x00010000
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX
WS_CLIPCHILDREN = 0x02000000
WS_CLIPSIBLINGS = 0x04000000
WS_EX_LAYERED = 0x00080000
WM_DESTROY = 0x0002
WM_CREATE = 0x0001
WM_CLOSE = 0x0010
WM_ERASEBKGND = 0x0014
WM_NCHITTEST = 0x0084
WM_NCCALCSIZE = 0x0083
WM_NCPAINT = 0x0085
WM_NCACTIVATE = 0x0086
WM_TIMER = 0x0113
WM_USER = 0x0400
WM_INVOKE_TASK = WM_USER + 100
HTCLIENT = 1
HTCAPTION = 2
HTLEFT = 10
HTRIGHT = 11
HTTOP = 12
HTTOPLEFT = 13
HTTOPRIGHT = 14
HTBOTTOM = 15
HTBOTTOMLEFT = 16
HTBOTTOMRIGHT = 17
IDC_ARROW = 32512
CS_HREDRAW = 0x0002
CS_VREDRAW = 0x0001
CS_DROPSHADOW = 0x00020000
SW_SHOW = 5
ERROR_SUCCESS = 0
CW_USEDEFAULT = 0x80000000
SM_CXSCREEN = 0
SM_CYSCREEN = 1
SWP_NOZORDER = 0x0004
DWMWA_WINDOW_CORNER_PREFERENCE = 33
DWMWA_SYSTEMBACKDROP_TYPE = 38
DWMWCP_ROUND = 2
LWA_COLORKEY = 0x00000001
LWA_ALPHA = 0x00000002
ULW_COLORKEY = 0x00000001
ULW_ALPHA = 0x00000002
ULW_OPAQUE = 0x00000004
GWL_EXSTYLE = -20
)
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
}
type Msg struct {
Hwnd uint32
Message uint32
Wparam uintptr
Lparam uintptr
Time uint32
Pt Point
}
type WindowConfig struct {
Title string
Width int
Height int
ClassName string
Border bool
Frameless bool // 无边框模式
MaxBtn bool
MinBtn bool
Resize bool
Center bool
Icon uintptr // 窗口图标 (HICON)
Rounded bool // 圆角窗口
CornerRadius int // 圆角半径,默认10
Handler NotifyHandler
}
type U struct {
ID string `json:"id"`
Action string `json:"action"`
Value interface{} `json:"value"`
}
type Dispatcher struct {
mu sync.Mutex
tasks []func()
hwnd uintptr
}
func NewDispatcher(hwnd uintptr) *Dispatcher {
return &Dispatcher{
hwnd: hwnd,
tasks: make([]func(), 0),
}
}
func (d *Dispatcher) Dispatch(f func()) {
d.mu.Lock()
d.tasks = append(d.tasks, f)
d.mu.Unlock()
procPostMessage.Call(d.hwnd, WM_INVOKE_TASK, 0, 0)
}
func (d *Dispatcher) ProcessTasks() {
d.mu.Lock()
tasks := d.tasks
d.tasks = nil
d.mu.Unlock()
for _, task := range tasks {
task()
}
}
type Window struct {
hwnd uint32
config WindowConfig
notifyHandler *NotifyHandler
eventHandler *EventHandler
htmlContent string
loadFile string
onCreate func()
timers map[int]func()
nextTimerId int
timerHandler *EventHandler
closing bool
dispatcher *Dispatcher
eventHandlers map[uint32]ElementHandler
OnButtonClick ElementHandler
OnMouse MouseHandler
OnSelectionChanged StringHandler
OnValueChange StringHandler
OnVisibleChange BoolHandler
OnButtonStateChanged BoolHandler
OnHyperlinkClick ElementHandler
OnMinimize func() bool
}
func NewWindow(config WindowConfig) *Window {
if config.ClassName == "" {
config.ClassName = "HTMLayoutWindow"
}
if config.Width == 0 {
config.Width = 400
}
if config.Height == 0 {
config.Height = 300
}
gw := &Window{
config: config,
}
if config.Handler.Behaviors == nil {
config.Handler.Behaviors = map[string]*EventHandler{}
}
gw.SetNotifyHandler(&config.Handler)
return gw
}
func (w *Window) SetHtml(html string) *Window {
w.htmlContent = html
return w
}
func (w *Window) LoadFile(uri string) *Window {
w.htmlContent = ""
absPath, err := filepath.Abs(uri)
if err != nil {
log.Println("LoadFile error:", err)
w.loadFile = uri
} else {
w.loadFile = "file:///" + filepath.ToSlash(absPath)
}
log.Println("LoadFile:", w.loadFile)
return w
}
func (w *Window) SetEventHandler(handler *EventHandler) *Window {
w.eventHandler = handler
return w
}
func (w *Window) SetNotifyHandler(handler *NotifyHandler) *Window {
if handler.OnLoadData == nil {
handler.OnLoadData = defaultOnLoadData
}
w.notifyHandler = handler
return w
}
type ResourceLoader func(uri string) ([]byte, uint32, bool)
var resourceLoaders = make(map[string]ResourceLoader)
var loadedResources = make(map[string][]byte)
func RegisterResourceLoader(scheme string, loader ResourceLoader) {
resourceLoaders[scheme] = loader
}
func (w *Window) Dispatch(fn func()) {
if w.dispatcher != nil {
w.dispatcher.Dispatch(fn)
}
}
func defaultOnLoadData(params *NmhlLoadData) uintptr {
if params.Uri == nil {
return 0
}
uri := utf16ToString(params.Uri)
// 先检查缓存
if data, ok := loadedResources[uri]; ok && len(data) > 0 {
params.OutData = uintptr(unsafe.Pointer(&data[0]))
params.OutDataSize = int32(len(data))
params.DataType = GetResourceDataType(uri)
return 1
}
// 检查自定义资源加载器
for scheme, loader := range resourceLoaders {
prefix := scheme + "://"
if strings.HasPrefix(uri, prefix) {
data, dataType, ok := loader(uri)
if !ok || len(data) == 0 {
return 0
}
loadedResources[uri] = data
params.OutData = uintptr(unsafe.Pointer(&data[0]))
params.OutDataSize = int32(len(data))
params.DataType = dataType
return 1
}
}
// 检查是否是 resources:// 开头
if !isResourcesURI(uri) {
return 0
}
// 提取资源名称,移除 resources:// 前缀和末尾的斜杠
resourceName := uri[11:]
resourceName = strings.TrimSuffix(resourceName, "/")
filePath := filepath.Join(resourcesDir, resourceName)
data, err := readFileBytes(filePath)
if err != nil {
return 0
}
// 保存到 map,确保数据在函数返回后仍然有效
loadedResources[uri] = data
// 使用 map 中存储的数据指针,而不是局部变量 data 的指针
storedData := loadedResources[uri]
if len(storedData) == 0 {
return 0
}
params.OutData = uintptr(unsafe.Pointer(&storedData[0]))
params.OutDataSize = int32(len(storedData))
// 根据文件扩展名设置数据类型
params.DataType = GetResourceDataType(resourceName)
return 1
}
// isResourcesURI 检查是否是 resources:// URI
func isResourcesURI(uri string) bool {
return strings.HasPrefix(uri, "resources://")
}
// GetResourceDataType 根据文件扩展名返回资源数据类型
func GetResourceDataType(filename string) uint32 {
ext := filepath.Ext(filename)
switch ext {
case ".html", ".htm":
return HLRT_DATA_HTML
case ".css":
return HLRT_DATA_STYLE
case ".js":
return HLRT_DATA_SCRIPT
case ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".svg":
return HLRT_DATA_IMAGE
case ".ttf", ".otf", ".woff", ".woff2":
return HLRT_DATA_HTML
default:
return HLRT_DATA_HTML
}
}
func readFileBytes(path string) ([]byte, error) {
data, err := os.ReadFile(path)
return data, err
}
func (w *Window) OnCreateCallback(fn func()) *Window {
w.onCreate = fn
return w
}
func (w *Window) GetHwnd() uintptr {
return uintptr(w.hwnd)
}
func (w *Window) GetIcon() uintptr {
return w.config.Icon
}
func (w *Window) GetRootElement() *Element {
return RootElement(w.hwnd)
}
func (w *Window) GetElementById(id string) *Element {
root := RootElement(w.hwnd)
if root == nil {
return nil
}
return root.GetElementById(id)
}
func (w *Window) Run() {
className := syscall.StringToUTF16Ptr(w.config.ClassName)
hInstance, _, _ := procGetModuleHandle.Call()
cursor, _, _ := procLoadCursor.Call(IDC_ARROW)
classStyle := uint32(CS_HREDRAW | CS_VREDRAW)
if w.config.Frameless {
classStyle |= CS_DROPSHADOW
}
wc := wndClassEx{
Size: uint32(unsafe.Sizeof(wndClassEx{})),
Style: classStyle,
WndProc: syscall.NewCallback(w.wndProc),
ClsExtra: 0,
WndExtra: 0,
Instance: hInstance,
Icon: w.config.Icon,
Cursor: cursor,
Background: 6,
MenuName: nil,
ClassName: className,
IconSm: w.config.Icon,
}
if _, errno := registerClassEx(&wc); errno != ERROR_SUCCESS {
log.Panic("Failed to register window class: ", errno)
}
// 窗口样式设置
var style uint32
if w.config.Frameless {
// 无边框模式
style = WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
if w.config.Resize {
style |= WS_THICKFRAME
}
} else if w.config.Border {
// 自定义边框 - 有边框但无标题栏
style = WS_POPUP | WS_THICKFRAME | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
} else {
// 标准窗口
style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
if w.config.MaxBtn {
style |= WS_MAXIMIZEBOX
}
if w.config.MinBtn {
style |= WS_MINIMIZEBOX
}
if w.config.Resize {
style |= WS_THICKFRAME
}
}
x := uintptr(CW_USEDEFAULT)
y := uintptr(CW_USEDEFAULT)
// 获取 DPI 缩放因子,根据 DPI 缩放窗口大小
// 这样窗口在不同 DPI 显示器上显示相同的物理大小
dpiScale := GetDpiScale()
width := uintptr(float64(w.config.Width) * dpiScale)
height := uintptr(float64(w.config.Height) * dpiScale)
log.Printf("[Window] Config: %dx%d, DPI scale: %.2f, Final size: %dx%d", w.config.Width, w.config.Height, dpiScale, width, height)
if w.config.Center {
screenWidth, _, _ := procGetSystemMetrics.Call(SM_CXSCREEN)
screenHeight, _, _ := procGetSystemMetrics.Call(SM_CYSCREEN)
x = (uintptr(screenWidth) - width) / 2
y = (uintptr(screenHeight) - height) / 2
}
hwnd, errno := createWindowEx(
0, className,
syscall.StringToUTF16Ptr(w.config.Title),
uint32(style),
x, y,
width, height,
0, 0, hInstance, 0)
if errno != ERROR_SUCCESS {
log.Panic("Failed to create window: ", errno)
}
w.hwnd = hwnd
if w.config.Rounded && w.config.Frameless {
radius := w.config.CornerRadius
if radius <= 0 {
radius = 10
}
// 圆角半径也需要根据 DPI 缩放
scaledRadius := int(float64(radius) * dpiScale)
setRoundedRegion(uint32(hwnd), int(width), int(height), scaledRadius)
}
procShowWindow.Call(uintptr(hwnd), SW_SHOW)
procUpdateWindow.Call(uintptr(hwnd))
var msg Msg
for {
if r, errno := getMessage(&msg, 0, 0, 0); errno != ERROR_SUCCESS {
log.Panic("GetMessage error: ", errno)
} else if r == 0 {
break
}
translateMessage(&msg)
dispatchMessage(&msg)
}
}
func (w *Window) wndProc(hwnd uintptr, msg uint32, wparam uintptr, lparam uintptr) uintptr {
// 如果窗口正在关闭,跳过 HTMLayout 处理
if w.closing && msg != WM_DESTROY {
return defWindowProc(uint32(hwnd), msg, wparam, lparam)
}
result, handled := ProcNoDefault(uint32(hwnd), msg, wparam, lparam)
if handled {
return result
}
switch msg {
case WM_CREATE:
w.hwnd = uint32(hwnd)
w.dispatcher = NewDispatcher(hwnd)
// HTMLAYOUT_FONT_SMOOTHING = 4, // value: 0 - system default, 1 - no smoothing, 2 - std smoothing, 3 - clear type
SetOption(uint32(hwnd), HTMLAYOUT_FONT_SMOOTHING, 4)
SetOption(uint32(hwnd), HTMLAYOUT_ANIMATION_THREAD, 1)
if w.notifyHandler != nil {
AttachNotifyHandler(uint32(hwnd), w.notifyHandler)
}
// 始终设置默认事件处理器(处理窗口控制属性)
if w.eventHandler == nil {
w.setupDefaultEventHandler()
}
AttachWindowEventHandler(uint32(hwnd), w.eventHandler)
if w.htmlContent != "" {
err := LoadHtml(uint32(hwnd), []byte(w.htmlContent), "")
if err != nil {
log.Println("LoadHtml error:", err)
}
} else if w.loadFile != "" {
err := LoadResource(uint32(hwnd), w.loadFile)
if err != nil {
log.Println("LoadResource error:", err)
}
}
if w.onCreate != nil {
w.onCreate()
}
return 0
case WM_ERASEBKGND:
return 1
case WM_NCHITTEST:
if w.config.Frameless {
x := int(int16(lparam & 0xFFFF))
y := int(int16((lparam >> 16) & 0xFFFF))
ht := w.hitTest(x, y)
if ht != HTCLIENT {
return uintptr(ht)
}
}
case WM_NCCALCSIZE:
if w.config.Frameless {
return 0
}
case WM_NCPAINT:
if w.config.Frameless {
return 0
}
case WM_NCACTIVATE:
if w.config.Frameless {
if wparam == 0 {
return 1
}
return 0
}
case WM_CLOSE:
w.closing = true
// 先停止 HTMLayout 动画线程
SetOption(uint32(hwnd), HTMLAYOUT_ANIMATION_THREAD, 0)
// 清理 loadedResources 中的资源引用
for k := range loadedResources {
delete(loadedResources, k)
}
if w.eventHandler != nil {
DetachWindowEventHandler(w.hwnd)
w.eventHandler = nil
}
if w.notifyHandler != nil {
DetachNotifyHandler(w.hwnd)
w.notifyHandler = nil
}
destroyWindow(w.hwnd)
return 0
case WM_DESTROY:
postQuitMessage(0)
return 0
case WM_INVOKE_TASK:
if w.dispatcher != nil {
w.dispatcher.ProcessTasks()
}
return 0
// 处理托盘图标消息
case 0x0401: // WM_TRAYMSG
switch lparam {
case 0x0201: // WM_LBUTTONDOWN
// 左键点击托盘图标,显示窗口
w.Restore()
w.Show()
return 0
case 0x0203: // WM_LBUTTONDBLCLK
// 左键双击托盘图标,显示窗口
w.Restore()
w.Show()
return 0
}
}
return defWindowProc(uint32(hwnd), msg, wparam, lparam)
}
func (w *Window) hitTest(screenX, screenY int) int {
// 检查窗口是否仍然有效
if w.hwnd == 0 {
return HTCLIENT
}
// 将屏幕坐标转换为窗口客户区坐标
pt := struct{ X, Y int32 }{int32(screenX), int32(screenY)}
if procScreenToClient != nil {
procScreenToClient.Call(uintptr(w.hwnd), uintptr(unsafe.Pointer(&pt)))
}
// 查找该位置的元素
elem := FindElement(w.hwnd, int(pt.X), int(pt.Y))
if elem == nil {
return HTCLIENT
}
// 检查元素及其父元素是否有 -gohl-drag 属性
for e := elem; e != nil; {
if _, hasDrag := e.Attr("-gohl-drag"); hasDrag {
return HTCAPTION
}
parent := e.Parent()
if parent == nil {
break
}
e = parent
}
// 检查是否在边框区域(用于调整窗口大小)
if w.config.Resize {
var rect struct{ Left, Top, Right, Bottom int32 }
procGetWindowRect.Call(uintptr(w.hwnd), uintptr(unsafe.Pointer(&rect)))
borderWidth := int32(5)
onLeft := pt.X < borderWidth
onRight := pt.X > (rect.Right - rect.Left - borderWidth)
onTop := pt.Y < borderWidth
onBottom := pt.Y > (rect.Bottom - rect.Top - borderWidth)
if onTop && onLeft {
return HTTOPLEFT
}
if onTop && onRight {
return HTTOPRIGHT
}
if onBottom && onLeft {
return HTBOTTOMLEFT
}
if onBottom && onRight {
return HTBOTTOMRIGHT
}
if onTop {
return HTTOP
}
if onBottom {
return HTBOTTOM
}
if onLeft {
return HTLEFT
}
if onRight {
return HTRIGHT
}
}
return HTCLIENT
}
func (w *Window) On(eventType uint32, handler ElementHandler) {
if w.eventHandlers == nil {
w.eventHandlers = make(map[uint32]ElementHandler)
}
w.eventHandlers[eventType] = handler
}
func (w *Window) Fire(eventType uint32) bool {
if w.eventHandlers == nil {
return true
}
if handler, ok := w.eventHandlers[eventType]; ok {
return handler(nil)
}
return true
}
func (w *Window) setupDefaultEventHandler() {
w.eventHandler = &EventHandler{
OnMouse: func(he HELEMENT, params *MouseParams) bool {
elem := NewElementFromHandle(params.Target)
if elem.OnMouse != nil {
return elem.OnMouse(elem, params)
}
if w.OnMouse != nil {
return w.OnMouse(elem, params)
}
return false
},
// true 表示事件已处理(已消费),false 表示未处理(未消费)
OnBehaviorEvent: func(he HELEMENT, params *BehaviorEventParams) bool {
elem := NewElementFromHandle(params.Target)
//跳过捕获阶段的事件,否则会触发2次
if params.Cmd&SINKING != 0 {
return false
}
switch params.Cmd & 0xFF {
case BUTTON_CLICK:
if _, hasMin := elem.Attr("-gohl-min"); hasMin {
w.Minimize()
return true
}
if _, hasMax := elem.Attr("-gohl-max"); hasMax {
isMaximized, _, _ := procIsZoomed.Call(uintptr(w.hwnd))
if isMaximized != 0 {
w.Restore()
} else {
w.Maximize()
}
return true
}
if _, hasClose := elem.Attr("-gohl-close"); hasClose {
w.Close()
return true
}
if elem.OnClick != nil {
return elem.OnClick(elem)
}
if w.OnButtonClick != nil {
return w.OnButtonClick(elem)
}
case BUTTON_STATE_CHANGED:
if elem.OnButtonStateChanged != nil {
return elem.OnButtonStateChanged(elem, elem.IsChecked())
}
if w.OnButtonStateChanged != nil {
return w.OnButtonStateChanged(elem, elem.IsChecked())
}
case VISIUAL_STATUS_CHANGED:
if elem.OnVisibleChange != nil {
return elem.OnVisibleChange(elem, elem.IsVisible())
}
if w.OnVisibleChange != nil {
return w.OnVisibleChange(elem, elem.IsVisible())
}
case SELECT_SELECTION_CHANGED:
if elem.OnSelectionChanged != nil {
value, _ := elem.GetValue()
return elem.OnSelectionChanged(elem, value)
}
if w.OnSelectionChanged != nil {
value, _ := elem.GetValue()
return w.OnSelectionChanged(elem, value)
}
case EDIT_VALUE_CHANGED:
tagName := elem.Type()
if tagName != "input" && tagName != "textarea" {
return false
}
if elem.OnValueChange != nil {
return elem.OnValueChange(elem, elem.Text())
}
if w.OnValueChange != nil {
return w.OnValueChange(elem, elem.Text())
}
case HYPERLINK_CLICK:
if elem.OnHyperlinkClick != nil {
return elem.OnHyperlinkClick(elem)
}
if w.OnHyperlinkClick != nil {
return w.OnHyperlinkClick(elem)
}
}
return false
// return invoke(elem, params.Cmd)
},
OnTimer: func(he HELEMENT, params *TimerParams) bool {
timerId := int(params.TimerId)
log.Printf("[OnTimer] timerId=%d", timerId)
if w.timers != nil {
if callback, exists := w.timers[timerId]; exists {
callback()
delete(w.timers, timerId)
return true
}
}
return false
},
}
}
func (w *Window) GetElementValue(id string) string {
root := RootElement(w.hwnd)
if root == nil {
return ""
}
elements := root.Select("#" + id)
if len(elements) == 0 {
return ""
}
elem := elements[0]
if val, err := elem.ValueAsString(); err == nil {
return val
}
if val := elem.Text(); val != "" {
return val
}
return ""
}
func (w *Window) SetElementValue(id string, value string) {
root := RootElement(w.hwnd)
if root == nil {
return
}
elements := root.Select("#" + id)
if len(elements) > 0 {
elem := elements[0]
elemType := elem.Type()
if elemType == "select" || elemType == "input" || elemType == "textarea" {
elem.SetValue(value)
}
}
}
func (w *Window) UpdateUI(updates ...U) {
w.Dispatch(func() {
root := RootElement(w.hwnd)
if root == nil {
return
}
for _, update := range updates {
elem := root.GetElementById(update.ID)
if elem == nil {
continue
}
switch update.Action {
case "text":
if val, ok := update.Value.(string); ok {
elem.SetText(val)
}
case "html":
if val, ok := update.Value.(string); ok {
elem.SetHtml(val)
}
case "value":
if val, ok := update.Value.(string); ok {
elem.SetValue(val)
}
case "class":
if val, ok := update.Value.(string); ok {
elem.SetAttr("class", val)
}
case "addClass":
if val, ok := update.Value.(string); ok {
currentClass, _ := elem.Attr("class")
if currentClass != "" {
elem.SetAttr("class", currentClass+" "+val)
} else {
elem.SetAttr("class", val)
}
}
case "removeClass":
if val, ok := update.Value.(string); ok {
currentClass, _ := elem.Attr("class")
if currentClass != "" {
classes := removeClass(currentClass, val)
elem.SetAttr("class", classes)
}
}
case "show":
if val, ok := update.Value.(bool); ok {
if val {
elem.Show()
} else {
elem.Hide()
}
}
case "hide":
elem.Hide()
case "attr":
if val, ok := update.Value.(map[string]interface{}); ok {
for k, v := range val {
if vs, ok := v.(string); ok {
elem.SetAttr(k, vs)
}
}
}
case "style":
if val, ok := update.Value.(map[string]interface{}); ok {
for k, v := range val {
if vs, ok := v.(string); ok {
elem.SetStyle(k, vs)
}
}
}
case "enabled":
if val, ok := update.Value.(bool); ok {
if val {
elem.SetState(STATE_DISABLED, false)
} else {
elem.SetState(STATE_DISABLED, true)
}
}
}