-
Notifications
You must be signed in to change notification settings - Fork 0
/
sliceviewbase.go
2073 lines (1876 loc) · 62.1 KB
/
sliceviewbase.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 (
"encoding/json"
"fmt"
"image"
"log"
"reflect"
"sort"
"sync"
"github.com/chewxy/math32"
"github.com/goki/gi/gi"
"github.com/goki/gi/oswin"
"github.com/goki/gi/oswin/dnd"
"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/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/mat32"
"github.com/goki/pi/filecat"
)
////////////////////////////////////////////////////////////////////////////////////////
// SliceViewer
// 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
// Config configures the view
Config()
// IsConfiged returns true if is fully configured for display
IsConfiged() bool
// SliceGrid returns the SliceGrid grid frame widget, which contains all the
// fields and values
SliceGrid() *gi.Frame
// ScrollBar returns the SliceGrid scrollbar
ScrollBar() *gi.ScrollBar
// RowWidgetNs returns number of widgets per row and offset for index label
RowWidgetNs() (nWidgPerRow, idxOff int)
// SliceSize returns the current size of the slice and sets SliceSize
UpdtSliceSize() int
// LayoutSliceGrid does the proper layout of slice grid depending on allocated size
// returns true if UpdateSliceGrid should be called after this
LayoutSliceGrid() bool
// UpdateSliceGrid updates grid display -- robust to any time calling
UpdateSliceGrid()
// StyleRow calls a custom style function on given row (and field)
StyleRow(svnp reflect.Value, widg gi.Node2D, idx, fidx int, vv ValueView)
// 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
// SelectRowWidgets sets the selection state of given row of widgets
SelectRowWidgets(row int, sel bool)
// 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, updt bool)
// MimeDataType returns the data type for mime clipboard (copy / paste) data
// e.g., filecat.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)
// ItemCtxtMenu pulls up the context menu for given slice index
ItemCtxtMenu(idx int)
}
////////////////////////////////////////////////////////////////////////////////////////
// SliceViewBase
// 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 Inactive for select-only mode, which emits WidgetSig WidgetSelected
// signals when selection is updated.
type SliceViewBase struct {
gi.Frame
Slice interface{} `copy:"-" view:"-" json:"-" xml:"-" desc:"the slice that we are a view onto -- must be a pointer to that slice"`
ViewMu *sync.Mutex `copy:"-" view:"-" json:"-" xml:"-" desc:"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"`
SliceNPVal reflect.Value `copy:"-" view:"-" json:"-" xml:"-" desc:"non-ptr reflect.Value of the slice"`
SliceValView ValueView `copy:"-" view:"-" json:"-" xml:"-" desc:"ValueView for the slice itself, if this was created within value view framework -- otherwise nil"`
isArray bool `copy:"-" view:"-" json:"-" xml:"-" desc:"whether the slice is actually an array -- no modifications -- set by SetSlice"`
NoAdd bool `desc:"if true, user cannot add elements to the slice"`
NoDelete bool `desc:"if true, user cannot delete elements from the slice"`
ShowViewCtxtMenu bool `desc:"if the type we're viewing has its own CtxtMenu property defined, should we also still show the view's standard context menu?"`
Changed bool `desc:"has the slice been edited?"`
Values []ValueView `copy:"-" view:"-" json:"-" xml:"-" desc:"ValueView representations of the slice values"`
ShowIndex bool `xml:"index" desc:"whether to show index or not -- updated from 'index' property (bool)"`
InactKeyNav bool `xml:"inact-key-nav" desc:"support key navigation when inactive (default true) -- updated from 'intact-key-nav' property (bool) -- no focus really plausible in inactive case, so it uses a low-pri capture of up / down events"`
SelVal interface{} `copy:"-" view:"-" json:"-" xml:"-" desc:"current selection value -- initially select this value if set"`
SelectedIdx int `copy:"-" json:"-" xml:"-" desc:"index of currently-selected item, in Inactive mode only"`
SelectMode bool `copy:"-" desc:"editing-mode select rows mode"`
SelectedIdxs map[int]struct{} `copy:"-" desc:"list of currently-selected slice indexes"`
DraggedIdxs []int `copy:"-" desc:"list of currently-dragged indexes"`
SliceViewSig ki.Signal `copy:"-" json:"-" xml:"-" desc:"slice view specific signals: insert, delete, double-click"`
ViewSig ki.Signal `copy:"-" json:"-" xml:"-" desc:"signal for valueview -- only one signal sent when a value has been set -- all related value views interconnect with each other to update when others update"`
ViewPath string `desc:"a record of parent View names that have led up to this view -- displayed as extra contextual information in view dialog windows"`
TmpSave ValueView `copy:"-" json:"-" xml:"-" desc:"value view that needs to have SaveTmp called on it whenever a change is made to one of the underlying values -- pass this down to any sub-views created from a parent"`
ToolbarSlice interface{} `copy:"-" view:"-" json:"-" xml:"-" desc:"the slice that we successfully set a toolbar for"`
SliceSize int `view:"inactive" copy:"-" json:"-" xml:"-" desc:"size of slice"`
DispRows int `view:"inactive" copy:"-" json:"-" xml:"-" desc:"actual number of rows displayed = min(VisRows, SliceSize)"`
StartIdx int `view:"inactive" copy:"-" json:"-" xml:"-" desc:"starting slice index of visible rows"`
RowHeight float32 `view:"inactive" copy:"-" json:"-" xml:"-" desc:"height of a single row"`
VisRows int `view:"inactive" copy:"-" json:"-" xml:"-" desc:"total number of rows visible in allocated display size"`
LayoutHeight float32 `copy:"-" view:"-" json:"-" xml:"-" desc:"the height of grid from last layout -- determines when update needed"`
RenderedRows int `copy:"-" view:"-" json:"-" xml:"-" desc:"the number of rows rendered -- determines update"`
InFocusGrab bool `copy:"-" view:"-" json:"-" xml:"-" desc:"guard for recursive focus grabbing"`
InFullRebuild bool `copy:"-" view:"-" json:"-" xml:"-" desc:"guard for recursive rebuild"`
CurIdx int `copy:"-" view:"-" json:"-" xml:"-" desc:"temp idx state for e.g., dnd"`
}
var KiT_SliceViewBase = kit.Types.AddType(&SliceViewBase{}, nil)
// AddNewSliceViewBase adds a new sliceview to given parent node, with given name.
func AddNewSliceViewBase(parent ki.Ki, name string) *SliceViewBase {
return parent.AddNewChild(KiT_SliceViewBase, name).(*SliceViewBase)
}
func (sv *SliceViewBase) Disconnect() {
sv.Frame.Disconnect()
sv.SliceViewSig.DisconnectAll()
sv.ViewSig.DisconnectAll()
}
func (sv *SliceViewBase) AsSliceViewBase() *SliceViewBase {
return sv
}
// Each SliceView must implement its own SetSlice, Config, etc pipeline.
// This one is for a basic SliceView
// the only interface call is UpdateSliceGrid()
// SetSlice sets the source slice that we are viewing -- rebuilds the children
// to represent this slice
func (sv *SliceViewBase) SetSlice(sl interface{}) {
if kit.IfaceIsNil(sl) {
sv.Slice = nil
return
}
if sv.Slice == sl && sv.IsConfiged() {
sv.Update()
return
}
updt := sv.UpdateStart()
sv.StartIdx = 0
sv.Slice = sl
sv.SliceNPVal = kit.NonPtrValue(reflect.ValueOf(sv.Slice))
sv.isArray = kit.NonPtrType(reflect.TypeOf(sl)).Kind() == reflect.Array
if !sv.IsInactive() {
sv.SelectedIdx = -1
}
sv.ResetSelectedIdxs()
sv.SelectMode = false
sv.SetFullReRender()
sv.ShowIndex = true
if sidxp, err := sv.PropTry("index"); err == nil {
sv.ShowIndex, _ = kit.ToBool(sidxp)
}
sv.InactKeyNav = true
if siknp, err := sv.PropTry("inact-key-nav"); err == nil {
sv.InactKeyNav, _ = kit.ToBool(siknp)
}
sv.Config()
sv.UpdateEnd(updt)
}
// Update is the high-level update display call -- robust to any changes
func (sv *SliceViewBase) Update() {
wupdt := sv.TopUpdateStart()
defer sv.TopUpdateEnd(wupdt)
updt := sv.UpdateStart()
sv.This().(SliceViewer).LayoutSliceGrid()
sv.This().(SliceViewer).UpdateSliceGrid()
sv.UpdateEnd(updt)
}
// SliceViewSignals are signals that sliceview can send, mostly for editing
// mode. Selection events are sent on WidgetSig WidgetSelected signals in
// both modes.
type SliceViewSignals int
const (
// SliceViewDoubleClicked emitted during inactive mode when item
// double-clicked -- can be used for accepting dialog.
SliceViewDoubleClicked SliceViewSignals = iota
// SliceViewInserted emitted when a new item is inserted -- data is index of new item
SliceViewInserted
// SliceViewDeleted emitted when an item is deleted -- data is index of item deleted
SliceViewDeleted
SliceViewSignalsN
)
//go:generate stringer -type=SliceViewSignals
// UpdateValues updates the widget display of slice values, assuming same slice config
func (sv *SliceViewBase) UpdateValues() {
updt := sv.UpdateStart()
for _, vv := range sv.Values {
vv.UpdateWidget()
}
sv.UpdateEnd(updt)
}
// Config configures a standard setup of the overall Frame
func (sv *SliceViewBase) Config() {
sv.Lay = gi.LayoutVert
sv.SetProp("spacing", gi.StdDialogVSpaceUnits)
config := kit.TypeAndNameList{}
config.Add(gi.KiT_ToolBar, "toolbar")
config.Add(gi.KiT_Layout, "grid-lay")
mods, updt := sv.ConfigChildren(config, ki.UniqueNames)
gl := sv.GridLayout()
gl.Lay = gi.LayoutHoriz
gl.SetStretchMax() // for this to work, ALL layers above need it too
gconfig := kit.TypeAndNameList{}
gconfig.Add(gi.KiT_Frame, "grid")
gconfig.Add(gi.KiT_ScrollBar, "scrollbar")
gl.ConfigChildren(gconfig, ki.UniqueNames) // covered by above
sv.ConfigSliceGrid()
sv.ConfigToolbar()
if mods {
sv.SetFullReRender()
sv.UpdateEnd(updt)
}
}
// IsConfiged returns true if the widget is fully configured
func (sv *SliceViewBase) IsConfiged() bool {
if len(sv.Kids) == 0 {
return false
}
return true
}
// GridLayout returns the Layout containing the Grid and the scrollbar
func (sv *SliceViewBase) GridLayout() *gi.Layout {
return sv.ChildByName("grid-lay", 0).(*gi.Layout)
}
// SliceGrid returns the SliceGrid grid frame widget, which contains all the
// fields and values
func (sv *SliceViewBase) SliceGrid() *gi.Frame {
return sv.GridLayout().ChildByName("grid", 0).(*gi.Frame)
}
// ScrollBar returns the SliceGrid scrollbar
func (sv *SliceViewBase) ScrollBar() *gi.ScrollBar {
return sv.GridLayout().ChildByName("scrollbar", 1).(*gi.ScrollBar)
}
// ToolBar returns the toolbar widget
func (sv *SliceViewBase) ToolBar() *gi.ToolBar {
tbi := sv.ChildByName("toolbar", 1)
if tbi == nil {
return nil
}
return tbi.(*gi.ToolBar)
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (sv *SliceViewBase) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 2
if !sv.IsInactive() && !sv.isArray {
if !sv.NoAdd {
nWidgPerRow += 1
}
if !sv.NoDelete {
nWidgPerRow += 1
}
}
idxOff = 1
if !sv.ShowIndex {
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
}
// 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()
}
// ConfigSliceGrid configures the SliceGrid for the current slice
// it is only called once at start, under overall Config
func (sv *SliceViewBase) ConfigSliceGrid() {
sg := sv.This().(SliceViewer).SliceGrid()
updt := sg.UpdateStart()
defer sg.UpdateEnd(updt)
nWidgPerRow, idxOff := sv.RowWidgetNs()
sg.Lay = gi.LayoutGrid
sg.Stripes = gi.RowStripes
sg.SetProp("columns", nWidgPerRow)
// setting a pref here is key for giving it a scrollbar in larger context
sg.SetMinPrefHeight(units.NewEm(6))
sg.SetMinPrefWidth(units.NewCh(20))
sg.SetStretchMax() // for this to work, ALL layers above need it too
sg.SetProp("overflow", gi.OverflowScroll) // this still gives it true size during PrefSize
if kit.IfaceIsNil(sv.Slice) {
return
}
sz := sv.This().(SliceViewer).UpdtSliceSize()
if sz == 0 {
return
}
sg.DeleteChildren(ki.DestroyKids)
sg.Kids = make(ki.Slice, nWidgPerRow)
// at this point, we make one dummy row to get size of widgets
val := kit.OnePtrUnderlyingValue(sv.SliceNPVal.Index(0)) // deal with pointer lists
vv := ToValueView(val.Interface(), "")
if vv == nil { // shouldn't happen
return
}
vv.SetSliceValue(val, sv.Slice, 0, sv.TmpSave, sv.ViewPath)
vtyp := vv.WidgetType()
itxt := fmt.Sprintf("%05d", 0)
labnm := fmt.Sprintf("index-%v", itxt)
valnm := fmt.Sprintf("value-%v", itxt)
if sv.ShowIndex {
idxlab := &gi.Label{}
sg.SetChild(idxlab, 0, labnm)
idxlab.Text = itxt
}
widg := ki.NewOfType(vtyp).(gi.Node2D)
sg.SetChild(widg, idxOff, valnm)
vv.ConfigWidget(widg)
if !sv.IsInactive() && !sv.isArray {
cidx := idxOff
if !sv.NoAdd {
cidx++
addnm := fmt.Sprintf("add-%v", itxt)
addact := gi.Action{}
sg.SetChild(&addact, cidx, addnm)
addact.SetIcon("plus")
}
if !sv.NoDelete {
cidx++
delnm := fmt.Sprintf("del-%v", itxt)
delact := gi.Action{}
sg.SetChild(&delact, cidx, delnm)
delact.SetIcon("minus")
}
}
sv.ConfigScroll()
}
// ConfigScroll configures the scrollbar
func (sv *SliceViewBase) ConfigScroll() {
sb := sv.This().(SliceViewer).ScrollBar()
sb.Dim = mat32.Y
sb.Defaults()
sb.Tracking = true
if sv.Sty.Layout.ScrollBarWidth.Dots == 0 {
sb.SetFixedWidth(units.NewPx(16))
} else {
sb.SetFixedWidth(sv.Sty.Layout.ScrollBarWidth)
}
sb.SetStretchMaxHeight()
sb.Min = 0
sb.Step = 1
sv.UpdateScroll()
sb.SliderSig.Connect(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig != int64(gi.SliderValueChanged) {
return
}
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
wupdt := sv.TopUpdateStart()
svv.This().(SliceViewer).UpdateSliceGrid()
svv.ViewportSafe().ReRender2DNode(svv.This().(gi.Node2D))
svv.TopUpdateEnd(wupdt)
})
}
// UpdateScroll updates grid scrollbar based on display
func (sv *SliceViewBase) UpdateScroll() {
sb := sv.This().(SliceViewer).ScrollBar()
updt := sb.UpdateStart()
sb.Max = float32(sv.SliceSize) + 0.01 // bit of extra to ensure last line always shows up
if sv.DispRows > 0 {
sb.PageStep = float32(sv.DispRows) * sb.Step
sb.ThumbVal = float32(sv.DispRows)
} else {
sb.PageStep = 10 * sb.Step
sb.ThumbVal = 10
}
sb.TrackThr = sb.Step
sb.SetValue(float32(sv.StartIdx)) // essential for updating pos from value
if sv.DispRows == sv.SliceSize {
sb.Off = true
} else {
sb.Off = false
}
sb.UpdateEnd(updt)
}
func (sv *SliceViewBase) AvailHeight() float32 {
sg := sv.This().(SliceViewer).SliceGrid()
sgHt := sg.LayState.Alloc.Size.Y
if sgHt == 0 {
return 0
}
sgHt -= sg.ExtraSize.Y + sg.Sty.BoxSpace()*2
return sgHt
}
// LayoutSliceGrid does the proper layout of slice grid depending on allocated size
// returns true if UpdateSliceGrid should be called after this
func (sv *SliceViewBase) LayoutSliceGrid() bool {
sv.ViewMuLock()
defer sv.ViewMuUnlock()
sg := sv.This().(SliceViewer).SliceGrid()
if kit.IfaceIsNil(sv.Slice) {
sg.DeleteChildren(ki.DestroyKids)
return false
}
sz := sv.This().(SliceViewer).UpdtSliceSize()
if sz == 0 {
sg.DeleteChildren(ki.DestroyKids)
return false
}
nWidgPerRow, _ := sv.RowWidgetNs()
if len(sg.GridData) > 0 && len(sg.GridData[gi.Row]) > 0 {
sv.RowHeight = sg.GridData[gi.Row][0].AllocSize + sg.Spacing.Dots
}
if sv.Sty.Font.Face == nil {
sv.Sty.Font.OpenFont(&sv.Sty.UnContext)
}
sv.RowHeight = math32.Max(sv.RowHeight, sv.Sty.Font.Face.Metrics.Height)
mvp := sv.ViewportSafe()
if mvp != nil && mvp.HasFlag(int(gi.VpFlagPrefSizing)) {
sv.VisRows = gi.LayoutPrefMaxRows
sv.LayoutHeight = float32(sv.VisRows) * sv.RowHeight
} else {
sgHt := sv.AvailHeight()
sv.LayoutHeight = sgHt
if sgHt == 0 {
return false
}
sv.VisRows = int(math32.Floor(sgHt / sv.RowHeight))
}
sv.DispRows = ints.MinInt(sv.SliceSize, sv.VisRows)
nWidg := nWidgPerRow * sv.DispRows
updt := sg.UpdateStart()
defer sg.UpdateEnd(updt)
if sv.Values == nil || sg.NumChildren() != nWidg {
sg.DeleteChildren(ki.DestroyKids)
sv.Values = make([]ValueView, sv.DispRows)
sg.Kids = make(ki.Slice, nWidg)
}
sv.ConfigScroll()
return true
}
func (sv *SliceViewBase) SliceGridNeedsLayout() bool {
sgHt := sv.AvailHeight()
if sgHt != sv.LayoutHeight {
return true
}
return sv.RenderedRows != sv.DispRows
}
// UpdateSliceGrid updates grid display -- robust to any time calling
func (sv *SliceViewBase) UpdateSliceGrid() {
if kit.IfaceIsNil(sv.Slice) {
return
}
sv.ViewMuLock()
defer sv.ViewMuUnlock()
sz := sv.This().(SliceViewer).UpdtSliceSize()
if sz == 0 {
return
}
sg := sv.This().(SliceViewer).SliceGrid()
sv.DispRows = ints.MinInt(sv.SliceSize, sv.VisRows)
nWidgPerRow, idxOff := sv.RowWidgetNs()
nWidg := nWidgPerRow * sv.DispRows
wupdt := sv.TopUpdateStart()
defer sv.TopUpdateEnd(wupdt)
updt := sg.UpdateStart()
defer sg.UpdateEnd(updt)
if sv.Values == nil || sg.NumChildren() != nWidg { // shouldn't happen..
sv.ViewMuUnlock()
sv.LayoutSliceGrid()
sv.ViewMuLock()
nWidg = nWidgPerRow * sv.DispRows
}
if sz > sv.DispRows {
sb := sv.This().(SliceViewer).ScrollBar()
sv.StartIdx = int(sb.Value)
lastSt := sz - sv.DispRows
sv.StartIdx = ints.MinInt(lastSt, sv.StartIdx)
sv.StartIdx = ints.MaxInt(0, sv.StartIdx)
} else {
sv.StartIdx = 0
}
for i := 0; i < sv.DispRows; i++ {
ridx := i * nWidgPerRow
si := sv.StartIdx + i // slice idx
issel := sv.IdxIsSelected(si)
val := kit.OnePtrUnderlyingValue(sv.SliceNPVal.Index(si)) // deal with pointer lists
var vv ValueView
if sv.Values[i] == nil {
vv = ToValueView(val.Interface(), "")
sv.Values[i] = vv
} else {
vv = sv.Values[i]
}
vv.SetSliceValue(val, sv.Slice, si, sv.TmpSave, sv.ViewPath)
vtyp := vv.WidgetType()
itxt := fmt.Sprintf("%05d", i)
sitxt := fmt.Sprintf("%05d", si)
labnm := fmt.Sprintf("index-%v", itxt)
valnm := fmt.Sprintf("value-%v", itxt)
if sv.ShowIndex {
var idxlab *gi.Label
if sg.Kids[ridx] != nil {
idxlab = sg.Kids[ridx].(*gi.Label)
} else {
idxlab = &gi.Label{}
sg.SetChild(idxlab, ridx, labnm)
idxlab.SetProp("slv-row", i) // all sigs deal with disp rows
idxlab.Selectable = true
idxlab.Redrawable = true
idxlab.Sty.Template = "giv.SliceViewBase.IndexLabel"
idxlab.WidgetSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.WidgetSelected) {
wbb := send.(gi.Node2D).AsWidget()
row := wbb.Prop("slv-row").(int)
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.UpdateSelectRow(row, wbb.IsSelected())
}
})
}
idxlab.CurBgColor = gi.Prefs.Colors.Background
idxlab.SetText(sitxt)
idxlab.SetSelectedState(issel)
}
var widg gi.Node2D
if sg.Kids[ridx+idxOff] != nil {
widg = sg.Kids[ridx+idxOff].(gi.Node2D)
vv.UpdateWidget()
if sv.IsInactive() {
widg.AsNode2D().SetInactive()
}
widg.AsNode2D().SetSelectedState(issel)
} else {
widg = ki.NewOfType(vtyp).(gi.Node2D)
sg.SetChild(widg, ridx+idxOff, valnm)
vv.ConfigWidget(widg)
wb := widg.AsWidget()
// wb.Sty.Template = "giv.SliceViewBase.ItemWidget." + vtyp.Name()
if sv.IsInactive() {
widg.AsNode2D().SetInactive()
if wb != nil {
wb.SetProp("slv-row", i)
wb.ClearSelected()
wb.WidgetSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.WidgetSelected) || sig == int64(gi.WidgetFocused) {
wbb := send.(gi.Node2D).AsWidget()
row := wbb.Prop("slv-row").(int)
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.UpdateSelectRow(row, wbb.IsSelected())
}
})
}
} else {
vvb := vv.AsValueViewBase()
vvb.ViewSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
svv, _ := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.SetChanged()
})
if !sv.isArray {
cidx := ridx + idxOff
if !sv.NoAdd {
cidx++
addnm := fmt.Sprintf("add-%v", itxt)
addact := gi.Action{}
sg.SetChild(&addact, cidx, addnm)
addact.SetIcon("plus")
addact.Tooltip = "insert a new element at this index"
addact.Data = i
addact.Sty.Template = "giv.SliceViewBase.AddAction"
addact.ActionSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.SliceNewAtRow(act.Data.(int) + 1)
})
}
if !sv.NoDelete {
cidx++
delnm := fmt.Sprintf("del-%v", itxt)
delact := gi.Action{}
sg.SetChild(&delact, cidx, delnm)
delact.SetIcon("minus")
delact.Tooltip = "delete this element"
delact.Data = i
delact.Sty.Template = "giv.SliceViewBase.DelAction"
delact.ActionSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.SliceDeleteAtRow(act.Data.(int), true)
})
}
}
}
}
sv.This().(SliceViewer).StyleRow(sv.SliceNPVal, widg, si, 0, vv)
}
if sv.SelVal != nil {
sv.SelectedIdx, _ = SliceIdxByValue(sv.Slice, sv.SelVal)
}
if sv.IsInactive() && sv.SelectedIdx >= 0 {
sv.SelectIdxWidgets(sv.SelectedIdx, true)
}
sv.UpdateScroll()
}
// 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.ViewSig.Emit(sv.This(), 0, nil)
sv.ToolBar().UpdateActions() // nil safe
}
// SliceNewAtRow inserts a new blank element at given display row
func (sv *SliceViewBase) SliceNewAtRow(row int) {
sv.This().(SliceViewer).SliceNewAt(sv.StartIdx + 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.isArray {
return
}
sv.ViewMuLock() // no return! must unlock before return below
updt := sv.UpdateStart()
defer sv.UpdateEnd(updt)
sltyp := kit.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.SliceValView != nil {
vvb := sv.SliceValView.AsValueViewBase()
if vvb.Owner != nil {
if ownki, ok := vvb.Owner.(ki.Ki); ok {
gi.NewKiDialog(sv.ViewportSafe(), ownki.BaseIface(),
gi.DlgOpts{Title: "Slice New", Prompt: "Number and Type of Items to Insert:"},
sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.DialogAccepted) {
// svv, _ := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
dlg, _ := send.(*gi.Dialog)
n, typ := gi.NewKiDialogValues(dlg)
updt := ownki.UpdateStart()
for i := 0; i < n; i++ {
nm := fmt.Sprintf("New%v%v", typ.Name(), idx+1+i)
ownki.InsertNewChild(typ, idx+1+i, nm)
}
sv.SetChanged()
ownki.UpdateEnd(updt)
}
})
}
}
} else {
nval := reflect.New(kit.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 = kit.NonPtrValue(reflect.ValueOf(sv.Slice)) // need to update after changes
if sv.TmpSave != nil {
sv.TmpSave.SaveTmp()
}
sv.SetChanged()
sv.ScrollBar().SetFullReRender()
sv.ViewMuUnlock()
sv.This().(SliceViewer).LayoutSliceGrid()
sv.This().(SliceViewer).UpdateSliceGrid()
sv.ViewSig.Emit(sv.This(), 0, nil)
sv.SliceViewSig.Emit(sv.This(), int64(SliceViewInserted), idx)
}
// SliceDeleteAtRow deletes element at given display row
// if updt is true, then update the grid after
func (sv *SliceViewBase) SliceDeleteAtRow(row int, updt bool) {
sv.This().(SliceViewer).SliceDeleteAt(sv.StartIdx+row, updt)
}
// SliceDeleteAt deletes element at given index from slice
// if updt is true, then update the grid after
func (sv *SliceViewBase) SliceDeleteAt(idx int, doupdt bool) {
if sv.isArray {
return
}
sv.ViewMuLock()
updt := sv.UpdateStart()
defer sv.UpdateEnd(updt)
kit.SliceDeleteAt(sv.Slice, idx)
if sv.TmpSave != nil {
sv.TmpSave.SaveTmp()
}
sv.ViewMuUnlock()
sv.SetChanged()
if doupdt {
sv.ScrollBar().SetFullReRender()
sv.This().(SliceViewer).LayoutSliceGrid()
sv.This().(SliceViewer).UpdateSliceGrid()
}
sv.ViewSig.Emit(sv.This(), 0, nil)
sv.SliceViewSig.Emit(sv.This(), int64(SliceViewDeleted), idx)
}
// ConfigToolbar configures the toolbar actions
func (sv *SliceViewBase) ConfigToolbar() {
if kit.IfaceIsNil(sv.Slice) || sv.IsInactive() {
return
}
if sv.ToolbarSlice == sv.Slice {
return
}
tb := sv.ToolBar()
ndef := 2 // number of default actions
if sv.isArray || sv.IsInactive() || sv.NoAdd {
ndef = 1
}
if len(*tb.Children()) < ndef {
tb.SetStretchMaxWidth()
tb.AddAction(gi.ActOpts{Label: "UpdtView", Icon: "update", Tooltip: "update this SliceView to reflect current state of slice"},
sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.This().(SliceViewer).UpdateSliceGrid()
})
if ndef > 1 {
tb.AddAction(gi.ActOpts{Label: "Add", Icon: "plus", Tooltip: "add a new element to the slice"},
sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
svv := recv.Embed(KiT_SliceViewBase).(*SliceViewBase)
svv.This().(SliceViewer).SliceNewAt(-1)
})
}
}
sz := len(*tb.Children())
if sz > ndef {
for i := sz - 1; i >= ndef; i-- {
tb.DeleteChildAtIndex(i, ki.DestroyKids)
}
}
if HasToolBarView(sv.Slice) {
ToolBarView(sv.Slice, sv.Viewport, tb)
tb.SetFullReRender()
}
sv.ToolbarSlice = sv.Slice
}
func (sv *SliceViewBase) Style2D() {
sv.Frame.Style2D()
if !sv.This().(SliceViewer).IsConfiged() {
return
}
mvp := sv.ViewportSafe()
if mvp != nil && (mvp.IsDoingFullRender() || mvp.HasFlag(int(gi.VpFlagPrefSizing))) {
if sv.This().(SliceViewer).LayoutSliceGrid() {
sv.This().(SliceViewer).UpdateSliceGrid()
}
}
if sv.IsInactive() {
sv.SetCanFocus()
}
sg := sv.This().(SliceViewer).SliceGrid()
sg.StartFocus() // need to call this when window is actually active
}
func (sv *SliceViewBase) Render2D() {
if win := sv.ParentWindow(); win != nil {
if !win.IsResizing() {
win.MainMenuUpdateActives()
}
}
if !sv.This().(SliceViewer).IsConfiged() {
return
}
sv.ToolBar().UpdateActions()
if !sv.SliceGridNeedsLayout() && sv.FullReRenderIfNeeded() {
return
}
if sv.PushBounds() {
if !sv.InFullRebuild && sv.SliceGridNeedsLayout() {
// note: we are outside of slice grid and thus cannot do proper layout during Layout2D
// as we don't yet know the size of grid -- so we catch it here at next step and just
// rebuild as needed.
sv.RenderedRows = sv.DispRows
sv.This().(SliceViewer).LayoutSliceGrid()
// sv.This().(SliceViewer).UpdateSliceGrid() // not updating
sv.InFullRebuild = true
sv.ReRender2DTree()
sv.InFullRebuild = false
if sv.SelectedIdx > -1 {
sv.ScrollToIdx(sv.SelectedIdx)
}
sv.PopBounds()
return
}
sv.FrameStdRender()
sv.This().(gi.Node2D).ConnectEvents2D()
sv.RenderScrolls()
sv.Render2DChildren()
sv.PopBounds()
} else {
sv.DisconnectAllEvents(gi.AllPris)
}
}
func (sv *SliceViewBase) ConnectEvents2D() {
sv.SliceViewBaseEvents()
}
func (sv *SliceViewBase) HasFocus2D() bool {
if !sv.ContainsFocus() {
return false
}
if sv.IsInactive() {
return sv.InactKeyNav
}
return true
}
//////////////////////////////////////////////////////////////////////////////
// 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) interface{} {
if idx < 0 || idx >= sv.SliceSize {
fmt.Printf("giv.SliceViewBase: slice index out of range: %v\n", idx)
return nil
}
val := kit.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.DispRows
}
// IsIdxVisible returns true if slice index is currently visible
func (sv *SliceViewBase) IsIdxVisible(idx int) bool {
return sv.IsRowInBounds(idx - sv.StartIdx)
}
// RowFirstWidget returns the first widget for given row (could be index or
// not) -- false if out of range
func (sv *SliceViewBase) RowFirstWidget(row int) (*gi.WidgetBase, bool) {
if !sv.ShowIndex {
return nil, false
}
if !sv.IsRowInBounds(row) {
return nil, false
}
nWidgPerRow, _ := sv.This().(SliceViewer).RowWidgetNs()
sg := sv.This().(SliceViewer).SliceGrid()
widg := sg.Kids[row*nWidgPerRow].(gi.Node2D).AsWidget()
return widg, 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 (sv *SliceViewBase) RowGrabFocus(row int) *gi.WidgetBase {
if !sv.IsRowInBounds(row) || sv.InFocusGrab { // range check
return nil
}
nWidgPerRow, idxOff := sv.This().(SliceViewer).RowWidgetNs()