-
Notifications
You must be signed in to change notification settings - Fork 6
/
uing.nim
3536 lines (2727 loc) · 110 KB
/
uing.nim
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
## High level wrapper for libui-ng.
##
## Documentation mainly from `ui.h <https://github.com/libui-ng/libui-ng/blob/master/ui.h>`_
##
## :Author: Jasmine
##
## # See also
## - `genui <uing/genui.html>`_ macro
import std/times
import std/colors
import uing/rawui except Color
type
Widget* = ref object of RootRef ## abstract Widget base class.
internalImpl*: pointer
func impl*(w: Widget): ptr[Control] = cast[ptr Control](w.internalImpl)
## Default internal implementation of Widgets
proc init*() =
## Initialize the application
var
o: rawui.InitOptions
err = rawui.init(addr o)
if err != nil:
let msg = $err
freeInitError(err)
raise newException(ValueError, msg)
proc uninit*() =
## Un-Initialize the application
##
## Usually not needed as `mainLoop() <#mainLoop>`_ calls this for you.
rawui.uninit()
proc quit* =
## Quit the application
rawui.quit()
proc quitAll*(errorcode: int = QuitSuccess) =
## Quit both UIng and the program altogether
rawui.quit()
system.quit(errorcode)
proc mainLoop*() =
rawui.main()
rawui.uninit()
proc pollingMainLoop*(poll: proc(timeout: int); timeout: int) =
## Can be used to merge an async event loop with libui-ng's event loop.
##
## Implemented using timeouts and polling because that's the only
## thing that truely composes.
rawui.mainSteps()
while true:
poll(timeout)
discard rawui.mainStep(0) # != 0: break
rawui.uninit()
template newFinal(result) =
#proc finalize(x: type(result)) {.nimcall.} =
# controlDestroy(x.impl)
new result#, finalize
template genCallback(name, typ, on) {.dirty.} =
proc name(w: ptr rawui.typ; data: pointer) {.cdecl.} =
let widget = cast[typ](data)
if widget.on != nil: widget.on(widget)
template genImplProcs(t: untyped) {.dirty.} =
type `Raw t` = ptr[rawui.t]
func impl*(b: t): `Raw t` = cast[`Raw t`](b.internalImpl)
## Gets internal implementation of `b`
func `impl=`*(b: t, r: `Raw t`) = b.internalImpl = pointer(r)
## Sets internal implementation of `b`
# -------------------- Non-Widgets --------------------------------------
# -------- funcs --------
export ForEach
type
TimerProc = ref object
fn: proc(): bool
proc queueMain*(f: proc (data: pointer) {.cdecl.}; data: pointer) =
rawui.queueMain(f, data)
proc mainSteps*() =
rawui.mainSteps()
proc mainStep*(wait: int): bool {.discardable.} =
bool rawui.mainStep(cint wait)
proc wrapTimerProc(data: pointer): cint {.cdecl.} =
let f = cast[TimerProc](data)
result = cint f.fn()
if result == 0: # a result of 0 means to stop the timer
GC_unref f
proc timer*(milliseconds: int; fun: proc (): bool) =
## Call `fun` after `milliseconds` milliseconds.
## This is repeated until `fun` returns `false`.
##
## .. note:: This cannot be called from any thread, unlike
## `queueMain() <#queueMain,proc(pointer),pointer>`_
##
## .. note:: The minimum exact timing, either accuracy (timer burst, etc.)
## or granularity (15ms on Windows, etc.), is OS-defined
# TODO If its "OS-defined" then tell me?
let fn = TimerProc(fn: fun)
GC_ref fn
rawui.timer(cint milliseconds, wrapTimerProc, cast[pointer](fn))
proc free*(str: cstring) = rawui.freeText(str)
## Free the memory of a returned string.
##
## Every time a string is returned from libui, this method should be called.
# -------- Font Descriptor --------
export TextWeight, TextItalic, TextStretch, FontDescriptor
proc loadControlFont*(f: ptr FontDescriptor) =
rawui.loadControlFont f
proc free*(f: ptr FontDescriptor) =
rawui.freeFontDescriptor f
# -------- Area --------
# TODO add documentation for Area
type
Area* = ref object of Widget
handler: ptr AreaHandler
scrolling*: bool
export
WindowResizeEdge,
Modifiers,
ExtKey,
AreaDrawParams,
AreaMouseEvent,
AreaKeyEvent,
AreaHandler
genImplProcs(Area)
proc `size=`*(a: Area, size: tuple[width, height: int]) =
areaSetSize(a.impl, cint size.width, cint size.height)
proc queueRedrawAll*(a: Area) =
areaQueueRedrawAll(a.impl)
proc beginUserWindowMove*(a: Area) =
areaBeginUserWindowMove(a.impl)
proc beginUserWindowResize*(a: Area; edge: WindowResizeEdge) =
areaBeginUserWindowResize(a.impl, edge)
proc scrollTo*(a: Area, x, y, width, height: float) =
areaScrollTo(a.impl, cdouble x, cdouble y, cdouble width, cdouble height)
proc handler*(a: Area): ptr AreaHandler =
a.handler
proc newArea*(ah: ptr AreaHandler): Area =
newFinal result
result.handler = ah
result.impl = rawui.newArea(ah)
proc newScrollingArea*(ah: ptr AreaHandler; width, height: int): Area =
newFinal result
result.handler = ah
result.scrolling = true
result.impl = rawui.newScrollingArea(ah, cint width, cint height)
# -------- Drawing --------
# TODO add documentation for all of this
type
DrawPath* = ref object
internalImpl: pointer
export
DrawMatrix,
DrawFillMode,
DrawBrushType,
DrawLineCap,
DrawLineJoin,
DrawStrokeParams,
DrawDefaultMiterLimit,
DrawBrushGradientStop
genImplProcs(DrawPath)
proc newDrawPath*(fillMode: DrawFillMode): DrawPath =
newFinal result
result.impl = rawui.drawNewPath(fillMode)
proc free*(p: DrawPath) = drawFreePath(p.impl)
proc newFigure*(p: DrawPath; x: float; y: float) = drawPathNewFigure(p.impl, cdouble x, cdouble y)
proc newFigureWithArc*(p: DrawPath; xCenter, yCenter, radius, startAngle, sweep: float; negative: int) =
drawPathNewFigureWithArc(
p.impl,
cdouble xCenter,
cdouble yCenter,
cdouble radius,
cdouble startAngle,
cdouble sweep,
cint negative
)
proc lineTo*(p: DrawPath; x, y: float) =
drawPathLineTo(p.impl, cdouble x, cdouble y)
proc arcTo*(p: DrawPath; xCenter, yCenter, radius, startAngle, sweep: float; negative: int) =
drawPathArcTo(
p.impl,
cdouble xCenter,
cdouble yCenter,
cdouble radius,
cdouble startAngle,
cdouble sweep,
cint negative
)
proc bezierTo*(p: DrawPath; c1x, c1y, c2x, c2y, endX, endY: float) =
drawPathBezierTo(
p.impl,
cdouble c1x,
cdouble c1y,
cdouble c2x,
cdouble c2y,
cdouble endX,
cdouble endY
)
proc closeFigure*(p: DrawPath) = drawPathCloseFigure(p.impl)
proc addRectangle*(p: DrawPath; x, y, width, height: float) =
drawPathAddRectangle(p.impl, cdouble x, cdouble y, cdouble width, cdouble height)
proc ended*(p: DrawPath): bool =
bool drawPathEnded(p.impl)
proc `end`*(p: DrawPath) =
drawPathEnd(p.impl)
proc stroke*(c: ptr DrawContext; path: DrawPath; b: ptr DrawBrush; p: ptr DrawStrokeParams) =
rawui.drawStroke(c, path.impl, b, p)
proc fill*(c: ptr DrawContext; path: DrawPath; b: ptr DrawBrush) =
rawui.drawFill(c, path.impl, b)
proc transform*(c: ptr DrawContext; m: ptr DrawMatrix) =
drawTransform(c, m)
proc setIdentity*(m: ptr DrawMatrix) =
drawMatrixSetIdentity(m)
proc translate*(m: ptr DrawMatrix; x, y: float) =
drawMatrixTranslate(m, cdouble x, cdouble y)
proc scale*(m: ptr DrawMatrix; xCenter, yCenter, x, y: float) =
drawMatrixScale(m, cdouble xCenter, cdouble yCenter, cdouble x, cdouble y)
proc rotate*(m: ptr DrawMatrix; x, y, amount: float) =
drawMatrixRotate(m, cdouble x, cdouble y, cdouble amount)
proc skew*(m: ptr DrawMatrix; x, y, xamount, yamount: float) =
drawMatrixSkew(m, cdouble x, cdouble y, cdouble xamount, cdouble yamount)
proc multiply*(dest, src: ptr DrawMatrix) =
drawMatrixMultiply(dest, src)
proc invertible*(m: ptr DrawMatrix): bool =
bool drawMatrixInvertible(m)
proc invert*(m: ptr DrawMatrix): int =
int drawMatrixInvert(m)
proc transformPoint*(m: ptr DrawMatrix): tuple[x, y: float] =
var x, y: cdouble
drawMatrixTransformPoint(m, addr x, addr y)
result = (x: float x, y: float y)
proc transformSize*(m: ptr DrawMatrix): tuple[x, y: float] =
var x, y: cdouble
drawMatrixTransformSize(m, addr x, addr y)
result = (x: float x, y: float y)
proc clip*(c: ptr DrawContext; path: DrawPath) =
drawClip(c, path.impl)
proc save*(c: ptr DrawContext) =
drawSave(c)
proc restore*(c: ptr DrawContext) =
drawRestore(c)
# -------- Attributes --------
type
Attribute* = ref object
## `Attribute` stores information about an attribute in a
## `AttributedString`.
##
## You do not create `Attribute`s directly; instead, you create a
## `Attribute` of a given type using the specialized constructor
## functions. For every Unicode codepoint in the `AttributedString`,
## at most one value of each attribute type can be applied.
##
## `Attributes` are immutable.
internalImpl: pointer
AttributedString* = ref object
## `AttributedString` represents a string of UTF-8 text that can
## optionally be embellished with formatting attributes. libui-ng
## provides the list of formatting attributes, which cover common
## formatting traits like boldface and color as well as advanced
## typographical features provided by OpenType like superscripts
## and small caps. These attributes can be combined in a variety of
## ways.
##
## Attributes are applied to runs of Unicode codepoints in the string.
## Zero-length runs are elided. Consecutive runs that have the same
## attribute type and value are merged. Each attribute is independent
## of each other attribute; overlapping attributes of different types
## do not split each other apart, but different values of the same
## attribute type do.
##
## The empty string can also be represented by `AttributedString`,
## but because of the no-zero-length-attribute rule, it will not have
## attributes.
##
## A `AttributedString` takes ownership of all attributes given to
## it, as it may need to duplicate or delete Attribute objects at
## any time. By extension, when you free a `AttributedString`,
## all Attributes within will also be freed. Each method will
## describe its own rules in more details.
##
## In addition, `AttributedString` provides facilities for moving
## between grapheme clusters, which represent a character
## from the point of view of the end user. The cursor of a text editor
## is always placed on a grapheme boundary, so you can use these
## features to move the cursor left or right by one "character".
##
## `AttributedString` does not provide enough information to be able
## to draw itself onto a `DrawContext` or respond to user actions.
## In order to do that, you'll need to use a `DrawTextLayout <#DrawTextLayout>`_,
## which is built from the combination of a `AttributedString` and a set
## of layout-specific properties.
internalImpl: pointer
export AttributeType
genImplProcs(Attribute)
genImplProcs(AttributedString)
proc newAttributedString*(initialString: string): AttributedString =
## Creates a new AttributedString from `initialString`.
## The returned string will be entirely unattributed.
newFinal result
result.impl = rawui.newAttributedString(cstring initialString)
proc free*(a: AttributedString) =
## Destroys the AttributedString `a`.
## It will also free all Attributes within.
freeAttributedString(a.impl)
proc `$`*(s: AttributedString): string =
## Returns the textual content of `s` as a string.
let cstr = attributedStringString(s.impl)
result = $cstr
if cstr != nil: freeText(cstr)
proc len*(s: AttributedString): int =
## Returns the number of UTF-8 bytes in the textual content of `s`
int attributedStringLen(s.impl)
proc addUnattributed*(s: AttributedString; str: string) =
## Adds string `str` to the end of `s`.
## The new substring will be unattributed.
attributedStringAppendUnattributed(s.impl, cstring str)
proc insertAtUnattributed*(s: AttributedString; str: string; at: int) =
## Adds the string `str` to `s` at the byte position specified by `at`.
## The new substring will be unattributed; existing attributes will be
## moved along with their text.
attributedStringInsertAtUnattributed(s.impl, cstring str, csize_t at)
proc delete*(s: AttributedString; start, `end`: int) =
## Deletes the characters and attributes of `s` in the byte range
## [`start`, `end`).
attributedStringDelete(s.impl, csize_t start, csize_t `end`)
proc setAttribute*(s: AttributedString; a: Attribute; start, `end`: int) =
## Sets `a` in the byte range [`start`, `end`) of `s`. Any existing
## attributes in that byte range of the same type are removed. You
## should not use `a` after this function returns.
attributedStringSetAttribute(s.impl, a.impl, csize_t start, csize_t `end`)
proc addWithAttributes*(s: AttributedString; str: string; attrs: varargs[Attribute]) =
## Adds string `str` to the end of `s`. The new substring will have
## the attributes `attrs` applied to it.
let
start = s.len
`end` = start + str.len
s.addUnattributed str
for attr in attrs:
s.setAttribute attr, start, `end`
proc addWithAttributes*(s: AttributedString; str: string; attrs: openArray[Attribute]) =
## Adds string `str` to the end of `s`. The new substring will have
## the attributes `attrs` applied to it.
let
start = s.len
`end` = start + str.len
s.addUnattributed str
for attr in attrs:
s.setAttribute attr, start, `end`
type
AttributedStringForEachAttributeFunc = ref object
fun: proc (s: AttributedString; a: Attribute, start, `end`: int): ForEach
proc wrapAttributedStringForEachAttributeFunc(s: ptr rawui.AttributedString;
a: ptr rawui.Attribute; start: csize_t; `end`: csize_t; data: pointer): ForEach {.cdecl.} =
let
f = cast[AttributedStringForEachAttributeFunc](data)
attrstr = new AttributedString
attr = new Attribute
attrstr.impl = s
attr.impl = a
result = f.fun(attrstr, attr, int start, int `end`)
if result == ForEachStop:
GC_unref f
proc forEachAttribute*(str: AttributedString; fun: proc (s: AttributedString; a: Attribute, start, `end`: int): ForEach) =
## enumerates all the Attributes in `str`. Within `fun`, `str`
## still owns the attribute; you can neither free it nor save
## it for later use.
##
## .. error:: You cannot modify `str` in `fun`.
let forEachFunc = AttributedStringForEachAttributeFunc(fun: fun)
GC_ref forEachFunc
attributedStringForEachAttribute(str.impl, wrapAttributedStringForEachAttributeFunc, cast[pointer](forEachFunc))
proc numGraphemes*(s: AttributedString): int =
int attributedStringNumGraphemes(s.impl)
proc byteIndexToGrapheme*(s: AttributedString; pos: int): int =
int attributedStringByteIndexToGrapheme(s.impl, csize_t pos)
proc graphemeToByteIndex*(s: AttributedString; pos: int): int =
int attributedStringGraphemeToByteIndex(s.impl, csize_t pos)
# attribute
proc free*(a: Attribute) =
## Frees a `Attribute`. You generally do not need to
## call this yourself, as `AttributedString` does this for you.
##
## .. error:: It is an error to call this function on a `Attribute`
## that has been given to a `AttributedString`.
##
## You can call this, however, if you created a `Attribute` that
## you aren't going to use later.
freeAttribute(a.impl)
proc getType*(a: Attribute): AttributeType =
## Returns the AttributeType of `a`.
attributeGetType(a.impl)
proc newFamilyAttribute*(family: string): Attribute =
## Creates a new Attribute that changes the
## font family of the text it is applied to.
## Font family names are case-insensitive.
newFinal result
result.impl = rawui.newFamilyAttribute(cstring family)
proc family*(a: Attribute): string =
## Returns the font family stored in `a`.
##
## .. error:: It is an error to call this on a
## `Attribute` that does not hold a font family.
let cstr = attributeFamily(a.impl)
result = $cstr
if cstr != nil: freeText(cstr)
proc newSizeAttribute*(size: float): Attribute =
## Creates a new `Attribute` that changes the
## size of the text it is applied to, in typographical points.
newFinal result
result.impl = rawui.newSizeAttribute(cdouble size)
proc size*(a: Attribute): float =
## Returns the font size stored in `a`.
##
## .. error:: It is an error to
## call this on a `Attribute` that does not hold a font size.
float rawui.attributeSize(a.impl)
export TextWeight, TextItalic
proc newWeightAttribute*(weight: TextWeight): Attribute =
## Creates a new Attribute that changes the
## weight of the text it is applied to.
newFinal result
result.impl = rawui.newWeightAttribute(weight)
proc weight*(a: Attribute): TextWeight =
## Returns the font weight stored in `a`.
##
## .. error:: It is an error
## to call this on a Attribute that does not hold a font weight.
attributeWeight(a.impl)
proc newItalicAttribute*(italic: TextItalic): Attribute =
## Creates a new Attribute that changes the
## italic mode of the text it is applied to.
newFinal result
result.impl = rawui.newItalicAttribute(italic)
proc italic*(a: Attribute): TextItalic =
## Returns the font italic mode stored in `a`.
##
## .. error:: It is an error to call this on a Attribute
## that does not hold a font italic mode.
attributeItalic(a.impl)
export TextStretch
proc newStretchAttribute*(stretch: TextStretch): Attribute =
## Creates a new Attribute that changes the
## stretch of the text it is applied to.
newFinal result
result.impl = rawui.newStretchAttribute(stretch)
proc stretch*(a: Attribute): TextStretch =
## Returns the font stretch stored in `a`.
##
## .. error:: It is an
## error to call this on a Attribute that does not hold a font stretch.
attributeStretch(a.impl)
proc newColorAttribute*(r, g, b: float; a: float = 1.0): Attribute =
## Creates a new Attribute that changes the
## color of the text it is applied to.
##
## .. error:: It is an error to specify an invalid color.
newFinal result
result.impl = rawui.newColorAttribute(r, g, b, a)
proc newColorAttribute*(color: Color; a: float = 1.0): Attribute =
## Creates a new Attribute that changes the
## color of the text it is applied to.
##
## .. error:: It is an error to specify an invalid color.
let (r, g, b) = color.extractRGB()
newFinal result
result.impl = rawui.newColorAttribute(r/255, g/255, b/255, a)
proc color*(a: Attribute): tuple[r, g, b, alpha: float] =
## Returns the text color stored in `a`.
##
## .. error:: It is an error to call this on a Attribute
## that does not hold a text color.
var r, g, b, alpha: cdouble
attributeColor(a.impl, addr r, addr g, addr b, addr alpha)
result = (r: float r, g: float g, b: float b, alpha: float alpha)
proc newBackgroundColorAttribute*(r, g, b: float; a: float = 1.0): Attribute =
## Creates a new Attribute that changes the background color
## of the text it is applied to.
##
## .. error:: It is an error to specify an invalid color.
newFinal result
result.impl = rawui.newBackgroundAttribute(cdouble r, cdouble g, cdouble b, cdouble a)
proc newBackgroundColorAttribute*(color: Color, a: float = 1.0): Attribute =
## Creates a new Attribute that changes the background color
## of the text it is applied to.
##
## .. error:: It is an error to specify an invalid color.
let (r, g, b) = color.extractRGB()
newFinal result
result.impl = rawui.newBackgroundAttribute(cdouble r/255, cdouble g/255, cdouble b/255, cdouble a)
export Underline, UnderlineColor
proc newUnderlineAttribute*(u: Underline): Attribute =
## Creates a new Attribute that changes the type of
## underline on the text it is applied to.
newFinal result
result.impl = rawui.newUnderlineAttribute(u)
proc underline*(a: Attribute): Underline =
## Returns the underline type stored in `a`.
##
## .. error:: It is an error to call this
## on a Attribute that does not hold an
## underline style.
attributeUnderline(a.impl)
proc newUnderlineColorAttribute*(u: UnderlineColor; r = 0.0, g = 0.0, b = 0.0, a: float = 0.0): Attribute =
## Creates a new Attribute that changes the color of the underline on
## the text it is applied to.
##
## .. error:: If the specified color type is `UnderlineColorCustom`, it is an
## error to specify an invalid color value. Otherwise, the color values
## are ignored and should be specified as zero.
newFinal result
result.impl = rawui.newUnderlineColorAttribute(u, cdouble r, cdouble g, cdouble b, cdouble a)
proc newUnderlineColorAttribute*(u: UnderlineColor; color: Color, a: float = 0.0): Attribute =
## Creates a new Attribute that changes the color of the underline on
## the text it is applied to.
##
## .. error:: If the specified color type is `UnderlineColorCustom`, it is an
## error to specify an invalid color value. Otherwise, the color values
## are ignored and should be specified as zero.
let (r, g, b) = color.extractRGB()
newFinal result
result.impl = rawui.newUnderlineColorAttribute(u, cdouble r/255, cdouble g/255, cdouble b/255, cdouble a)
proc underlineColor*(a: Attribute): tuple[u: UnderlineColor, r, g, b, alpha: float] =
## Returns the underline color stored in `a`.
##
## .. error:: It is an error to call this on a Attribute
## that does not hold an underline color.
var r, g, b, alpha: cdouble
var u: UnderlineColor
attributeUnderlineColor(a.impl, addr u, addr r, addr g, addr b, addr alpha)
result = (u: u, r: float r, g: float g, b: float b, alpha: float alpha)
# -------- Open Type Features --------
type
OpenTypeFeatures* = ref object
## OpenTypeFeatures represents a set of OpenType feature
## tag-value pairs, for applying OpenType features to text.
## OpenType feature tags are four-character codes defined by
## OpenType that cover things from design features like small
## caps and swashes to language-specific glyph shapes and
## beyond. Each tag may only appear once in any given
## OpenTypeFeatures instance. Each value is a 32-bit integer,
## often used as a Boolean flag, but sometimes as an index to choose
## a glyph shape to use.
##
## If a font does not support a certain feature, that feature will be
## ignored.
##
## See the OpenType specification at
## https://www.microsoft.com/typography/otspec/featuretags.htm
## for the complete list of available features, information on specific
## features, and how to use them.
internalImpl: pointer
genImplProcs(OpenTypeFeatures)
proc newOpenTypeFeatures*(): OpenTypeFeatures =
## Returns a new OpenTypeFeatures instance, with no tags yet added.
newFinal result
result.impl = rawui.newOpenTypeFeatures()
proc free*(otf: OpenTypeFeatures) =
## Frees `otf`
freeOpenTypeFeatures(otf.impl)
proc clone*(otf: OpenTypeFeatures): OpenTypeFeatures =
## Makes a copy of `otf` and returns it.
## Changing one will not affect the other.
newFinal result
result.impl = openTypeFeaturesClone(otf.impl)
proc add*(otf: OpenTypeFeatures; a, b, c, d: char, value: uint32) =
## Adds the given feature tag and value to otf.
## The feature tag is specified by a, b, c, and d. If there is
## already a value associated with the specified tag in otf, the old
## value is removed.
openTypeFeaturesAdd(otf.impl, a, b, c, d, value)
proc add*(otf: OpenTypeFeatures; abcd: string, value: uint32 | bool) =
## Alias of `add <#add,OpenTypeFeatures,char,char,char,char,uint32>`_.
## `a`, `b`, `c`, and `d` are instead a string of 4 characters, each
## character representing `a`, `b`, `c`, and `d` respectively.
if abcd.len != 4:
raise newException(ValueError, "String has an invalid length; it must have a length of 4.")
openTypeFeaturesAdd(otf.impl, abcd[0], abcd[1], abcd[2], abcd[3], uint32 value)
proc remove*(otf: OpenTypeFeatures; a, b, c, d: char) =
## Removes the given feature tag and value from otf.
## If the tag is not present in otf, this function does nothing.
openTypeFeaturesRemove(otf.impl, a, b, c, d)
proc remove*(otf: OpenTypeFeatures; abcd: string) =
## Alias of `remove <#remove,OpenTypeFeatures,char,char,char,char>`_.
## `a`, `b`, `c`, and `d` are instead a string of 4 characters, each
## character representing `a`, `b`, `c`, and `d` respectively.
if abcd.len != 4:
raise newException(ValueError, "String has an invalid length; it must have a length of 4.")
openTypeFeaturesRemove(otf.impl, abcd[0], abcd[1], abcd[2], abcd[3])
proc get*(otf: OpenTypeFeatures; a, b, c, d: char, value: var int): bool =
## Determines whether the given feature tag is present in `otf`.
## If it is, `value` is set to the tag's value and
## `true` is returned. Otherwise, `false` is returned.
##
## Note that if this function returns `false`, `value` isn't
## changed. This is important: if a feature is not present in a
## `OpenTypeFeatures`, the feature is **NOT** treated as if its
## value was zero anyway. Script-specific font shaping rules and
## font-specific feature settings may use a different default value
## for a feature. You should likewise not treat a missing feature as
## having a value of zero either. Instead, a missing feature should
## be treated as having some unspecified default value.
var val = uint32 value
result = bool openTypeFeaturesGet(otf.impl, a, b, c, d, addr val)
value = int val
proc get*(otf: OpenTypeFeatures; abcd: string, value: var int): bool =
## Alias of `get <#get,OpenTypeFeatures,char,char,char,char,uint32>`_.
## `a`, `b`, `c`, and `d` are instead a string of 4 characters, each
## character representing `a`, `b`, `c`, and `d` respectively.
if abcd.len != 4:
raise newException(ValueError, "String has an invalid length; it must have a length of 4.")
otf.get(abcd[0], abcd[1], abcd[2], abcd[3], value)
type
OpenTypeFeaturesForEachFunc = ref object
fun: proc (otf: OpenTypeFeatures; abcd: string; value: int): ForEach
proc wrapOpenTypeFeaturesForEachFunc(otf: ptr rawui.OpenTypeFeatures; a, b, c, d: char; value: uint32;
data: pointer): ForEach {.cdecl.} =
let
f = cast[OpenTypeFeaturesForEachFunc](data)
openType = new OpenTypeFeatures
openType.impl = otf
result = f.fun(openType, a & b & c & d, int value)
if result == ForEachStop:
GC_unref f
proc forEach*(otf: OpenTypeFeatures; f: proc (otf: OpenTypeFeatures; abcd: string; value: int): ForEach) =
## Executes `f` for every tag-value pair in `otf`.
## The enumeration order is unspecified.
##
## .. error:: You cannot modify `otf` while this function
## is running.
let forEachFunc = OpenTypeFeaturesForEachFunc(fun: f)
GC_ref forEachFunc
openTypeFeaturesForEach(otf.impl, wrapOpenTypeFeaturesForEachFunc, cast[pointer](forEachFunc))
proc newFeaturesAttribute*(otf: OpenTypeFeatures): Attribute =
## Creates a and returns new Attribute that changes
## the font family of the text it is applied to. otf is copied; you may
## free it after this function returns.
newFinal result
result.impl = rawui.newFeaturesAttribute(otf.impl)
proc features*(a: Attribute): OpenTypeFeatures =
## Returns the OpenType features stored in `a`.
##
## .. error:: It is an error to call this on a Attribute
## that does not hold OpenType features.
newFinal result
result.impl = rawui.attributeFeatures(a.impl)
# -------- Draw Text --------
type
DrawTextLayout* = ref object
## `DrawTextLayout` is a concrete representation of a
## `AttributedString` that can be displayed in a `DrawContext`.
## It includes information important for the drawing of a block of
## text, including the bounding box to wrap the text within, the
## alignment of lines of text within that box, areas to mark as
## being selected, and other things.
##
## Unlike `AttributedString`, the content of a `DrawTextLayout` is
## immutable once it has been created.
##
## .. note:: There are OS-specific differences with text drawing
## that libui-ng can't account for
internalImpl: pointer
export
DrawTextAlign,
DrawTextLayoutParams,
DrawContext,
DrawBrush,
DrawBrushType
genImplProcs(DrawTextLayout)
proc newDrawTextLayout*(params: ptr DrawTextLayoutParams): DrawTextLayout =
## Creates a new DrawTextLayout from the given parameters `params`.
newFinal result
result.impl = drawNewTextLayout(params)
proc free*(tl: DrawTextLayout) =
## Frees `tl`. The underlying `AttributedString` is not freed.
drawFreeTextLayout(tl.impl)
proc drawText*(c: ptr DrawContext; tl: DrawTextLayout; point: tuple[x, y: float]) =
## Draws `tl` in `c` with the top-left point of `tl` at (`point.x`, `point.y`).
rawui.drawText(c, tl.impl, cdouble point.x, cdouble point.y)
proc extents*(tl: DrawTextLayout): tuple[width, height: float] =
## Returns the width and height of `tl`.
## The returned width may be smaller than the width passed
## into `newDrawTextLayout() <#newDrawTextLayout,ptr.DrawTextLayoutParams>`_
## depending on how the text in `tl` is wrapped. Therefore,
## you can use this function to get the actual size of the
## text layout.
var w, h: cdouble
drawTextLayoutExtents(tl.impl, addr w, addr h)
result = (width: float w, height: float h)
# ------------------- Widgets --------------------------------------
# ------------------- Button --------------------------------------
type
Button* = ref object of Widget
## A widget that visually represents a button
## to be clicked by the user to trigger an action.
onclick*: proc (sender: Button) ## callback for when the button is clicked.
genCallback wrapOnClick, Button, onclick
genImplProcs(Button)
proc text*(b: Button): string =
## Returns the button label text.
let cstr = buttonText(b.impl)
result = $cstr
if cstr != nil: freeText(cstr)
proc `text=`*(b: Button; text: string) =
## Sets the button label text.
##
## :b: Button instance
## :text: Label text
buttonSetText(b.impl, text)
proc newButton*(text: string; onclick: proc(sender: Button) = nil): Button =
## Creates and returns a new button.
##
## :text: Button label text
## :onclick: callback for when the button is clicked.
newFinal(result)
result.impl = rawui.newButton(text)
result.onclick = onclick
result.impl.buttonOnClicked(wrapOnClick, cast[pointer](result))
# ------------------------ RadioButtons ----------------------------
type
RadioButtons* = ref object of Widget
## A multiple choice widget of check buttons from which only one can be selected at a time.
items*: seq[string] ## Seq of text of the radio buttons
onselected*: proc(sender: RadioButtons) ## Callback for when radio button is selected.
genImplProcs(RadioButtons)
proc add*(r: RadioButtons; items: varargs[string, `$`]) =
## Appends a radio button.
##
## :r: RadioButtons instance.
## :items: Radio button text(s).
for text in items:
radioButtonsAppend(r.impl, cstring text)
r.items.add text
proc selected*(r: RadioButtons): int =
## Returns the index of the item selected.
##
## :r: RadioButtons instance.
radioButtonsSelected(r.impl)
proc `selected=`*(r: RadioButtons, index: int) =
## Sets the item selected.
##
## :r: RadioButtons instance.
## :index: Index of the item to be selected, `-1` to clear selection.