/
textfield.go
2051 lines (1882 loc) · 52.4 KB
/
textfield.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
// Copyright (c) 2018, Cogent Core. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"fmt"
"image"
"log/slog"
"slices"
"sync"
"time"
"unicode"
"cogentcore.org/core/abilities"
"cogentcore.org/core/colors"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/events/key"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/mimedata"
"cogentcore.org/core/paint"
"cogentcore.org/core/parse/complete"
"cogentcore.org/core/states"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
"cogentcore.org/core/units"
"golang.org/x/image/draw"
)
// TextField is a widget for editing a line of text.
// With the default WhiteSpaceNormal style setting,
// text will wrap onto multiple lines as needed.
// Set to WhiteSpaceNowrap (e.g., Styles.SetTextWrap(false)) to
// force everything to be on a single line.
// With multi-line wrapped text, the text is still treated as a contiguous
// wrapped text.
type TextField struct { //core:embedder
WidgetBase
// Type is the styling type of the text field.
Type TextFieldTypes
// Placeholder is the text that is displayed
// when the text field is empty.
Placeholder string
// Validator is a function used to validate the input
// of the text field. If it returns a non-nil error,
// then an error color, icon, and tooltip will be displayed.
Validator func() error `json:"-" xml:"-"`
// LeadingIcon, if specified, indicates to add a button
// at the start of the text field with this icon.
LeadingIcon icons.Icon `set:"-"`
// LeadingIconOnClick, if specified, is the function to call when
// the LeadingIcon is clicked. If this is nil, the leading icon
// will not be interactive.
LeadingIconOnClick func(e events.Event) `json:"-" xml:"-"`
// TrailingIcon, if specified, indicates to add a button
// at the end of the text field with this icon.
TrailingIcon icons.Icon `set:"-"`
// TrailingIconOnClick, if specified, is the function to call when
// the TrailingIcon is clicked. If this is nil, the trailing icon
// will not be interactive.
TrailingIconOnClick func(e events.Event) `json:"-" xml:"-"`
// NoEcho is whether replace displayed characters with bullets to conceal text
// (for example, for a password input).
NoEcho bool
// CursorWidth is the width of the text field cursor.
// It should be set in Style like all other style properties.
// By default, it is 1dp.
CursorWidth units.Value
// CursorColor is the color used for the text field cursor (caret).
// It should be set in Style like all other style properties.
// By default, it is [colors.Scheme.Primary.Base].
CursorColor image.Image
// PlaceholderColor is the color used for the Placeholder text.
// It should be set in Style like all other style properties.
// By default, it is [colors.Scheme.OnSurfaceVariant].
PlaceholderColor image.Image
// SelectColor is the color used for the text selection background color.
// It should be set in Style like all other style properties.
// By default, it is [colors.Scheme.Select.Container]
SelectColor image.Image
// Complete contains functions and data for text field completion.
// It must be set using [TextField.SetCompleter].
Complete *Complete `copier:"-" json:"-" xml:"-" set:"-"`
// Txt is the last saved value of the text string being edited.
Txt string `json:"-" xml:"-" set:"-"`
// Edited is whether the text has been edited relative to the original.
Edited bool `json:"-" xml:"-" set:"-"`
// EditTxt is the live text string being edited, with the latest modifications.
EditTxt []rune `copier:"-" json:"-" xml:"-" set:"-"`
// Error is the current validation error of the text field.
Error error `json:"-" xml:"-" set:"-"`
// EffPos is the effective position with any leading icon space added.
EffPos math32.Vector2 `copier:"-" json:"-" xml:"-" set:"-"`
// EffSize is the effective size, subtracting any leading and trailing icon space.
EffSize math32.Vector2 `copier:"-" json:"-" xml:"-" set:"-"`
// StartPos is the starting display position in the string.
StartPos int `copier:"-" json:"-" xml:"-" set:"-"`
// EndPos is the ending display position in the string.
EndPos int `copier:"-" json:"-" xml:"-" set:"-"`
// CursorPos is the current cursor position.
CursorPos int `copier:"-" json:"-" xml:"-" set:"-"`
// CursorLine is the current cursor line position.
CursorLine int `copier:"-" json:"-" xml:"-" set:"-"`
// CharWidth is the approximate number of chars that can be
// displayed at any time, which is computed from the font size.
CharWidth int `copier:"-" json:"-" xml:"-" set:"-"`
// SelectStart is the starting position of selection in the string.
SelectStart int `copier:"-" json:"-" xml:"-" set:"-"`
// SelectEnd is the ending position of selection in the string.
SelectEnd int `copier:"-" json:"-" xml:"-" set:"-"`
// SelectInit is the initial selection position (where it started).
SelectInit int `copier:"-" json:"-" xml:"-" set:"-"`
// SelectMode is whether to select text as the cursor moves.
SelectMode bool `copier:"-" json:"-" xml:"-"`
// RenderAll is the render version of entire text, for sizing.
RenderAll paint.Text `copier:"-" json:"-" xml:"-" set:"-"`
// RenderVis is the render version of just the visible text.
RenderVis paint.Text `copier:"-" json:"-" xml:"-" set:"-"`
// number of lines from last render update, for word-wrap version
NLines int `copier:"-" json:"-" xml:"-" set:"-"`
// FontHeight is the font height cached during styling.
FontHeight float32 `copier:"-" json:"-" xml:"-" set:"-"`
// BlinkOn oscillates between on and off for blinking.
BlinkOn bool `copier:"-" json:"-" xml:"-" set:"-"`
// CursorMu is the mutex for updating the cursor between blinker and field.
CursorMu sync.Mutex `copier:"-" json:"-" xml:"-" view:"-" set:"-"`
// the undo manager
UndoMgr TextFieldUndoMgr
}
// TextFieldTypes is an enum containing the
// different possible types of text fields
type TextFieldTypes int32 //enums:enum -trim-prefix TextField
const (
// TextFieldFilled represents a filled
// TextField with a background color
// and a bottom border
TextFieldFilled TextFieldTypes = iota
// TextFieldOutlined represents an outlined
// TextField with a border on all sides
// and no background color
TextFieldOutlined
)
func (tf *TextField) OnInit() {
tf.WidgetBase.OnInit()
tf.HandleEvents()
tf.SetStyles()
tf.AddContextMenu(tf.ContextMenu)
}
func (tf *TextField) OnAdd() {
tf.WidgetBase.OnAdd()
tf.OnClose(func(e events.Event) {
tf.EditDone() // todo: this must be protected against something else, for race detector
})
}
func (tf *TextField) SetStyles() {
tf.Style(func(s *styles.Style) {
s.SetAbilities(true, abilities.Activatable, abilities.Focusable, abilities.Hoverable, abilities.Slideable, abilities.DoubleClickable, abilities.TripleClickable)
tf.CursorWidth.Dp(1)
tf.SelectColor = colors.C(colors.Scheme.Select.Container)
tf.PlaceholderColor = colors.C(colors.Scheme.OnSurfaceVariant)
tf.CursorColor = colors.C(colors.Scheme.Primary.Base)
s.VirtualKeyboard = styles.KeyboardSingleLine
if !tf.IsReadOnly() {
s.Cursor = cursors.Text
}
s.GrowWrap = false // note: doesn't work with Grow
s.Grow.Set(1, 0)
s.Min.Y.Em(1.1)
s.Min.X.Ch(20)
s.Max.X.Ch(40)
s.Padding.Set(units.Dp(8), units.Dp(8))
if tf.LeadingIcon.IsSet() {
s.Padding.Left.Dp(12)
}
if tf.TrailingIcon.IsSet() {
s.Padding.Right.Dp(12)
}
s.Text.Align = styles.Start
s.Color = colors.C(colors.Scheme.OnSurface)
switch tf.Type {
case TextFieldFilled:
s.Border.Style.Set(styles.BorderNone)
s.Border.Style.Bottom = styles.BorderSolid
s.Border.Width.Zero()
s.Border.Color.Zero()
s.Border.Radius = styles.BorderRadiusExtraSmallTop
s.Background = colors.C(colors.Scheme.SurfaceContainer)
s.MaxBorder = s.Border
s.MaxBorder.Width.Bottom = units.Dp(2)
s.MaxBorder.Color.Bottom = colors.C(colors.Scheme.Primary.Base)
if !tf.IsReadOnly() && s.Is(states.Focused) {
s.Border = s.MaxBorder
} else {
s.Border.Width.Bottom = units.Dp(1)
s.Border.Color.Bottom = colors.C(colors.Scheme.OnSurfaceVariant)
}
if tf.Error != nil {
s.Border.Color.Bottom = colors.C(colors.Scheme.Error.Base)
}
case TextFieldOutlined:
s.Border.Style.Set(styles.BorderSolid)
s.Border.Radius = styles.BorderRadiusExtraSmall
s.MaxBorder = s.Border
s.MaxBorder.Width.Set(units.Dp(2))
s.MaxBorder.Color.Set(colors.C(colors.Scheme.Primary.Base))
if !tf.IsReadOnly() && s.Is(states.Focused) {
s.Border = s.MaxBorder
} else {
s.Border.Width.Set(units.Dp(1))
s.Border.Color.Set(colors.C(colors.Scheme.Outline))
}
if tf.Error != nil {
s.Border.Color.Set(colors.C(colors.Scheme.Error.Base))
}
}
if tf.IsReadOnly() {
s.Border.Color.Zero()
s.Border.Width.Zero()
s.Border.Radius.Zero()
s.MaxBorder = s.Border
s.Background = nil
}
if s.Is(states.Selected) {
s.Background = colors.C(colors.Scheme.Select.Container)
}
})
tf.StyleFinal(func(s *styles.Style) {
tf.SetAbilities(!tf.IsReadOnly(), abilities.Focusable)
})
tf.OnWidgetAdded(func(w Widget) {
switch w.PathFrom(tf) {
case "parts":
w.Style(func(s *styles.Style) {
s.Align.Content = styles.Center
s.Align.Items = styles.Center
s.Text.AlignV = styles.Center
s.Gap.Zero()
})
case "parts/lead-icon":
lead := w.(*Button)
lead.Type = ButtonAction
lead.Style(func(s *styles.Style) {
s.Padding.Zero()
s.Color = colors.C(colors.Scheme.OnSurfaceVariant)
s.Margin.SetRight(units.Dp(8))
if tf.LeadingIconOnClick == nil {
s.SetAbilities(false, abilities.Activatable, abilities.Focusable, abilities.Hoverable)
s.Cursor = cursors.None
}
// If we are responsible for a positive (non-disabled) state layer
// (instead of our parent), then we amplify it so that it is clear
// that we ourself are receiving a state layer amplifying event.
// Otherwise, we set our state color to that of our parent
// so that it does not appear as if we are getting interaction ourself;
// instead, we are a part of our parent and render a background color no
// different than them.
if s.Is(states.Hovered) || s.Is(states.Focused) || s.Is(states.Active) {
s.StateLayer *= 3
} else {
s.StateColor = tf.Styles.Color
}
})
lead.OnClick(func(e events.Event) {
if tf.LeadingIconOnClick != nil {
tf.LeadingIconOnClick(e)
}
})
case "parts/trail-icon":
trail := w.(*Button)
trail.Type = ButtonAction
trail.Style(func(s *styles.Style) {
s.Padding.Zero()
s.Color = colors.C(colors.Scheme.OnSurfaceVariant)
if tf.Error != nil {
s.Color = colors.C(colors.Scheme.Error.Base)
}
s.Margin.SetLeft(units.Dp(8))
if tf.TrailingIconOnClick == nil || tf.Error != nil {
s.SetAbilities(false, abilities.Activatable, abilities.Focusable, abilities.Hoverable)
s.Cursor = cursors.None
// need to clear state in case it was set when there
// was no error
s.State = 0
}
// same reasoning as for leading icon
if s.Is(states.Hovered) || s.Is(states.Focused) || s.Is(states.Active) {
s.StateLayer *= 3
} else {
s.StateColor = tf.Styles.Color
}
})
trail.OnClick(func(e events.Event) {
if tf.TrailingIconOnClick != nil {
tf.TrailingIconOnClick(e)
}
})
case "parts/error":
w.Style(func(s *styles.Style) {
s.Color = colors.C(colors.Scheme.Error.Base)
})
}
})
}
func (tf *TextField) Destroy() {
tf.StopCursor()
tf.WidgetBase.Destroy()
}
// Text returns the current text -- applies any unapplied changes first, and
// sends a signal if so -- this is the end-user method to get the current
// value of the field.
func (tf *TextField) Text() string {
tf.EditDone()
return tf.Txt
}
// SetText sets the text to be edited and reverts any current edit
// to reflect this new text.
func (tf *TextField) SetText(txt string) *TextField {
if tf.Txt == txt && !tf.Edited {
return tf
}
tf.Txt = txt
tf.Revert()
return tf
}
// SetLeadingIcon sets the leading icon of the text field to the given icon.
// If an on click function is specified, it also sets the leading icon on click
// function to that function. If no function is specified, it does not
// override any already set function.
func (tf *TextField) SetLeadingIcon(icon icons.Icon, onClick ...func(e events.Event)) *TextField {
tf.LeadingIcon = icon
if len(onClick) > 0 {
tf.LeadingIconOnClick = onClick[0]
}
return tf
}
// SetTrailingIcon sets the trailing icon of the text field to the given icon.
// If an on click function is specified, it also sets the trailing icon on click
// function to that function. If no function is specified, it does not
// override any already set function.
func (tf *TextField) SetTrailingIcon(icon icons.Icon, onClick ...func(e events.Event)) *TextField {
tf.TrailingIcon = icon
if len(onClick) > 0 {
tf.TrailingIconOnClick = onClick[0]
}
return tf
}
// AddClearButton adds a trailing icon button at the end
// of the textfield that clears the text in the textfield when pressed
func (tf *TextField) AddClearButton() *TextField {
return tf.SetTrailingIcon(icons.Close, func(e events.Event) {
tf.Clear()
})
}
// SetTypePassword enables [TextField.NoEcho] and adds a trailing
// icon button at the end of the textfield that toggles [TextField.NoEcho].
// It also sets [styles.Style.VirtualKeyboard] to [styles.KeyboardPassword].
func (tf *TextField) SetTypePassword() *TextField {
tf.SetNoEcho(true).SetTrailingIcon(icons.Visibility, func(e events.Event) {
tf.NoEcho = !tf.NoEcho
if tf.NoEcho {
tf.TrailingIcon = icons.Visibility
} else {
tf.TrailingIcon = icons.VisibilityOff
}
if icon := tf.TrailingIconButton(); icon != nil {
icon.SetIcon(tf.TrailingIcon).Update()
}
}).Style(func(s *styles.Style) {
s.VirtualKeyboard = styles.KeyboardPassword
})
return tf
}
// EditDone completes editing and copies the active edited text to the text --
// called when the return key is pressed or goes out of focus
func (tf *TextField) EditDone() {
if tf.Edited {
tf.Edited = false
tf.Txt = string(tf.EditTxt)
tf.SendChange()
// widget can be killed after SendChange
if tf.This() == nil {
return
}
}
tf.ClearSelected()
tf.ClearCursor()
}
// Revert aborts editing and reverts to last saved text
func (tf *TextField) Revert() {
tf.EditTxt = []rune(tf.Txt)
tf.Edited = false
tf.StartPos = 0
tf.EndPos = tf.CharWidth
tf.SelectReset()
tf.NeedsRender()
}
// Clear clears any existing text
func (tf *TextField) Clear() {
tf.Edited = true
tf.EditTxt = tf.EditTxt[:0]
tf.StartPos = 0
tf.EndPos = 0
tf.SelectReset()
tf.SetFocusEvent() // this is essential for ensuring that the clear applies after focus is lost..
tf.NeedsRender()
}
// Validate runs [TextField.Validator] and takes any necessary actions
// as a result of that.
func (tf *TextField) Validate() {
if tf.Validator == nil {
return
}
err := tf.Validator()
if err == nil {
if tf.Error == nil {
return
}
tf.Error = nil
tf.TrailingIconButton().SetIcon(tf.TrailingIcon).Update()
return
}
tf.Error = err
if tf.TrailingIconButton() == nil {
tf.SetTrailingIcon(icons.Blank).Update()
}
tf.TrailingIconButton().SetIcon(icons.Error).Update()
// show the error tooltip immediately
tf.Send(events.LongHoverStart)
}
func (tf *TextField) WidgetTooltip() string {
if tf.Error == nil {
return tf.Tooltip
}
return tf.Error.Error()
}
//////////////////////////////////////////////////////////////////////////////////////////
// Cursor Navigation
// CursorForward moves the cursor forward
func (tf *TextField) CursorForward(steps int) {
tf.CursorPos += steps
if tf.CursorPos > len(tf.EditTxt) {
tf.CursorPos = len(tf.EditTxt)
}
if tf.CursorPos > tf.EndPos {
inc := tf.CursorPos - tf.EndPos
tf.EndPos += inc
}
tf.CursorLine, _, _ = tf.RenderAll.RuneSpanPos(tf.CursorPos)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorForwardWord moves the cursor forward by words
func (tf *TextField) CursorForwardWord(steps int) {
for i := 0; i < steps; i++ {
sz := len(tf.EditTxt)
if sz > 0 && tf.CursorPos < sz {
ch := tf.CursorPos
var done = false
for ch < sz && !done { // if on a wb, go past
r1 := tf.EditTxt[ch]
r2 := rune(-1)
if ch < sz-1 {
r2 = tf.EditTxt[ch+1]
}
if IsWordBreak(r1, r2) {
ch++
} else {
done = true
}
}
done = false
for ch < sz && !done {
r1 := tf.EditTxt[ch]
r2 := rune(-1)
if ch < sz-1 {
r2 = tf.EditTxt[ch+1]
}
if !IsWordBreak(r1, r2) {
ch++
} else {
done = true
}
}
tf.CursorPos = ch
} else {
tf.CursorPos = sz
}
}
if tf.CursorPos > len(tf.EditTxt) {
tf.CursorPos = len(tf.EditTxt)
}
if tf.CursorPos > tf.EndPos {
inc := tf.CursorPos - tf.EndPos
tf.EndPos += inc
}
tf.CursorLine, _, _ = tf.RenderAll.RuneSpanPos(tf.CursorPos)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorBackward moves the cursor backward
func (tf *TextField) CursorBackward(steps int) {
tf.CursorPos -= steps
if tf.CursorPos < 0 {
tf.CursorPos = 0
}
if tf.CursorPos <= tf.StartPos {
dec := min(tf.StartPos, 8)
tf.StartPos -= dec
}
tf.CursorLine, _, _ = tf.RenderAll.RuneSpanPos(tf.CursorPos)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorBackwardWord moves the cursor backward by words
func (tf *TextField) CursorBackwardWord(steps int) {
for i := 0; i < steps; i++ {
sz := len(tf.EditTxt)
if sz > 0 && tf.CursorPos > 0 {
ch := min(tf.CursorPos, sz-1)
var done = false
for ch < sz && !done { // if on a wb, go past
r1 := tf.EditTxt[ch]
r2 := rune(-1)
if ch > 0 {
r2 = tf.EditTxt[ch-1]
}
if IsWordBreak(r1, r2) {
ch--
if ch == -1 {
done = true
}
} else {
done = true
}
}
done = false
for ch < sz && ch >= 0 && !done {
r1 := tf.EditTxt[ch]
r2 := rune(-1)
if ch > 0 {
r2 = tf.EditTxt[ch-1]
}
if !IsWordBreak(r1, r2) {
ch--
} else {
done = true
}
}
tf.CursorPos = ch
} else {
tf.CursorPos = 0
}
}
if tf.CursorPos < 0 {
tf.CursorPos = 0
}
if tf.CursorPos <= tf.StartPos {
dec := min(tf.StartPos, 8)
tf.StartPos -= dec
}
tf.CursorLine, _, _ = tf.RenderAll.RuneSpanPos(tf.CursorPos)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorDown moves the cursor down
func (tf *TextField) CursorDown(steps int) {
if tf.NLines <= 1 {
return
}
if tf.CursorLine >= tf.NLines-1 {
return
}
_, ri, _ := tf.RenderAll.RuneSpanPos(tf.CursorPos)
tf.CursorLine = min(tf.CursorLine+steps, tf.NLines-1)
tf.CursorPos, _ = tf.RenderAll.SpanPosToRuneIndex(tf.CursorLine, ri)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorUp moves the cursor up
func (tf *TextField) CursorUp(steps int) {
if tf.NLines <= 1 {
return
}
if tf.CursorLine <= 0 {
return
}
_, ri, _ := tf.RenderAll.RuneSpanPos(tf.CursorPos)
tf.CursorLine = max(tf.CursorLine-steps, 0)
tf.CursorPos, _ = tf.RenderAll.SpanPosToRuneIndex(tf.CursorLine, ri)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorStart moves the cursor to the start of the text, updating selection
// if select mode is active
func (tf *TextField) CursorStart() {
tf.CursorPos = 0
tf.StartPos = 0
tf.EndPos = min(len(tf.EditTxt), tf.StartPos+tf.CharWidth)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorEnd moves the cursor to the end of the text
func (tf *TextField) CursorEnd() {
ed := len(tf.EditTxt)
tf.CursorPos = ed
tf.EndPos = len(tf.EditTxt) // try -- display will adjust
tf.StartPos = max(0, tf.EndPos-tf.CharWidth)
if tf.SelectMode {
tf.SelectRegUpdate(tf.CursorPos)
}
tf.NeedsRender()
}
// CursorBackspace deletes character(s) immediately before cursor
func (tf *TextField) CursorBackspace(steps int) {
if tf.HasSelection() {
tf.DeleteSelection()
return
}
if tf.CursorPos < steps {
steps = tf.CursorPos
}
if steps <= 0 {
return
}
tf.Edited = true
tf.EditTxt = append(tf.EditTxt[:tf.CursorPos-steps], tf.EditTxt[tf.CursorPos:]...)
tf.CursorBackward(steps)
tf.NeedsRender()
}
// CursorDelete deletes character(s) immediately after the cursor
func (tf *TextField) CursorDelete(steps int) {
if tf.HasSelection() {
tf.DeleteSelection()
return
}
if tf.CursorPos+steps > len(tf.EditTxt) {
steps = len(tf.EditTxt) - tf.CursorPos
}
if steps <= 0 {
return
}
tf.Edited = true
tf.EditTxt = append(tf.EditTxt[:tf.CursorPos], tf.EditTxt[tf.CursorPos+steps:]...)
tf.NeedsRender()
}
// CursorBackspaceWord deletes words(s) immediately before cursor
func (tf *TextField) CursorBackspaceWord(steps int) {
if tf.HasSelection() {
tf.DeleteSelection()
return
}
org := tf.CursorPos
tf.CursorBackwardWord(steps)
tf.Edited = true
tf.EditTxt = append(tf.EditTxt[:tf.CursorPos], tf.EditTxt[org:]...)
tf.NeedsRender()
}
// CursorDeleteWord deletes word(s) immediately after the cursor
func (tf *TextField) CursorDeleteWord(steps int) {
if tf.HasSelection() {
tf.DeleteSelection()
return
}
// note: no update b/c signal from buf will drive update
org := tf.CursorPos
tf.CursorForwardWord(steps)
tf.Edited = true
tf.EditTxt = append(tf.EditTxt[:tf.CursorPos], tf.EditTxt[org:]...)
tf.NeedsRender()
}
// CursorKill deletes text from cursor to end of text
func (tf *TextField) CursorKill() {
steps := len(tf.EditTxt) - tf.CursorPos
tf.CursorDelete(steps)
}
///////////////////////////////////////////////////////////////////////////////
// Selection
// ClearSelected resets both the global selected flag and any current selection
func (tf *TextField) ClearSelected() {
tf.SetState(false, states.Selected)
tf.SelectReset()
}
// HasSelection returns whether there is a selected region of text
func (tf *TextField) HasSelection() bool {
tf.SelectUpdate()
return tf.SelectStart < tf.SelectEnd
}
// Selection returns the currently selected text
func (tf *TextField) Selection() string {
if tf.HasSelection() {
return string(tf.EditTxt[tf.SelectStart:tf.SelectEnd])
}
return ""
}
// SelectModeToggle toggles the SelectMode, updating selection with cursor movement
func (tf *TextField) SelectModeToggle() {
if tf.SelectMode {
tf.SelectMode = false
} else {
tf.SelectMode = true
tf.SelectInit = tf.CursorPos
tf.SelectStart = tf.CursorPos
tf.SelectEnd = tf.SelectStart
}
}
// ShiftSelect sets the selection start if the shift key is down but wasn't previously.
// If the shift key has been released, the selection info is cleared.
func (tf *TextField) ShiftSelect(e events.Event) {
hasShift := e.HasAnyModifier(key.Shift)
if hasShift && !tf.SelectMode {
tf.SelectModeToggle()
}
if !hasShift && tf.SelectMode {
tf.SelectReset()
}
}
// SelectRegUpdate updates current select region based on given cursor position
// relative to SelectStart position
func (tf *TextField) SelectRegUpdate(pos int) {
if pos < tf.SelectInit {
tf.SelectStart = pos
tf.SelectEnd = tf.SelectInit
} else {
tf.SelectStart = tf.SelectInit
tf.SelectEnd = pos
}
tf.SelectUpdate()
}
// SelectAll selects all the text
func (tf *TextField) SelectAll() {
tf.SelectStart = 0
tf.SelectInit = 0
tf.SelectEnd = len(tf.EditTxt)
if TheApp.SystemPlatform().IsMobile() {
tf.Send(events.ContextMenu)
}
tf.NeedsRender()
}
// IsWordBreak defines what counts as a word break for the purposes of selecting words
func (tf *TextField) IsWordBreak(r rune) bool {
return unicode.IsSpace(r) || unicode.IsSymbol(r) || unicode.IsPunct(r)
}
// SelectWord selects the word (whitespace delimited) that the cursor is on
func (tf *TextField) SelectWord() {
sz := len(tf.EditTxt)
if sz <= 3 {
tf.SelectAll()
return
}
tf.SelectStart = tf.CursorPos
if tf.SelectStart >= sz {
tf.SelectStart = sz - 2
}
if !tf.IsWordBreak(tf.EditTxt[tf.SelectStart]) {
for tf.SelectStart > 0 {
if tf.IsWordBreak(tf.EditTxt[tf.SelectStart-1]) {
break
}
tf.SelectStart--
}
tf.SelectEnd = tf.CursorPos + 1
for tf.SelectEnd < sz {
if tf.IsWordBreak(tf.EditTxt[tf.SelectEnd]) {
break
}
tf.SelectEnd++
}
} else { // keep the space start -- go to next space..
tf.SelectEnd = tf.CursorPos + 1
for tf.SelectEnd < sz {
if !tf.IsWordBreak(tf.EditTxt[tf.SelectEnd]) {
break
}
tf.SelectEnd++
}
for tf.SelectEnd < sz { // include all trailing spaces
if tf.IsWordBreak(tf.EditTxt[tf.SelectEnd]) {
break
}
tf.SelectEnd++
}
}
tf.SelectInit = tf.SelectStart
if TheApp.SystemPlatform().IsMobile() {
tf.Send(events.ContextMenu)
}
tf.NeedsRender()
}
// SelectReset resets the selection
func (tf *TextField) SelectReset() {
tf.SelectMode = false
if tf.SelectStart == 0 && tf.SelectEnd == 0 {
return
}
tf.SelectStart = 0
tf.SelectEnd = 0
tf.NeedsRender()
}
// SelectUpdate updates the select region after any change to the text, to keep it in range
func (tf *TextField) SelectUpdate() {
if tf.SelectStart < tf.SelectEnd {
ed := len(tf.EditTxt)
if tf.SelectStart < 0 {
tf.SelectStart = 0
}
if tf.SelectEnd > ed {
tf.SelectEnd = ed
}
} else {
tf.SelectReset()
}
}
// Cut cuts any selected text and adds it to the clipboard
func (tf *TextField) Cut() {
if tf.NoEcho {
return
}
cut := tf.DeleteSelection()
if cut != "" {
em := tf.EventMgr()
if em != nil {
em.Clipboard().Write(mimedata.NewText(cut))
}
}
}
// DeleteSelection deletes any selected text, without adding to clipboard --
// returns text deleted
func (tf *TextField) DeleteSelection() string {
tf.SelectUpdate()
if !tf.HasSelection() {
return ""
}
cut := tf.Selection()
tf.Edited = true
tf.EditTxt = append(tf.EditTxt[:tf.SelectStart], tf.EditTxt[tf.SelectEnd:]...)
if tf.CursorPos > tf.SelectStart {
if tf.CursorPos < tf.SelectEnd {
tf.CursorPos = tf.SelectStart
} else {
tf.CursorPos -= tf.SelectEnd - tf.SelectStart
}
}
tf.SelectReset()
tf.NeedsRender()
return cut
}
// Copy copies any selected text to the clipboard.
// Satisfies Clipper interface -- can be extended in subtypes.
// optionally resetting the current selection
func (tf *TextField) Copy(reset bool) {
if tf.NoEcho {
return
}
tf.SelectUpdate()
if !tf.HasSelection() {
return
}
md := mimedata.NewText(tf.Text())
tf.Clipboard().Write(md)
if reset {
tf.SelectReset()
}
}
// Paste inserts text from the clipboard at current cursor position -- if
// cursor is within a current selection, that selection is replaced.
// Satisfies Clipper interface -- can be extended in subtypes.
func (tf *TextField) Paste() {
data := tf.Clipboard().Read([]string{mimedata.TextPlain})
if data != nil {
if tf.CursorPos >= tf.SelectStart && tf.CursorPos < tf.SelectEnd {
tf.DeleteSelection()
}
tf.InsertAtCursor(data.Text(mimedata.TextPlain))
}
}
// InsertAtCursor inserts given text at current cursor position
func (tf *TextField) InsertAtCursor(str string) {
if tf.HasSelection() {
tf.Cut()
}
tf.Edited = true
rs := []rune(str)
rsl := len(rs)
nt := append(tf.EditTxt, rs...) // first append to end
copy(nt[tf.CursorPos+rsl:], nt[tf.CursorPos:]) // move stuff to end
copy(nt[tf.CursorPos:], rs) // copy into position
tf.EditTxt = nt
tf.EndPos += rsl
tf.CursorForward(rsl)
tf.NeedsRender()
}