forked from SolarLune/masterplan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgui.go
1395 lines (1080 loc) · 34.9 KB
/
gui.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 main
import (
"bufio"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/atotto/clipboard"
rl "github.com/gen2brain/raylib-go/raylib"
)
const (
GUI_OUTLINE = "GUI_OUTLINE"
GUI_OUTLINE_HIGHLIGHTED = "GUI_OUTLINE_HIGHLIGHTED"
GUI_OUTLINE_DISABLED = "GUI_OUTLINE_DISABLED"
GUI_INSIDE = "GUI_INSIDE"
GUI_INSIDE_HIGHLIGHTED = "GUI_INSIDE_HIGHLIGHTED"
GUI_INSIDE_DISABLED = "GUI_INSIDE_DISABLED"
GUI_FONT_COLOR = "GUI_FONT_COLOR"
GUI_NOTE_COLOR = "GUI_NOTE_COLOR"
GUI_SHADOW_COLOR = "GUI_SHADOW_COLOR"
)
const (
TEXTBOX_ALIGN_LEFT = iota
TEXTBOX_ALIGN_CENTER
TEXTBOX_ALIGN_RIGHT
TEXTBOX_ALIGN_UPPER = iota
_ // Center works for this, too
TEXTBOX_ALIGN_BOTTOM
)
var currentTheme = "Sunlight" // Default theme for new projects and new sessions is the Sunlight theme
var guiColors map[string]map[string]rl.Color
func getThemeColor(colorConstant string) rl.Color {
return guiColors[currentTheme][colorConstant]
}
func loadThemes() {
newGUIColors := map[string]map[string]rl.Color{}
filepath.Walk(GetPath("assets", "themes"), func(fp string, info os.FileInfo, err error) error {
if !info.IsDir() {
themeFile, err := os.Open(fp)
if err == nil {
defer themeFile.Close()
_, themeName := filepath.Split(fp)
themeName = strings.Split(themeName, ".json")[0]
// themeData := []byte{}
themeData := ""
var jsonData map[string][]uint8
scanner := bufio.NewScanner(themeFile)
for scanner.Scan() {
// themeData = append(themeData, scanner.Bytes()...)
themeData += scanner.Text()
}
json.Unmarshal([]byte(themeData), &jsonData)
// A length of 0 means JSON couldn't properly unmarshal the data, so it was mangled somehow.
if len(jsonData) > 0 {
newGUIColors[themeName] = map[string]rl.Color{}
for key, value := range jsonData {
if !strings.Contains(key, "//") { // Strings that begin with "//" are ignored
newGUIColors[themeName][key] = rl.Color{value[0], value[1], value[2], value[3]}
}
}
} else {
newGUIColors[themeName] = guiColors[themeName]
}
}
}
if err != nil {
return err
}
return nil
})
guiColors = newGUIColors
}
func ImmediateIconButton(rect, iconSrcRec rl.Rectangle, rotation float32, text string, disabled bool) bool {
clicked := false
outlineColor := getThemeColor(GUI_OUTLINE)
insideColor := getThemeColor(GUI_INSIDE)
if disabled {
outlineColor = getThemeColor(GUI_OUTLINE_DISABLED)
insideColor = getThemeColor(GUI_INSIDE_DISABLED)
} else {
if rl.CheckCollisionPointRec(GetMousePosition(), rect) {
outlineColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
insideColor = getThemeColor(GUI_INSIDE_HIGHLIGHTED)
if rl.IsMouseButtonDown(rl.MouseLeftButton) {
outlineColor = getThemeColor(GUI_OUTLINE_DISABLED)
insideColor = getThemeColor(GUI_INSIDE_DISABLED)
} else if rl.IsMouseButtonReleased(rl.MouseLeftButton) {
clicked = true
}
}
}
rl.DrawRectangleRec(rect, insideColor)
rl.DrawRectangleLinesEx(rect, 1, outlineColor)
textWidth := rl.MeasureTextEx(guiFont, text, guiFontSize, spacing)
pos := rl.Vector2{rect.X + (rect.Width / 2) - textWidth.X/2 + (iconSrcRec.Width / 2), rect.Y + (rect.Height / 2) - textWidth.Y/2}
pos.X = float32(math.Round(float64(pos.X)))
pos.Y = float32(math.Round(float64(pos.Y)))
iconDstRec := rect
iconDstRec.X += iconSrcRec.Width / 4 * 3
iconDstRec.Y += iconSrcRec.Height / 4 * 3
iconDstRec.Width = iconSrcRec.Width
iconDstRec.Height = iconSrcRec.Height
rl.DrawTexturePro(
currentProject.GUI_Icons,
iconSrcRec,
iconDstRec,
rl.Vector2{iconSrcRec.Width / 2, iconSrcRec.Height / 2},
rotation,
getThemeColor(GUI_FONT_COLOR))
DrawGUIText(pos, text)
return clicked
}
func ImmediateButton(rect rl.Rectangle, text string, disabled bool) bool {
return ImmediateIconButton(rect, rl.Rectangle{}, 0, text, disabled)
}
type PersistentGUIElement interface {
Update()
}
type DropdownMenu struct {
Rect rl.Rectangle
Name string
Options []string
Open bool
ChoiceIndex int
Clicked bool
}
func NewDropdown(x, y, w, h float32, name string, options ...string) *DropdownMenu {
return &DropdownMenu{
Name: name,
Rect: rl.Rectangle{x, y, w, h},
Options: options,
ChoiceIndex: -1,
}
}
func (dropdown *DropdownMenu) Update() {
dropdown.Clicked = false
dropdown.ChoiceIndex = -1
outlineColor := getThemeColor(GUI_OUTLINE)
insideColor := getThemeColor(GUI_INSIDE)
arrowColor := getThemeColor(GUI_FONT_COLOR)
if rl.CheckCollisionPointRec(GetMousePosition(), dropdown.Rect) {
outlineColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
insideColor = getThemeColor(GUI_INSIDE_HIGHLIGHTED)
arrowColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
if rl.IsMouseButtonDown(rl.MouseLeftButton) {
outlineColor = getThemeColor(GUI_OUTLINE_DISABLED)
insideColor = getThemeColor(GUI_INSIDE_DISABLED)
arrowColor = getThemeColor(GUI_OUTLINE_DISABLED)
} else if rl.IsMouseButtonReleased(rl.MouseLeftButton) {
dropdown.Open = !dropdown.Open
dropdown.Clicked = true
}
} else if dropdown.Open {
arrowColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
outlineColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
insideColor = getThemeColor(GUI_INSIDE_HIGHLIGHTED)
}
rl.DrawRectangleRec(dropdown.Rect, insideColor)
rl.DrawRectangleLinesEx(dropdown.Rect, 1, outlineColor)
textWidth := rl.MeasureTextEx(guiFont, dropdown.Name, guiFontSize, spacing)
pos := rl.Vector2{dropdown.Rect.X + (dropdown.Rect.Width / 2) - textWidth.X/2, dropdown.Rect.Y + (dropdown.Rect.Height / 2) - textWidth.Y/2}
pos.X = float32(math.Round(float64(pos.X)))
pos.Y = float32(math.Round(float64(pos.Y)))
DrawGUIText(pos, dropdown.Name)
rl.DrawTexturePro(currentProject.GUI_Icons, rl.Rectangle{16, 16, 16, 16}, rl.Rectangle{dropdown.Rect.X + (dropdown.Rect.Width - 24), dropdown.Rect.Y + 8, 16, 16}, rl.Vector2{}, 0, arrowColor)
// rl.DrawPoly(rl.Vector2{dropdown.Rect.X + dropdown.Rect.Width - 14, dropdown.Rect.Y + dropdown.Rect.Height/2}, 3, 7, 26, getThemeColor(GUI_FONT_COLOR))
if dropdown.Open {
y := float32(0)
for i, option := range dropdown.Options {
txt := fmt.Sprintf("%d: %s", i+1, option)
rect := dropdown.Rect
textWidth = rl.MeasureTextEx(guiFont, txt, guiFontSize, spacing)
rect.X += rect.Width
rect.Width = textWidth.X + 16
rect.Y += y
if ImmediateButton(rect, txt, false) {
dropdown.Clicked = true
dropdown.ChoiceIndex = i
dropdown.Open = false
}
y += rect.Height
}
}
}
func (dropdown *DropdownMenu) ChoiceAsString() string {
if dropdown.ChoiceIndex >= 0 && len(dropdown.Options) > dropdown.ChoiceIndex {
return dropdown.Options[dropdown.ChoiceIndex]
}
return ""
}
type Checkbox struct {
Rect rl.Rectangle
Checked bool
Changed bool
}
func NewCheckbox(x, y, w, h float32) *Checkbox {
checkbox := &Checkbox{Rect: rl.Rectangle{x, y, w, h}}
return checkbox
}
func (checkbox *Checkbox) Update() {
checkbox.Changed = false
rl.DrawRectangleRec(checkbox.Rect, getThemeColor(GUI_INSIDE))
outlineColor := getThemeColor(GUI_OUTLINE)
if rl.IsMouseButtonPressed(rl.MouseLeftButton) && rl.CheckCollisionPointRec(GetMousePosition(), checkbox.Rect) {
checkbox.Checked = !checkbox.Checked
checkbox.Changed = true
}
if checkbox.Checked {
r := checkbox.Rect
r.X += 4
r.Y += 4
r.Width -= 8
r.Height -= 8
rl.DrawRectangleRec(r, getThemeColor(GUI_OUTLINE_HIGHLIGHTED))
outlineColor = getThemeColor(GUI_OUTLINE_HIGHLIGHTED)
}
rl.DrawRectangleLinesEx(checkbox.Rect, 1, outlineColor)
}
type Spinner struct {
Rect rl.Rectangle
Options []string
CurrentChoice int
Changed bool
// Expanded bool
}
func NewSpinner(x, y, w, h float32, options ...string) *Spinner {
spinner := &Spinner{Rect: rl.Rectangle{x, y, w, h}, Options: options}
return spinner
}
func (spinner *Spinner) Update() {
spinner.Changed = false
// This kind of works, but not really, because you can click on an item in the menu, but then
// you also click on the item underneath the menu. :(
// clickedSpinner := false
// if ImmediateButton(rect, spinner.ChoiceAsString(), false) {
// spinner.Expanded = !spinner.Expanded
// clickedSpinner = true
// }
// if spinner.Expanded {
// for i, choice := range spinner.Options {
// if choice == spinner.ChoiceAsString() {
// continue
// }
// rect.Y += rect.Height
// if ImmediateButton(rect, choice, false) {
// spinner.CurrentChoice = i
// spinner.Expanded = false
// spinner.Changed = true
// clickedSpinner = true
// }
// }
// }
// if rl.IsMouseButtonReleased(rl.MouseLeftButton) && !clickedSpinner {
// spinner.Expanded = false
// }
rl.DrawRectangleRec(spinner.Rect, getThemeColor(GUI_INSIDE))
rl.DrawRectangleLinesEx(spinner.Rect, 1, getThemeColor(GUI_OUTLINE))
if len(spinner.Options) > 0 {
text := spinner.ChoiceAsString()
textLength := rl.MeasureTextEx(guiFont, text, guiFontSize, spacing)
x := float32(math.Round(float64(spinner.Rect.X + spinner.Rect.Width/2 - textLength.X/2)))
y := float32(math.Round(float64(spinner.Rect.Y + spinner.Rect.Height/2 - textLength.Y/2)))
DrawGUIText(rl.Vector2{x, y}, text)
}
if ImmediateButton(rl.Rectangle{spinner.Rect.X, spinner.Rect.Y, spinner.Rect.Height, spinner.Rect.Height}, "<", false) {
spinner.CurrentChoice--
spinner.Changed = true
}
if ImmediateButton(rl.Rectangle{spinner.Rect.X + spinner.Rect.Width - spinner.Rect.Height, spinner.Rect.Y, spinner.Rect.Height, spinner.Rect.Height}, ">", false) {
spinner.CurrentChoice++
spinner.Changed = true
}
if spinner.CurrentChoice < 0 {
spinner.CurrentChoice = len(spinner.Options) - 1
} else if spinner.CurrentChoice >= len(spinner.Options) {
spinner.CurrentChoice = 0
}
}
func (spinner *Spinner) SetChoice(choice string) bool {
for index, o := range spinner.Options {
if choice == o {
spinner.CurrentChoice = index
return true
}
}
return false
}
func (spinner *Spinner) ChoiceAsString() string {
return spinner.Options[spinner.CurrentChoice]
}
func (spinner *Spinner) ChoiceAsInt() int {
n := 0
n, _ = strconv.Atoi(spinner.ChoiceAsString())
return n
}
type ProgressBar struct {
Rect rl.Rectangle
Percentage int32
}
func NewProgressBar(x, y, w, h float32, options ...string) *ProgressBar {
progressBar := &ProgressBar{Rect: rl.Rectangle{x, y, w, h}}
return progressBar
}
func (progressBar *ProgressBar) Update() {
rl.DrawRectangleRec(progressBar.Rect, getThemeColor(GUI_INSIDE))
rl.DrawRectangleLinesEx(progressBar.Rect, 1, getThemeColor(GUI_OUTLINE))
if ImmediateButton(rl.Rectangle{progressBar.Rect.X, progressBar.Rect.Y, progressBar.Rect.Height, progressBar.Rect.Height}, "-", false) {
progressBar.Percentage -= 5
}
if ImmediateButton(rl.Rectangle{progressBar.Rect.X + progressBar.Rect.Width - progressBar.Rect.Height, progressBar.Rect.Y, progressBar.Rect.Height, progressBar.Rect.Height}, "+", false) {
progressBar.Percentage += 5
}
w := progressBar.Rect.Width - 4 - (progressBar.Rect.Height * 2)
f := float32(progressBar.Percentage) / 100
r := rl.Rectangle{progressBar.Rect.X + 2 + progressBar.Rect.Height, progressBar.Rect.Y + 2, w * f, progressBar.Rect.Height - 4}
if progressBar.Percentage < 0 {
progressBar.Percentage = 0
} else if progressBar.Percentage > 100 {
progressBar.Percentage = 100
}
rl.DrawRectangleRec(r, getThemeColor(GUI_OUTLINE))
pos := rl.Vector2{progressBar.Rect.X + progressBar.Rect.X/2 + 2, progressBar.Rect.Y + progressBar.Rect.Height/2 - 4}
DrawGUIText(pos, "%d"+"%", progressBar.Percentage)
}
type NumberSpinner struct {
Rect rl.Rectangle
Textbox *Textbox
Minimum int
Maximum int
Loop bool // If the spinner loops when attempting to add a number past the max
}
func NewNumberSpinner(x, y, w, h float32) *NumberSpinner {
numberSpinner := &NumberSpinner{Rect: rl.Rectangle{x, y, w, h}, Textbox: NewTextbox(x+h, y, w-(h*2), h)}
numberSpinner.Textbox.AllowAlphaCharacters = false
numberSpinner.Textbox.AllowNewlines = false
numberSpinner.Textbox.HorizontalAlignment = TEXTBOX_ALIGN_CENTER
numberSpinner.Textbox.VerticalAlignment = TEXTBOX_ALIGN_CENTER
numberSpinner.Textbox.SetText("0")
numberSpinner.Minimum = -math.MaxInt64
numberSpinner.Maximum = math.MaxInt64
return numberSpinner
}
func (numberSpinner *NumberSpinner) Update() {
numberSpinner.Textbox.Rect.X = numberSpinner.Rect.X + numberSpinner.Rect.Height
numberSpinner.Textbox.Rect.Y = numberSpinner.Rect.Y
numberSpinner.Textbox.Update()
minusButton := ImmediateButton(rl.Rectangle{numberSpinner.Rect.X, numberSpinner.Rect.Y, numberSpinner.Rect.Height, numberSpinner.Rect.Height}, "-", false)
plusButton := ImmediateButton(rl.Rectangle{numberSpinner.Textbox.Rect.X + numberSpinner.Textbox.Rect.Width, numberSpinner.Rect.Y, numberSpinner.Rect.Height, numberSpinner.Rect.Height}, "+", false)
if !numberSpinner.Textbox.Focused {
if numberSpinner.Textbox.Text() == "" {
numberSpinner.Textbox.SetText("0")
}
num := numberSpinner.GetNumber()
if minusButton {
num--
}
if plusButton {
num++
}
if num < numberSpinner.Minimum {
if numberSpinner.Loop {
num = numberSpinner.Maximum
} else {
num = numberSpinner.Minimum
}
} else if num > numberSpinner.Maximum && numberSpinner.Maximum > -1 {
if numberSpinner.Loop {
num = numberSpinner.Minimum
} else {
num = numberSpinner.Maximum
}
}
numberSpinner.Textbox.SetText(strconv.Itoa(num))
}
}
func (numberSpinner *NumberSpinner) GetNumber() int {
num, _ := strconv.Atoi(numberSpinner.Textbox.Text())
return num
}
func (numberSpinner *NumberSpinner) SetNumber(number int) {
numberSpinner.Textbox.SetText(strconv.Itoa(number))
}
type Textbox struct {
// Used to be a string, but now is a []rune so it can deal with UTF8 characters like À properly, HOPEFULLY
text []rune
Focused bool
Rect rl.Rectangle
Visible bool
AllowNewlines bool
AllowAlphaCharacters bool
MaxCharactersPerLine int
Changed bool
HorizontalAlignment int
VerticalAlignment int
SelectedRange [2]int
SelectionStart int
LeadingSelectionEdge int
MinSize rl.Vector2
MaxSize rl.Vector2
KeyholdTimer int
CaretPos int
lineHeight float32
}
func NewTextbox(x, y, w, h float32) *Textbox {
textbox := &Textbox{Rect: rl.Rectangle{x, y, w, h}, Visible: true,
MinSize: rl.Vector2{w, h}, MaxSize: rl.Vector2{9999, 9999}, MaxCharactersPerLine: math.MaxInt64, AllowAlphaCharacters: true,
SelectedRange: [2]int{-1, -1}}
textbox.lineHeight, _ = TextHeight(textbox.Text(), true)
return textbox
}
func (textbox *Textbox) ClosestPointInText(point rl.Vector2) int {
if len(textbox.text) == 0 {
return 0
}
closestLineIndex := -1
closestLineDiff := float32(-1)
for i := range textbox.Lines() {
lineY := textbox.Rect.Y + (textbox.lineHeight * float32(i))
diff := float32(math.Abs(float64(lineY - point.Y)))
if closestLineDiff < 0 || diff < closestLineDiff {
closestLineIndex = i
closestLineDiff = diff
}
}
line := textbox.Lines()[closestLineIndex]
x := textbox.Rect.X
if textbox.HorizontalAlignment == TEXTBOX_ALIGN_RIGHT {
x = textbox.Rect.X + textbox.Rect.Width - GUITextWidth(string(line))
point.X += 8
} else if textbox.HorizontalAlignment == TEXTBOX_ALIGN_CENTER {
x = textbox.Rect.X + (textbox.Rect.Width-GUITextWidth(string(line)))/2
point.X += 8
}
// Adding a space so you can select the point after the line ends
line = append(line, ' ')
closestCharIndex := -1
closestCharDiff := float32(-1)
for i, char := range line {
x += rl.MeasureTextEx(guiFont, string(char), guiFontSize, spacing).X + spacing
diff := math.Abs(float64(x - point.X))
if closestCharDiff < 0 || diff < float64(closestCharDiff) {
closestCharIndex = i
closestCharDiff = float32(diff)
}
}
index := 0
for l := range textbox.Lines() {
if l < closestLineIndex {
index += len(textbox.Lines()[l]) + 1 // The +1 is for the newline character
} else {
index += closestCharIndex
break
}
}
// WARNING! The index can be at the very end of the array (so the index could be 3 with text of "abc")
return index
}
func (textbox *Textbox) InsertCharacterAtCaret(char rune) {
// Oh LORDY this was the only way I could get this to work
a := []rune{}
b := []rune{char}
for _, r := range textbox.text[:textbox.CaretPos] {
a = append(a, r)
}
if textbox.CaretPos < len(textbox.text) {
for _, r := range textbox.text[textbox.CaretPos:] {
b = append(b, r)
}
}
textbox.text = append(a, b...)
textbox.CaretPos++
textbox.Changed = true
}
func (textbox *Textbox) InsertTextAtCaret(text string) {
for _, char := range text {
textbox.InsertCharacterAtCaret(char)
}
}
func (textbox *Textbox) Lines() [][]rune {
// This used to return []string, one string for each line, but a string is basically a human-readable version of a string of
// bytes / unicode characters. Some characters, like ß, are actually composed of multiple bytes. Since this is the case,
// it's wise to return an array of runes, which are individual characters, rather than a string, which can't be reliably
// iterated over without accidentally messing up those multi-byte characters.
lines := [][]rune{}
lines = append(lines, []rune{})
currentLine := 0
for _, t := range textbox.text {
if t == '\n' {
currentLine++
lines = append(lines, []rune{})
} else {
lines[currentLine] = append(lines[currentLine], t)
}
}
return lines
}
func (textbox *Textbox) LineNumberByPosition(position int) int {
for i, line := range textbox.Lines() {
position -= len(line) + 1 // Lines are split by "\n", so they're not included in the line length
if position < 0 {
return i
}
}
return 0
}
func (textbox *Textbox) PositionInLine(position int) int {
start := 0
sub := textbox.text[position:]
for i := len(sub); i > position; i-- {
if textbox.text[i] == '\n' {
start = i
break
}
}
return len(textbox.text[start:])
}
func (textbox *Textbox) CharacterToPoint(position int) rl.Vector2 {
startX := textbox.Rect.X
y := textbox.Rect.Y + 2
if textbox.HorizontalAlignment == TEXTBOX_ALIGN_RIGHT {
startX += textbox.Rect.Width - GUITextWidth(string(textbox.Lines()[textbox.LineNumberByPosition(position)])) - 8
} else if textbox.HorizontalAlignment == TEXTBOX_ALIGN_CENTER {
startX += (textbox.Rect.Width-GUITextWidth(string(textbox.Lines()[textbox.LineNumberByPosition(position)])))/2 - 8
}
x := startX
for index, char := range textbox.text {
if index == position {
break
}
if string(char) == "\n" {
y += textbox.lineHeight
x = startX
}
x += rl.MeasureTextEx(guiFont, string(char), guiFontSize, spacing).X + spacing
}
return rl.Vector2{x, y}
}
func (textbox *Textbox) CharacterToRect(position int) rl.Rectangle {
rect := rl.Rectangle{}
if position < len(textbox.text) {
pos := textbox.CharacterToPoint(position)
letterSize := rl.MeasureTextEx(guiFont, string(textbox.text[position]), guiFontSize, spacing)
rect.X = pos.X
rect.Y = pos.Y
rect.Width = letterSize.X + spacing
rect.Height = letterSize.Y
}
return rect
}
func (textbox *Textbox) FindFirstCharAfterCaret(char rune) int {
for i := textbox.CaretPos; i < len(textbox.text); i++ {
if textbox.text[i] == char {
return i
}
}
return -1
}
func (textbox *Textbox) FindLastCharBeforeCaret(char rune) int {
for i := textbox.CaretPos - 1; i > 0; i-- {
if i < len(textbox.text) && textbox.text[i] == char {
return i
}
}
return -1
}
func (textbox *Textbox) Update() {
hMargin := float32(2)
vMargin := float32(2)
textbox.Changed = false
if rl.IsMouseButtonPressed(rl.MouseLeftButton) {
textbox.Focused = rl.CheckCollisionPointRec(GetMousePosition(), textbox.Rect)
}
if textbox.Focused {
prevCaretPos := textbox.CaretPos
if rl.IsKeyPressed(rl.KeyEscape) {
textbox.Focused = false
}
if textbox.AllowNewlines && (rl.IsKeyPressed(rl.KeyEnter) || rl.IsKeyPressed(rl.KeyKpEnter)) {
textbox.Changed = true
if textbox.RangeSelected() {
textbox.DeleteSelectedText()
}
textbox.InsertCharacterAtCaret('\n')
}
control := rl.IsKeyDown(rl.KeyLeftControl) || rl.IsKeyDown(rl.KeyRightControl)
shift := rl.IsKeyDown(rl.KeyLeftShift) || rl.IsKeyDown(rl.KeyRightShift)
if strings.Contains(runtime.GOOS, "darwin") && !control {
control = rl.IsKeyDown(rl.KeyLeftSuper) || rl.IsKeyDown(rl.KeyRightSuper)
}
if control {
if rl.IsKeyPressed(rl.KeyA) {
textbox.SelectAllText()
}
}
letter := int(rl.GetKeyPressed())
if letter != -1 {
numbers := []int{
rl.KeyZero,
rl.KeyNine,
}
npNumbers := []int{
rl.KeyKp0,
rl.KeyKp9,
}
isNum := (letter >= numbers[0] && letter <= numbers[1]) || (letter >= npNumbers[0] && letter <= npNumbers[1])
if len(textbox.Lines()[textbox.LineNumberByPosition(textbox.CaretPos)]) < textbox.MaxCharactersPerLine {
if letter != 0 && (textbox.AllowAlphaCharacters || isNum) {
if textbox.RangeSelected() {
textbox.DeleteSelectedText()
}
textbox.ClearSelection()
textbox.InsertCharacterAtCaret(rune(letter))
}
}
}
mousePos := GetMousePosition()
mousePos.X += hMargin + (rl.MeasureTextEx(guiFont, "A", guiFontSize, spacing).X / 2)
mousePos.Y += hMargin - (textbox.lineHeight / 2)
if rl.IsMouseButtonPressed(rl.MouseLeftButton) {
textbox.CaretPos = textbox.ClosestPointInText(mousePos)
if !shift {
textbox.ClearSelection()
}
if !textbox.RangeSelected() {
textbox.SelectionStart = textbox.CaretPos
}
}
if rl.IsMouseButtonDown(rl.MouseLeftButton) {
textbox.SelectedRange[0] = textbox.SelectionStart
textbox.CaretPos = textbox.ClosestPointInText(mousePos)
textbox.SelectedRange[1] = textbox.CaretPos
}
keyState := map[int32]int{
rl.KeyBackspace: 0,
rl.KeyRight: 0,
rl.KeyLeft: 0,
rl.KeyUp: 0,
rl.KeyDown: 0,
rl.KeyDelete: 0,
rl.KeyHome: 0,
rl.KeyEnd: 0,
rl.KeyV: 0,
}
for k := range keyState {
if rl.IsKeyPressed(k) {
keyState[k] = 1
textbox.KeyholdTimer = 0
} else if rl.IsKeyDown(k) {
textbox.KeyholdTimer++
if textbox.KeyholdTimer > 30 {
keyState[k] = 1
}
} else if rl.IsKeyReleased(k) {
textbox.KeyholdTimer = 0
}
}
if keyState[rl.KeyRight] > 0 {
nextNewWord := textbox.FindFirstCharAfterCaret(' ')
nextNewLine := textbox.FindFirstCharAfterCaret('\n')
if nextNewWord < 0 || (nextNewWord >= 0 && nextNewLine >= 0 && nextNewLine < nextNewWord) {
nextNewWord = nextNewLine
}
if nextNewWord == textbox.CaretPos {
nextNewWord++
}
if control {
if nextNewWord > 0 {
textbox.CaretPos = nextNewWord
} else {
textbox.CaretPos = len(textbox.text)
}
} else {
textbox.CaretPos++
}
if !shift {
textbox.ClearSelection()
}
} else if keyState[rl.KeyLeft] > 0 {
prevNewWord := textbox.FindLastCharBeforeCaret(' ')
prevNewLine := textbox.FindLastCharBeforeCaret('\n')
if prevNewWord < 0 || (prevNewWord >= 0 && prevNewLine >= 0 && prevNewLine > prevNewWord) {
prevNewWord = prevNewLine
}
prevNewWord++
if textbox.CaretPos == prevNewWord {
prevNewWord--
}
if control {
if prevNewWord > 0 {
textbox.CaretPos = prevNewWord
} else {
textbox.CaretPos = 0
}
} else {
textbox.CaretPos--
}
if !shift {
textbox.ClearSelection()
}
} else if keyState[rl.KeyUp] > 0 {
lineIndex := textbox.LineNumberByPosition(textbox.CaretPos)
if lineIndex > 0 {
pos := textbox.CharacterToPoint(textbox.CaretPos)
pos.Y -= textbox.lineHeight
pos.X += 6 // To combat drifting (THIS IS THE BEST I CAN DO, OKAY)
textbox.CaretPos = textbox.ClosestPointInText(pos)
} else {
textbox.CaretPos = 0
}
if !shift {
textbox.ClearSelection()
}
} else if keyState[rl.KeyDown] > 0 {
lineIndex := textbox.LineNumberByPosition(textbox.CaretPos)
if lineIndex < len(textbox.Lines())-1 {
pos := textbox.CharacterToPoint(textbox.CaretPos)
pos.Y += textbox.lineHeight
pos.X += 6
textbox.CaretPos = textbox.ClosestPointInText(pos)
} else {
textbox.CaretPos = len(textbox.text)
}
if !shift {
textbox.ClearSelection()
}
} else if keyState[rl.KeyV] > 0 && control {
clipboardText, _ := clipboard.ReadAll()
if clipboardText != "" {
textbox.Changed = true
if textbox.RangeSelected() {
textbox.DeleteSelectedText()
}
textbox.InsertTextAtCaret(clipboardText)
}
}
if !textbox.RangeSelected() && shift {
if textbox.CaretPos != prevCaretPos && !textbox.Changed {
textbox.SelectionStart = prevCaretPos
}
}
if shift {
textbox.SelectedRange[0] = textbox.SelectionStart
textbox.SelectedRange[1] = textbox.CaretPos
}
if textbox.SelectedRange[1] < textbox.SelectedRange[0] || textbox.SelectedRange[0] > textbox.SelectedRange[1] {
temp := textbox.SelectedRange[0]
textbox.SelectedRange[0] = textbox.SelectedRange[1]
textbox.SelectedRange[1] = temp
}
// Specifically want these two shortcuts to be here, underneath the above code block to ensure the selected range is valid before
// we mess with it
if control {
if textbox.RangeSelected() {
if rl.IsKeyPressed(rl.KeyC) {
clipboard.WriteAll(string(textbox.text[textbox.SelectedRange[0]:textbox.SelectedRange[1]]))
} else if rl.IsKeyPressed(rl.KeyX) {
clipboard.WriteAll(string(textbox.text[textbox.SelectedRange[0]:textbox.SelectedRange[1]]))
textbox.DeleteSelectedText()
}
}
}
if keyState[rl.KeyHome] > 0 {
textbox.CaretPos = 0
} else if keyState[rl.KeyEnd] > 0 {
textbox.CaretPos = len(textbox.text)
}
if keyState[rl.KeyBackspace] > 0 {
textbox.Changed = true
if textbox.RangeSelected() {
textbox.DeleteSelectedText()
} else if textbox.CaretPos > 0 {
textbox.CaretPos--
textbox.text = append(textbox.text[:textbox.CaretPos], textbox.text[textbox.CaretPos+1:]...)