forked from go-qml/qml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qml.go
952 lines (860 loc) · 28.1 KB
/
qml.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
package qml
// #include <stdlib.h>
//
// #include "capi.h"
//
import "C"
import (
"errors"
"fmt"
"image"
"image/color"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"sync/atomic"
"unsafe"
)
// InitOptions holds options to initialize the qml package.
type InitOptions struct {
// Reserved for coming options.
}
var initialized int32
// Init initializes the qml package with the provided parameters.
// If the options parameter is nil, default options suitable for a
// normal graphic application will be used.
//
// Init must be called only once, and before any other functionality
// from the qml package is used.
func Init(options *InitOptions) {
if !atomic.CompareAndSwapInt32(&initialized, 0, 1) {
panic("qml.Init called more than once")
}
guiLoopReady.Lock()
go guiLoop()
guiLoopReady.Lock()
}
// Engine provides an environment for instantiating QML components.
type Engine struct {
Common
values map[interface{}]*valueFold
destroyed bool
imageProviders map[string]*func(providerId string, width, height int) image.Image
}
var engines = make(map[unsafe.Pointer]*Engine)
// NewEngine returns a new QML engine.
//
// The Destory method must be called to finalize the engine and
// release any resources used.
func NewEngine() *Engine {
engine := &Engine{values: make(map[interface{}]*valueFold)}
gui(func() {
engine.addr = C.newEngine(nil)
engine.engine = engine
engine.imageProviders = make(map[string]*func(providerId string, width, height int) image.Image)
engines[engine.addr] = engine
stats.enginesAlive(+1)
})
return engine
}
func (e *Engine) assertValid() {
if e.destroyed {
panic("engine already destroyed")
}
}
// Destroy finalizes the engine and releases any resources used.
// The engine must not be used after calling this method.
//
// It is safe to call Destroy more than once.
func (e *Engine) Destroy() {
if !e.destroyed {
gui(func() {
if !e.destroyed {
e.destroyed = true
C.delObjectLater(e.addr)
if len(e.values) == 0 {
delete(engines, e.addr)
} else {
// The engine reference keeps those values alive.
// The last value destroyed will clear it.
}
stats.enginesAlive(-1)
}
})
}
}
// Load loads a new component with the provided location and with the
// content read from r. The location informs the resource name for
// logged messages, and its path is used to locate any other resources
// referenced by the QML content.
//
// Once a component is loaded, component instances may be created from
// the resulting object via its Create and CreateWindow methods.
func (e *Engine) Load(location string, r io.Reader) (Object, error) {
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
if colon, slash := strings.Index(location, ":"), strings.Index(location, "/"); colon == -1 || slash <= colon {
// TODO Better testing for this.
if filepath.IsAbs(location) {
location = "file:" + filepath.ToSlash(location)
} else {
dir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("cannot obtain absolute path: %v", err)
}
location = "file:" + filepath.ToSlash(filepath.Join(dir, location))
}
}
cdata, cdatalen := unsafeBytesData(data)
cloc, cloclen := unsafeStringData(location)
comp := &Common{engine: e}
gui(func() {
// TODO The component's parent should probably be the engine.
comp.addr = C.newComponent(e.addr, nilPtr)
C.componentSetData(comp.addr, cdata, cdatalen, cloc, cloclen)
message := C.componentErrorString(comp.addr)
if message != nilCharPtr {
err = errors.New(strings.TrimRight(C.GoString(message), "\n"))
C.free(unsafe.Pointer(message))
}
})
if err != nil {
return nil, err
}
return comp, nil
}
// LoadFile loads a component from the provided QML file.
// Resources referenced by the QML content will be resolved relative to its path.
//
// Once a component is loaded, component instances may be created from
// the resulting object via its Create and CreateWindow methods.
func (e *Engine) LoadFile(path string) (Object, error) {
// TODO Test this.
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return e.Load(path, f)
}
// LoadString loads a component from the provided QML string.
// The location informs the resource name for logged messages, and its
// path is used to locate any other resources referenced by the QML content.
//
// Once a component is loaded, component instances may be created from
// the resulting object via its Create and CreateWindow methods.
func (e *Engine) LoadString(location, qml string) (Object, error) {
return e.Load(location, strings.NewReader(qml))
}
// Context returns the engine's root context.
func (e *Engine) Context() *Context {
e.assertValid()
var ctx Context
ctx.engine = e
gui(func() {
ctx.addr = C.engineRootContext(e.addr)
})
return &ctx
}
// TODO ObjectOf is probably still worth it, but turned out unnecessary
// for GL functionality. Test it properly before introducing it.
// ObjectOf returns the QML Object representation of the provided Go value
// within the e engine.
//func (e *Engine) ObjectOf(value interface{}) Object {
// // TODO Would be good to preserve identity on the Go side. See unpackDataValue as well.
// return &Common{
// engine: e,
// addr: wrapGoValue(e, value, cppOwner),
// }
//}
// Painter is provided to Paint methods on Go types that have displayable content.
type Painter struct {
enigne *Engine
obj Object
}
// Object returns the underlying object being painted.
func (p *Painter) Object() Object {
return p.obj
}
// AddImageProvider registers f to be called when an image is requested by QML code
// with the specified provider identifier. It is a runtime error to register the same
// provider identifier multiple times.
//
// The imgId provided to f is the requested image source, with the "image:" scheme
// and provider identifier removed. For example, with an image image source of
// "image://myprovider/icons/home.ext", the respective imgId would be "icons/home.ext".
//
// If either the width or the height parameters provided to f are zero, no specific
// size for the image was requested. If non-zero, the returned image should have the
// the provided size, and will be resized if the returned image has a different size.
//
// See the documentation for more details on image providers:
//
// http://qt-project.org/doc/qt-5.0/qtquick/qquickimageprovider.html
//
func (e *Engine) AddImageProvider(prvId string, f func(imgId string, width, height int) image.Image) {
if _, ok := e.imageProviders[prvId]; ok {
panic(fmt.Sprintf("engine already has an image provider with id %q", prvId))
}
e.imageProviders[prvId] = &f
cprvId, cprvIdLen := unsafeStringData(prvId)
gui(func() {
qprvId := C.newString(cprvId, cprvIdLen)
defer C.delString(qprvId)
C.engineAddImageProvider(e.addr, qprvId, unsafe.Pointer(&f))
})
}
//export hookRequestImage
func hookRequestImage(imageFunc unsafe.Pointer, cid *C.char, cidLen, cwidth, cheight C.int) unsafe.Pointer {
f := *(*func(imgId string, width, height int) image.Image)(imageFunc)
id := unsafeString(cid, cidLen)
width := int(cwidth)
height := int(cheight)
img := f(id, width, height)
var cimage unsafe.Pointer
rect := img.Bounds()
width = rect.Max.X - rect.Min.X
height = rect.Max.Y - rect.Min.Y
cimage = C.newImage(C.int(width), C.int(height))
var cbits []byte
cbitsh := (*reflect.SliceHeader)((unsafe.Pointer)(&cbits))
cbitsh.Data = (uintptr)((unsafe.Pointer)(C.imageBits(cimage)))
cbitsh.Len = width * height * 4 // RGBA
cbitsh.Cap = cbitsh.Len
i := 0
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
r, g, b, a := img.At(x, y).RGBA()
*(*uint32)(unsafe.Pointer(&cbits[i])) = (a>>8)<<24 | (r>>8)<<16 | (g>>8)<<8 | (b >> 8)
i += 4
}
}
return cimage
}
// Context represents a QML context that can hold variables visible
// to logic running within it.
type Context struct {
Common
}
// SetVar makes the provided value available as a variable with the
// given name for QML code executed within the c context.
//
// If value is a struct, its exported fields are also made accessible to
// QML code as attributes of the named object. The attribute name in the
// object has the same name of the Go field name, except for the first
// letter which is lowercased. This is conventional and enforced by
// the QML implementation.
//
// The engine will hold a reference to the provided value, so it will
// not be garbage collected until the engine is destroyed, even if the
// value is unused or changed.
func (ctx *Context) SetVar(name string, value interface{}) {
cname, cnamelen := unsafeStringData(name)
gui(func() {
var dvalue C.DataValue
packDataValue(value, &dvalue, ctx.engine, cppOwner)
qname := C.newString(cname, cnamelen)
defer C.delString(qname)
C.contextSetProperty(ctx.addr, qname, &dvalue)
})
}
// SetVars makes the exported fields of the provided value available as
// variables for QML code executed within the c context. The variable names
// will have the same name of the Go field names, except for the first
// letter which is lowercased. This is conventional and enforced by
// the QML implementation.
//
// The engine will hold a reference to the provided value, so it will
// not be garbage collected until the engine is destroyed, even if the
// value is unused or changed.
func (ctx *Context) SetVars(value interface{}) {
gui(func() {
C.contextSetObject(ctx.addr, wrapGoValue(ctx.engine, value, cppOwner))
})
}
// Var returns the context variable with the given name.
func (ctx *Context) Var(name string) interface{} {
cname, cnamelen := unsafeStringData(name)
var dvalue C.DataValue
gui(func() {
qname := C.newString(cname, cnamelen)
defer C.delString(qname)
C.contextGetProperty(ctx.addr, qname, &dvalue)
})
return unpackDataValue(&dvalue, ctx.engine)
}
// TODO Context.Spawn() => Context
// Object is the common interface implemented by all QML types.
//
// See the documentation of Common for details about this interface.
type Object interface {
Common() *Common
TypeName() string
Interface() interface{}
Set(property string, value interface{})
Property(name string) interface{}
Int(property string) int
Int64(property string) int64
Float64(property string) float64
Bool(property string) bool
String(property string) string
Color(property string) color.RGBA
Object(property string) Object
Slice(property string, result interface{})
ObjectByName(objectName string) Object
Call(method string, params ...interface{}) interface{}
Create(ctx *Context) Object
CreateWindow(ctx *Context) *Window
Destroy()
On(signal string, function interface{})
}
// List holds a QML list.
type List struct {
// In the future this will be able to hold a reference to QML-owned
// lists, so they can be mutated.
data []interface{}
}
// Len returns the number of elements in the list.
func (list *List) Len() int {
return len(list.data)
}
// Slice allocates a new slice and copies the list content into it,
// performing type conversions as possible, and then assigns the result
// to the slice pointed to by sliceAddr.
// Slice panics if the list values are not compatible with the
// provided slice.
func (list *List) Slice(sliceAddr interface{}) {
toPtr := reflect.ValueOf(sliceAddr)
if toPtr.Kind() != reflect.Ptr || toPtr.Type().Elem().Kind() != reflect.Slice {
panic(fmt.Sprintf("Slice got a sliceAddr parameter that is not a slice address: %#v", sliceAddr))
}
convertAndSet(toPtr.Elem(), reflect.ValueOf(list), reflect.Value{})
}
// Common implements the common behavior of all QML objects.
// It implements the Object interface.
type Common struct {
addr unsafe.Pointer
engine *Engine
}
var _ Object = (*Common)(nil)
// Common returns obj itself.
//
// This provides access to the underlying *Common for types that
// embed it, when these are used via the Object interface.
func (obj *Common) Common() *Common {
return obj
}
// TypeName returns the underlying type name for the held value.
func (obj *Common) TypeName() string {
var name string
gui(func() {
name = C.GoString(C.objectTypeName(obj.addr))
})
return name
}
// Interface returns the underlying Go value that is being held by
// the object wrapper.
//
// It is a runtime error to call Interface on values that are not
// backed by a Go value.
func (obj *Common) Interface() interface{} {
var result interface{}
var cerr *C.error
gui(func() {
var fold *valueFold
if cerr = C.objectGoAddr(obj.addr, (*unsafe.Pointer)(unsafe.Pointer(&fold))); cerr == nil {
result = fold.gvalue
}
})
cmust(cerr)
return result
}
// Set changes the named object property to the given value.
func (obj *Common) Set(property string, value interface{}) {
cproperty := C.CString(property)
defer C.free(unsafe.Pointer(cproperty))
var cerr *C.error
gui(func() {
var dvalue C.DataValue
packDataValue(value, &dvalue, obj.engine, cppOwner)
cerr = C.objectSetProperty(obj.addr, cproperty, &dvalue)
})
cmust(cerr)
}
// Property returns the current value for a property of the object.
// If the property type is known, type-specific methods such as Int
// and String are more convenient to use.
// Property panics if the property does not exist.
func (obj *Common) Property(name string) interface{} {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
var dvalue C.DataValue
var found C.int
gui(func() {
found = C.objectGetProperty(obj.addr, cname, &dvalue)
})
if found == 0 {
panic(fmt.Sprintf("object does not have a %q property", name))
}
return unpackDataValue(&dvalue, obj.engine)
}
// Int returns the int value of the named property.
// Int panics if the property cannot be represented as an int.
func (obj *Common) Int(property string) int {
switch value := obj.Property(property).(type) {
case int:
return value
case int64:
if int64(int(value)) != value {
panic(fmt.Sprintf("value of property %q is too large for int: %#v", property, value))
}
return int(value)
case float32:
return int(value)
case float64:
return int(value)
default:
panic(fmt.Sprintf("value of property %q cannot be represented as an int: %#v", property, value))
}
}
// Int64 returns the int64 value of the named property.
// Int64 panics if the property cannot be represented as an int64.
func (obj *Common) Int64(property string) int64 {
switch value := obj.Property(property).(type) {
case int:
return int64(value)
case int64:
return value
case float32:
return int64(value)
case float64:
return int64(value)
default:
panic(fmt.Sprintf("value of property %q cannot be represented as an int64: %#v", property, value))
}
}
// Float64 returns the float64 value of the named property.
// Float64 panics if the property cannot be represented as float64.
func (obj *Common) Float64(property string) float64 {
switch value := obj.Property(property).(type) {
case int:
return float64(value)
case int64:
return float64(value)
case float32:
return float64(value)
case float64:
return value
default:
panic(fmt.Sprintf("value of property %q cannot be represented as a float64: %#v", property, value))
}
}
// Bool returns the bool value of the named property.
// Bool panics if the property is not a bool.
func (obj *Common) Bool(property string) bool {
value := obj.Property(property)
if b, ok := value.(bool); ok {
return b
}
panic(fmt.Sprintf("value of property %q is not a bool: %#v", property, value))
}
// String returns the string value of the named property.
// String panics if the property is not a string.
func (obj *Common) String(property string) string {
value := obj.Property(property)
if s, ok := value.(string); ok {
return s
}
panic(fmt.Sprintf("value of property %q is not a string: %#v", property, value))
}
// Color returns the RGBA value of the named property.
// Color panics if the property is not a color.
func (obj *Common) Color(property string) color.RGBA {
value := obj.Property(property)
c, ok := value.(color.RGBA)
if !ok {
panic(fmt.Sprintf("value of property %q is not a color: %#v", property, value))
}
return c
}
// Object returns the object value of the named property.
// Object panics if the property is not a QML object.
func (obj *Common) Object(property string) Object {
value := obj.Property(property)
object, ok := value.(Object)
if !ok {
panic(fmt.Sprintf("value of property %q is not a QML object: %#v", property, value))
}
return object
}
// Slice allocates a new slice and copies the content of the named list
// property to it, performing type conversions as possible, and then
// assigns the result to the slice pointed to by sliceAddr.
// Slice panics if the property value is not a list with proper values.
func (obj *Common) Slice(property string, sliceAddr interface{}) {
value := obj.Property(property)
list, ok := value.(*List)
if !ok {
panic(fmt.Sprintf("value of property %q is not a QML list: %#v", property, value))
}
list.Slice(sliceAddr)
}
// ObjectByName returns the Object value of the descendant object that
// was defined with the objectName property set to the provided value.
// ObjectByName panics if the object is not found.
func (obj *Common) ObjectByName(objectName string) Object {
cname, cnamelen := unsafeStringData(objectName)
var dvalue C.DataValue
gui(func() {
qname := C.newString(cname, cnamelen)
defer C.delString(qname)
C.objectFindChild(obj.addr, qname, &dvalue)
})
object, ok := unpackDataValue(&dvalue, obj.engine).(Object)
if !ok {
panic(fmt.Sprintf("cannot find descendant with objectName == %q", objectName))
}
return object
}
// Call calls the given object method with the provided parameters.
// Call panics if the method does not exist.
func (obj *Common) Call(method string, params ...interface{}) interface{} {
if len(params) > len(dataValueArray) {
panic("too many parameters")
}
cmethod, cmethodLen := unsafeStringData(method)
var result C.DataValue
var cerr *C.error
gui(func() {
for i, param := range params {
packDataValue(param, &dataValueArray[i], obj.engine, jsOwner)
}
cerr = C.objectInvoke(obj.addr, cmethod, cmethodLen, &result, &dataValueArray[0], C.int(len(params)))
})
cmust(cerr)
return unpackDataValue(&result, obj.engine)
}
// Create creates a new instance of the component held by obj.
// The component instance runs under the ctx context. If ctx is nil,
// it runs under the same context as obj.
//
// The Create method panics if called on an object that does not
// represent a QML component.
func (obj *Common) Create(ctx *Context) Object {
if C.objectIsComponent(obj.addr) == 0 {
panic("object is not a component")
}
var root Common
root.engine = obj.engine
gui(func() {
ctxaddr := nilPtr
if ctx != nil {
ctxaddr = ctx.addr
}
root.addr = C.componentCreate(obj.addr, ctxaddr)
})
return &root
}
// CreateWindow creates a new instance of the component held by obj,
// and creates a new window holding the instance as its root object.
// The component instance runs under the ctx context. If ctx is nil,
// it runs under the same context as obj.
//
// The CreateWindow method panics if called on an object that
// does not represent a QML component.
func (obj *Common) CreateWindow(ctx *Context) *Window {
if C.objectIsComponent(obj.addr) == 0 {
panic("object is not a component")
}
var win Window
win.engine = obj.engine
gui(func() {
ctxaddr := nilPtr
if ctx != nil {
ctxaddr = ctx.addr
}
win.addr = C.componentCreateWindow(obj.addr, ctxaddr)
})
return &win
}
// Destroy finalizes the value and releases any resources used.
// The value must not be used after calling this method.
func (obj *Common) Destroy() {
// TODO We might hook into the destroyed signal, and prevent this object
// from being used in post-destruction crash-prone ways.
gui(func() {
if obj.addr != nilPtr {
C.delObjectLater(obj.addr)
obj.addr = nilPtr
}
})
}
var connectedFunction = make(map[*interface{}]bool)
// On connects the named signal from obj with the provided function, so that
// when obj next emits that signal, the function is called with the parameters
// the signal carries.
//
// The provided function must accept a number of parameters that is equal to
// or less than the number of parameters provided by the signal, and the
// resepctive parameter types must match exactly or be conversible according
// to normal Go rules.
//
// For example:
//
// obj.On("clicked", func() { fmt.Println("obj got a click") })
//
// Note that Go uses the real signal name, rather than the one used when
// defining QML signal handlers ("clicked" rather than "onClicked").
//
// For more details regarding signals and QML see:
//
// http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-connections.html
//
func (obj *Common) On(signal string, function interface{}) {
funcv := reflect.ValueOf(function)
funct := funcv.Type()
if funcv.Kind() != reflect.Func {
panic("function provided to On is not a function or method")
}
if funct.NumIn() > C.MaxParams {
panic("function takes too many arguments")
}
csignal, csignallen := unsafeStringData(signal)
var cerr *C.error
gui(func() {
cerr = C.objectConnect(obj.addr, csignal, csignallen, obj.engine.addr, unsafe.Pointer(&function), C.int(funcv.Type().NumIn()))
if cerr == nil {
connectedFunction[&function] = true
stats.connectionsAlive(+1)
}
})
cmust(cerr)
}
//export hookSignalDisconnect
func hookSignalDisconnect(funcp unsafe.Pointer) {
before := len(connectedFunction)
delete(connectedFunction, (*interface{})(funcp))
if before == len(connectedFunction) {
panic("disconnecting unknown signal function")
}
stats.connectionsAlive(-1)
}
//export hookSignalCall
func hookSignalCall(enginep unsafe.Pointer, funcp unsafe.Pointer, args *C.DataValue) {
engine := engines[enginep]
if engine == nil {
panic("signal called after engine was destroyed")
}
funcv := reflect.ValueOf(*(*interface{})(funcp))
funct := funcv.Type()
numIn := funct.NumIn()
var params [C.MaxParams]reflect.Value
for i := 0; i < numIn; i++ {
arg := (*C.DataValue)(unsafe.Pointer(uintptr(unsafe.Pointer(args)) + uintptr(i)*dataValueSize))
param := reflect.ValueOf(unpackDataValue(arg, engine))
if paramt := funct.In(i); param.Type() != paramt {
// TODO Provide a better error message when this fails.
param = param.Convert(paramt)
}
params[i] = param
}
funcv.Call(params[:numIn])
}
func cerror(cerr *C.error) error {
err := errors.New(C.GoString((*C.char)(unsafe.Pointer(cerr))))
C.free(unsafe.Pointer(cerr))
return err
}
func cmust(cerr *C.error) {
if cerr != nil {
panic(cerror(cerr).Error())
}
}
// TODO Signal emitting support for go values.
// Window represents a QML window where components are rendered.
type Window struct {
Common
}
// Show exposes the window.
func (win *Window) Show() {
gui(func() {
C.windowShow(win.addr)
})
}
// Hide hides the window.
func (win *Window) Hide() {
gui(func() {
C.windowHide(win.addr)
})
}
// PlatformId returns the window's platform id.
//
// For platforms where this id might be useful, the value returned will
// uniquely represent the window inside the corresponding screen.
func (win *Window) PlatformId() uintptr {
var id uintptr
gui(func() {
id = uintptr(C.windowPlatformId(win.addr))
})
return id
}
// Root returns the root object being rendered.
//
// If the window was defined in QML code, the root object is the window itself.
func (win *Window) Root() Object {
var obj Common
obj.engine = win.engine
gui(func() {
obj.addr = C.windowRootObject(win.addr)
})
return &obj
}
// Wait blocks the current goroutine until the window is closed.
func (win *Window) Wait() {
// XXX Test this.
var m sync.Mutex
m.Lock()
gui(func() {
// TODO Must be able to wait for the same Window from multiple goroutines.
// TODO If the window is not visible, must return immediately.
waitingWindows[win.addr] = &m
C.windowConnectHidden(win.addr)
})
m.Lock()
}
var waitingWindows = make(map[unsafe.Pointer]*sync.Mutex)
//export hookWindowHidden
func hookWindowHidden(addr unsafe.Pointer) {
m, ok := waitingWindows[addr]
if !ok {
panic("window is not waiting")
}
delete(waitingWindows, addr)
m.Unlock()
}
// Snapshot returns an image with the visible contents of the window.
// The main GUI thread is paused while the data is being acquired.
func (win *Window) Snapshot() image.Image {
// TODO Test this.
var cimage unsafe.Pointer
gui(func() {
cimage = C.windowGrabWindow(win.addr)
})
defer C.delImage(cimage)
// This should be safe to be done out of the main GUI thread.
var cwidth, cheight C.int
C.imageSize(cimage, &cwidth, &cheight)
var cbits []byte
cbitsh := (*reflect.SliceHeader)((unsafe.Pointer)(&cbits))
cbitsh.Data = (uintptr)((unsafe.Pointer)(C.imageConstBits(cimage)))
cbitsh.Len = int(cwidth * cheight * 8) // ARGB
cbitsh.Cap = cbitsh.Len
image := image.NewRGBA(image.Rect(0, 0, int(cwidth), int(cheight)))
l := int(cwidth * cheight * 4)
for i := 0; i < l; i += 4 {
var c uint32 = *(*uint32)(unsafe.Pointer(&cbits[i]))
image.Pix[i+0] = byte(c >> 16)
image.Pix[i+1] = byte(c >> 8)
image.Pix[i+2] = byte(c)
image.Pix[i+3] = byte(c >> 24)
}
return image
}
// TypeSpec holds the specification of a QML type that is backed by Go logic.
//
// The type specification must be registered with the RegisterTypes function
// before it will be visible to QML code, as in:
//
// qml.RegisterTypes("GoExtensions", 1, 0, []qml.TypeSpec{{
// Name: "Person",
// Init: func(p *Person, obj qml.Object) {},
// }})
//
// See the package documentation for more details.
//
type TypeSpec struct {
// Name holds the identifier the type is known as.
Name string
// Init must be set to a function that is called when QML code requests
// the creation of a new value of this type. The provided function must
// have the following type:
//
// func(value *CustomType, object qml.Object)
//
// Where CustomType is the custom type being registered. The function will
// be called with a newly created *CustomType and its respective qml.Object.
Init interface{}
// Singleton defines whether a single instance of the type should be used
// for all accesses, as a singleton value. If true, all properties of the
// singleton value are directly accessible under the type name.
Singleton bool
private struct{} // Force use of fields by name.
}
var types []*TypeSpec
// RegisterTypes registers the provided list of type specifications for use
// by QML code. To access the registered types, they must be imported from the
// provided location and major.minor version numbers.
//
// For example, with a location "GoExtensions", major 4, and minor 2, this statement
// imports all the registered types in the module's namespace:
//
// import GoExtensions 4.2
//
// See the documentation on QML import statements for details on these:
//
// http://qt-project.org/doc/qt-5.0/qtqml/qtqml-syntax-imports.html
//
func RegisterTypes(location string, major, minor int, types []TypeSpec) {
for i := range types {
err := registerType(location, major, minor, &types[i])
if err != nil {
panic(err)
}
}
}
func registerType(location string, major, minor int, spec *TypeSpec) error {
// Copy and hold a reference to the spec data.
localSpec := *spec
f := reflect.ValueOf(localSpec.Init)
ft := f.Type()
if ft.Kind() != reflect.Func {
return fmt.Errorf("TypeSpec.Init must be a function, got %#v", localSpec.Init)
}
if ft.NumIn() != 2 {
return fmt.Errorf("TypeSpec.Init's function must accept two arguments: %s", ft)
}
firstArg := ft.In(0)
if firstArg.Kind() != reflect.Ptr || firstArg.Elem().Kind() == reflect.Ptr {
return fmt.Errorf("TypeSpec.Init's function must take a pointer type as the second argument: %s", ft)
}
if ft.In(1) != typeObject {
return fmt.Errorf("TypeSpec.Init's function must take qml.Object as the second argument: %s", ft)
}
customType := typeInfo(reflect.New(firstArg.Elem()).Interface())
var err error
gui(func() {
cloc := C.CString(location)
cname := C.CString(localSpec.Name)
cres := C.int(0)
if localSpec.Singleton {
cres = C.registerSingleton(cloc, C.int(major), C.int(minor), cname, customType, unsafe.Pointer(&localSpec))
} else {
cres = C.registerType(cloc, C.int(major), C.int(minor), cname, customType, unsafe.Pointer(&localSpec))
}
// It doesn't look like it keeps references to these, but it's undocumented and unclear.
C.free(unsafe.Pointer(cloc))
C.free(unsafe.Pointer(cname))
if cres == -1 {
err = fmt.Errorf("QML engine failed to register type; invalid type location or name?")
} else {
types = append(types, &localSpec)
}
})
return err
}