/
element.go
1037 lines (899 loc) · 32.9 KB
/
element.go
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
/*
#cgo CFLAGS: -I./htmlayout/include
#cgo LDFLAGS: ./htmlayout/lib/HTMLayout.lib
#include <stdlib.h>
#include <htmlayout.h>
*/
import "C"
import (
"fmt"
"errors"
"regexp"
"runtime"
"strconv"
"strings"
"reflect"
"unicode/utf16"
"unsafe"
)
const (
HLDOM_OK = C.HLDOM_OK
HLDOM_INVALID_HWND = C.HLDOM_INVALID_HWND
HLDOM_INVALID_HANDLE = C.HLDOM_INVALID_HANDLE
HLDOM_PASSIVE_HANDLE = C.HLDOM_PASSIVE_HANDLE
HLDOM_INVALID_PARAMETER = C.HLDOM_INVALID_PARAMETER
HLDOM_OPERATION_FAILED = C.HLDOM_OPERATION_FAILED
HLDOM_OK_NOT_HANDLED = C.HLDOM_OK_NOT_HANDLED
HV_OK_TRUE = 0xffffffff
HV_OK = C.HV_OK
HV_BAD_PARAMETER = C.HV_BAD_PARAMETER
HV_INCOMPATIBLE_TYPE = C.HV_INCOMPATIBLE_TYPE
STATE_LINK = 0x00000001 // selector :link, any element having href attribute
STATE_HOVER = 0x00000002 // selector :hover, element is under the cursor, mouse hover
STATE_ACTIVE = 0x00000004 // selector :active, element is activated, e.g. pressed
STATE_FOCUS = 0x00000008 // selector :focus, element is in focus
STATE_VISITED = 0x00000010 // selector :visited, aux flag - not used internally now.
STATE_CURRENT = 0x00000020 // selector :current, current item in collection, e.g. current <option> in <select>
STATE_CHECKED = 0x00000040 // selector :checked, element is checked (or selected), e.g. check box or itme in multiselect
STATE_DISABLED = 0x00000080 // selector :disabled, element is disabled, behavior related flag.
STATE_READONLY = 0x00000100 // selector :read-only, element is read-only, behavior related flag.
STATE_EXPANDED = 0x00000200 // selector :expanded, element is in expanded state - nodes in tree view e.g. <options> in <select>
STATE_COLLAPSED = 0x00000400 // selector :collapsed, mutually exclusive with EXPANDED
STATE_INCOMPLETE = 0x00000800 // selector :incomplete, element has images (back/fore/bullet) requested but not delivered.
STATE_ANIMATING = 0x00001000 // selector :animating, is currently animating
STATE_FOCUSABLE = 0x00002000 // selector :focusable, shall accept focus
STATE_ANCHOR = 0x00004000 // selector :anchor, first element in selection (<select miltiple>), STATE_CURRENT is the current.
STATE_SYNTHETIC = 0x00008000 // selector :synthetic, synthesized DOM elements - e.g. all missed cells in tables (<td>) are getting this flag
STATE_OWNS_POPUP = 0x00010000 // selector :owns-popup, anchor(owner) element of visible popup.
STATE_TABFOCUS = 0x00020000 // selector :tab-focus, element got focus by tab traversal. engine set it together with :focus.
STATE_EMPTY = 0x00040000 // selector :empty - element is empty.
STATE_BUSY = 0x00080000 // selector :busy, element is busy. HTMLayoutRequestElementData will set this flag if
// external data was requested for the element. When data will be delivered engine will reset this flag on the element.
STATE_DRAG_OVER = 0x00100000 // drag over the block that can accept it (so is current drop target). Flag is set for the drop target block. At any given moment of time it can be only one such block.
STATE_DROP_TARGET = 0x00200000 // active drop target. Multiple elements can have this flag when D&D is active.
STATE_MOVING = 0x00400000 // dragging/moving - the flag is set for the moving element (copy of the drag-source).
STATE_COPYING = 0x00800000 // dragging/copying - the flag is set for the copying element (copy of the drag-source).
STATE_DRAG_SOURCE = 0x00C00000 // is set in element that is being dragged.
STATE_POPUP = 0x40000000 // this element is in popup state and presented to the user - out of flow now
STATE_PRESSED = 0x04000000 // pressed - close to active but has wider life span - e.g. in MOUSE_UP it
// is still on, so behavior can check it in MOUSE_UP to discover CLICK condition.
STATE_HAS_CHILDREN = 0x02000000 // has more than one child.
STATE_HAS_CHILD = 0x01000000 // has single child.
STATE_IS_LTR = 0x20000000 // selector :ltr, the element or one of its nearest container has @dir and that dir has "ltr" value
STATE_IS_RTL = 0x10000000 // selector :rtl, the element or one of its nearest container has @dir and that dir has "rtl" value
RESET_STYLE_THIS = 0x0020 // reset styles - this may require if you have styles dependent from attributes,
RESET_STYLE_DEEP = 0x0010 // use these flags after SetAttribute then. RESET_STYLE_THIS is faster than RESET_STYLE_DEEP.
MEASURE_INPLACE = 0x0001 // use this flag if you do not expect any dimensional changes - this is faster than REMEASURE
MEASURE_DEEP = 0x0002 // use this flag if changes of some attributes/content may cause change of dimensions of the element
REDRAW_NOW = 0x8000
BAD_HELEMENT = HELEMENT(unsafe.Pointer(uintptr(0)))
)
var errorToString = map[HLDOM_RESULT]string{
HLDOM_OK: "HLDOM_OK",
HLDOM_INVALID_HWND: "HLDOM_INVALID_HWND",
HLDOM_INVALID_HANDLE: "HLDOM_INVALID_HANDLE",
HLDOM_PASSIVE_HANDLE: "HLDOM_PASSIVE_HANDLE",
HLDOM_INVALID_PARAMETER: "HLDOM_INVALID_PARAMETER",
HLDOM_OPERATION_FAILED: "HLDOM_OPERATION_FAILED",
HLDOM_OK_NOT_HANDLED: "HLDOM_OK_NOT_HANDLED",
}
var valueErrorToString = map[VALUE_RESULT]string{
HV_OK_TRUE: "HV_OK_TRUE",
HV_OK: "HV_OK",
HV_BAD_PARAMETER: "HV_BAD_PARAMETER",
HV_INCOMPATIBLE_TYPE: "HV_INCOMPATIBLE_TYPE",
}
var whitespaceSplitter = regexp.MustCompile(`(\S+)`)
// DomError represents an htmlayout error with an associated
// dom error code
type DomError struct {
Result HLDOM_RESULT
Message string
}
func (e *DomError) Error() string {
return fmt.Sprintf("%s: %s", errorToString[e.Result], e.Message)
}
func domResultAsString(result HLDOM_RESULT) string {
return errorToString[result]
}
func domPanic(result C.HLDOM_RESULT, message ...interface{}) {
panic(&DomError{HLDOM_RESULT(result), fmt.Sprint(message...)})
}
type ValueError struct {
Result VALUE_RESULT
Message string
}
func (e *ValueError) Error() string {
return fmt.Sprintf("%s: %s", valueErrorToString[e.Result], e.Message)
}
func valuePanic(result C.UINT, message ...interface{}) {
panic(&ValueError{VALUE_RESULT(result), fmt.Sprint(message...)})
}
// Returns the utf-16 encoding of the utf-8 string s,
// with a terminating NUL added.
func stringToUtf16(s string) []uint16 {
return utf16.Encode([]rune(s + "\x00"))
}
// Returns the utf-8 encoding of the utf-16 sequence s,
// with a terminating NUL removed.
func utf16ToString(s *uint16) string {
if s == nil {
panic("null cstring")
}
us := make([]uint16, 0, 256)
for p := uintptr(unsafe.Pointer(s)); ; p += 2 {
u := *(*uint16)(unsafe.Pointer(p))
if u == 0 {
return string(utf16.Decode(us))
}
us = append(us, u)
}
return ""
}
func utf16ToStringLength(s *uint16, length int) string {
if s == nil {
panic("null cstring")
}
us := make([]uint16, 0, 256)
for p, i := uintptr(unsafe.Pointer(s)), 0; i < length; p, i = p+2, i+1 {
u := *(*uint16)(unsafe.Pointer(p))
us = append(us, u)
}
return string(utf16.Decode(us))
}
// Returns pointer to the utf-16 encoding of
// the utf-8 string s, with a terminating NUL added.
func stringToUtf16Ptr(s string) *uint16 {
return &stringToUtf16(s)[0]
}
func use(handle HELEMENT) {
if dr := C.HTMLayout_UseElement(handle); dr != HLDOM_OK {
domPanic(dr, "UseElement")
}
}
func unuse(handle HELEMENT) {
if handle != nil {
if dr := C.HTMLayout_UnuseElement(handle); dr != HLDOM_OK {
domPanic(dr, "UnuseElement")
}
}
}
/*
Element
Represents a single DOM element, owns and manages a Handle
*/
type Element struct {
handle HELEMENT
}
// Constructors
func NewElementFromHandle(h HELEMENT) *Element {
if h == BAD_HELEMENT {
panic("Nil helement")
}
e := &Element{BAD_HELEMENT}
e.setHandle(h)
runtime.SetFinalizer(e, (*Element).finalize)
return e
}
func NewElement(tagName string) *Element {
var handle HELEMENT = BAD_HELEMENT
szName := C.CString(tagName)
defer C.free(unsafe.Pointer(szName))
if ret := C.HTMLayoutCreateElement((*C.CHAR)(szName), nil, (*C.HELEMENT)(&handle)); ret != HLDOM_OK {
domPanic(ret, "Failed to create new element")
}
return NewElementFromHandle(handle)
}
func RootElement(hwnd uint32) *Element {
var handle HELEMENT = BAD_HELEMENT
if ret := C.HTMLayoutGetRootElement(C.HWND(C.HANDLE(uintptr(hwnd))), (*C.HELEMENT)(&handle)); ret != HLDOM_OK {
domPanic(ret, "Failed to get root element")
}
return NewElementFromHandle(handle)
}
func FocusedElement(hwnd uint32) *Element {
var handle HELEMENT = BAD_HELEMENT
if ret := C.HTMLayoutGetFocusElement(C.HWND(C.HANDLE(uintptr(hwnd))), (*C.HELEMENT)(&handle)); ret != HLDOM_OK {
domPanic(ret, "Failed to get focus element")
}
if handle != BAD_HELEMENT {
return NewElementFromHandle(handle)
}
return nil
}
// Finalizer method, only to be called from Release or by
// the Go runtime
func (e *Element) finalize() {
// Detach handlers
if attachedHandlers, hasHandlers := eventHandlers[e.handle]; hasHandlers {
for handler := range attachedHandlers {
tag := uintptr(unsafe.Pointer(handler))
C.HTMLayoutDetachEventHandler(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag))
}
delete(eventHandlers, e.handle)
}
// Release the underlying htmlayout handle
unuse(e.handle)
e.handle = BAD_HELEMENT
}
func (e *Element) Release() {
// Unregister the finalizer so that it does not get called by Go
// and then explicitly finalize this element
runtime.SetFinalizer(e, nil)
e.finalize()
}
func (e *Element) setHandle(h HELEMENT) {
use(h)
unuse(e.handle)
e.handle = h
}
func (e *Element) Handle() HELEMENT {
return e.handle
}
func (e *Element) Equals(other *Element) bool {
return other != nil && e.handle == other.handle
}
// This is the same as AttachHandler, except that behaviors are singleton instances stored
// in a master map. They may be shared among many elements since they have no state.
// The only reason we keep a separate set of the behaviors is so that the event handler
// dispatch method can tell if an event handler is a behavior or a regular handler.
func (e *Element) attachBehavior(handler *EventHandler) {
tag := uintptr(unsafe.Pointer(handler))
if subscription := handler.Subscription(); subscription == HANDLE_ALL {
if ret := C.HTMLayoutAttachEventHandler(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag)); ret != HLDOM_OK {
domPanic(ret, "Failed to attach event handler to element")
}
} else {
if ret := C.HTMLayoutAttachEventHandlerEx(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag), C.UINT(subscription)); ret != HLDOM_OK {
domPanic(ret, "Failed to attach event handler to element")
}
}
}
func (e *Element) AttachHandler(handler *EventHandler) {
attachedHandlers, hasAttachments := eventHandlers[e.handle]
if hasAttachments {
if _, exists := attachedHandlers[handler]; exists {
// This exact event handler is already attached to this exact element.
return
}
}
// Don't let the caller disable ATTACH/DETACH events, otherwise we
// won't know when to throw out our event handler object
subscription := handler.Subscription()
subscription &= ^uint32(DISABLE_INITIALIZATION & 0xffffffff)
tag := uintptr(unsafe.Pointer(handler))
if subscription == HANDLE_ALL {
if ret := C.HTMLayoutAttachEventHandler(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag)); ret != HLDOM_OK {
domPanic(ret, "Failed to attach event handler to element")
}
} else {
if ret := C.HTMLayoutAttachEventHandlerEx(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag), C.UINT(subscription)); ret != HLDOM_OK {
domPanic(ret, "Failed to attach event handler to element")
}
}
if !hasAttachments {
eventHandlers[e.handle] = make(map[*EventHandler]bool, 8)
}
eventHandlers[e.handle][handler] = true
}
func (e *Element) DetachHandler(handler *EventHandler) {
tag := uintptr(unsafe.Pointer(handler))
if attachedHandlers, exists := eventHandlers[e.handle]; exists {
if _, exists := attachedHandlers[handler]; exists {
if ret := C.HTMLayoutDetachEventHandler(e.handle, (*[0]byte)(unsafe.Pointer(goElementProc)), C.LPVOID(tag)); ret != HLDOM_OK {
domPanic(ret, "Failed to detach event handler from element")
}
delete(attachedHandlers, handler)
if len(attachedHandlers) == 0 {
delete(eventHandlers, e.handle)
}
return
}
}
panic("cannot detach, handler was not registered")
}
func (e *Element) Update(restyle, restyleDeep, remeasure, remeasureDeep, render bool) {
var flags uint32
if restyle {
if restyleDeep {
flags |= RESET_STYLE_DEEP
} else {
flags |= RESET_STYLE_THIS
}
}
if remeasure {
if remeasureDeep {
flags |= MEASURE_DEEP
} else {
flags |= MEASURE_INPLACE
}
}
if render {
flags |= REDRAW_NOW
}
if ret := C.HTMLayoutUpdateElementEx(e.handle, C.UINT(flags)); ret != HLDOM_OK {
domPanic(ret, "Failed to update element")
}
}
func (e *Element) Capture() {
if ret := C.HTMLayoutSetCapture(e.handle); ret != HLDOM_OK {
domPanic(ret, "Failed to set capture for element")
}
}
func (e *Element) ReleaseCapture() {
if ok := C.ReleaseCapture(); ok == 0 {
panic("Failed to release capture for element")
}
}
// Functions for querying elements
func (e *Element) Select(selector string) []*Element {
szSelector := C.CString(selector)
defer C.free(unsafe.Pointer(szSelector))
results := make([]*Element, 0, 32)
if ret := C.HTMLayoutSelectElements(e.handle, (*C.CHAR)(szSelector), (*[0]byte)(unsafe.Pointer(goSelectCallback)), C.LPVOID(unsafe.Pointer(&results))); ret != HLDOM_OK {
domPanic(ret, "Failed to select dom elements, selector: '", selector, "'")
}
return results
}
// Searches up the parent chain to find the first element that matches the given selector.
// Includes the element in the search. Depth indicates how far the search should progress.
// Depth = 1 means only consider this element. Depth = 0 means search all the way up to the
// root. Any other positive value of depth limits the length of the search.
func (e *Element) SelectParentLimit(selector string, depth int) *Element {
szSelector := C.CString(selector)
defer C.free(unsafe.Pointer(szSelector))
var parent C.HELEMENT
if ret := C.HTMLayoutSelectParent(e.handle, (*C.CHAR)(szSelector), C.UINT(depth), &parent); ret != HLDOM_OK {
domPanic(ret, "Failed to select parent dom elements, selector: '", selector, "'")
}
if parent != nil {
return NewElementFromHandle(HELEMENT(parent))
}
return nil
}
func (e *Element) SelectParent(selector string) *Element {
return e.SelectParentLimit(selector, 0)
}
// For delivering programmatic events to this element.
// Returns true if the event was handled, false otherwise
func (e *Element) SendEvent(eventCode uint, source *Element, reason uint32) bool {
var handled C.BOOL = 0
if ret := C.HTMLayoutSendEvent(e.handle, C.UINT(eventCode), source.handle, C.UINT_PTR(reason), &handled); ret != HLDOM_OK {
domPanic(ret, "Failed to send event")
}
return handled != 0
}
// For asynchronously delivering programmatic events to this element.
func (e *Element) PostEvent(eventCode uint, source *Element, reason uint32) {
if ret := C.HTMLayoutPostEvent(e.handle, C.UINT(eventCode), source.handle, C.UINT(reason)); ret != HLDOM_OK {
domPanic(ret, "Failed to post event")
}
}
//
// DOM structure accessors/modifiers:
//
func (e *Element) ChildCount() uint {
var count C.UINT
if ret := C.HTMLayoutGetChildrenCount(e.handle, &count); ret != HLDOM_OK {
domPanic(ret, "Failed to get child count")
}
return uint(count)
}
func (e *Element) Child(index uint) *Element {
var child C.HELEMENT
if ret := C.HTMLayoutGetNthChild(e.handle, C.UINT(index), &child); ret != HLDOM_OK {
domPanic(ret, "Failed to get child at index: ", index)
}
return NewElementFromHandle(HELEMENT(child))
}
func (e *Element) Children() []*Element {
slice := make([]*Element, 0, 32)
for i := uint(0); i < e.ChildCount(); i++ {
slice = append(slice, e.Child(i))
}
return slice
}
func (e *Element) Index() uint {
var index C.UINT
if ret := C.HTMLayoutGetElementIndex(e.handle, &index); ret != HLDOM_OK {
domPanic(ret, "Failed to get element's index")
}
return uint(index)
}
func (e *Element) Parent() *Element {
var parent C.HELEMENT
if ret := C.HTMLayoutGetParentElement(e.handle, &parent); ret != HLDOM_OK {
domPanic(ret, "Failed to get parent")
}
if parent != nil {
return NewElementFromHandle(HELEMENT(parent))
}
return nil
}
func (e *Element) InsertChild(child *Element, index uint) {
if ret := C.HTMLayoutInsertElement(child.handle, e.handle, C.UINT(index)); ret != HLDOM_OK {
domPanic(ret, "Failed to insert child element at index: ", index)
}
}
func (e *Element) AppendChild(child *Element) {
count := e.ChildCount()
if ret := C.HTMLayoutInsertElement(child.handle, e.handle, C.UINT(count)); ret != HLDOM_OK {
domPanic(ret, "Failed to append child element")
}
}
func (e *Element) Detach() {
if ret := C.HTMLayoutDetachElement(e.handle); ret != HLDOM_OK {
domPanic(ret, "Failed to detach element from dom")
}
}
func (e *Element) Delete() {
if ret := C.HTMLayoutDeleteElement(e.handle); ret != HLDOM_OK {
domPanic(ret, "Failed to delete element from dom")
}
e.finalize()
}
// Makes a deep clone of the receiver, the resulting subtree is not attached to the dom.
func (e *Element) Clone() *Element {
var clone C.HELEMENT
if ret := C.HTMLayoutCloneElement(e.handle, &clone); ret != HLDOM_OK {
domPanic(ret, "Failed to clone element")
}
return NewElementFromHandle(HELEMENT(clone))
}
func (e *Element) Swap(other *Element) {
if ret := C.HTMLayoutSwapElements(e.handle, other.handle); ret != HLDOM_OK {
domPanic(ret, "Failed to swap elements")
}
}
// Sorts 'count' child elements starting at index 'start'. Uses comparator to define the
// order. Comparator should return -1, or 0, or 1 to indicate less, equal or greater
func (e *Element) SortChildrenRange(start, count uint, comparator func(*Element, *Element) int) {
end := start + count
arg := uintptr(unsafe.Pointer(&comparator))
if ret := C.HTMLayoutSortElements(e.handle, C.UINT(start), C.UINT(end), (*[0]byte)(unsafe.Pointer(goElementComparator)), C.LPVOID(arg)); ret != HLDOM_OK {
domPanic(ret, "Failed to sort elements")
}
}
func (e *Element) SortChildren(comparator func(*Element, *Element) int) {
e.SortChildrenRange(0, e.ChildCount(), comparator)
}
func (e *Element) SetTimer(ms int) {
if ret := C.HTMLayoutSetTimer(e.handle, C.UINT(ms)); ret != HLDOM_OK {
domPanic(ret, "Failed to set timer")
}
}
func (e *Element) CancelTimer() {
e.SetTimer(0)
}
func (e *Element) Hwnd() uint32 {
var hwnd uint32
if ret := C.HTMLayoutGetElementHwnd(e.handle, (*C.HWND)(unsafe.Pointer(&hwnd)), 0); ret != HLDOM_OK {
domPanic(ret, "Failed to get element's hwnd")
}
return hwnd
}
func (e *Element) RootHwnd() uint32 {
var hwnd uint32
if ret := C.HTMLayoutGetElementHwnd(e.handle, (*C.HWND)(unsafe.Pointer(&hwnd)), 1); ret != HLDOM_OK {
domPanic(ret, "Failed to get element's root hwnd")
}
return hwnd
}
func (e *Element) Html() string {
var data *C.char
if ret := C.HTMLayoutGetElementHtml(e.handle, (*C.LPBYTE)(unsafe.Pointer(&data)), C.BOOL(0)); ret != HLDOM_OK {
domPanic(ret, "Failed to get inner html")
}
return C.GoString(data)
}
func (e *Element) OuterHtml() string {
var data *C.char
if ret := C.HTMLayoutGetElementHtml(e.handle, (*C.LPBYTE)(unsafe.Pointer(&data)), C.BOOL(1)); ret != HLDOM_OK {
domPanic(ret, "Failed to get outer html")
}
return C.GoString(data)
}
func (e *Element) Type() string {
var data *C.char
if ret := C.HTMLayoutGetElementType(e.handle, (*C.LPCSTR)(unsafe.Pointer(&data))); ret != HLDOM_OK {
domPanic(ret, "Failed to get element type")
}
return C.GoString(data)
}
func (e *Element) SetHtml(html string) {
szHtml := C.CString(html)
defer C.free(unsafe.Pointer(szHtml))
if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(html)), SIH_REPLACE_CONTENT); ret != HLDOM_OK {
domPanic(ret, "Failed to replace element's html")
}
}
func (e *Element) PrependHtml(prefix string) {
szHtml := C.CString(prefix)
defer C.free(unsafe.Pointer(szHtml))
if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(prefix)), SIH_INSERT_AT_START); ret != HLDOM_OK {
domPanic(ret, "Failed to prepend to element's html")
}
}
func (e *Element) AppendHtml(suffix string) {
szHtml := C.CString(suffix)
defer C.free(unsafe.Pointer(szHtml))
if ret := C.HTMLayoutSetElementHtml(e.handle, (*C.BYTE)(unsafe.Pointer(szHtml)), C.DWORD(len(suffix)), SIH_APPEND_AFTER_LAST); ret != HLDOM_OK {
domPanic(ret, "Failed to append to element's html")
}
}
func (e *Element) SetText(text string) {
szText := C.CString(text)
defer C.free(unsafe.Pointer(szText))
if ret := C.HTMLayoutSetElementInnerText(e.handle, (*C.BYTE)(unsafe.Pointer(szText)), C.UINT(len(text))); ret != HLDOM_OK {
domPanic(ret, "Failed to replace element's text")
}
}
func (e *Element) Text() string {
var data *C.char
if ret := C.HTMLayoutGetElementInnerText(e.handle, (*C.LPBYTE)(unsafe.Pointer(&data))); ret != HLDOM_OK {
domPanic(ret, "Failed to get text")
}
return C.GoString(data)
}
//
// HTML attribute accessors/modifiers:
//
// Returns the value of attr and a boolean indicating whether or not that attr exists.
// If the boolean is true, then the returned string is valid.
func (e *Element) Attr(key string) (string, bool) {
szValue := (*C.WCHAR)(nil)
szKey := C.CString(key)
defer C.free(unsafe.Pointer(szKey))
if ret := C.HTMLayoutGetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.LPCWSTR)(&szValue)); ret != HLDOM_OK {
domPanic(ret, "Failed to get attribute: ", key)
}
if szValue != nil {
return utf16ToString((*uint16)(szValue)), true
}
return "", false
}
func (e *Element) AttrAsFloat(key string) (float64, bool, error) {
var f float64
var err error
if s, exists := e.Attr(key); !exists {
return 0.0, false, nil
} else if f, err = strconv.ParseFloat(s, 64); err != nil {
return 0.0, true, err
}
return float64(f), true, nil
}
func (e *Element) AttrAsInt(key string) (int, bool, error) {
var i int
var err error
if s, exists := e.Attr(key); !exists {
return 0, false, nil
} else if i, err = strconv.Atoi(s); err != nil {
return 0, true, err
}
return i, true, nil
}
func (e *Element) SetAttr(key string, value interface{}) {
szKey := C.CString(key)
defer C.free(unsafe.Pointer(szKey))
var ret C.HLDOM_RESULT = HLDOM_OK
switch v := value.(type) {
case string:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(v)))
case float32:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(strconv.FormatFloat(float64(v), 'g', -1, 64))))
case float64:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(strconv.FormatFloat(float64(v), 'g', -1, 64))))
case int:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(strconv.Itoa(v))))
case int32:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(strconv.FormatInt(int64(v), 10))))
case int64:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(stringToUtf16Ptr(strconv.FormatInt(v, 10))))
case nil:
ret = C.HTMLayoutSetAttributeByName(e.handle, (*C.CHAR)(szKey), nil)
default:
panic(fmt.Sprintf("Don't know how to format this argument type: %s", reflect.TypeOf(v)))
}
if ret != HLDOM_OK {
domPanic(ret, "Failed to set attribute: "+key)
}
}
func (e *Element) RemoveAttr(key string) {
e.SetAttr(key, nil)
}
func (e *Element) AttrByIndex(index int) (string, string) {
szValue := (*C.WCHAR)(nil)
szName := (*C.CHAR)(nil)
if ret := C.HTMLayoutGetNthAttribute(e.handle, C.UINT(index), (*C.LPCSTR)(&szName), (*C.LPCWSTR)(&szValue)); ret != HLDOM_OK {
domPanic(ret, fmt.Sprintf("Failed to get attribute by index: %u", index))
}
return C.GoString((*C.char)(szName)), utf16ToString((*uint16)(szValue))
}
func (e *Element) AttrCount() uint {
var count C.UINT = 0
if ret := C.HTMLayoutGetAttributeCount(e.handle, &count); ret != HLDOM_OK {
domPanic(ret, "Failed to get attribute count")
}
return uint(count)
}
//
// CSS style attribute accessors/mutators
//
// Returns the value of the style and a boolean indicating whether or not that style exists.
// If the boolean is true, then the returned string is valid.
func (e *Element) Style(key string) (string, bool) {
szValue := (*C.WCHAR)(nil)
szKey := C.CString(key)
defer C.free(unsafe.Pointer(szKey))
if ret := C.HTMLayoutGetStyleAttribute(e.handle, (*C.CHAR)(szKey), (*C.LPCWSTR)(&szValue)); ret != HLDOM_OK {
domPanic(ret, "Failed to get style: "+key)
}
if szValue != nil {
return utf16ToString((*uint16)(szValue)), true
}
return "", false
}
func (e *Element) SetStyle(key string, value interface{}) {
szKey := C.CString(key)
defer C.free(unsafe.Pointer(szKey))
var valuePtr *uint16 = nil
switch v := value.(type) {
case string:
valuePtr = stringToUtf16Ptr(v)
case float32:
valuePtr = stringToUtf16Ptr(strconv.FormatFloat(float64(v), 'g', -1, 64))
case float64:
valuePtr = stringToUtf16Ptr(strconv.FormatFloat(float64(v), 'g', -1, 64))
case int:
valuePtr = stringToUtf16Ptr(strconv.Itoa(v))
case int32:
valuePtr = stringToUtf16Ptr(strconv.FormatInt(int64(v), 10))
case int64:
valuePtr = stringToUtf16Ptr(strconv.FormatInt(v, 10))
case nil:
valuePtr = nil
default:
panic(fmt.Sprintf("Don't know how to format this argument type: %s", reflect.TypeOf(v)))
}
if ret := C.HTMLayoutSetStyleAttribute(e.handle, (*C.CHAR)(szKey), (*C.WCHAR)(valuePtr)); ret != HLDOM_OK {
domPanic(ret, "Failed to set style: "+key)
}
}
func (e *Element) RemoveStyle(key string) {
e.SetStyle(key, nil)
}
func (e *Element) ClearStyles(key string) {
if ret := C.HTMLayoutSetStyleAttribute(e.handle, nil, nil); ret != HLDOM_OK {
domPanic(ret, "Failed to clear all styles")
}
}
//
// Element state manipulation
//
// Gets the whole set of state flags for this element
func (e *Element) StateFlags() uint32 {
var state C.UINT
if ret := C.HTMLayoutGetElementState(e.handle, &state); ret != HLDOM_OK {
domPanic(ret, "Failed to get element state flags")
}
return uint32(state)
}
// Replaces the whole set of state flags with the specified value
func (e *Element) SetStateFlags(flags uint32) {
shouldUpdate := C.BOOL(1)
if ret := C.HTMLayoutSetElementState(e.handle, C.UINT(flags), C.UINT(^flags), shouldUpdate); ret != HLDOM_OK {
domPanic(ret, "Failed to set element state flags")
}
}
// Returns true if the specified flag is "on"
func (e *Element) State(flag uint32) bool {
return e.StateFlags()&flag != 0
}
// Sets the specified flag to "on" or "off" according to the value of the provided boolean
func (e *Element) SetState(flag uint32, on bool) {
addBits := uint32(0)
clearBits := uint32(0)
if on {
addBits = flag
} else {
clearBits = flag
}
shouldUpdate := C.BOOL(1)
if ret := C.HTMLayoutSetElementState(e.handle, C.UINT(addBits), C.UINT(clearBits), shouldUpdate); ret != HLDOM_OK {
domPanic(ret, "Failed to set element state flag")
}
}
//
// Functions for retrieving/setting the various dimensions of an element
//
func (e *Element) Move(x, y int) {
if ret := C.HTMLayoutMoveElement(e.handle, C.INT(x), C.INT(y)); ret != HLDOM_OK {
domPanic(ret, "Failed to move element")
}
}
func (e *Element) Resize(x, y, w, h int) {
if ret := C.HTMLayoutMoveElementEx(e.handle, C.INT(x), C.INT(y), C.INT(w), C.INT(h)); ret != HLDOM_OK {
domPanic(ret, "Failed to resize element")
}
}
func (e *Element) getRect(rectTypeFlags uint32) (left, top, right, bottom int) {
r := Rect{}
if ret := C.HTMLayoutGetElementLocation(e.handle, (C.LPRECT)(unsafe.Pointer(&r)), C.UINT(rectTypeFlags)); ret != HLDOM_OK {
domPanic(ret, "Failed to get element rect")
}
return int(r.Left), int(r.Top), int(r.Right), int(r.Bottom)
}
func (e *Element) ContentBox() (left, top, right, bottom int) {
return e.getRect(CONTENT_BOX)
}
func (e *Element) ContentViewBox() (left, top, right, bottom int) {
return e.getRect(CONTENT_BOX | VIEW_RELATIVE)
}
func (e *Element) ContentBoxSize() (width, height int) {
l, t, r, b := e.getRect(CONTENT_BOX)
return int(r - l), int(b - t)
}
func (e *Element) PaddingBox() (left, top, right, bottom int) {
return e.getRect(PADDING_BOX)
}
func (e *Element) PaddingViewBox() (left, top, right, bottom int) {
return e.getRect(PADDING_BOX | VIEW_RELATIVE)
}
func (e *Element) PaddingBoxSize() (width, height int) {
l, t, r, b := e.getRect(PADDING_BOX)
return int(r - l), int(b - t)
}
func (e *Element) BorderBox() (left, top, right, bottom int) {
return e.getRect(BORDER_BOX)
}
func (e *Element) BorderViewBox() (left, top, right, bottom int) {
return e.getRect(BORDER_BOX | VIEW_RELATIVE)
}
func (e *Element) BorderBoxSize() (width, height int) {
l, t, r, b := e.getRect(BORDER_BOX)
return int(r - l), int(b - t)
}
func (e *Element) MarginBox() (left, top, right, bottom int) {
return e.getRect(MARGIN_BOX)
}
func (e *Element) MarginViewBox() (left, top, right, bottom int) {
return e.getRect(MARGIN_BOX | VIEW_RELATIVE)
}
func (e *Element) MarginBoxSize() (width, height int) {
l, t, r, b := e.getRect(MARGIN_BOX)
return int(r - l), int(b - t)
}
//
// Functions for retrieving/setting the value in widget input controls
//
type textValueParams struct {
MethodId uint32
Text *uint16
Length uint32
}
func (e *Element) ValueAsString() (string, error) {
args := &textValueParams{ MethodId: GET_TEXT_VALUE }
ret := C.HTMLayoutCallBehaviorMethod(e.handle, (*C.METHOD_PARAMS)(unsafe.Pointer(args)))
if ret == HLDOM_OK_NOT_HANDLED {
domPanic(ret, "This type of element does not provide data in this way. Try a <widget>.")
} else if ret != HLDOM_OK {
domPanic(ret, "Could not get text value")
}
if args.Text == nil {
return "", errors.New("Nil string pointer")
}
return utf16ToStringLength(args.Text, int(args.Length)), nil
}
func (e *Element) SetValue(value interface{}) {
switch v := value.(type) {
case string:
args := &textValueParams{
MethodId: SET_TEXT_VALUE,
Text: stringToUtf16Ptr(v),
Length: uint32(len(v)),
}
ret := C.HTMLayoutCallBehaviorMethod(e.handle, (*C.METHOD_PARAMS)(unsafe.Pointer(args)))
if ret == HLDOM_OK_NOT_HANDLED {
domPanic(ret, "This type of element does not accept data in this way. Try a <widget>.")
} else if ret != HLDOM_OK {
domPanic(ret, "Could not set text value")
}
default:
panic("Don't know how to set values of this type")
}
}
//
// The following are not strictly wrappers of htmlayout functions, but rather convenience
// functions that are helpful in common use cases
//
func (e *Element) Describe() string {
s := e.Type()
if value, exists := e.Attr("id"); exists {
s += "#" + value
}
if value, exists := e.Attr("class"); exists {
values := strings.Split(value, " ")
for _, v := range values {
s += "." + v
}
}
return s
}
// Returns the first of the child elements matching the selector. If no elements
// match, the function panics
func (e *Element) SelectFirst(selector string) *Element {
results := e.Select(selector)
if len(results) == 0 {
panic(fmt.Sprintf("No elements match selector '%s'", selector))
}
return results[0]
}
// Returns the only child element that matches the selector. If no elements match
// or more than one element matches, the function panics
func (e *Element) SelectUnique(selector string) *Element {
results := e.Select(selector)
if len(results) == 0 {
panic(fmt.Sprintf("No elements match selector '%s'", selector))
} else if len(results) > 1 {
panic(fmt.Sprintf("More than one element match selector '%s'", selector))
}
return results[0]
}
// A wrapper of SelectUnique that auto-prepends a hash to the provided id.
// Useful when selecting elements base on a programmatically retrieved id (which does
// not already have the hash on it)
func (e *Element) SelectId(id string) *Element {
return e.SelectUnique(fmt.Sprintf("#%s", id))
}
//
// Functions for manipulating the set of classes applied to this element:
//
// Returns true if the specified class is among those listed in the "class" attribute.
func (e *Element) HasClass(class string) bool {
if classList, exists := e.Attr("class"); !exists {
return false
} else if classes := whitespaceSplitter.FindAllString(classList, -1); classes == nil {
return false
} else {
for _, item := range classes {
if class == item {
return true
}
}
}