/
sliceview.go
2353 lines (2115 loc) · 64.8 KB
/
sliceview.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 giv
import (
"encoding/json"
"fmt"
"image"
"image/color"
"log"
"log/slog"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"cogentcore.org/core/abilities"
"cogentcore.org/core/colors"
"cogentcore.org/core/colors/gradient"
"cogentcore.org/core/cursors"
"cogentcore.org/core/enums"
"cogentcore.org/core/events"
"cogentcore.org/core/fi"
"cogentcore.org/core/gi"
"cogentcore.org/core/gti"
"cogentcore.org/core/icons"
"cogentcore.org/core/keyfun"
"cogentcore.org/core/ki"
"cogentcore.org/core/laser"
"cogentcore.org/core/mat32"
"cogentcore.org/core/mimedata"
"cogentcore.org/core/states"
"cogentcore.org/core/styles"
"cogentcore.org/core/units"
)
////////////////////////////////////////////////////////
// SliceView
// SliceView represents a slice, creating an interactive viewer / editor of the
// elements as rows in a table. Widgets to show the index / value pairs, within an
// overall frame.
// Set to ReadOnly for select-only mode, which emits WidgetSig WidgetSelected
// signals when selection is updated.
type SliceView struct {
SliceViewBase
// optional styling function
StyleFunc SliceViewStyleFunc `copier:"-" view:"-" json:"-" xml:"-"`
}
// check for interface impl
var _ SliceViewer = (*SliceView)(nil)
// SliceViewStyleFunc is a styling function for custom styling and
// configuration of elements in the slice view.
type SliceViewStyleFunc func(w gi.Widget, s *styles.Style, row int)
func (sv *SliceView) HasStyleFunc() bool {
return sv.StyleFunc != nil
}
func (sv *SliceView) StyleRow(w gi.Widget, idx, fidx int) {
if sv.StyleFunc != nil {
sv.StyleFunc(w, &w.AsWidget().Styles, idx)
}
}
////////////////////////////////////////////////////////
// SliceViewBase
// note on implementation:
// * For a given slice type, the full set of widgets for VisRows is created
// during the Layout process (Initially MinRows are created to get row height,
// then the full set of visible rows is created during SizeFinal). The
// SliceViewConfiged flag indicates that this has been done -- when the slice
// type changes (SetSlice), this flag is reset and a new layout is triggered.
// Other externally-driven layout changes just update VisRows accordingly.
//
// * UpdateWidgets updates the view based on any changes in the slice data,
// scrolling, etc.
//
// * The standard Update call will do the right thing: Config does UpdateWidgets
// whenever SliceViewConfiged is set, and layout makes widgets as needed.
// ApplyStyle is generally neeed after UpdateWidgets (state flag changes)
// followed by Render.
//
// * SliceViewGrid handles all the layout logic to start with a minimum number of
// rows and then computes the total number visible based on allocated size.
// SliceViewFlags extend WidgetFlags to hold SliceView state
type SliceViewFlags gi.WidgetFlags //enums:bitflag -trim-prefix SliceView
const (
// SliceViewConfigured indicates that the widgets have been configured
SliceViewConfigured SliceViewFlags = SliceViewFlags(gi.WidgetFlagsN) + iota
// SliceViewIsArray is whether the slice is actually an array -- no modifications -- set by SetSlice
SliceViewIsArray
// SliceViewShowIndex is whether to show index or not
SliceViewShowIndex
// SliceViewReadOnlyKeyNav is whether support key navigation when ReadOnly (default true).
// uses a capture of up / down events to manipulate selection, not focus.
SliceViewReadOnlyKeyNav
// SliceViewSelectMode is whether to be in select rows mode or editing mode
SliceViewSelectMode
// SliceViewReadOnlyMultiSel: if view 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
SliceViewReadOnlyMultiSel
// SliceViewInFocusGrab is a guard for recursive focus grabbing
SliceViewInFocusGrab
// SliceViewInFullRebuild is a guard for recursive rebuild
SliceViewInFullRebuild
)
const (
SliceViewRowProp = "sv-row"
SliceViewColProp = "sv-col"
)
// SliceViewer is the interface used by SliceViewBase to
// support any abstractions needed for different types of slice views.
type SliceViewer interface {
// AsSliceViewBase returns the base for direct access to relevant fields etc
AsSliceViewBase() *SliceViewBase
// SliceGrid returns the SliceViewGrid grid Layout widget,
// which contains all the fields and values
SliceGrid() *SliceViewGrid
// RowWidgetNs returns number of widgets per row and
// offset for index label
RowWidgetNs() (nWidgPerRow, idxOff int)
// UpdtSliceSize updates the current size of the slice
// and sets SliceSize if changed.
UpdtSliceSize() int
// StyleValueWidget performs additional value widget styling
StyleValueWidget(w gi.Widget, s *styles.Style, row, col int)
// ConfigRows configures VisRows worth of widgets
// to display slice data.
ConfigRows()
// UpdateWidgets updates the row widget display to
// represent the current state of the slice data,
// including which range of data is being displayed.
// This is called for scrolling, navigation etc.
UpdateWidgets()
// HasStyleFunc returns whether there is a custom style function.
HasStyleFunc() bool
// StyleRow calls a custom style function on given row (and field)
StyleRow(w gi.Widget, idx, fidx int)
// RowFirstWidget returns the first widget for given row
// (could be index or not) -- false if out of range
RowFirstWidget(row int) (*gi.WidgetBase, bool)
// 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) *gi.WidgetBase
// SliceNewAt inserts a new blank element at given
// index in the slice. -1 means the end.
SliceNewAt(idx int)
// SliceDeleteAt deletes element at given index from slice
// if updt is true, then update the grid after
SliceDeleteAt(idx int)
// MimeDataType returns the data type for mime clipboard
// (copy / paste) data e.g., fi.DataJson
MimeDataType() string
// CopySelToMime copies selected rows to mime data
CopySelToMime() mimedata.Mimes
// PasteAssign assigns mime data (only the first one!) to this idx
PasteAssign(md mimedata.Mimes, idx int)
// PasteAtIdx inserts object(s) from mime data at
// (before) given slice index
PasteAtIdx(md mimedata.Mimes, idx int)
MakePasteMenu(m *gi.Scene, md mimedata.Mimes, idx int, mod events.DropMods, fun func())
DragStart(e events.Event)
DragDrop(e events.Event)
DropFinalize(de *events.DragDrop)
DropDeleteSource(e events.Event)
}
// SliceViewBase is the base for SliceView and TableView and any other viewers
// 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.
// Set to ReadOnly for select-only mode, which emits WidgetSig WidgetSelected
// signals when selection is updated.
type SliceViewBase struct {
gi.Frame
// the slice that we are a view onto -- must be a pointer to that slice
Slice any `set:"-" json:"-" xml:"-"`
// MinRows specifies the minimum number of rows to display, to ensure
// at least this amount is displayed.
MinRows int `default:"4"`
// a record of parent View names that have led up to this view -- displayed as extra contextual information in view dialog windows
ViewPath string
// optional mutex that, if non-nil, will be used around any updates that
// read / modify the underlying Slice data.
// Can be used to protect against random updating if your code has specific
// update points that can be likewise protected with this same mutex.
ViewMu *sync.Mutex `copier:"-" view:"-" json:"-" xml:"-"`
// Changed indicates whether the underlying slice
// has been edited in any way
Changed bool `set:"-"`
// current selection value -- initially select this value if set
SelVal any `copier:"-" view:"-" json:"-" xml:"-"`
// index of currently selected item
SelectedIndex int `copier:"-" json:"-" xml:"-"`
// index of row to select at start
InitSelectedIndex int `copier:"-" json:"-" xml:"-"`
// list of currently-selected slice indexes
SelectedIndexs 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 `set:"-" copier:"-" json:"-" xml:"-"`
// NormalCursor is the cached cursor to display when there
// is no row being hovered.
NormalCursor cursors.Cursor `copier:"-" xml:"-" json:"-" set:"-"`
// CurrentCursor is the cached cursor that should currently be
// displayed.
CurrentCursor cursors.Cursor `copier:"-" xml:"-" json:"-" set:"-"`
// non-ptr reflect.Value of the slice
SliceNPVal reflect.Value `set:"-" copier:"-" view:"-" json:"-" xml:"-"`
// Value for the slice itself, if this was created within value view framework -- otherwise nil
SliceValue Value `set:"-" copier:"-" view:"-" json:"-" xml:"-"`
// Value representations of the slice values
Values []Value `set:"-" copier:"-" view:"-" json:"-" xml:"-"`
// currently-hovered row
HoverRow int `set:"-" view:"-" copier:"-" json:"-" xml:"-"`
// list of currently-dragged indexes
DraggedIndexes []int `set:"-" view:"-" copier:"-" json:"-" xml:"-"`
// total number of rows visible in allocated display size
VisRows int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// starting slice index of visible rows
StartIndex int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// size of slice
SliceSize int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// iteration through the configuration process, reset when a new slice type is set
ConfigIter int `set:"-" edit:"-" copier:"-" json:"-" xml:"-"`
// temp idx state for e.g., dnd
TmpIndex int `set:"-" copier:"-" view:"-" json:"-" xml:"-"`
// ElVal is a Value representation of the underlying element type
// which is used whenever there are no slice elements available
ElVal reflect.Value `set:"-" copier:"-" view:"-" json:"-" xml:"-"`
// maximum width of value column in chars, if string
MaxWidth int `set:"-" copier:"-" json:"-" xml:"-"`
}
func (sv *SliceViewBase) FlagType() enums.BitFlagSetter {
return (*SliceViewFlags)(&sv.Flags)
}
func (sv *SliceViewBase) OnInit() {
sv.Frame.OnInit()
sv.HandleEvents()
sv.SetStyles()
sv.AddContextMenu(sv.ContextMenu)
}
func (sv *SliceViewBase) SetStyles() {
sv.InitSelectedIndex = -1
sv.HoverRow = -1
sv.MinRows = 4
sv.SetFlag(false, SliceViewSelectMode)
sv.SetFlag(true, SliceViewShowIndex)
sv.SetFlag(true, SliceViewReadOnlyKeyNav)
svi := sv.This().(SliceViewer)
sv.Style(func(s *styles.Style) {
s.SetAbilities(true, abilities.Clickable, abilities.DoubleClickable, abilities.TripleClickable)
s.SetAbilities(!sv.IsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Cursor = sv.CurrentCursor
s.Direction = styles.Column
// absorb horizontal here, vertical in view
s.Overflow.X = styles.OverflowAuto
s.Grow.Set(1, 1)
})
if !sv.IsReadOnly() {
sv.On(events.DragStart, func(e events.Event) {
svi.DragStart(e)
})
sv.On(events.DragEnter, func(e events.Event) {
e.SetHandled()
})
sv.On(events.DragLeave, func(e events.Event) {
e.SetHandled()
})
sv.On(events.Drop, func(e events.Event) {
svi.DragDrop(e)
})
sv.On(events.DropDeleteSource, func(e events.Event) {
svi.DropDeleteSource(e)
})
}
sv.StyleFinal(func(s *styles.Style) {
sv.NormalCursor = s.Cursor
})
sv.OnWidgetAdded(func(w gi.Widget) {
switch w.PathFrom(sv) {
case "grid": // slice grid
sg := w.(*SliceViewGrid)
sg.Style(func(s *styles.Style) {
sg.MinRows = sv.MinRows
s.Display = styles.Grid
nWidgPerRow, _ := svi.RowWidgetNs()
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) {
sv.SetFocusEvent()
row, _, isValid := sg.IndexFromPixel(e.Pos())
if isValid {
sv.UpdateSelectRow(row, e.SelectMode())
sv.LastClick = row + sv.StartIndex
}
}
sg.OnClick(oc)
sg.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)
sv.HandleEvent(e)
})
}
if w.Parent().PathFrom(sv) == "grid" {
switch {
case strings.HasPrefix(w.Name(), "index-"):
wb := w.AsWidget()
w.Style(func(s *styles.Style) {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(!sv.IsReadOnly(), abilities.Draggable, abilities.Droppable)
s.Cursor = cursors.None
nd := mat32.Log10(float32(sv.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
})
wb.OnDoubleClick(sv.HandleEvent)
wb.On(events.ContextMenu, sv.HandleEvent)
if !sv.IsReadOnly() {
w.On(events.DragStart, func(e events.Event) {
svi.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) {
svi.DragDrop(e)
})
w.On(events.DropDeleteSource, func(e events.Event) {
svi.DropDeleteSource(e)
})
}
case strings.HasPrefix(w.Name(), "value-"):
wb := w.AsWidget()
w.Style(func(s *styles.Style) {
if sv.IsReadOnly() {
s.SetAbilities(true, abilities.DoubleClickable)
s.SetAbilities(false, abilities.Hoverable, abilities.Focusable, abilities.Activatable, abilities.TripleClickable)
wb.SetReadOnly(true)
}
row, col := sv.WidgetIndex(w)
row += sv.StartIndex
sv.This().(SliceViewer).StyleValueWidget(w, s, row, col)
if row < sv.SliceSize {
sv.This().(SliceViewer).StyleRow(w, row, col)
}
})
wb.OnSelect(func(e events.Event) {
e.SetHandled()
row, _ := sv.WidgetIndex(w)
sv.UpdateSelectRow(row, e.SelectMode())
sv.LastClick = row + sv.StartIndex
})
wb.OnDoubleClick(sv.HandleEvent)
wb.On(events.ContextMenu, sv.HandleEvent)
}
}
})
}
// StyleValueWidget performs additional value widget styling
func (sv *SliceViewBase) StyleValueWidget(w gi.Widget, s *styles.Style, row, col int) {
if sv.MaxWidth > 0 {
hv := units.Ch(float32(sv.MaxWidth))
s.Min.X.Val = max(s.Min.X.Val, hv.Convert(s.Min.X.Un, &s.UnitContext).Val)
}
s.SetTextWrap(false)
}
func (sv *SliceViewBase) AsSliceViewBase() *SliceViewBase {
return sv
}
func (sv *SliceViewBase) SetSliceBase() {
sv.SetFlag(false, SliceViewConfigured, SliceViewSelectMode)
sv.ConfigIter = 0
sv.StartIndex = 0
sv.VisRows = sv.MinRows
if !sv.IsReadOnly() {
sv.SelectedIndex = -1
}
sv.ResetSelectedIdxs()
}
// SetSlice sets the source slice that we are viewing.
// This ReConfigs 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 (sv *SliceViewBase) SetSlice(sl any) *SliceViewBase {
if laser.AnyIsNil(sl) {
sv.Slice = nil
return sv
}
newslc := false
if reflect.TypeOf(sl).Kind() != reflect.Pointer { // prevent crash on non-comparable
newslc = true
} else {
newslc = sv.Slice != sl
}
if !newslc && sv.Is(SliceViewConfigured) {
sv.ConfigIter = 0
sv.Update()
return sv
}
sv.SetSliceBase()
sv.Slice = sl
sv.SliceNPVal = laser.NonPtrValue(reflect.ValueOf(sv.Slice))
isArray := laser.NonPtrType(reflect.TypeOf(sl)).Kind() == reflect.Array
sv.SetFlag(isArray, SliceViewIsArray)
// make sure elements aren't nil to prevent later panics
for i := 0; i < sv.SliceNPVal.Len(); i++ {
val := sv.SliceNPVal.Index(i)
k := val.Kind()
if (k == reflect.Chan || k == reflect.Func || k == reflect.Interface || k == reflect.Map || k == reflect.Pointer || k == reflect.Slice) && val.IsNil() {
val.Set(reflect.New(laser.NonPtrType(val.Type())))
}
}
sv.ElVal = laser.SliceElValue(sl)
sv.Update()
return sv
}
// IsNil returns true if the Slice is nil
func (sv *SliceViewBase) IsNil() bool {
return laser.AnyIsNil(sv.Slice)
}
// RowFromEventPos returns the widget row, slice index, and
// whether the index is in slice range, for given event position.
func (sv *SliceViewBase) RowFromEventPos(e events.Event) (row, idx int, isValid bool) {
sg := sv.This().(SliceViewer).SliceGrid()
row, _, isValid = sg.IndexFromPixel(e.Pos())
if !isValid {
return
}
idx = row + sv.StartIndex
if row < 0 || idx >= sv.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 (sv *SliceViewBase) ClickSelectEvent(e events.Event) bool {
row, _, isValid := sv.RowFromEventPos(e)
if !isValid {
e.SetHandled()
} else {
sv.UpdateSelectRow(row, e.SelectMode())
}
return isValid
}
// BindSelect makes the slice view a read-only selection slice view and then
// binds its events to its scene and its current selection index to the given value.
func (sv *SliceViewBase) BindSelect(val *int) *SliceViewBase {
sv.SetReadOnly(true)
sv.OnSelect(func(e events.Event) {
*val = sv.SelectedIndex
})
sv.OnDoubleClick(func(e events.Event) {
if sv.ClickSelectEvent(e) {
*val = sv.SelectedIndex
sv.Scene.SendKeyFun(keyfun.Accept, e) // activates Ok button code
}
})
return sv
}
// Config configures a standard setup of the overall Frame
func (sv *SliceViewBase) Config() {
sv.ConfigSliceView()
}
// ConfigSliceView handles entire config.
// ReConfig calls this, followed by ApplyStyleTree so we don't need to call that.
func (sv *SliceViewBase) ConfigSliceView() {
if sv.Is(SliceViewConfigured) {
sv.This().(SliceViewer).UpdateWidgets()
return
}
sv.ConfigFrame()
sv.This().(SliceViewer).ConfigRows()
sv.This().(SliceViewer).UpdateWidgets()
sv.ApplyStyleTree()
sv.NeedsLayout()
}
func (sv *SliceViewBase) ConfigFrame() {
if sv.HasChildren() {
return
}
sv.VisRows = sv.MinRows
NewSliceViewGrid(sv, "grid")
}
// SliceGrid returns the SliceGrid grid frame widget, which contains all the
// fields and values
func (sv *SliceViewBase) SliceGrid() *SliceViewGrid {
return sv.ChildByName("grid", 0).(*SliceViewGrid)
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (sv *SliceViewBase) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 2
idxOff = 1
if !sv.Is(SliceViewShowIndex) {
nWidgPerRow -= 1
idxOff = 0
}
return
}
// UpdtSliceSize updates and returns the size of the slice
// and sets SliceSize
func (sv *SliceViewBase) UpdtSliceSize() int {
sz := sv.SliceNPVal.Len()
sv.SliceSize = sz
return sz
}
// WidgetIndex returns the row and column indexes for given widget,
// from the props set during construction.
func (sv *SliceViewBase) WidgetIndex(w gi.Widget) (row, col int) {
if rwi := w.Prop(SliceViewRowProp); rwi != nil {
row = rwi.(int)
}
if cli := w.Prop(SliceViewColProp); cli != nil {
col = cli.(int)
}
return
}
// ViewMuLock locks the ViewMu if non-nil
func (sv *SliceViewBase) ViewMuLock() {
if sv.ViewMu == nil {
return
}
sv.ViewMu.Lock()
}
// ViewMuUnlock Unlocks the ViewMu if non-nil
func (sv *SliceViewBase) ViewMuUnlock() {
if sv.ViewMu == nil {
return
}
sv.ViewMu.Unlock()
}
// UpdateStartIdx updates StartIdx to fit current view
func (sv *SliceViewBase) UpdateStartIdx() {
sz := sv.This().(SliceViewer).UpdtSliceSize()
if sz > sv.VisRows {
lastSt := sz - sv.VisRows
sv.StartIndex = min(lastSt, sv.StartIndex)
sv.StartIndex = max(0, sv.StartIndex)
} else {
sv.StartIndex = 0
}
}
// UpdateScroll updates the scroll value
func (sv *SliceViewBase) UpdateScroll() {
sg := sv.This().(SliceViewer).SliceGrid()
if sg == nil {
return
}
sg.UpdateScroll(sv.StartIndex)
}
// ConfigRows configures VisRows worth of widgets
// to display slice data.
func (sv *SliceViewBase) ConfigRows() {
sg := sv.This().(SliceViewer).SliceGrid()
if sg == nil {
return
}
sv.SetFlag(true, SliceViewConfigured)
sg.SetFlag(true, gi.LayoutNoKeys)
sv.ViewMuLock()
defer sv.ViewMuUnlock()
sg.DeleteChildren()
sv.Values = nil
sv.This().(SliceViewer).UpdtSliceSize()
if sv.IsNil() {
return
}
nWidgPerRow, idxOff := sv.RowWidgetNs()
nWidg := nWidgPerRow * sv.VisRows
sg.Styles.Columns = nWidgPerRow
sv.Values = make([]Value, sv.VisRows)
sg.Kids = make(ki.Slice, nWidg)
for i := 0; i < sv.VisRows; i++ {
si := i
ridx := i * nWidgPerRow
var val reflect.Value
if si < sv.SliceSize {
val = laser.OnePtrUnderlyingValue(sv.SliceNPVal.Index(si)) // deal with pointer lists
} else {
val = sv.ElVal
}
vv := ToValue(val.Interface(), "")
sv.Values[i] = vv
vv.SetSliceValue(val, sv.Slice, si, sv.ViewPath)
vv.SetReadOnly(sv.IsReadOnly())
vtyp := vv.WidgetType()
itxt := strconv.Itoa(i)
sitxt := strconv.Itoa(si)
labnm := "index-" + itxt
valnm := "value-" + itxt
if sv.Is(SliceViewShowIndex) {
idxlab := &gi.Label{}
sg.SetChild(idxlab, ridx, labnm)
idxlab.SetText(sitxt)
idxlab.OnSelect(func(e events.Event) {
e.SetHandled()
sv.UpdateSelectRow(i, e.SelectMode())
sv.LastClick = i + sv.StartIndex
})
idxlab.SetProp(SliceViewRowProp, i)
}
w := ki.NewOfType(vtyp).(gi.Widget)
sg.SetChild(w, ridx+idxOff, valnm)
Config(vv, w)
w.SetProp(SliceViewRowProp, i)
if !sv.IsReadOnly() {
vv.OnChange(func(e events.Event) {
sv.SendChange(e)
})
vv.AsWidgetBase().OnInput(sv.HandleEvent)
}
if i == 0 {
sv.MaxWidth = 0
_, isString := vv.(*StringValue)
npv := laser.NonPtrValue(val)
if isString && sv.SliceSize > 0 && npv.Kind() == reflect.String {
mxw := 0
for rw := 0; rw < sv.SliceSize; rw++ {
val := laser.OnePtrUnderlyingValue(sv.SliceNPVal.Index(rw)).Elem()
str := val.String()
mxw = max(mxw, len(str))
}
sv.MaxWidth = mxw
}
}
}
sv.ConfigTree()
sv.ApplyStyleTree()
}
// UpdateWidgets updates the row widget display to
// represent the current state of the slice data,
// including which range of data is being displayed.
// This is called for scrolling, navigation etc.
func (sv *SliceViewBase) UpdateWidgets() {
sg := sv.This().(SliceViewer).SliceGrid()
if sg == nil || sv.VisRows == 0 || sg.VisRows == 0 || !sg.HasChildren() {
return
}
sv.ViewMuLock()
defer sv.ViewMuUnlock()
sv.This().(SliceViewer).UpdtSliceSize()
nWidgPerRow, idxOff := sv.RowWidgetNs()
scrollTo := -1
if sv.SelVal != nil {
idx, ok := SliceIdxByValue(sv.Slice, sv.SelVal)
if ok {
sv.SelectedIndex = idx
scrollTo = sv.SelectedIndex
}
sv.SelVal = nil
sv.InitSelectedIndex = -1
} else if sv.InitSelectedIndex >= 0 {
sv.SelectedIndex = sv.InitSelectedIndex
sv.InitSelectedIndex = -1
scrollTo = sv.SelectedIndex
}
if scrollTo >= 0 {
sv.ScrollToIdx(scrollTo)
}
sv.UpdateStartIdx()
for i := 0; i < sv.VisRows; i++ {
ridx := i * nWidgPerRow
w := sg.Kids[ridx+idxOff].(gi.Widget)
vv := sv.Values[i]
si := sv.StartIndex + i // slice idx
invis := si >= sv.SliceSize
var idxlab *gi.Label
if sv.Is(SliceViewShowIndex) {
idxlab = sg.Kids[ridx].(*gi.Label)
idxlab.SetText(strconv.Itoa(si)).Config()
idxlab.SetState(invis, states.Invisible)
}
w.SetState(invis, states.Invisible)
if si < sv.SliceSize {
val := laser.OnePtrUnderlyingValue(sv.SliceNPVal.Index(si)) // deal with pointer lists
vv.SetSliceValue(val, sv.Slice, si, sv.ViewPath)
vv.SetReadOnly(sv.IsReadOnly())
vv.Update()
if sv.IsReadOnly() {
w.AsWidget().SetReadOnly(true)
}
} else {
vv.SetSliceValue(sv.ElVal, sv.Slice, 0, sv.ViewPath)
vv.Update()
w.AsWidget().SetSelected(false)
if sv.Is(SliceViewShowIndex) {
idxlab.SetSelected(false)
}
}
if sv.This().(SliceViewer).HasStyleFunc() {
w.ApplyStyle()
}
}
sg.NeedsRender()
}
// SetChanged sets the Changed flag and emits the ViewSig signal for the
// SliceViewBase, indicating that some kind of edit / change has taken place to
// the table data. It isn't really practical to record all the different
// types of changes, so this is just generic.
func (sv *SliceViewBase) SetChanged() {
sv.Changed = true
sv.SendChange()
}
// SliceNewAtRow inserts a new blank element at given display row
func (sv *SliceViewBase) SliceNewAtRow(row int) {
sv.This().(SliceViewer).SliceNewAt(sv.StartIndex + row)
}
// SliceNewAt inserts a new blank element at given index in the slice -- -1
// means the end
func (sv *SliceViewBase) SliceNewAt(idx int) {
if sv.Is(SliceViewIsArray) {
return
}
sv.ViewMuLock() // no return! must unlock before return below
sv.SliceNewAtSel(idx)
sltyp := laser.SliceElType(sv.Slice) // has pointer if it is there
iski := ki.IsKi(sltyp)
slptr := sltyp.Kind() == reflect.Ptr
svl := reflect.ValueOf(sv.Slice)
sz := sv.SliceSize
svnp := sv.SliceNPVal
if iski && sv.SliceValue != nil {
vd := sv.SliceValue.AsValueData()
if vd.Owner != nil {
if ownki, ok := vd.Owner.(ki.Ki); ok {
d := gi.NewBody().AddTitle("Slice New").AddText("Number and Type of Items to Insert:")
nd := &gi.NewItemsData{}
w := NewValue(d, nd).AsWidget()
ki.ChildByType[*gi.Chooser](w, ki.Embeds).SetTypes(gti.AllEmbeddersOf(ownki.BaseType())...).SetCurrentIndex(0)
d.AddBottomBar(func(pw gi.Widget) {
d.AddCancel(pw)
d.AddOk(pw).OnClick(func(e events.Event) {
for i := 0; i < nd.Number; i++ {
nm := fmt.Sprintf("New%v%v", nd.Type.Name, idx+1+i)
ownki.InsertNewChild(nd.Type, idx+1+i, nm)
}
sv.SetChanged()
})
})
d.NewDialog(sv).Run()
}
}
} else {
nval := reflect.New(laser.NonPtrType(sltyp)) // make the concrete el
if !slptr {
nval = nval.Elem() // use concrete value
}
svnp = reflect.Append(svnp, nval)
if idx >= 0 && idx < sz {
reflect.Copy(svnp.Slice(idx+1, sz+1), svnp.Slice(idx, sz))
svnp.Index(idx).Set(nval)
}
svl.Elem().Set(svnp)
}
if idx < 0 {
idx = sz
}
sv.SliceNPVal = laser.NonPtrValue(reflect.ValueOf(sv.Slice)) // need to update after changes
sv.This().(SliceViewer).UpdtSliceSize()
sv.SelectIdxAction(idx, events.SelectOne)
sv.ViewMuUnlock()
sv.SetChanged()
sv.This().(SliceViewer).UpdateWidgets()
sv.IdxGrabFocus(idx)
sv.NeedsLayout()
}
// SliceDeleteAtRow deletes element at given display row
// if updt is true, then update the grid after
func (sv *SliceViewBase) SliceDeleteAtRow(row int) {
sv.This().(SliceViewer).SliceDeleteAt(sv.StartIndex + row)
}
// SliceNewAtSel updates selected rows based on
// inserting new element at given index.
// must be called with successful SliceNewAt
func (sv *SliceViewBase) SliceNewAtSel(idx int) {
sl := sv.SelectedIdxsList(false) // ascending
sv.ResetSelectedIdxs()
for _, ix := range sl {
if ix >= idx {
ix++
}
sv.SelectedIndexs[ix] = struct{}{}
}
}
// SliceDeleteAtSel updates selected rows based on
// deleting element at given index
// must be called with successful SliceDeleteAt
func (sv *SliceViewBase) SliceDeleteAtSel(idx int) {
sl := sv.SelectedIdxsList(true) // desscending
sv.ResetSelectedIdxs()
for _, ix := range sl {
switch {
case ix == idx:
continue
case ix > idx:
ix--
}
sv.SelectedIndexs[ix] = struct{}{}
}
}
// SliceDeleteAt deletes element at given index from slice
func (sv *SliceViewBase) SliceDeleteAt(idx int) {
if sv.Is(SliceViewIsArray) {
return
}
if idx < 0 || idx >= sv.SliceSize {
return
}
sv.ViewMuLock()
sv.SliceDeleteAtSel(idx)
laser.SliceDeleteAt(sv.Slice, idx)
sv.This().(SliceViewer).UpdtSliceSize()
sv.ViewMuUnlock()
sv.SetChanged()
sv.This().(SliceViewer).UpdateWidgets()
sv.NeedsRender()
}
// ConfigToolbar configures a [gi.Toolbar] for this view
func (sv *SliceViewBase) ConfigToolbar(tb *gi.Toolbar) {
if laser.AnyIsNil(sv.Slice) {
return
}
if sv.Is(SliceViewIsArray) || sv.IsReadOnly() {
return
}
gi.NewButton(tb, "slice-add").SetText("Add").SetIcon(icons.Add).SetTooltip("add a new element to the slice").
OnClick(func(e events.Event) {
sv.This().(SliceViewer).SliceNewAt(-1)
})
}
////////////////////////////////////////////////////////////
// Row access methods
// NOTE: row = physical GUI display row, idx = slice index
// not the same!
// SliceVal returns value interface at given slice index
// must be protected by mutex
func (sv *SliceViewBase) SliceVal(idx int) any {
if idx < 0 || idx >= sv.SliceSize {
fmt.Printf("giv.SliceViewBase: slice index out of range: %v\n", idx)
return nil
}
val := laser.OnePtrUnderlyingValue(sv.SliceNPVal.Index(idx)) // deal with pointer lists
vali := val.Interface()
return vali
}
// IsRowInBounds returns true if disp row is in bounds
func (sv *SliceViewBase) IsRowInBounds(row int) bool {
return row >= 0 && row < sv.VisRows