-
Notifications
You must be signed in to change notification settings - Fork 6
/
koi.nim
executable file
·7915 lines (6162 loc) · 212 KB
/
koi.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
import std/hashes
import std/json
import std/lenientops
import std/math
import std/options
import std/sequtils
import std/sets
import std/setutils
import std/strformat
import std/strutils
import std/tables
import std/unicode
import glfw
import nanovg
import koi/deps/with
import koi/glad/gl
import koi/rect
import koi/ringbuffer
import koi/utils
export CursorShape
# {{{ Types
type ItemId* = int64
# {{{ DrawLayer*
#
type
DrawLayer* = enum
layerDefault,
layerDialog,
layerPopup,
layerWidgetOverlay,
layerTooltip,
layerGlobalOverlay,
layerWindowDecoration
# }}}
# {{{ ColorPickerState
type
ColorPickerColorMode = enum
ccmRGB, ccmHSV, ccmHex
ColorPickerMouseMode = enum
cmmNormal, cmmLMBDown, cmmDragWheel, cmmDragTriangle
ColorPickerStateVars = object
opened: bool
colorMode: ColorPickerColorMode
lastColorMode: ColorPickerColorMode
mouseMode: ColorPickerMouseMode
activeItem: ItemId
h, s, v: float
hexString: string
lastHue: float
colorCopyBuffer: Color
# }}}
# {{{ DialogState
type
DialogStateVars = object
widgetInsidePopupCapturedFocus: bool
# }}}
# {{{ DropDownState
type
DropDownState = enum
dsClosed, dsOpenLMBPressed, dsOpen
DropDownStateVars = ref object of RootObj
state: DropDownState
# Drop-down in open mode, 0 if no drop-down is open currently
activeItem: ItemId
# The item list is displayed starting from the item with this index
displayStartItem: float
# }}}
# {{{ PopupState
type
PopupState = enum
psOpenLMBDown, psOpen
PopupStateVars = object
state: PopupState
prevLayer: DrawLayer
closed: bool
widgetInsidePopupCapturedFocus: bool
# }}}
# {{{ RadioButtonState
type
RadioButtonStateVars = object
activeItem: ItemId
# }}}
# {{{ SectionHeaderState
type
SectionHeaderStateVars = object
openSubHeaders: bool
# }}}
# {{{ ScrollBarState
type
ScrollBarState = enum
sbsDefault,
sbsDragNormal,
sbsDragHidden,
sbsTrackClickFirst,
sbsTrackClickDelay,
sbsTrackClickRepeat
ScrollBarStateVars = object
state: ScrollBarState
# Set when the LMB is pressed inside the scroll bar's track but outside of
# the knob:
# -1 = LMB pressed on the left side of the knob
# 1 = LMB pressed on the right side of the knob
clickDir: float
# }}}
# {{{ ScrollViewState
type
ScrollViewStateVars = object
activeItem: ItemId
# }}}
# {{{ SliderState
type
SliderState = enum
ssDefault,
ssDragHidden,
ssEditValue,
ssCancel
SliderStateVars = object
state: SliderState
# Whether the cursor was moved before releasing the LMB in drag mode
cursorMoved: bool
cursorPosX: float
cursorPosY: float
valueText: string
editModeItem: ItemId
textFieldId: ItemId
oldValue: float
# }}}
# {{{ TextAreaState
type
TextSelection = object
# Rune position of the start of the selection (inclusive),
# -1 if nothing is selected
startPos: int
# Rune position of the end of the selection (exclusive)
endPos: Natural
type
TextAreaState = enum
tasDefault
tasEditLMBPressed,
tasEdit
tasDragStart,
tasDoubleClicked
TextAreaStateVars = ref object of RootObj
state: TextAreaState
# The cursor is before the Rune with this index. If the cursor is at the end
# of the text, the cursor pos equals the length of the text. From this
# follows that the cursor position for an empty string is 0.
cursorPos: Natural
# Current text selection
selection: TextSelection
# Text area item in edit mode, 0 if no text area is being edited
activeItem: ItemId
# The text is displayed starting from the row with this index
displayStartRow: float
# The original text is stored when going into edit mode so it can be
# restored if the editing is cancelled
originalText: string
# Used by the move cursor to next/previous line actions
lastCursorXPos: Option[float]
# }}}
# {{{ TextFieldState
type
TextFieldState = enum
tfsDefault,
tfsEditLMBPressed,
tfsEdit
tfsDragStart,
tfsDragDelay,
tfsDragScroll,
tfsDoubleClicked
TextFieldStateVars = object
state: TextFieldState
# The cursor is before the Rune with this index. If the cursor is at the end
# of the text, the cursor pos equals the length of the text. From this
# follows that the cursor position for an empty string is 0.
cursorPos: Natural
# Current text selection
selection: TextSelection
# Text field item in edit mode, 0 if no text field is being edited
activeItem: ItemId
# The text is displayed starting from the Rune with this index
displayStartPos: Natural
# The text will be drawn at thix X coordinate (can be smaller than the
# starting X coordinate of the textbox)
displayStartX: float
# The original text is stored when going into edit mode so it can be
# restored if the editing is cancelled
originalText: string
# }}}
# {{{ TooltipState
type
TooltipState = enum
tsOff, tsShowDelay, tsShow, tsFadeOutDelay, tsFadeOut
TooltipStateVars = object
state: TooltipState
lastState: TooltipState
# Used for the various tooltip delays & timeouts
t0: float
text: string
# Hot item from the last frame
lastHotItem: ItemId
# }}}
# {{{ WidgetState*
type WidgetState* = enum
wsNormal, wsHover, wsDown,
wsActive, wsActiveHover, wsActiveDown,
wsDisabled
# }}}
# {{{ WidgetGrouping
type WidgetGrouping = enum
wgNone, wgStart, wgMiddle, wgEnd
# }}}
# {{{ UIState
type
EventKind* = enum
ekKey, ekMouseButton, ekScroll
Event* = object
case kind*: EventKind
of ekKey:
key*: Key
action*: KeyAction
of ekMouseButton:
button*: MouseButton
pressed*: bool
x*, y*: float64
of ekScroll:
ox*, oy*: float64
mods*: set[ModifierKey]
UIState = object
# General state
# *************
hasEvent: bool
currEvent: Event
eventHandled: bool
# Frames left to render; this is decremented in endFrame()
framesLeft: Natural
# Scale factor
scale: float
# This is the draw layer all widgets will draw on
# TODO bit hacky, it's needed only for drawing the CSD decoration on top
# of everything
currentLayer: DrawLayer
# Window dimensions (in virtual pixels)
winWidth, winHeight: float
# Set if a widget has captured the focus (e.g., a textfield in edit mode)
# so all other UI interactions (hovers, tooltips, etc.) should be disabled
focusCaptured: bool
tooltipState: TooltipStateVars
# True if a dialog is currently open
dialogOpen: bool
# Reset to empty seq at the start of the frame
drawOffsetStack: seq[DrawOffset]
# Hit checking clip rectangle (e.g., when inside a scrollview)
# TODO should dialog and popup use this as well? or instead of
# focuscaptured?
hitClipRect: Rect
oldHitClipRect: Rect
# Mouse state
# -----------
mx, my: float
# When widgetMouseDrag is true, only dx and dy are updated instead
# of mx and my
widgetMouseDrag: bool
dx, dy: float
# Mouse cursor position from the last frame
lastmx, lastmy: float
mbLeftDown: bool
mbRightDown: bool
mbMiddleDown: bool
# Time and position of the last left mouse button down event (for
# double-click detenction)
mbLeftDownT: float
mbLeftDownX: float
mbLeftDownY: float
lastMbLeftDownT: float
lastMbLeftDownX: float
lastMbLeftDownY: float
cursorShape: CursorShape
# Keyboard state
# --------------
keyStates: array[ord(Key.high), bool]
# Active & hot items
# ------------------
hotItem: ItemId # reset at the start of the frame to 0
activeItem: ItemId
# General purpose widget states
# -----------------------------
# For relative mouse movement calculations
x0, y0: float
# For delays & timeouts
t0: float
# For keeping track of the cursor in hidden drag mode.
# Dragging can be only active along the X or Y-axis, but not both:
# - in horizontal drag mode: dragX >= 0, dragY < 0
# - in vertical drag mode: dragX < 0, dragY >= 0
dragX, dragY: float
# Widget-specific states
# **********************
# Global widget states (per widget type)
colorPickerState: ColorPickerStateVars
dialogState: DialogStateVars
popupState: PopupStateVars
radioButtonState: RadioButtonStateVars
scrollBarState: ScrollBarStateVars
scrollViewState: ScrollViewStateVars
sectionHeaderState: SectionHeaderStateVars
sliderState: SliderStateVars
textFieldState: TextFieldStateVars
# Per-instance data storage for widgets that require it (e.g., ScrollView)
itemState: Table[ItemId, ref RootObj]
# Auto-layout
# ***********
autoLayoutParams: AutoLayoutParams
autoLayoutState: AutoLayoutStateVars
# Tab-activation
# **************
tabActivationState: TabActivationStateVars
DrawOffset = object
# Origin offset, used for relative coordinate handling (e.g., in dialogs)
ox, oy: float
AutoLayoutParams* = object
itemsPerRow*: Natural
rowWidth*: float
# Replace with table of 'itemsPerRow' number of column widths
labelWidth*: float
sectionPad*: float
leftPad*: float
rightPad*: float
rowPad*: float
rowGroupPad*: float
defaultRowHeight*: float
defaultItemHeight*: float
AutoLayoutStateVars = object
rowWidth: float
rowHeight: float
x, y: float
currColIndex: Natural
nextRowHeight: Option[float]
nextItemWidth: float
nextItemHeight: float
firstRow: bool
prevSection: bool
groupBegin: bool
TabActivationStateVars = object
prevItem: ItemId
itemToActivate: ItemId
activateNext: bool
activatePrev: bool
# }}}
# }}}
# {{{ Globals
var
g_nvgContext: NVGContext
g_uiState: UIState
g_cursorArrow: Cursor
g_cursorIBeam: Cursor
g_cursorCrosshair: Cursor
g_cursorHand: Cursor
g_cursorResizeEW: Cursor
g_cursorResizeNS: Cursor
g_cursorResizeNWSE: Cursor
g_cursorResizeNESW: Cursor
g_cursorResizeAll: Cursor
let
HighlightColor = rgb(1.0, 0.65, 0.0)
HighlightLowColor = rgb(0.9, 0.55, 0.0)
# }}}
# {{{ Configuration
# TODO these could become settable global parameters
const
TooltipShowDelay = 0.4
TooltipFadeOutDelay = 0.1
TooltipFadeOutDuration = 0.4
TextFieldScrollDelay = 0.1
ScrollBarFineDragDivisor = 10.0
ScrollBarUltraFineDragDivisor = 100.0
ScrollBarTrackClickRepeatDelay = 0.3
ScrollBarTrackClickRepeatTimeout = 0.05
SliderFineDragDivisor = 10.0
SliderUltraFineDragDivisor = 100.0
# TODO make it a font param for every widget
TextVertAlignFactor = 0.55
DoubleClickMaxDelay = 0.1
DoubleClickMaxXOffs = 4.0
DoubleClickMaxYOffs = 4.0
WindowEdgePad = 10.0
# }}}
# {{{ Event helpers
func hashId*(id: string): ItemId =
let hash32 = hash(id).uint32
# Make sure the IDs are always positive integers
let h = int64(hash32) - int32.low + 1
assert h > 0
h
func mkIdString*(filename: string, line: int, id: string): string =
result = filename & ":" & $line & ":" & id
var g_nextIdString: string
var g_lastIdString: string
proc generateId*(filename: string, line: int, id: string = ""): ItemId =
let idString = mkIdString(filename, line, id)
g_lastIdString = idString
hashId(idString)
proc getNextId*(filename: string, line: int, id: string = ""): ItemId =
if g_nextIdString == "":
result = generateId(filename, line, id)
else:
result = hashId(g_nextIdString)
g_nextIdString = ""
proc lastIdString*(): string = g_lastIdString
proc setNextId*(id: string) =
g_nextIdString = id
proc setFramesLeft*(n: Natural = 5) =
alias(ui, g_uiState)
ui.framesLeft = 5
proc mouseInside*(x, y, w, h: float): bool =
alias(ui, g_uiState)
ui.mx >= x and ui.mx <= x+w and
ui.my >= y and ui.my <= y+h
proc isHot*(id: ItemId): bool =
g_uiState.hotItem == id
proc setHot*(id: ItemId) =
alias(ui, g_uiState)
ui.hotItem = id
proc isActive*(id: ItemId): bool =
g_uiState.activeItem == id
proc setActive*(id: ItemId) =
g_uiState.activeItem = id
proc hasHotItem*(): bool =
g_uiState.hotItem > 0
proc hasNoActiveItem*(): bool =
g_uiState.activeItem == 0
proc hasActiveItem*(): bool =
g_uiState.activeItem > 0
proc isDialogOpen*(): bool =
g_uiState.dialogOpen
proc setHitClip*(x, y, w, h: float) =
alias(ui, g_uiState)
ui.hitClipRect = rect(x, y, w, h)
proc resetHitClip*() =
alias(ui, g_uiState)
ui.hitClipRect = rect(0, 0, ui.winWidth, ui.winHeight)
proc focusCaptured*(): bool = g_uiState.focusCaptured
proc setFocusCaptured*(c: bool) =
g_uiState.focusCaptured = c
proc isHit*(x, y, w, h: float): bool =
alias(ui, g_uiState)
let r = rect(x, y, w, h).intersect(ui.hitClipRect)
if r.isSome:
let r = r.get
result = not ui.focusCaptured and mouseInside(r.x, r.y, r.w, r.h)
else:
result = false
proc winWidth*(): float = g_uiState.winWidth
proc winHeight*(): float = g_uiState.winHeight
proc mx*(): float = g_uiState.mx
proc my*(): float = g_uiState.my
proc lastmx*(): float = g_uiState.lastmx
proc lastmy*(): float = g_uiState.lastmy
proc hasEvent*(): bool =
alias(ui, g_uiState)
not ui.focusCaptured and ui.hasEvent and (not ui.eventHandled)
proc currEvent*(): Event = g_uiState.currEvent
proc eventHandled*(): bool = g_uiState.eventHandled
proc setEventHandled*() = g_uiState.eventHandled = true
proc mbLeftDown*(): bool = g_uiState.mbLeftDown
proc mbRightDown*(): bool = g_uiState.mbRightDown
proc mbMiddleDown*(): bool = g_uiState.mbMiddleDown
proc isKeyDown*(key: Key): bool =
if key == keyUnknown: false
else: g_uiState.keyStates[ord(key)]
proc shiftDown*(): bool = isKeyDown(keyLeftShift) or isKeyDown(keyRightShift)
proc altDown*(): bool = isKeyDown(keyLeftAlt) or isKeyDown(keyRightAlt)
proc ctrlDown*(): bool = isKeyDown(keyLeftControl) or isKeyDown(keyRightControl)
proc superDown*(): bool = isKeyDown(keyLeftSuper) or isKeyDown(keyRightSuper)
# }}}
# {{{ Drawing & widget utils
# {{{ getPxRatio*()
proc getPxRatio*(): float =
let win = glfw.currentContext()
let (winWidth, _) = win.size
let (fbWidth, _) = win.framebufferSize
result = fbWidth / (winWidth / g_uiState.scale)
# }}}
# {{{ snapToGrid*()
func snapToGrid*(x, y, w, h: float,
strokeWidth: float = 0.0): (float, float, float, float) =
let s = (strokeWidth mod 2) * 0.5
let
x = round(x) - s
y = round(y) - s
w = round(w) + s*2
h = round(h) + s*2
result = (x, y, w, h)
# }}}
# {{{ fitRectWithinWindow*()
proc fitRectWithinWindow*(w, h: float, ax, ay, aw, ah: float,
align: HorizontalAlign): (float, float) =
alias(ui, g_uiState)
var x = case align
of haLeft: ax
of haCenter: ax+aw*0.5 - w*0.5
of haRight: ax+aw
var y = ay+ah
let pad = WindowEdgePad
if x+w > ui.winWidth - pad: x = ax+aw - w
if y+h > ui.winHeight - pad: y = ay-h
if x < pad: x = pad
elif x+w > ui.winWidth - pad: x = ui.winWidth - pad - w
if y < pad: y = pad
elif y+h > ui.winHeight - pad: y = ui.winHeight - pad - h
result = (x, y)
# }}}
# {{{ setFont*()
proc setFont*(vg: NVGContext, size: float, name: string = "sans-bold",
horizAlign: HorizontalAlign = haLeft,
vertAlign: VerticalAlign = vaMiddle) =
vg.fontFace(name)
vg.fontSize(size)
vg.textAlign(horizAlign, vertAlign)
# }}}
# {{{ textBreakLines*()
type
TextRow* = object
startPos*: Natural
startBytePos*: Natural
endPos*: Natural
endBytePos*: Natural
nextRowPos*: int
nextRowBytePos*: int
width*: float
# TODO
# minX*: cfloat
# maxX*: cfloat
const TextBreakRunes = @[
# Breaking spaces
"\u0020", # space
"\u2000", # en quad
"\u2001", # em quad
"\u2002", # en space
"\u2003", # em space
"\u2004", # three-per-em space
"\u2005", # four-per-em space
"\u2006", # six-per-em space
"\u2008", # punctuation space
"\u2009", # thin space
"\u200a", # hair space
"\u205f", # medium mathematical space
"\u3000", # ideographic space
# Breaking hyphens
"\u002d", # hyphen-minus
"\u00ad", # soft hyphen (shy)
"\u2010", # hyphen
"\u2012", # figure dash
"\u2013", # en dash
"\u007c", # vertical line
].mapIt(it.runeAt(0))
# TODO support for start & end pos
proc textBreakLines*(text: string, maxWidth: float,
maxRows: int = -1): seq[TextRow] =
# TODO use global expandable array
var glyphs: array[1024, GlyphPosition]
result = newSeq[TextRow]()
if text == "":
return @[TextRow(
startPos: 0,
startBytePos: 0,
endPos: 0,
endBytePos: 0,
nextRowPos: -1,
nextRowBytePos: -1,
width: 0
)]
let textLen = text.runeLen
proc fillGlyphsBuffer(textPos, textBytePos: Natural) =
glyphs[0] = glyphs[^2]
glyphs[1] = glyphs[^1]
# TODO using maxX as the next start pos might not be entirely accurate
# we should use the x pos of the next glyph
discard g_nvgContext.textGlyphPositions(glyphs[1].maxX, 0, text,
startPos = textBytePos,
toOpenArray(glyphs, 2, glyphs.high))
const
NewLine = "\n".runeAt(0)
var
prevRune: Rune
textPos = 0 # current rune position
textBytePos = 0 # byte offset of the current rune
prevTextPos = 0
prevTextBytePos = 0
# glyphPos is ahead by 1 rune, so glyphs[glyphPos].x will give us the end
# of the current rune
glyphPos = 3
rowStartPos, rowStartBytePos: Natural
rowStartX = glyphs[0].x
lastBreakPos = -1
lastBreakBytePos = -1
lastBreakPosStartX: float
lastBreakPosPrev, lastBreakBytePosPrev: Natural
fillGlyphsBuffer(textPos, textBytePos)
for rune in text.runes:
if glyphPos >= glyphs.len:
fillGlyphsBuffer(textPos, textBytePos)
glyphPos = 2
if rune == NewLine and prevRune != NewLine:
discard
else:
if prevRune == NewLine:
# we're at the rune after the endline
let newLineEndX = glyphs[glyphPos-1].x
let runeBeforeNewLineEndX = glyphs[glyphPos-2].x
let row = TextRow(
startPos: rowStartPos,
startBytePos: rowStartBytePos,
endPos: prevTextPos,
endBytePos: prevTextBytePos,
nextRowPos: textPos,
nextRowBytePos: textBytePos,
width: runeBeforeNewLineEndX - rowStartX
)
result.add(row)
rowStartPos = row.nextRowPos
rowStartBytePos = row.nextRowBytePos
rowStartX = newLineEndX
lastBreakPos = -1
lastBreakBytePos = -1
else: # not a new line
# are we at the start of a new word?
if prevRune in TextBreakRunes and rune notin TextBreakRunes:
lastBreakPos = textPos
lastBreakBytePos = textBytePos
lastBreakPosPrev = prevTextPos
lastBreakBytePosPrev = prevTextBytePos
let prevRuneEndX = glyphs[glyphPos-1].x
lastBreakPosStartX = prevRuneEndX
let currRuneEndX = glyphs[glyphPos].x
if currRuneEndX - rowStartX > maxWidth:
# break line at the last found break position
if lastBreakPos > 0:
let row = TextRow(
startPos: rowStartPos,
startBytePos: rowStartBytePos,
endPos: lastBreakPosPrev,
endBytePos: lastBreakBytePosPrev,
nextRowPos: lastBreakPos,
nextRowBytePos: lastBreakBytePos,
width: lastBreakPosStartX - rowStartX
)
result.add(row)
rowStartPos = row.nextRowPos
rowStartBytePos = row.nextRowBytePos
rowStartX = lastBreakPosStartX
lastBreakPos = -1
lastBreakBytePos = -1
# no break position has been found (the line is basically a single
# long word)
else:
let prevRuneEndX = glyphs[glyphPos-1].x
let row = TextRow(
startPos: rowStartPos,
startBytePos: rowStartBytePos,
endPos: prevTextPos,
endBytePos: prevTextBytePos,
nextRowPos: textPos,
nextRowBytePos: textBytePos,
width: prevRuneEndX - rowStartX
)
result.add(row)
rowStartPos = row.nextRowPos
rowStartBytePos = row.nextRowBytePos
rowStartX = prevRuneEndX
lastBreakPos = -1
lastBreakBytePos = -1
# flush last row if we're processing the last rune
if textPos == textLen-1:
if rune == NewLine:
let runeBeforeNewLineEndX = glyphs[glyphPos-1].x
let lastEmptyRowStartPos = textLen
let lastEmptyRowStartBytePos = textBytePos+1
result.add(TextRow(
startPos: rowStartPos,
startBytePos: rowStartBytePos,
endPos: textPos,
endBytePos: textBytePos,
nextRowPos: lastEmptyRowStartPos,
nextRowBytePos: lastEmptyRowStartBytePos,
width: runeBeforeNewLineEndX - rowStartX
))
result.add(TextRow(
startPos: lastEmptyRowStartPos,
startBytePos: lastEmptyRowStartBytePos,
endPos: lastEmptyRowStartPos,
endBytePos: lastEmptyRowStartBytePos,
nextRowPos: -1,
nextRowBytePos: -1,
width: 0
))
else:
let currRuneEndX = glyphs[glyphPos].x
result.add(TextRow(
startPos: rowStartPos,
startBytePos: rowStartBytePos,
endPos: textPos,
endBytePos: textBytePos,
nextRowPos: -1,
nextRowBytePos: -1,
width: currRuneEndX - rowStartX
))
prevRune = rune
prevTextPos = textPos
prevTextBytePos = textBytePos
inc(textPos)
inc(textBytePos, rune.size)
inc(glyphPos)
# }}}
# {{{ pushDrawOffset*()
proc pushDrawOffset*(ds: DrawOffset) =
g_uiState.drawOffsetStack.add(ds)
# }}}
# {{{ popDrawOffset*()
proc popDrawOffset*() =
alias(ui, g_uiState)
if ui.drawOffsetStack.len > 1:
discard ui.drawOffsetStack.pop()
# }}}
# {{{ drawOffset*()
proc drawOffset(): DrawOffset =
g_uiState.drawOffsetStack[^1]
# }}}
# {{{ addDrawOffset*()
proc addDrawOffset*(x, y: float): (float, float) =
let offs = drawOffset()
result = (offs.ox + x, offs.oy + y)
# }}}
# {{{ toHex*()
func toHex*(c: Color): string =
const RgbMax = 255
(c.r * RgbMax).int.toHex(2) &
(c.g * RgbMax).int.toHex(2) &
(c.b * RgbMax).int.toHex(2)
# }}}
# {{{ colorFromHex*()
func colorFromHexStr*(s: string): Color =
const RgbMax = 255
try:
let r = parseHexInt(s.substr(0, 1)) / RgbMax
let g = parseHexInt(s.substr(2, 3)) / RgbMax
let b = parseHexInt(s.substr(4, 5)) / RgbMax
result = rgb(r, g, b)
except CatchableError:
discard
# }}}
# {{{ rightClippedRoundedRect*()
proc rightClippedRoundedRect*(vg: NVGContext, x, y, w, h, r, clipW: float,
grouping: WidgetGrouping = wgNone) =
alias(vg, g_nvgContext)
vg.beginPath()
if grouping == wgMiddle:
vg.rect(x, y, clipW, h)
else:
if clipW < r:
# top left
if grouping == wgEnd:
vg.moveTo(x, y)
vg.lineTo(x+clipW, y)
else:
let da = arccos((r - clipW) / r)
vg.arc(x+r, y+r, r, PI, PI + da, pwCW)
# bottom left
if grouping == wgStart:
vg.lineTo(x+clipW, y+h)
vg.lineTo(x, y+h)
else:
let da = arccos((r - clipW) / r)
vg.arc(x+r, y+h-r, r, PI - da, PI, pwCW)
vg.closePath()
elif clipW <= w-r:
# top left