-
Notifications
You must be signed in to change notification settings - Fork 0
/
textview.go
4861 lines (4522 loc) · 135 KB
/
textview.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, The GoKi Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package giv
import (
"fmt"
"image"
"image/draw"
"log"
"strings"
"sync"
"time"
"unicode"
"github.com/goki/gi/girl"
"github.com/goki/gi/gist"
"github.com/goki/gi/giv/textbuf"
"github.com/goki/gi/histyle"
"github.com/goki/gi/oswin/cursor"
"github.com/goki/mat32"
"github.com/chewxy/math32"
"github.com/goki/gi/gi"
"github.com/goki/gi/oswin"
"github.com/goki/gi/oswin/key"
"github.com/goki/gi/oswin/mimedata"
"github.com/goki/gi/oswin/mouse"
"github.com/goki/gi/units"
"github.com/goki/ki/indent"
"github.com/goki/ki/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/pi/filecat"
"github.com/goki/pi/lex"
"github.com/goki/pi/pi"
"github.com/goki/pi/token"
)
// TextView is a widget for editing multiple lines of text (as compared to
// TextField for a single line). The View is driven by a TextBuf buffer which
// contains all the text, and manages all the edits, sending update signals
// out to the views -- multiple views can be attached to a given buffer. All
// updating in the TextView should be within a single goroutine -- it would
// require extensive protections throughout code otherwise.
type TextView struct {
gi.WidgetBase
Buf *TextBuf `json:"-" xml:"-" desc:"the text buffer that we're editing"`
Placeholder string `json:"-" xml:"placeholder" desc:"text that is displayed when the field is empty, in a lower-contrast manner"`
CursorWidth units.Value `xml:"cursor-width" desc:"width of cursor -- set from cursor-width property (inherited)"`
NLines int `json:"-" xml:"-" desc:"number of lines in the view -- sync'd with the Buf after edits, but always reflects storage size of Renders etc"`
Renders []girl.Text `json:"-" xml:"-" desc:"renders of the text lines, with one render per line (each line could visibly wrap-around, so these are logical lines, not display lines)"`
Offs []float32 `json:"-" xml:"-" desc:"starting offsets for top of each line"`
LineNoDigs int `json:"-" xml:"-" desc:"number of line number digits needed"`
LineNoOff float32 `json:"-" xml:"-" desc:"horizontal offset for start of text after line numbers"`
LineNoRender girl.Text `json:"-" xml:"-" desc:"render for line numbers"`
LinesSize image.Point `json:"-" xml:"-" desc:"total size of all lines as rendered"`
RenderSz mat32.Vec2 `json:"-" xml:"-" desc:"size params to use in render call"`
CursorPos lex.Pos `json:"-" xml:"-" desc:"current cursor position"`
CursorCol int `json:"-" xml:"-" desc:"desired cursor column -- where the cursor was last when moved using left / right arrows -- used when doing up / down to not always go to short line columns"`
ScrollToCursorOnRender bool `json:"-" xml:"-" desc:"if true, scroll screen to cursor on next render"`
PosHistIdx int `json:"-" xml:"-" desc:"current index within PosHistory"`
SelectStart lex.Pos `json:"-" xml:"-" desc:"starting point for selection -- will either be the start or end of selected region depending on subsequent selection."`
SelectReg textbuf.Region `json:"-" xml:"-" desc:"current selection region"`
PrevSelectReg textbuf.Region `json:"-" xml:"-" desc:"previous selection region, that was actually rendered -- needed to update render"`
Highlights []textbuf.Region `json:"-" xml:"-" desc:"highlighted regions, e.g., for search results"`
Scopelights []textbuf.Region `json:"-" xml:"-" desc:"highlighted regions, specific to scope markers"`
SelectMode bool `json:"-" xml:"-" desc:"if true, select text as cursor moves"`
ForceComplete bool `json:"-" xml:"-" desc:"if true, complete regardless of any disqualifying reasons"`
ISearch ISearch `json:"-" xml:"-" desc:"interactive search data"`
QReplace QReplace `json:"-" xml:"-" desc:"query replace data"`
TextViewSig ki.Signal `json:"-" xml:"-" view:"-" desc:"signal for text view -- see TextViewSignals for the types"`
LinkSig ki.Signal `json:"-" xml:"-" view:"-" desc:"signal for clicking on a link -- data is a string of the URL -- if nobody receiving this signal, calls TextLinkHandler then URLHandler"`
StateStyles [TextViewStatesN]gist.Style `json:"-" xml:"-" desc:"normal style and focus style"`
FontHeight float32 `json:"-" xml:"-" desc:"font height, cached during styling"`
LineHeight float32 `json:"-" xml:"-" desc:"line height, cached during styling"`
VisSize image.Point `json:"-" xml:"-" desc:"height in lines and width in chars of the visible area"`
BlinkOn bool `json:"-" xml:"-" desc:"oscillates between on and off for blinking"`
CursorMu sync.Mutex `json:"-" xml:"-" view:"-" desc:"mutex protecting cursor rendering -- shared between blink and main code"`
HasLinks bool `json:"-" xml:"-" desc:"at least one of the renders has links -- determines if we set the cursor for hand movements"`
lastRecenter int
lastAutoInsert rune
lastFilename gi.FileName
}
var KiT_TextView = kit.Types.AddType(&TextView{}, TextViewProps)
// AddNewTextView adds a new textview to given parent node, with given name.
func AddNewTextView(parent ki.Ki, name string) *TextView {
return parent.AddNewChild(KiT_TextView, name).(*TextView)
}
func (tv *TextView) Disconnect() {
tv.WidgetBase.Disconnect()
tv.TextViewSig.DisconnectAll()
tv.LinkSig.DisconnectAll()
}
var TextViewProps = ki.Props{
"EnumType:Flag": KiT_TextViewFlags,
"white-space": gist.WhiteSpacePreWrap,
"border-width": 0, // don't render our own border
"cursor-width": units.NewPx(3),
"border-color": &gi.Prefs.Colors.Border,
"border-style": gist.BorderSolid,
"padding": units.NewPx(2),
"margin": units.NewPx(2),
"vertical-align": gist.AlignTop,
"text-align": gist.AlignLeft,
"tab-size": 4,
"color": &gi.Prefs.Colors.Font,
"background-color": &gi.Prefs.Colors.Background,
TextViewSelectors[TextViewActive]: ki.Props{
"background-color": "highlight-10",
},
TextViewSelectors[TextViewFocus]: ki.Props{
"background-color": "lighter-0",
},
TextViewSelectors[TextViewInactive]: ki.Props{
"background-color": "highlight-20",
},
TextViewSelectors[TextViewSel]: ki.Props{
"background-color": &gi.Prefs.Colors.Select,
},
TextViewSelectors[TextViewHighlight]: ki.Props{
"background-color": &gi.Prefs.Colors.Highlight,
},
}
// TextViewSignals are signals that text view can send
type TextViewSignals int64
const (
// TextViewDone signal indicates return was pressed and an edit was completed -- data is the text
TextViewDone TextViewSignals = iota
// TextViewSelected signal indicates some text was selected (for Inactive state, selection is via WidgetSig)
TextViewSelected
// TextViewCursorMoved signal indicates cursor moved emitted for every cursor movement -- e.g., for displaying cursor pos
TextViewCursorMoved
// TextViewISearch is emitted for every update of interactive search process -- see
// ISearch.* members for current state
TextViewISearch
// TextViewQReplace is emitted for every update of query-replace process -- see
// QReplace.* members for current state
TextViewQReplace
// TextViewSignalsN is the number of TextViewSignals
TextViewSignalsN
)
//go:generate stringer -type=TextViewSignals
// TextViewStates are mutually-exclusive textfield states -- determines appearance
type TextViewStates int32
const (
// TextViewActive is the normal state -- there but not being interacted with
TextViewActive TextViewStates = iota
// TextViewFocus states means textvieww is the focus -- will respond to keyboard input
TextViewFocus
// TextViewInactive means the textview is inactive -- not editable
TextViewInactive
// TextViewSel means the text region is selected
TextViewSel
// TextViewHighlight means the text region is highlighted
TextViewHighlight
// TextViewStatesN is the number of textview states
TextViewStatesN
)
//go:generate stringer -type=TextViewStates
// Style selector names for the different states
var TextViewSelectors = []string{":active", ":focus", ":inactive", ":selected", ":highlight"}
// TextViewFlags extend NodeBase NodeFlags to hold TextView state
type TextViewFlags int
//go:generate stringer -type=TextViewFlags
var KiT_TextViewFlags = kit.Enums.AddEnumExt(gi.KiT_NodeFlags, TextViewFlagsN, kit.BitFlag, nil)
const (
// TextViewNeedsRefresh indicates when refresh is required
TextViewNeedsRefresh TextViewFlags = TextViewFlags(gi.NodeFlagsN) + iota
// TextViewInReLayout indicates that we are currently resizing ourselves via parent layout
TextViewInReLayout
// TextViewRenderScrolls indicates that parent layout scrollbars need to be re-rendered at next rerender
TextViewRenderScrolls
// TextViewFocusActive is set if the keyboard focus is active -- when we lose active focus we apply changes
TextViewFocusActive
// TextViewHasLineNos indicates that this view has line numbers (per TextBuf option)
TextViewHasLineNos
// TextViewLastWasTabAI indicates that last key was a Tab auto-indent
TextViewLastWasTabAI
// TextViewLastWasUndo indicates that last key was an undo
TextViewLastWasUndo
TextViewFlagsN
)
// IsFocusActive returns true if we have active focus for keyboard input
func (tv *TextView) IsFocusActive() bool {
return tv.HasFlag(int(TextViewFocusActive))
}
// 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 (tv *TextView) EditDone() {
if tv.Buf != nil {
tv.Buf.EditDone()
}
tv.ClearSelected()
}
// Refresh re-displays everything anew from the buffer
func (tv *TextView) Refresh() {
if tv == nil || tv.This() == nil {
return
}
if !tv.This().(gi.Node2D).IsVisible() {
return
}
tv.LayoutAllLines(false)
tv.RenderAllLines()
tv.ClearNeedsRefresh()
}
// Remarkup triggers a complete re-markup of the entire text --
// can do this when needed if the markup gets off due to multi-line
// formatting issues -- via Recenter key
func (tv *TextView) ReMarkup() {
if tv.Buf == nil {
return
}
tv.Buf.ReMarkup()
}
// NeedsRefresh checks if a refresh is required -- atomically safe for other
// routines to set the NeedsRefresh flag
func (tv *TextView) NeedsRefresh() bool {
return tv.HasFlag(int(TextViewNeedsRefresh))
}
// SetNeedsRefresh flags that a refresh is required -- atomically safe for
// other routines to call this
func (tv *TextView) SetNeedsRefresh() {
tv.SetFlag(int(TextViewNeedsRefresh))
}
// ClearNeedsRefresh clears needs refresh flag -- atomically safe
func (tv *TextView) ClearNeedsRefresh() {
tv.ClearFlag(int(TextViewNeedsRefresh))
}
// RefreshIfNeeded re-displays everything if SetNeedsRefresh was called --
// returns true if refreshed
func (tv *TextView) RefreshIfNeeded() bool {
if tv.NeedsRefresh() {
tv.Refresh()
return true
}
return false
}
// IsChanged returns true if buffer was changed (edited)
func (tv *TextView) IsChanged() bool {
if tv.Buf != nil && tv.Buf.IsChanged() {
return true
}
return false
}
// HasLineNos returns true if view is showing line numbers (per textbuf option, cached here)
func (tv *TextView) HasLineNos() bool {
return tv.HasFlag(int(TextViewHasLineNos))
}
// Clear resets all the text in the buffer for this view
func (tv *TextView) Clear() {
if tv.Buf == nil {
return
}
tv.Buf.New(0)
}
///////////////////////////////////////////////////////////////////////////////
// Buffer communication
// ResetState resets all the random state variables, when opening a new buffer etc
func (tv *TextView) ResetState() {
tv.SelectReset()
tv.Highlights = nil
tv.ISearch.On = false
tv.QReplace.On = false
if tv.Buf == nil || tv.lastFilename != tv.Buf.Filename { // don't reset if reopening..
tv.CursorPos = lex.Pos{}
}
if tv.Buf != nil {
tv.Buf.SetInactive(tv.IsInactive())
}
}
// SetBuf sets the TextBuf that this is a view of, and interconnects their signals
func (tv *TextView) SetBuf(buf *TextBuf) {
if buf != nil && tv.Buf == buf {
return
}
// had := false
if tv.Buf != nil {
// had = true
tv.Buf.DeleteView(tv)
}
tv.Buf = buf
tv.ResetState()
if buf != nil {
buf.AddView(tv)
bhl := len(buf.PosHistory)
if bhl > 0 {
tv.CursorPos = buf.PosHistory[bhl-1]
tv.PosHistIdx = bhl - 1
}
}
tv.LayoutAllLines(false)
tv.SetFullReRender()
tv.UpdateSig()
tv.SetCursorShow(tv.CursorPos)
}
// LinesInserted inserts new lines of text and reformats them
func (tv *TextView) LinesInserted(tbe *textbuf.Edit) {
stln := tbe.Reg.Start.Ln + 1
nsz := (tbe.Reg.End.Ln - tbe.Reg.Start.Ln)
if stln > len(tv.Renders) { // invalid
return
}
// Renders
tmprn := make([]girl.Text, nsz)
nrn := append(tv.Renders, tmprn...)
copy(nrn[stln+nsz:], nrn[stln:])
copy(nrn[stln:], tmprn)
tv.Renders = nrn
// Offs
tmpof := make([]float32, nsz)
nof := append(tv.Offs, tmpof...)
copy(nof[stln+nsz:], nof[stln:])
copy(nof[stln:], tmpof)
tv.Offs = nof
tv.NLines += nsz
tv.LayoutLines(tbe.Reg.Start.Ln, tbe.Reg.End.Ln, false)
tv.RenderAllLines()
}
// LinesDeleted deletes lines of text and reformats remaining one
func (tv *TextView) LinesDeleted(tbe *textbuf.Edit) {
stln := tbe.Reg.Start.Ln
edln := tbe.Reg.End.Ln
dsz := edln - stln
tv.Renders = append(tv.Renders[:stln], tv.Renders[edln:]...)
tv.Offs = append(tv.Offs[:stln], tv.Offs[edln:]...)
tv.NLines -= dsz
tv.LayoutLines(tbe.Reg.Start.Ln, tbe.Reg.Start.Ln, true)
tv.RenderAllLines()
}
// TextViewBufSigRecv receives a signal from the buffer and updates view accordingly
func TextViewBufSigRecv(rvwki ki.Ki, sbufki ki.Ki, sig int64, data interface{}) {
tv := rvwki.Embed(KiT_TextView).(*TextView)
if !tv.This().(gi.Node2D).IsVisible() {
return
}
switch TextBufSignals(sig) {
case TextBufDone:
case TextBufNew:
tv.ResetState()
tv.Refresh()
tv.SetCursorShow(tv.CursorPos)
case TextBufInsert:
if tv.Renders == nil { // not init yet
return
}
tbe := data.(*textbuf.Edit)
// fmt.Printf("tv %v got %v\n", tv.Nm, tbe.Reg.Start)
if tbe.Reg.Start.Ln != tbe.Reg.End.Ln {
// fmt.Printf("tv %v lines insert %v - %v\n", tv.Nm, tbe.Reg.Start, tbe.Reg.End)
tv.LinesInserted(tbe)
} else {
rerend := tv.LayoutLines(tbe.Reg.Start.Ln, tbe.Reg.End.Ln, false)
if rerend {
// fmt.Printf("tv %v line insert rerend %v - %v\n", tv.Nm, tbe.Reg.Start, tbe.Reg.End)
tv.RenderAllLines()
} else {
// fmt.Printf("tv %v line insert no rerend %v - %v. markup: %v\n", tv.Nm, tbe.Reg.Start, tbe.Reg.End, len(tv.Buf.HiTags[tbe.Reg.Start.Ln]))
tv.RenderLines(tbe.Reg.Start.Ln, tbe.Reg.End.Ln)
}
}
case TextBufDelete:
if tv.Renders == nil { // not init yet
return
}
tbe := data.(*textbuf.Edit)
if tbe.Reg.Start.Ln != tbe.Reg.End.Ln {
tv.LinesDeleted(tbe)
} else {
rerend := tv.LayoutLines(tbe.Reg.Start.Ln, tbe.Reg.End.Ln, true)
if rerend {
tv.RenderAllLines()
} else {
tv.RenderLines(tbe.Reg.Start.Ln, tbe.Reg.End.Ln)
}
}
case TextBufMarkUpdt:
tv.SetNeedsRefresh() // comes from another goroutine
case TextBufClosed:
tv.SetBuf(nil)
}
}
///////////////////////////////////////////////////////////////////////////////
// Text formatting and rendering
// ParentLayout returns our parent layout -- we ensure this is our immediate parent which is necessary
// for textview
func (tv *TextView) ParentLayout() *gi.Layout {
if tv.Par == nil {
return nil
}
pari, _ := gi.KiToNode2D(tv.Par)
return pari.AsLayout2D()
}
// RenderSize is the size we should pass to text rendering, based on alloc
func (tv *TextView) RenderSize() mat32.Vec2 {
spc := tv.Sty.BoxSpace()
if tv.Par == nil {
return mat32.Vec2Zero
}
parw := tv.ParentLayout()
if parw == nil {
log.Printf("giv.TextView Programmer Error: A TextView MUST be located within a parent Layout object -- instead parent is %v at: %v\n", ki.Type(tv.Par), tv.Path())
return mat32.Vec2Zero
}
parw.SetReRenderAnchor()
paloc := parw.LayState.Alloc.SizeOrig
if !paloc.IsNil() {
// fmt.Printf("paloc: %v, pvp: %v lineonoff: %v\n", paloc, parw.VpBBox, tv.LineNoOff)
tv.RenderSz = paloc.Sub(parw.ExtraSize).SubScalar(spc * 2)
tv.RenderSz.X -= spc // extra space
// fmt.Printf("alloc rendersz: %v\n", tv.RenderSz)
} else {
sz := tv.LayState.Alloc.SizeOrig
if sz.IsNil() {
sz = tv.LayState.SizePrefOrMax()
}
if !sz.IsNil() {
sz.SetSubScalar(2 * spc)
}
tv.RenderSz = sz
// fmt.Printf("fallback rendersz: %v\n", tv.RenderSz)
}
tv.RenderSz.X -= tv.LineNoOff
// fmt.Printf("rendersz: %v\n", tv.RenderSz)
return tv.RenderSz
}
// HiStyle applies the highlighting styles from buffer markup style
func (tv *TextView) HiStyle() {
if !tv.Buf.Hi.HasHi() {
return
}
tv.CSS = tv.Buf.Hi.CSSProps
if chp, ok := ki.SubProps(tv.CSS, ".chroma"); ok {
for ky, vl := range chp { // apply to top level
tv.SetProp(ky, vl)
}
}
}
// LayoutAllLines generates TextRenders of lines from our TextBuf, from the
// Markup version of the source, and returns whether the current rendered size
// is different from what it was previously
func (tv *TextView) LayoutAllLines(inLayout bool) bool {
if inLayout && tv.HasFlag(int(TextViewInReLayout)) {
return false
}
if tv.Buf == nil || tv.Buf.NumLines() == 0 {
tv.NLines = 0
return tv.ResizeIfNeeded(image.ZP)
}
tv.StyMu.RLock()
needSty := tv.Sty.Font.Size.Val == 0
tv.StyMu.RUnlock()
if needSty {
// fmt.Print("textview: no style\n")
return false
// tv.StyleTextView() // this fails on mac
}
tv.lastFilename = tv.Buf.Filename
tv.Buf.Hi.TabSize = tv.Sty.Text.TabSize
tv.HiStyle()
// fmt.Printf("layout all: %v\n", tv.Nm)
tv.NLines = tv.Buf.NumLines()
nln := tv.NLines
if cap(tv.Renders) >= nln {
tv.Renders = tv.Renders[:nln]
} else {
tv.Renders = make([]girl.Text, nln)
}
if cap(tv.Offs) >= nln {
tv.Offs = tv.Offs[:nln]
} else {
tv.Offs = make([]float32, nln)
}
tv.VisSizes()
sz := tv.RenderSz
// fmt.Printf("rendersize: %v\n", sz)
sty := &tv.Sty
fst := sty.Font
fst.BgColor.SetColor(nil)
off := float32(0)
mxwd := sz.X // always start with our render size
tv.Buf.MarkupMu.RLock()
tv.HasLinks = false
for ln := 0; ln < nln; ln++ {
tv.Renders[ln].SetHTMLPre(tv.Buf.Markup[ln], &fst, &sty.Text, &sty.UnContext, tv.CSS)
tv.Renders[ln].LayoutStdLR(&sty.Text, &sty.Font, &sty.UnContext, sz)
if !tv.HasLinks && len(tv.Renders[ln].Links) > 0 {
tv.HasLinks = true
}
tv.Offs[ln] = off
lsz := mat32.Max(tv.Renders[ln].Size.Y, tv.LineHeight)
off += lsz
mxwd = mat32.Max(mxwd, tv.Renders[ln].Size.X)
}
tv.Buf.MarkupMu.RUnlock()
extraHalf := tv.LineHeight * 0.5 * float32(tv.VisSize.Y)
nwSz := mat32.Vec2{mxwd, off + extraHalf}.ToPointCeil()
// fmt.Printf("lay lines: diff: %v old: %v new: %v\n", diff, tv.LinesSize, nwSz)
if inLayout {
tv.LinesSize = nwSz
return tv.SetSize()
}
return tv.ResizeIfNeeded(nwSz)
}
// SetSize updates our size only if larger than our allocation
func (tv *TextView) SetSize() bool {
sty := &tv.Sty
spc := sty.BoxSpace()
rndsz := tv.RenderSz
rndsz.X += tv.LineNoOff
netsz := mat32.Vec2{float32(tv.LinesSize.X) + tv.LineNoOff, float32(tv.LinesSize.Y)}
cursz := tv.LayState.Alloc.Size.SubScalar(2 * spc)
if cursz.X < 10 || cursz.Y < 10 {
nwsz := netsz.Max(rndsz)
tv.Size2DFromWH(nwsz.X, nwsz.Y)
tv.LayState.Size.Need = tv.LayState.Alloc.Size
tv.LayState.Size.Pref = tv.LayState.Alloc.Size
return true
}
nwsz := netsz.Max(rndsz)
alloc := tv.LayState.Alloc.Size
tv.Size2DFromWH(nwsz.X, nwsz.Y)
if alloc != tv.LayState.Alloc.Size {
tv.LayState.Size.Need = tv.LayState.Alloc.Size
tv.LayState.Size.Pref = tv.LayState.Alloc.Size
return true
}
// fmt.Printf("NO resize: netsz: %v cursz: %v rndsz: %v\n", netsz, cursz, rndsz)
return false
}
// ResizeIfNeeded resizes the edit area if different from current setting --
// returns true if resizing was performed
func (tv *TextView) ResizeIfNeeded(nwSz image.Point) bool {
if nwSz == tv.LinesSize {
return false
}
// fmt.Printf("%v needs resize: %v\n", tv.Nm, nwSz)
tv.LinesSize = nwSz
diff := tv.SetSize()
if !diff {
// fmt.Printf("%v resize no setsize: %v\n", tv.Nm, nwSz)
return false
}
ly := tv.ParentLayout()
if ly != nil {
tv.SetFlag(int(TextViewInReLayout))
gi.GatherSizes(ly) // can't call Size2D b/c that resets layout
ly.Layout2DTree()
tv.SetFlag(int(TextViewRenderScrolls))
tv.ClearFlag(int(TextViewInReLayout))
// fmt.Printf("resized: %v\n", tv.LayState.Alloc.Size)
}
return true
}
// LayoutLines generates render of given range of lines (including
// highlighting). end is *inclusive* line. isDel means this is a delete and
// thus offsets for all higher lines need to be recomputed. returns true if
// overall number of effective lines (e.g., from word-wrap) is now different
// than before, and thus a full re-render is needed.
func (tv *TextView) LayoutLines(st, ed int, isDel bool) bool {
if tv.Buf == nil || tv.Buf.NumLines() == 0 {
return false
}
sty := &tv.Sty
fst := sty.Font
fst.BgColor.SetColor(nil)
mxwd := float32(tv.LinesSize.X)
rerend := false
tv.Buf.MarkupMu.RLock()
for ln := st; ln <= ed; ln++ {
curspans := len(tv.Renders[ln].Spans)
tv.Renders[ln].SetHTMLPre(tv.Buf.Markup[ln], &fst, &sty.Text, &sty.UnContext, tv.CSS)
tv.Renders[ln].LayoutStdLR(&sty.Text, &sty.Font, &sty.UnContext, tv.RenderSz)
if !tv.HasLinks && len(tv.Renders[ln].Links) > 0 {
tv.HasLinks = true
}
nwspans := len(tv.Renders[ln].Spans)
if nwspans != curspans && (nwspans > 1 || curspans > 1) {
rerend = true
}
mxwd = mat32.Max(mxwd, tv.Renders[ln].Size.X)
}
tv.Buf.MarkupMu.RUnlock()
// update all offsets to end of text
if rerend || isDel || st != ed {
ofst := st - 1
if ofst < 0 {
ofst = 0
}
off := tv.Offs[ofst]
for ln := ofst; ln < tv.NLines; ln++ {
tv.Offs[ln] = off
lsz := mat32.Max(tv.Renders[ln].Size.Y, tv.LineHeight)
off += lsz
}
extraHalf := tv.LineHeight * 0.5 * float32(tv.VisSize.Y)
nwSz := mat32.Vec2{mxwd, off + extraHalf}.ToPointCeil()
tv.ResizeIfNeeded(nwSz)
} else {
nwSz := mat32.Vec2{mxwd, 0}.ToPointCeil()
nwSz.Y = tv.LinesSize.Y
tv.ResizeIfNeeded(nwSz)
}
return rerend
}
///////////////////////////////////////////////////////////////////////////////
// Cursor Navigation
// CursorMovedSig sends the signal that cursor has moved
func (tv *TextView) CursorMovedSig() {
tv.TextViewSig.Emit(tv.This(), int64(TextViewCursorMoved), tv.CursorPos)
}
// ValidateCursor sets current cursor to a valid cursor position
func (tv *TextView) ValidateCursor() {
if tv.Buf != nil {
tv.CursorPos = tv.Buf.ValidPos(tv.CursorPos)
} else {
tv.CursorPos = lex.PosZero
}
}
// WrappedLines returns the number of wrapped lines (spans) for given line number
func (tv *TextView) WrappedLines(ln int) int {
if ln >= len(tv.Renders) {
return 0
}
return len(tv.Renders[ln].Spans)
}
// WrappedLineNo returns the wrapped line number (span index) and rune index
// within that span of the given character position within line in position,
// and false if out of range (last valid position returned in that case -- still usable).
func (tv *TextView) WrappedLineNo(pos lex.Pos) (si, ri int, ok bool) {
if pos.Ln >= len(tv.Renders) {
return 0, 0, false
}
return tv.Renders[pos.Ln].RuneSpanPos(pos.Ch)
}
// SetCursor sets a new cursor position, enforcing it in range
func (tv *TextView) SetCursor(pos lex.Pos) {
if tv.NLines == 0 || tv.Buf == nil {
tv.CursorPos = lex.PosZero
return
}
wupdt := tv.TopUpdateStart()
defer tv.TopUpdateEnd(wupdt)
cpln := tv.CursorPos.Ln
tv.ClearScopelights()
tv.CursorPos = tv.Buf.ValidPos(pos)
if cpln != tv.CursorPos.Ln && tv.HasLineNos() { // update cursor position highlight
rs := tv.Render()
rs.PushBounds(tv.VpBBox)
rs.Lock()
tv.RenderLineNo(cpln, true, true) // render bg, and do vpupload
tv.RenderLineNo(tv.CursorPos.Ln, true, true)
rs.Unlock()
tv.Viewport.Render.PopBounds()
}
tv.Buf.MarkupLine(tv.CursorPos.Ln)
tv.CursorMovedSig()
txt := tv.Buf.Line(tv.CursorPos.Ln)
ch := tv.CursorPos.Ch
if ch < len(txt) {
r := txt[ch]
if r == '{' || r == '}' || r == '(' || r == ')' || r == '[' || r == ']' {
tp, found := tv.Buf.BraceMatch(txt[ch], tv.CursorPos)
if found {
tv.Scopelights = append(tv.Scopelights, textbuf.NewRegionPos(tv.CursorPos, lex.Pos{tv.CursorPos.Ln, tv.CursorPos.Ch + 1}))
tv.Scopelights = append(tv.Scopelights, textbuf.NewRegionPos(tp, lex.Pos{tp.Ln, tp.Ch + 1}))
if tv.CursorPos.Ln < tp.Ln {
tv.RenderLines(tv.CursorPos.Ln, tp.Ln)
} else {
tv.RenderLines(tp.Ln, tv.CursorPos.Ln)
}
}
}
}
}
// SetCursorShow sets a new cursor position, enforcing it in range, and shows
// the cursor (scroll to if hidden, render)
func (tv *TextView) SetCursorShow(pos lex.Pos) {
tv.SetCursor(pos)
tv.ScrollCursorToCenterIfHidden()
tv.RenderCursor(true)
}
// SetCursorCol sets the current target cursor column (CursorCol) to that
// of the given position
func (tv *TextView) SetCursorCol(pos lex.Pos) {
if wln := tv.WrappedLines(pos.Ln); wln > 1 {
si, ri, ok := tv.WrappedLineNo(pos)
if ok && si > 0 {
tv.CursorCol = ri
} else {
tv.CursorCol = pos.Ch
}
} else {
tv.CursorCol = pos.Ch
}
}
// SavePosHistory saves the cursor position in history stack of cursor positions
func (tv *TextView) SavePosHistory(pos lex.Pos) {
if tv.Buf == nil {
return
}
tv.Buf.SavePosHistory(pos)
tv.PosHistIdx = len(tv.Buf.PosHistory) - 1
}
// CursorToHistPrev moves cursor to previous position on history list --
// returns true if moved
func (tv *TextView) CursorToHistPrev() bool {
if tv.NLines == 0 || tv.Buf == nil {
tv.CursorPos = lex.PosZero
return false
}
sz := len(tv.Buf.PosHistory)
if sz == 0 {
return false
}
tv.PosHistIdx--
if tv.PosHistIdx < 0 {
tv.PosHistIdx = 0
return false
}
tv.PosHistIdx = ints.MinInt(sz-1, tv.PosHistIdx)
pos := tv.Buf.PosHistory[tv.PosHistIdx]
tv.CursorPos = tv.Buf.ValidPos(pos)
tv.CursorMovedSig()
tv.ScrollCursorToCenterIfHidden()
tv.RenderCursor(true)
return true
}
// CursorToHistNext moves cursor to previous position on history list --
// returns true if moved
func (tv *TextView) CursorToHistNext() bool {
if tv.NLines == 0 || tv.Buf == nil {
tv.CursorPos = lex.PosZero
return false
}
sz := len(tv.Buf.PosHistory)
if sz == 0 {
return false
}
tv.PosHistIdx++
if tv.PosHistIdx >= sz-1 {
tv.PosHistIdx = sz - 1
return false
}
pos := tv.Buf.PosHistory[tv.PosHistIdx]
tv.CursorPos = tv.Buf.ValidPos(pos)
tv.CursorMovedSig()
tv.ScrollCursorToCenterIfHidden()
tv.RenderCursor(true)
return true
}
// SelectRegUpdate updates current select region based on given cursor position
// relative to SelectStart position
func (tv *TextView) SelectRegUpdate(pos lex.Pos) {
if pos.IsLess(tv.SelectStart) {
tv.SelectReg.Start = pos
tv.SelectReg.End = tv.SelectStart
} else {
tv.SelectReg.Start = tv.SelectStart
tv.SelectReg.End = pos
}
}
// CursorSelect updates selection based on cursor movements, given starting
// cursor position and tv.CursorPos is current
func (tv *TextView) CursorSelect(org lex.Pos) {
if !tv.SelectMode {
return
}
tv.SelectRegUpdate(tv.CursorPos)
tv.RenderSelectLines()
}
// CursorForward moves the cursor forward
func (tv *TextView) CursorForward(steps int) {
wupdt := tv.TopUpdateStart()
defer tv.TopUpdateEnd(wupdt)
tv.ValidateCursor()
org := tv.CursorPos
for i := 0; i < steps; i++ {
tv.CursorPos.Ch++
if tv.CursorPos.Ch > tv.Buf.LineLen(tv.CursorPos.Ln) {
if tv.CursorPos.Ln < tv.NLines-1 {
tv.CursorPos.Ch = 0
tv.CursorPos.Ln++
} else {
tv.CursorPos.Ch = tv.Buf.LineLen(tv.CursorPos.Ln)
}
}
}
tv.SetCursorCol(tv.CursorPos)
tv.SetCursorShow(tv.CursorPos)
tv.CursorSelect(org)
}
// CursorForwardWord moves the cursor forward by words
func (tv *TextView) CursorForwardWord(steps int) {
wupdt := tv.TopUpdateStart()
defer tv.TopUpdateEnd(wupdt)
tv.ValidateCursor()
org := tv.CursorPos
for i := 0; i < steps; i++ {
txt := tv.Buf.Line(tv.CursorPos.Ln)
sz := len(txt)
if sz > 0 && tv.CursorPos.Ch < sz {
ch := tv.CursorPos.Ch
var done = false
for ch < sz && !done { // if on a wb, go past
r1 := txt[ch]
r2 := rune(-1)
if ch < sz-1 {
r2 = txt[ch+1]
}
if lex.IsWordBreak(r1, r2) {
ch++
} else {
done = true
}
}
done = false
for ch < sz && !done {
r1 := txt[ch]
r2 := rune(-1)
if ch < sz-1 {
r2 = txt[ch+1]
}
if !lex.IsWordBreak(r1, r2) {
ch++
} else {
done = true
}
}
tv.CursorPos.Ch = ch
} else {
if tv.CursorPos.Ln < tv.NLines-1 {
tv.CursorPos.Ch = 0
tv.CursorPos.Ln++
} else {
tv.CursorPos.Ch = tv.Buf.LineLen(tv.CursorPos.Ln)
}
}
}
tv.SetCursorCol(tv.CursorPos)
tv.SetCursorShow(tv.CursorPos)
tv.CursorSelect(org)
}
// CursorDown moves the cursor down line(s)
func (tv *TextView) CursorDown(steps int) {
wupdt := tv.TopUpdateStart()
defer tv.TopUpdateEnd(wupdt)
tv.ValidateCursor()
org := tv.CursorPos
pos := tv.CursorPos
for i := 0; i < steps; i++ {
gotwrap := false
if wln := tv.WrappedLines(pos.Ln); wln > 1 {
si, ri, _ := tv.WrappedLineNo(pos)
if si < wln-1 {
si++
mxlen := ints.MinInt(len(tv.Renders[pos.Ln].Spans[si].Text), tv.CursorCol)
if tv.CursorCol < mxlen {
ri = tv.CursorCol
} else {
ri = mxlen
}
nwc, _ := tv.Renders[pos.Ln].SpanPosToRuneIdx(si, ri)
if si == wln-1 && ri == mxlen {
nwc++
}
pos.Ch = nwc
gotwrap = true
}
}
if !gotwrap {
pos.Ln++
if pos.Ln >= tv.NLines {
pos.Ln = tv.NLines - 1
break
}
mxlen := ints.MinInt(tv.Buf.LineLen(pos.Ln), tv.CursorCol)
if tv.CursorCol < mxlen {
pos.Ch = tv.CursorCol
} else {
pos.Ch = mxlen
}
}
}
tv.SetCursorShow(pos)
tv.CursorSelect(org)
}
// CursorPageDown moves the cursor down page(s), where a page is defined abcdef
// dynamically as just moving the cursor off the screen
func (tv *TextView) CursorPageDown(steps int) {
wupdt := tv.TopUpdateStart()
defer tv.TopUpdateEnd(wupdt)
tv.ValidateCursor()
org := tv.CursorPos
for i := 0; i < steps; i++ {
lvln := tv.LastVisibleLine(tv.CursorPos.Ln)
tv.CursorPos.Ln = lvln
if tv.CursorPos.Ln >= tv.NLines {
tv.CursorPos.Ln = tv.NLines - 1
}
tv.CursorPos.Ch = ints.MinInt(tv.Buf.LineLen(tv.CursorPos.Ln), tv.CursorCol)
tv.ScrollCursorToTop()
tv.RenderCursor(true)
}
tv.SetCursor(tv.CursorPos)
tv.CursorSelect(org)
}