-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathlist.go
2021 lines (1832 loc) · 53.8 KB
/
list.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 (
"encoding/json"
"fmt"
"image"
"image/color"
"log"
"log/slog"
"reflect"
"sort"
"strconv"
"cogentcore.org/core/base/fileinfo"
"cogentcore.org/core/base/fileinfo/mimedata"
"cogentcore.org/core/base/reflectx"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/events"
"cogentcore.org/core/icons"
"cogentcore.org/core/keymap"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/styles/abilities"
"cogentcore.org/core/styles/states"
"cogentcore.org/core/styles/units"
"cogentcore.org/core/tree"
)
// List represents a slice value with a list of value widgets and optional index widgets.
// Use [ListBase.BindSelect] to make the list designed for item selection.
type List struct {
ListBase
// ListStyler is an optional styler for list items.
ListStyler ListStyler `copier:"-" json:"-" xml:"-"`
}
// ListStyler is a styling function for custom styling and
// configuration of elements in the list.
type ListStyler func(w Widget, s *styles.Style, row int)
func (ls *List) HasStyler() bool {
return ls.ListStyler != nil
}
func (ls *List) StyleRow(w Widget, idx, fidx int) {
if ls.ListStyler != nil {
ls.ListStyler(w, &w.AsWidget().Styles, idx)
}
}
// note on implementation:
// * ListGrid handles all the layout logic to start with a minimum number of
// rows and then computes the total number visible based on allocated size.
const (
// ListRowProperty is the tree property name for the row of a list element.
ListRowProperty = "ls-row"
// ListColProperty is the tree property name for the column of a list element.
ListColProperty = "ls-col"
)
// Lister is the interface used by [ListBase] to
// support any abstractions needed for different types of lists.
type Lister interface {
tree.Node
// AsListBase returns the base for direct access to relevant fields etc
AsListBase() *ListBase
// RowWidgetNs returns number of widgets per row and
// offset for index label
RowWidgetNs() (nWidgPerRow, idxOff int)
// UpdateSliceSize updates the current size of the slice
// and sets SliceSize if changed.
UpdateSliceSize() int
// UpdateMaxWidths updates the maximum widths per column based
// on estimates from length of strings (for string values)
UpdateMaxWidths()
// SliceIndex returns the logical slice index: si = i + StartIndex,
// the actual value index vi into the slice value (typically = si),
// which can be different if there is an index indirection as in
// tensorcore table.IndexView), and a bool that is true if the
// index is beyond the available data and is thus invisible,
// given the row index provided.
SliceIndex(i int) (si, vi int, invis bool)
// MakeRow adds config for one row at given widget row index.
// Plan must be the StructGrid Plan.
MakeRow(p *tree.Plan, i int)
// StyleValue performs additional value widget styling
StyleValue(w Widget, s *styles.Style, row, col int)
// HasStyler returns whether there is a custom style function.
HasStyler() bool
// StyleRow calls a custom style function on given row (and field)
StyleRow(w Widget, idx, fidx int)
// RowGrabFocus grabs the focus for the first focusable
// widget in given row.
// returns that element or nil if not successful
// note: grid must have already rendered for focus to be grabbed!
RowGrabFocus(row int) *WidgetBase
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
NewAt(idx int)
// DeleteAt deletes the element at the given index from the slice.
DeleteAt(idx int)
// MimeDataType returns the data type for mime clipboard
// (copy / paste) data e.g., fileinfo.DataJson
MimeDataType() string
// CopySelectToMime copies selected rows to mime data
CopySelectToMime() mimedata.Mimes
// PasteAssign assigns mime data (only the first one!) to this idx
PasteAssign(md mimedata.Mimes, idx int)
// PasteAtIndex inserts object(s) from mime data at
// (before) given slice index
PasteAtIndex(md mimedata.Mimes, idx int)
}
var _ Lister = &List{}
// ListBase is the base for [List] and [Table] and any other displays
// of array-like data. It automatically computes the number of rows that fit
// within its allocated space, and manages the offset view window into the full
// list of items, and supports row selection, copy / paste, Drag-n-Drop, etc.
// Use [ListBase.BindSelect] to make the list designed for item selection.
type ListBase struct { //core:no-new
Frame
// Slice is the pointer to the slice that we are viewing.
Slice any `set:"-"`
// ShowIndexes is whether to show the indexes of rows or not (default false).
ShowIndexes bool
// MinRows specifies the minimum number of rows to display, to ensure
// at least this amount is displayed.
MinRows int `default:"4"`
// SelectedValue is the current selection value.
// If it is set, it is used as the initially selected value.
SelectedValue any `copier:"-" display:"-" json:"-" xml:"-"`
// SelectedIndex is the index of the currently selected item.
SelectedIndex int `copier:"-" json:"-" xml:"-"`
// InitSelectedIndex is the index of the row to select at the start.
InitSelectedIndex int `copier:"-" json:"-" xml:"-"`
// SelectedIndexes is a list of currently selected slice indexes.
SelectedIndexes map[int]struct{} `set:"-" copier:"-"`
// lastClick is the last row that has been clicked on.
// This is used to prevent erroneous double click events
// from being sent when the user clicks on multiple different
// rows in quick succession.
lastClick int
// normalCursor is the cached cursor to display when there
// is no row being hovered.
normalCursor cursors.Cursor
// currentCursor is the cached cursor that should currently be
// displayed.
currentCursor cursors.Cursor
// sliceUnderlying is the underlying slice value.
sliceUnderlying reflect.Value
// currently hovered row
hoverRow int
// list of currently dragged indexes
draggedIndexes []int
// VisibleRows is the total number of rows visible in allocated display size.
VisibleRows int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// StartIndex is the starting slice index of visible rows.
StartIndex int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// SliceSize is the size of the slice.
SliceSize int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// MakeIter is the iteration through the configuration process,
// which is reset when a new slice type is set.
MakeIter int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// temp idx state for e.g., dnd
tmpIndex int
// elementValue is a [reflect.Value] representation of the underlying element type
// which is used whenever there are no slice elements available
elementValue reflect.Value
// maximum width of value column in chars, if string
maxWidth int
// ReadOnlyKeyNav is whether support key navigation when ReadOnly (default true).
// It uses a capture of up / down events to manipulate selection, not focus.
ReadOnlyKeyNav bool `default:"true"`
// SelectMode is whether to be in select rows mode or editing mode.
SelectMode bool `set:"-" copier:"-" json:"-" xml:"-"`
// ReadOnlyMultiSelect: if list is ReadOnly, default selection mode is to
// choose one row only. If this is true, standard multiple selection logic
// with modifier keys is instead supported.
ReadOnlyMultiSelect bool
// InFocusGrab is a guard for recursive focus grabbing.
InFocusGrab bool `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// isArray is whether the slice is actually an array.
isArray bool
// ListGrid is the [ListGrid] widget.
ListGrid *ListGrid `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
}
func (lb *ListBase) WidgetValue() any { return &lb.Slice }
func (lb *ListBase) Init() {
lb.Frame.Init()
lb.AddContextMenu(lb.contextMenu)
lb.InitSelectedIndex = -1
lb.hoverRow = -1
lb.MinRows = 4
lb.ReadOnlyKeyNav = true
lb.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.DoubleClickable, abilities.TripleClickable)
s.SetAbilities(!lb.IsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Cursor = lb.currentCursor
s.Direction = styles.Column
// absorb horizontal here, vertical in view
s.Overflow.X = styles.OverflowAuto
s.Grow.Set(1, 1)
})
if !lb.IsReadOnly() {
lb.On(events.DragStart, func(e events.Event) {
lb.dragStart(e)
})
lb.On(events.DragEnter, func(e events.Event) {
e.SetHandled()
})
lb.On(events.DragLeave, func(e events.Event) {
e.SetHandled()
})
lb.On(events.Drop, func(e events.Event) {
lb.dragDrop(e)
})
lb.On(events.DropDeleteSource, func(e events.Event) {
lb.dropDeleteSource(e)
})
}
lb.FinalStyler(func(s *styles.Style) {
lb.normalCursor = s.Cursor
})
lb.OnFinal(events.KeyChord, func(e events.Event) {
if lb.IsReadOnly() {
if lb.ReadOnlyKeyNav {
lb.keyInputReadOnly(e)
}
} else {
lb.keyInputEditable(e)
}
})
lb.On(events.MouseMove, func(e events.Event) {
row, _, isValid := lb.rowFromEventPos(e)
prevHoverRow := lb.hoverRow
if !isValid {
lb.hoverRow = -1
lb.Styles.Cursor = lb.normalCursor
} else {
lb.hoverRow = row
lb.Styles.Cursor = cursors.Pointer
}
lb.currentCursor = lb.Styles.Cursor
if lb.hoverRow != prevHoverRow {
lb.NeedsRender()
}
})
lb.On(events.MouseDrag, func(e events.Event) {
row, idx, isValid := lb.rowFromEventPos(e)
if !isValid {
return
}
lb.ListGrid.AutoScroll(math32.Vec2(0, float32(idx)))
prevHoverRow := lb.hoverRow
if !isValid {
lb.hoverRow = -1
lb.Styles.Cursor = lb.normalCursor
} else {
lb.hoverRow = row
lb.Styles.Cursor = cursors.Pointer
}
lb.currentCursor = lb.Styles.Cursor
if lb.hoverRow != prevHoverRow {
lb.NeedsRender()
}
})
lb.OnFirst(events.DoubleClick, func(e events.Event) {
row, _, isValid := lb.rowFromEventPos(e)
if !isValid {
return
}
if lb.lastClick != row+lb.StartIndex {
lb.ListGrid.Send(events.Click, e)
e.SetHandled()
}
})
// we must interpret triple click events as double click
// events for rapid cross-row double clicking to work correctly
lb.OnFirst(events.TripleClick, func(e events.Event) {
lb.Send(events.DoubleClick, e)
})
lb.Maker(func(p *tree.Plan) {
ls := lb.This.(Lister)
ls.UpdateSliceSize()
scrollTo := -1
if lb.SelectedValue != nil {
idx, ok := sliceIndexByValue(lb.Slice, lb.SelectedValue)
if ok {
lb.SelectedIndex = idx
scrollTo = lb.SelectedIndex
}
lb.SelectedValue = nil
lb.InitSelectedIndex = -1
} else if lb.InitSelectedIndex >= 0 {
lb.SelectedIndex = lb.InitSelectedIndex
lb.InitSelectedIndex = -1
scrollTo = lb.SelectedIndex
}
if scrollTo >= 0 {
lb.ScrollToIndex(scrollTo)
}
lb.Updater(func() {
lb.UpdateStartIndex()
})
lb.MakeGrid(p, func(p *tree.Plan) {
for i := 0; i < lb.VisibleRows; i++ {
ls.MakeRow(p, i)
}
})
})
}
func (lb *ListBase) SliceIndex(i int) (si, vi int, invis bool) {
si = lb.StartIndex + i
vi = si
invis = si >= lb.SliceSize
return
}
// StyleValue performs additional value widget styling
func (lb *ListBase) StyleValue(w Widget, s *styles.Style, row, col int) {
if lb.maxWidth > 0 {
hv := units.Ch(float32(lb.maxWidth))
s.Min.X.Value = max(s.Min.X.Value, hv.Convert(s.Min.X.Unit, &s.UnitContext).Value)
}
s.SetTextWrap(false)
}
func (lb *ListBase) AsListBase() *ListBase {
return lb
}
func (lb *ListBase) SetSliceBase() {
lb.SelectMode = false
lb.MakeIter = 0
lb.StartIndex = 0
lb.VisibleRows = lb.MinRows
if !lb.IsReadOnly() {
lb.SelectedIndex = -1
}
lb.ResetSelectedIndexes()
lb.This.(Lister).UpdateMaxWidths()
}
// SetSlice sets the source slice that we are viewing.
// This ReMakes the view for this slice if different.
// Note: it is important to at least set an empty slice of
// the desired type at the start to enable initial configuration.
func (lb *ListBase) SetSlice(sl any) *ListBase {
if reflectx.AnyIsNil(sl) {
lb.Slice = nil
return lb
}
// TODO: a lot of this garbage needs to be cleaned up.
// New is not working!
newslc := false
if reflect.TypeOf(sl).Kind() != reflect.Pointer { // prevent crash on non-comparable
newslc = true
} else {
newslc = lb.Slice != sl
}
if !newslc {
lb.MakeIter = 0
return lb
}
lb.Slice = sl
lb.sliceUnderlying = reflectx.Underlying(reflect.ValueOf(lb.Slice))
lb.isArray = reflectx.NonPointerType(reflect.TypeOf(sl)).Kind() == reflect.Array
lb.elementValue = reflectx.SliceElementValue(sl)
lb.SetSliceBase()
return lb
}
// rowFromEventPos returns the widget row, slice index, and
// whether the index is in slice range, for given event position.
func (lb *ListBase) rowFromEventPos(e events.Event) (row, idx int, isValid bool) {
sg := lb.ListGrid
row, _, isValid = sg.indexFromPixel(e.Pos())
if !isValid {
return
}
idx = row + lb.StartIndex
if row < 0 || idx >= lb.SliceSize {
isValid = false
}
return
}
// clickSelectEvent is a helper for processing selection events
// based on a mouse click, which could be a double or triple
// in addition to a regular click.
// Returns false if no further processing should occur,
// because the user clicked outside the range of active rows.
func (lb *ListBase) clickSelectEvent(e events.Event) bool {
row, _, isValid := lb.rowFromEventPos(e)
if !isValid {
e.SetHandled()
} else {
lb.updateSelectRow(row, e.SelectMode())
}
return isValid
}
// BindSelect makes the list a read-only selection list and then
// binds its events to its scene and its current selection index to the given value.
// It will send an [events.Change] event when the user changes the selection row.
func (lb *ListBase) BindSelect(val *int) *ListBase {
lb.SetReadOnly(true)
lb.OnSelect(func(e events.Event) {
*val = lb.SelectedIndex
lb.SendChange(e)
})
lb.OnDoubleClick(func(e events.Event) {
if lb.clickSelectEvent(e) {
*val = lb.SelectedIndex
lb.Scene.sendKey(keymap.Accept, e) // activate OK button
if lb.Scene.Stage.Type == DialogStage {
lb.Scene.Close() // also directly close dialog for value dialogs without OK button
}
}
})
return lb
}
func (lb *ListBase) UpdateMaxWidths() {
lb.maxWidth = 0
npv := reflectx.NonPointerValue(lb.elementValue)
isString := npv.Type().Kind() == reflect.String && npv.Type() != reflect.TypeFor[icons.Icon]()
if !isString || lb.SliceSize == 0 {
return
}
mxw := 0
for rw := 0; rw < lb.SliceSize; rw++ {
str := reflectx.ToString(lb.sliceElementValue(rw).Interface())
mxw = max(mxw, len(str))
}
lb.maxWidth = mxw
}
// sliceElementValue returns an underlying non-pointer [reflect.Value]
// of slice element at given index or ElementValue if out of range.
func (lb *ListBase) sliceElementValue(si int) reflect.Value {
var val reflect.Value
if si < lb.SliceSize {
val = reflectx.Underlying(lb.sliceUnderlying.Index(si)) // deal with pointer lists
} else {
val = reflectx.Underlying(lb.elementValue)
}
if !val.IsValid() {
val = reflectx.Underlying(lb.elementValue)
}
return val
}
func (lb *ListBase) MakeGrid(p *tree.Plan, maker func(p *tree.Plan)) {
tree.AddAt(p, "grid", func(w *ListGrid) {
lb.ListGrid = w
w.Styler(func(s *styles.Style) {
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
w.minRows = lb.MinRows
s.Display = styles.Grid
s.Columns = nWidgPerRow
s.Grow.Set(1, 1)
s.Overflow.Y = styles.OverflowAuto
s.Gap.Set(units.Em(0.5)) // note: match header
s.Align.Items = styles.Center
// baseline mins:
s.Min.X.Ch(20)
s.Min.Y.Em(6)
})
oc := func(e events.Event) {
lb.SetFocusEvent()
row, _, isValid := w.indexFromPixel(e.Pos())
if isValid {
lb.updateSelectRow(row, e.SelectMode())
lb.lastClick = row + lb.StartIndex
}
}
w.OnClick(oc)
w.On(events.ContextMenu, func(e events.Event) {
// we must select the row on right click so that the context menu
// corresponds to the right row
oc(e)
lb.HandleEvent(e)
})
w.Updater(func() {
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
w.Styles.Columns = nWidgPerRow
})
w.Maker(maker)
})
}
func (lb *ListBase) MakeValue(w Value, i int) {
ls := lb.This.(Lister)
wb := w.AsWidget()
wb.SetProperty(ListRowProperty, i)
wb.Styler(func(s *styles.Style) {
if lb.IsReadOnly() {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(false, abilities.Hoverable, abilities.Focusable, abilities.Activatable, abilities.TripleClickable)
s.SetReadOnly(true)
}
row, col := lb.widgetIndex(w)
row += lb.StartIndex
ls.StyleValue(w, s, row, col)
if row < lb.SliceSize {
ls.StyleRow(w, row, col)
}
})
wb.OnSelect(func(e events.Event) {
e.SetHandled()
row, _ := lb.widgetIndex(w)
lb.updateSelectRow(row, e.SelectMode())
lb.lastClick = row + lb.StartIndex
})
wb.OnDoubleClick(lb.HandleEvent)
wb.On(events.ContextMenu, lb.HandleEvent)
wb.OnFirst(events.ContextMenu, func(e events.Event) {
wb.Send(events.Select, e) // we must select the row for context menu actions
})
if !lb.IsReadOnly() {
wb.OnInput(lb.HandleEvent)
}
}
func (lb *ListBase) MakeRow(p *tree.Plan, i int) {
ls := lb.This.(Lister)
si, vi, invis := ls.SliceIndex(i)
itxt := strconv.Itoa(i)
val := lb.sliceElementValue(vi)
if lb.ShowIndexes {
lb.MakeGridIndex(p, i, si, itxt, invis)
}
valnm := fmt.Sprintf("value-%s-%s", itxt, reflectx.ShortTypeName(lb.elementValue.Type()))
tree.AddNew(p, valnm, func() Value {
return NewValue(val.Addr().Interface(), "")
}, func(w Value) {
wb := w.AsWidget()
lb.MakeValue(w, i)
if !lb.IsReadOnly() {
wb.OnChange(func(e events.Event) {
lb.This.(Lister).UpdateMaxWidths()
lb.SendChange(e)
})
}
wb.Updater(func() {
wb := w.AsWidget()
_, vi, invis := ls.SliceIndex(i)
val := lb.sliceElementValue(vi)
Bind(val.Addr().Interface(), w)
wb.SetReadOnly(lb.IsReadOnly())
wb.SetState(invis, states.Invisible)
if lb.This.(Lister).HasStyler() {
w.Style()
}
if invis {
wb.SetSelected(false)
}
})
})
}
func (lb *ListBase) MakeGridIndex(p *tree.Plan, i, si int, itxt string, invis bool) {
ls := lb.This.(Lister)
tree.AddAt(p, "index-"+itxt, func(w *Text) {
w.SetProperty(ListRowProperty, i)
w.Styler(func(s *styles.Style) {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(!lb.IsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Cursor = cursors.None
nd := math32.Log10(float32(lb.SliceSize))
nd = max(nd, 3)
s.Min.X.Ch(nd + 2)
s.Padding.Right.Dp(4)
s.Text.Align = styles.End
s.Min.Y.Em(1)
s.GrowWrap = false
})
w.OnSelect(func(e events.Event) {
e.SetHandled()
lb.updateSelectRow(i, e.SelectMode())
lb.lastClick = si
})
w.OnDoubleClick(lb.HandleEvent)
w.On(events.ContextMenu, lb.HandleEvent)
if !lb.IsReadOnly() {
w.On(events.DragStart, func(e events.Event) {
lb.dragStart(e)
})
w.On(events.DragEnter, func(e events.Event) {
e.SetHandled()
})
w.On(events.DragLeave, func(e events.Event) {
e.SetHandled()
})
w.On(events.Drop, func(e events.Event) {
lb.dragDrop(e)
})
w.On(events.DropDeleteSource, func(e events.Event) {
lb.dropDeleteSource(e)
})
}
w.Updater(func() {
si, _, invis := ls.SliceIndex(i)
sitxt := strconv.Itoa(si)
w.SetText(sitxt)
w.SetReadOnly(lb.IsReadOnly())
w.SetState(invis, states.Invisible)
if invis {
w.SetSelected(false)
}
})
})
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (lb *ListBase) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 2
idxOff = 1
if !lb.ShowIndexes {
nWidgPerRow -= 1
idxOff = 0
}
return
}
// UpdateSliceSize updates and returns the size of the slice
// and sets SliceSize
func (lb *ListBase) UpdateSliceSize() int {
sz := lb.sliceUnderlying.Len()
lb.SliceSize = sz
return sz
}
// widgetIndex returns the row and column indexes for given widget,
// from the properties set during construction.
func (lb *ListBase) widgetIndex(w Widget) (row, col int) {
if rwi := w.AsTree().Property(ListRowProperty); rwi != nil {
row = rwi.(int)
}
if cli := w.AsTree().Property(ListColProperty); cli != nil {
col = cli.(int)
}
return
}
// UpdateStartIndex updates StartIndex to fit current view
func (lb *ListBase) UpdateStartIndex() {
sz := lb.This.(Lister).UpdateSliceSize()
if sz > lb.VisibleRows {
lastSt := sz - lb.VisibleRows
lb.StartIndex = min(lastSt, lb.StartIndex)
lb.StartIndex = max(0, lb.StartIndex)
} else {
lb.StartIndex = 0
}
}
// updateScroll updates the scroll value
func (lb *ListBase) updateScroll() {
sg := lb.ListGrid
if sg == nil {
return
}
sg.updateScroll(lb.StartIndex)
}
// newAtRow inserts a new blank element at the given display row.
func (lb *ListBase) newAtRow(row int) {
lb.This.(Lister).NewAt(lb.StartIndex + row)
}
// NewAt inserts a new blank element at the given index in the slice.
// -1 indicates to insert the element at the end.
func (lb *ListBase) NewAt(idx int) {
if lb.isArray {
return
}
lb.NewAtSelect(idx)
reflectx.SliceNewAt(lb.Slice, idx)
if idx < 0 {
idx = lb.SliceSize
}
lb.This.(Lister).UpdateSliceSize()
lb.SelectIndexEvent(idx, events.SelectOne)
lb.UpdateChange()
lb.IndexGrabFocus(idx)
}
// deleteAtRow deletes the element at the given display row.
func (lb *ListBase) deleteAtRow(row int) {
lb.This.(Lister).DeleteAt(lb.StartIndex + row)
}
// NewAtSelect updates the selected rows based on
// inserting a new element at the given index.
func (lb *ListBase) NewAtSelect(i int) {
sl := lb.SelectedIndexesList(false) // ascending
lb.ResetSelectedIndexes()
for _, ix := range sl {
if ix >= i {
ix++
}
lb.SelectedIndexes[ix] = struct{}{}
}
}
// DeleteAtSelect updates the selected rows based on
// deleting the element at the given index.
func (lb *ListBase) DeleteAtSelect(i int) {
sl := lb.SelectedIndexesList(true) // desscending
lb.ResetSelectedIndexes()
for _, ix := range sl {
switch {
case ix == i:
continue
case ix > i:
ix--
}
lb.SelectedIndexes[ix] = struct{}{}
}
}
// DeleteAt deletes the element at the given index from the slice.
func (lb *ListBase) DeleteAt(i int) {
if lb.isArray {
return
}
if i < 0 || i >= lb.SliceSize {
return
}
lb.DeleteAtSelect(i)
reflectx.SliceDeleteAt(lb.Slice, i)
lb.This.(Lister).UpdateSliceSize()
lb.UpdateChange()
}
func (lb *ListBase) MakeToolbar(p *tree.Plan) {
if reflectx.AnyIsNil(lb.Slice) {
return
}
if lb.isArray || lb.IsReadOnly() {
return
}
tree.Add(p, func(w *Button) {
w.SetText("Add").SetIcon(icons.Add).SetTooltip("add a new element to the slice").
OnClick(func(e events.Event) {
lb.This.(Lister).NewAt(-1)
})
})
}
////////////////////////////////////////////////////////////
// Row access methods
// NOTE: row = physical GUI display row, idx = slice index
// not the same!
// sliceValue returns value interface at given slice index.
func (lb *ListBase) sliceValue(idx int) any {
if idx < 0 || idx >= lb.SliceSize {
fmt.Printf("core.ListBase: slice index out of range: %v\n", idx)
return nil
}
val := reflectx.UnderlyingPointer(lb.sliceUnderlying.Index(idx)) // deal with pointer lists
vali := val.Interface()
return vali
}
// IsRowInBounds returns true if disp row is in bounds
func (lb *ListBase) IsRowInBounds(row int) bool {
return row >= 0 && row < lb.VisibleRows
}
// rowFirstWidget returns the first widget for given row (could be index or
// not) -- false if out of range
func (lb *ListBase) rowFirstWidget(row int) (*WidgetBase, bool) {
if !lb.ShowIndexes {
return nil, false
}
if !lb.IsRowInBounds(row) {
return nil, false
}
nWidgPerRow, _ := lb.This.(Lister).RowWidgetNs()
sg := lb.ListGrid
w := sg.Children[row*nWidgPerRow].(Widget).AsWidget()
return w, true
}
// RowGrabFocus grabs the focus for the first focusable widget
// in given row. returns that element or nil if not successful
// note: grid must have already rendered for focus to be grabbed!
func (lb *ListBase) RowGrabFocus(row int) *WidgetBase {
if !lb.IsRowInBounds(row) || lb.InFocusGrab { // range check
return nil
}
nWidgPerRow, idxOff := lb.This.(Lister).RowWidgetNs()
ridx := nWidgPerRow * row
sg := lb.ListGrid
w := sg.Child(ridx + idxOff).(Widget).AsWidget()
if w.StateIs(states.Focused) {
return w
}
lb.InFocusGrab = true
w.SetFocusEvent()
lb.InFocusGrab = false
return w
}
// IndexGrabFocus grabs the focus for the first focusable widget
// in given idx. returns that element or nil if not successful.
func (lb *ListBase) IndexGrabFocus(idx int) *WidgetBase {
lb.ScrollToIndex(idx)
return lb.This.(Lister).RowGrabFocus(idx - lb.StartIndex)
}
// indexPos returns center of window position of index label for idx (ContextMenuPos)
func (lb *ListBase) indexPos(idx int) image.Point {
row := idx - lb.StartIndex
if row < 0 {
row = 0
}
if row > lb.VisibleRows-1 {
row = lb.VisibleRows - 1
}
var pos image.Point
w, ok := lb.rowFirstWidget(row)
if ok {
pos = w.ContextMenuPos(nil)
}
return pos
}
// rowFromPos returns the row that contains given vertical position, false if not found
func (lb *ListBase) rowFromPos(posY int) (int, bool) {
// todo: could optimize search to approx loc, and search up / down from there
for rw := 0; rw < lb.VisibleRows; rw++ {
w, ok := lb.rowFirstWidget(rw)
if ok {
if w.Geom.TotalBBox.Min.Y < posY && posY < w.Geom.TotalBBox.Max.Y {
return rw, true
}
}
}
return -1, false
}
// indexFromPos returns the idx that contains given vertical position, false if not found
func (lb *ListBase) indexFromPos(posY int) (int, bool) {
row, ok := lb.rowFromPos(posY)
if !ok {
return -1, false
}
return row + lb.StartIndex, true
}
// ScrollToIndexNoUpdate ensures that given slice idx is visible
// by scrolling display as needed.
// This version does not update the slicegrid.
// Just computes the StartIndex and updates the scrollbar
func (lb *ListBase) ScrollToIndexNoUpdate(idx int) bool {
if lb.VisibleRows == 0 {
return false
}
if idx < lb.StartIndex {
lb.StartIndex = idx
lb.StartIndex = max(0, lb.StartIndex)
lb.updateScroll()
return true
}
if idx >= lb.StartIndex+lb.VisibleRows {
lb.StartIndex = idx - (lb.VisibleRows - 4)
lb.StartIndex = max(0, lb.StartIndex)
lb.updateScroll()
return true
}
return false
}
// ScrollToIndex ensures that given slice idx is visible
// by scrolling display as needed.
func (lb *ListBase) ScrollToIndex(idx int) bool {
update := lb.ScrollToIndexNoUpdate(idx)
if update {
lb.Update()
}
return update
}
// sliceIndexByValue searches for first index that contains given value in slice;
// returns false if not found
func sliceIndexByValue(slc any, fldVal any) (int, bool) {
svnp := reflectx.NonPointerValue(reflect.ValueOf(slc))
sz := svnp.Len()
for idx := 0; idx < sz; idx++ {
rval := reflectx.NonPointerValue(svnp.Index(idx))
if rval.Interface() == fldVal {
return idx, true
}
}
return -1, false
}
// moveDown moves the selection down to next row, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (lb *ListBase) moveDown(selMode events.SelectModes) int {
if lb.SelectedIndex >= lb.SliceSize-1 {
lb.SelectedIndex = lb.SliceSize - 1
return -1
}
lb.SelectedIndex++
lb.SelectIndexEvent(lb.SelectedIndex, selMode)
return lb.SelectedIndex
}
// moveDownEvent moves the selection down to next row, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (lb *ListBase) moveDownEvent(selMode events.SelectModes) int {
nidx := lb.moveDown(selMode)
if nidx >= 0 {
lb.ScrollToIndex(nidx)
lb.Send(events.Select) // todo: need to do this for the item?
}
return nidx
}
// moveUp moves the selection up to previous idx, using given select mode
// (from keyboard modifiers) -- returns newly selected idx or -1 if failed
func (lb *ListBase) moveUp(selMode events.SelectModes) int {
if lb.SelectedIndex <= 0 {
lb.SelectedIndex = 0
return -1
}