-
Notifications
You must be signed in to change notification settings - Fork 0
/
sliceview.go
1576 lines (1455 loc) · 45.2 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, 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"
"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/pi/filecat"
)
////////////////////////////////////////////////////////////////////////////////////////
// SliceView
// SliceView represents a slice, creating a property editor of the values --
// constructs Children widgets to show the index / value pairs, within an
// overall frame. Set to Inactive for select-only mode, which emits WidgetSig
// WidgetSelected signals when selection is updated
type SliceView struct {
gi.Frame
Slice interface{} `desc:"the slice that we are a view onto -- must be a pointer to that slice"`
SliceValView ValueView `desc:"ValueView for the slice itself, if this was created within value view framework -- otherwise nil"`
isArray bool `desc:"whether the slice is actually an array -- no modifications -- set by SetSlice"`
AddOnly bool `desc:"can the user delete elements of the slice"`
DeleteOnly bool `desc:"can the user add elements to the slice"`
StyleFunc SliceViewStyleFunc `view:"-" json:"-" xml:"-" desc:"optional styling function"`
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 `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"`
VisRows int `desc:"number of rows visible in display"`
SelVal interface{} `view:"-" json:"-" xml:"-" desc:"current selection value -- initially select this value if set"`
SelectedIdx int `json:"-" xml:"-" desc:"index of currently-selected item, in Inactive mode only"`
SelectMode bool `desc:"editing-mode select rows mode"`
SelectedRows map[int]struct{} `desc:"list of currently-selected rows"`
DraggedRows []int `desc:"list of currently-dragged rows"`
SliceViewSig ki.Signal `json:"-" xml:"-" desc:"slice view interactive editing signals"`
ViewSig ki.Signal `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"`
TmpSave ValueView `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"`
BuiltSlice interface{} `view:"-" json:"-" xml:"-" desc:"the built slice"`
BuiltSize int
ToolbarSlice interface{} `desc:"the slice that we successfully set a toolbar for"`
inFocusGrab bool
curRow int // temp row variable used e.g., in Drop method
}
var KiT_SliceView = kit.Types.AddType(&SliceView{}, SliceViewProps)
// AddNewSliceView adds a new sliceview to given parent node, with given name.
func AddNewSliceView(parent ki.Ki, name string) *SliceView {
return parent.AddNewChild(KiT_SliceView, name).(*SliceView)
}
// SliceViewStyleFunc is a styling function for custom styling /
// configuration of elements in the view
type SliceViewStyleFunc func(sv *SliceView, slice interface{}, widg gi.Node2D, row int, vv ValueView)
// SetSlice sets the source slice that we are viewing -- rebuilds the children
// to represent this slice
func (sv *SliceView) SetSlice(sl interface{}, tmpSave ValueView) {
updt := false
if sv.Slice != sl {
updt = sv.UpdateStart()
sv.Slice = sl
sv.isArray = kit.NonPtrType(reflect.TypeOf(sl)).Kind() == reflect.Array
if !sv.IsInactive() {
sv.SelectedIdx = -1
}
sv.SelectedRows = make(map[int]struct{}, 10)
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.TmpSave = tmpSave
sv.UpdateFromSlice()
sv.UpdateEnd(updt)
}
var SliceViewProps = ki.Props{
"background-color": &gi.Prefs.Colors.Background,
"max-width": -1,
"max-height": -1,
}
// SliceViewSignals are signals that sliceview can send, mostly for editing
// mode. Selection events are sent on WidgetSig WidgetSelected signals in
// both modes.
type SliceViewSignals int64
const (
// SliceViewDoubleClicked emitted during inactive mode when item
// double-clicked -- can be used for accepting dialog.
SliceViewDoubleClicked SliceViewSignals = iota
// todo: add more signals as needed
SliceViewSignalsN
)
//go:generate stringer -type=SliceViewSignals
// UpdateFromSlice performs overall configuration for given slice
func (sv *SliceView) UpdateFromSlice() {
mods, updt := sv.StdConfig()
sv.ConfigSliceGrid(true)
sv.ConfigToolbar()
if mods {
sv.SetFullReRender()
sv.UpdateEnd(updt)
}
}
// UpdateValues updates the widget display of slice values, assuming same slice config
func (sv *SliceView) UpdateValues() {
updt := sv.UpdateStart()
for _, vv := range sv.Values {
vv.UpdateWidget()
}
sv.UpdateEnd(updt)
}
// StdFrameConfig returns a TypeAndNameList for configuring a standard Frame
// -- can modify as desired before calling ConfigChildren on Frame using this
func (sv *SliceView) StdFrameConfig() kit.TypeAndNameList {
config := kit.TypeAndNameList{}
config.Add(gi.KiT_ToolBar, "toolbar")
config.Add(gi.KiT_Frame, "slice-grid")
return config
}
// StdConfig configures a standard setup of the overall Frame -- returns mods,
// updt from ConfigChildren and does NOT call UpdateEnd
func (sv *SliceView) StdConfig() (mods, updt bool) {
sv.Lay = gi.LayoutVert
sv.SetProp("spacing", gi.StdDialogVSpaceUnits)
config := sv.StdFrameConfig()
mods, updt = sv.ConfigChildren(config, false)
return
}
// SliceGrid returns the SliceGrid grid frame widget, which contains all the
// fields and values, and its index, within frame -- nil, -1 if not found
func (sv *SliceView) SliceGrid() (*gi.Frame, int) {
idx, ok := sv.Children().IndexByName("slice-grid", 0)
if !ok {
return nil, -1
}
return sv.Child(idx).(*gi.Frame), idx
}
// ToolBar returns the toolbar widget
func (sv *SliceView) ToolBar() *gi.ToolBar {
idx, ok := sv.Children().IndexByName("toolbar", 0)
if !ok {
return nil
}
return sv.Child(idx).(*gi.ToolBar)
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (sv *SliceView) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 2
if !sv.IsInactive() && !sv.isArray {
if !sv.AddOnly {
nWidgPerRow += 1
}
if !sv.DeleteOnly {
nWidgPerRow += 1
}
}
idxOff = 1
if !sv.ShowIndex {
nWidgPerRow -= 1
idxOff = 0
}
return
}
// ConfigSliceGrid configures the SliceGrid for the current slice
func (sv *SliceView) ConfigSliceGrid(forceUpdt bool) {
if kit.IfaceIsNil(sv.Slice) {
return
}
mv := reflect.ValueOf(sv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
if !forceUpdt && sv.BuiltSlice == sv.Slice && sv.BuiltSize == sz {
return
}
sv.BuiltSlice = sv.Slice
sv.BuiltSize = sz
sg, _ := sv.SliceGrid()
if sg == nil {
return
}
updt := sg.UpdateStart()
sg.SetFullReRender()
defer sg.UpdateEnd(updt)
nWidgPerRow, _ := sv.RowWidgetNs()
sg.Lay = gi.LayoutGrid
sg.SetProp("columns", nWidgPerRow)
// setting a pref here is key for giving it a scrollbar in larger context
sg.SetMinPrefHeight(units.NewValue(1.5, units.Em))
sg.SetMinPrefWidth(units.NewValue(10, units.Em))
sg.SetStretchMaxHeight() // for this to work, ALL layers above need it too
sg.SetStretchMaxWidth() // for this to work, ALL layers above need it too
sv.Values = make([]ValueView, sz)
sg.DeleteChildren(true)
sg.Kids = make(ki.Slice, nWidgPerRow*sz)
sv.ConfigSliceGridRows()
}
// ConfigSliceGridRows configures the SliceGrid rows for the current slice --
// assumes .Kids is created at the right size -- only call this for a direct
// re-render e.g., after sorting
func (sv *SliceView) ConfigSliceGridRows() {
mv := reflect.ValueOf(sv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
sg, _ := sv.SliceGrid()
nWidgPerRow, idxOff := sv.RowWidgetNs()
updt := sg.UpdateStart()
defer sg.UpdateEnd(updt)
for i := 0; i < sz; i++ {
ridx := i * nWidgPerRow
val := kit.OnePtrUnderlyingValue(mvnp.Index(i)) // deal with pointer lists
vv := ToValueView(val.Interface(), "")
if vv == nil { // shouldn't happen
continue
}
vv.SetSliceValue(val, sv.Slice, i, sv.TmpSave)
sv.Values[i] = vv
vtyp := vv.WidgetType()
idxtxt := fmt.Sprintf("%05d", i)
labnm := fmt.Sprintf("index-%v", idxtxt)
valnm := fmt.Sprintf("value-%v", idxtxt)
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.Text = idxtxt
idxlab.SetProp("slv-index", i)
idxlab.Selectable = true
idxlab.WidgetSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.WidgetSelected) {
wbb := send.(gi.Node2D).AsWidget()
idx := wbb.Prop("slv-index").(int)
svv := recv.Embed(KiT_SliceView).(*SliceView)
svv.UpdateSelect(idx, wbb.IsSelected())
}
})
}
var widg gi.Node2D
if sg.Kids[ridx+idxOff] != nil {
widg = sg.Kids[ridx+idxOff].(gi.Node2D)
} else {
widg = ki.NewOfType(vtyp).(gi.Node2D)
sg.SetChild(widg, ridx+idxOff, valnm)
}
vv.ConfigWidget(widg)
if sv.IsInactive() {
widg.AsNode2D().SetInactive()
wb := widg.AsWidget()
if wb != nil {
wb.SetProp("slv-index", 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()
idx := wbb.Prop("slv-index").(int)
svv := recv.Embed(KiT_SliceView).(*SliceView)
svv.UpdateSelect(idx, wbb.IsSelected())
}
})
}
} else {
vvb := vv.AsValueViewBase()
vvb.ViewSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
svv, _ := recv.Embed(KiT_SliceView).(*SliceView)
svv.SetChanged()
})
if !sv.isArray {
cidx := ridx + idxOff
if !sv.DeleteOnly {
addnm := fmt.Sprintf("add-%v", idxtxt)
addact := gi.Action{}
cidx += 1
sg.SetChild(&addact, cidx, addnm)
addact.SetIcon("plus")
addact.Tooltip = "insert a new element at this index"
addact.Data = i
addact.ActionSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
svv := recv.Embed(KiT_SliceView).(*SliceView)
svv.SliceNewAt(act.Data.(int)+1, true)
})
}
if !sv.AddOnly {
delnm := fmt.Sprintf("del-%v", idxtxt)
delact := gi.Action{}
cidx += 1
sg.SetChild(&delact, cidx, delnm)
delact.SetIcon("minus")
delact.Tooltip = "delete this element"
delact.Data = i
delact.ActionSig.ConnectOnly(sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
svv := recv.Embed(KiT_SliceView).(*SliceView)
svv.SliceDeleteAt(act.Data.(int), true)
})
}
}
}
if sv.StyleFunc != nil {
sv.StyleFunc(sv, mvnp.Interface(), widg, i, vv)
}
}
if sv.SelVal != nil {
sv.SelectedIdx, _ = SliceRowByValue(sv.Slice, sv.SelVal)
}
if sv.IsInactive() && sv.SelectedIdx >= 0 {
sv.SelectRowWidgets(sv.SelectedIdx, true)
}
}
// SetChanged sets the Changed flag and emits the ViewSig signal for the
// SliceView, 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 *SliceView) SetChanged() {
sv.Changed = true
sv.ViewSig.Emit(sv.This(), 0, nil)
sv.ToolBar().UpdateActions() // nil safe
}
// SliceNewAt inserts a new blank element at given index in the slice -- -1
// means the end
func (sv *SliceView) SliceNewAt(idx int, reconfig bool) {
if sv.isArray {
return
}
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)
svnp := kit.NonPtrValue(svl)
if iski && sv.SliceValView != nil {
vvb := sv.SliceValView.AsValueViewBase()
if vvb.Owner != nil {
if ownki, ok := vvb.Owner.(ki.Ki); ok {
gi.NewKiDialog(sv.Viewport, 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_SliceView).(*SliceView)
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
}
sz := svnp.Len()
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 sv.TmpSave != nil {
sv.TmpSave.SaveTmp()
}
sv.SetChanged()
if reconfig {
sv.ConfigSliceGrid(true)
}
}
// SliceDeleteAt deletes element at given index from slice
func (sv *SliceView) SliceDeleteAt(idx int, reconfig bool) {
if sv.isArray {
return
}
updt := sv.UpdateStart()
defer sv.UpdateEnd(updt)
kit.SliceDeleteAt(sv.Slice, idx)
if sv.TmpSave != nil {
sv.TmpSave.SaveTmp()
}
sv.SetChanged()
if reconfig {
sv.ConfigSliceGrid(true)
}
}
// ConfigToolbar configures the toolbar actions
func (sv *SliceView) ConfigToolbar() {
if kit.IfaceIsNil(sv.Slice) || sv.IsInactive() {
return
}
if sv.ToolbarSlice == sv.Slice {
return
}
tb := sv.ToolBar()
nact := 1
if sv.isArray || sv.IsInactive() {
nact = 0
}
if len(*tb.Children()) < nact {
tb.SetStretchMaxWidth()
if !sv.isArray && !sv.DeleteOnly {
tb.AddAction(gi.ActOpts{Label: "Add", Icon: "plus"},
sv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
svv := recv.Embed(KiT_SliceView).(*SliceView)
svv.SliceNewAt(-1, true)
})
}
}
sz := len(*tb.Children())
if sz > nact {
for i := sz - 1; i >= nact; i-- {
tb.DeleteChildAtIndex(i, true)
}
}
if HasToolBarView(sv.Slice) {
ToolBarView(sv.Slice, sv.Viewport, tb)
}
sv.ToolbarSlice = sv.Slice
}
func (sv *SliceView) Style2D() {
if sv.Viewport != nil && sv.Viewport.IsDoingFullRender() {
sv.UpdateFromSlice()
}
sg, _ := sv.SliceGrid()
sg.StartFocus() // need to call this when window is actually active
sv.Frame.Style2D()
}
func (sv *SliceView) Render2D() {
sv.ToolBar().UpdateActions()
if win := sv.ParentWindow(); win != nil {
if !win.IsResizing() {
win.MainMenuUpdateActives()
}
}
if sv.FullReRenderIfNeeded() {
return
}
if sv.PushBounds() {
if sv.Sty.Font.Height > 0 {
sv.VisRows = (sv.VpBBox.Max.Y - sv.VpBBox.Min.Y) / int(1.8*sv.Sty.Font.Height)
} else {
sv.VisRows = 10
}
sv.FrameStdRender()
sv.This().(gi.Node2D).ConnectEvents2D()
sv.RenderScrolls()
sv.Render2DChildren()
sv.PopBounds()
if sv.SelectedIdx > -1 {
sv.ScrollToRow(sv.SelectedIdx)
}
} else {
sv.DisconnectAllEvents(gi.AllPris)
}
}
func (sv *SliceView) ConnectEvents2D() {
sv.SliceViewEvents()
}
func (sv *SliceView) HasFocus2D() bool {
if sv.IsInactive() {
return sv.InactKeyNav
}
return sv.ContainsFocus() // anyone within us gives us focus..
}
//////////////////////////////////////////////////////////////////////////////
// Row access methods
// RowVal returns value interface at given row
func (sv *SliceView) RowVal(row int) interface{} {
mv := reflect.ValueOf(sv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
if row < 0 || row >= sz {
fmt.Printf("giv.SliceView: row index out of range: %v\n", row)
return nil
}
val := kit.OnePtrUnderlyingValue(mvnp.Index(row)) // deal with pointer lists
vali := val.Interface()
return vali
}
// RowFirstWidget returns the first widget for given row (could be index or
// not) -- false if out of range
func (sv *SliceView) RowFirstWidget(row int) (*gi.WidgetBase, bool) {
if !sv.ShowIndex {
return nil, false
}
if sv.RowVal(row) == nil { // range check
return nil, false
}
nWidgPerRow, _ := sv.RowWidgetNs()
sg, _ := sv.SliceGrid()
if sg == nil {
return nil, false
}
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 *SliceView) RowGrabFocus(row int) *gi.WidgetBase {
if sv.RowVal(row) == nil || sv.inFocusGrab { // range check
return nil
}
nWidgPerRow, idxOff := sv.RowWidgetNs()
sg, _ := sv.SliceGrid()
if sg == nil {
return nil
}
ridx := nWidgPerRow * row
widg := sg.Child(ridx + idxOff).(gi.Node2D).AsWidget()
if widg.HasFocus() {
return widg
}
sv.inFocusGrab = true
defer func() { sv.inFocusGrab = false }()
if widg.CanFocus() {
widg.GrabFocus()
return widg
}
return nil
}
// RowPos returns center of window position of index label for row (ContextMenuPos)
func (sv *SliceView) RowPos(row int) image.Point {
var pos image.Point
widg, ok := sv.RowFirstWidget(row)
if ok {
pos = widg.ContextMenuPos()
}
return pos
}
// RowFromPos returns the row that contains given vertical position, false if not found
func (sv *SliceView) RowFromPos(posY int) (int, bool) {
// todo: could optimize search to approx loc, and search up / down from there
for rw := 0; rw < sv.BuiltSize; rw++ {
widg, ok := sv.RowFirstWidget(rw)
if ok {
if widg.WinBBox.Min.Y < posY && posY < widg.WinBBox.Max.Y {
return rw, true
}
}
}
return -1, false
}
// ScrollToRow ensures that given row is visible by scrolling layout as needed
// -- returns true if any scrolling was performed
func (sv *SliceView) ScrollToRow(row int) bool {
row = ints.MinInt(row, sv.BuiltSize-1)
sg, _ := sv.SliceGrid()
if widg, ok := sv.RowFirstWidget(row); ok {
return sg.ScrollToItem(widg)
}
return false
}
// SelectVal sets SelVal and attempts to find corresponding row, setting
// SelectedIdx and selecting row if found -- returns true if found, false
// otherwise.
func (sv *SliceView) SelectVal(val string) bool {
sv.SelVal = val
if sv.SelVal != nil {
idx, _ := SliceRowByValue(sv.Slice, sv.SelVal)
if idx >= 0 {
sv.ScrollToRow(idx)
sv.UpdateSelect(idx, true)
return true
}
}
return false
}
// SliceRowByValue searches for first row that contains given value in slice
// -- returns false if not found
func SliceRowByValue(struSlice interface{}, fldVal interface{}) (int, bool) {
mv := reflect.ValueOf(struSlice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
for row := 0; row < sz; row++ {
rval := kit.NonPtrValue(mvnp.Index(row))
if rval.Interface() == fldVal {
return row, true
}
}
return -1, false
}
/////////////////////////////////////////////////////////////////////////////
// Moving
// MoveDown moves the selection down to next row, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (sv *SliceView) MoveDown(selMode mouse.SelectModes) int {
if sv.SelectedIdx >= sv.BuiltSize-1 {
sv.SelectedIdx = sv.BuiltSize - 1
return -1
}
sv.SelectedIdx++
sv.SelectRowAction(sv.SelectedIdx, selMode)
return sv.SelectedIdx
}
// MoveDownAction moves the selection down to next row, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (sv *SliceView) MoveDownAction(selMode mouse.SelectModes) int {
nrow := sv.MoveDown(selMode)
if nrow >= 0 {
sv.ScrollToRow(nrow)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), nrow)
}
return nrow
}
// MoveUp moves the selection up to previous row, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (sv *SliceView) MoveUp(selMode mouse.SelectModes) int {
if sv.SelectedIdx <= 0 {
sv.SelectedIdx = 0
return -1
}
sv.SelectedIdx--
sv.SelectRowAction(sv.SelectedIdx, selMode)
return sv.SelectedIdx
}
// MoveUpAction moves the selection up to previous row, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (sv *SliceView) MoveUpAction(selMode mouse.SelectModes) int {
nrow := sv.MoveUp(selMode)
if nrow >= 0 {
sv.ScrollToRow(nrow)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), nrow)
}
return nrow
}
// MovePageDown moves the selection down to next page, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (sv *SliceView) MovePageDown(selMode mouse.SelectModes) int {
if sv.SelectedIdx >= sv.BuiltSize-1 {
sv.SelectedIdx = sv.BuiltSize - 1
return -1
}
sv.SelectedIdx += sv.VisRows
sv.SelectedIdx = ints.MinInt(sv.SelectedIdx, sv.BuiltSize-1)
sv.SelectRowAction(sv.SelectedIdx, selMode)
return sv.SelectedIdx
}
// MovePageDownAction moves the selection down to next page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (sv *SliceView) MovePageDownAction(selMode mouse.SelectModes) int {
nrow := sv.MovePageDown(selMode)
if nrow >= 0 {
sv.ScrollToRow(nrow)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), nrow)
}
return nrow
}
// MovePageUp moves the selection up to previous page, using given select mode
// (from keyboard modifiers) -- returns newly selected row or -1 if failed
func (sv *SliceView) MovePageUp(selMode mouse.SelectModes) int {
if sv.SelectedIdx <= 0 {
sv.SelectedIdx = 0
return -1
}
sv.SelectedIdx -= sv.VisRows
sv.SelectedIdx = ints.MaxInt(0, sv.SelectedIdx)
sv.SelectRowAction(sv.SelectedIdx, selMode)
return sv.SelectedIdx
}
// MovePageUpAction moves the selection up to previous page, using given select
// mode (from keyboard modifiers) -- and emits select event for newly selected
// row
func (sv *SliceView) MovePageUpAction(selMode mouse.SelectModes) int {
nrow := sv.MovePageUp(selMode)
if nrow >= 0 {
sv.ScrollToRow(nrow)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), nrow)
}
return nrow
}
//////////////////////////////////////////////////////////////////////////////
// Selection: user operates on the index labels
// SelectRowWidgets sets the selection state of given row of widgets
func (sv *SliceView) SelectRowWidgets(idx int, sel bool) {
sg, _ := sv.SliceGrid()
nWidgPerRow, idxOff := sv.RowWidgetNs()
rowidx := idx * nWidgPerRow
if sv.ShowIndex {
if sg.Kids.IsValidIndex(rowidx) == nil {
widg := sg.Child(rowidx).(gi.Node2D).AsNode2D()
widg.SetSelectedState(sel)
widg.UpdateSig()
}
}
if sg.Kids.IsValidIndex(rowidx+idxOff) == nil {
widg := sg.Child(rowidx + idxOff).(gi.Node2D).AsNode2D()
widg.SetSelectedState(sel)
widg.UpdateSig()
}
}
// UpdateSelect updates the selection for the given index -- callback from widgetsig select
func (sv *SliceView) UpdateSelect(idx int, sel bool) {
if sv.IsInactive() {
if sv.SelectedIdx == idx { // never unselect
sv.SelectRowWidgets(sv.SelectedIdx, true)
return
}
if sv.SelectedIdx >= 0 { // unselect current
sv.SelectRowWidgets(sv.SelectedIdx, false)
}
if sel {
sv.SelectedIdx = idx
sv.SelectRowWidgets(sv.SelectedIdx, true)
}
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), sv.SelectedIdx)
} else {
selMode := mouse.SelectOne
win := sv.Viewport.Win
if win != nil {
selMode = win.LastSelMode
}
sv.SelectRowAction(idx, selMode)
}
}
// RowIsSelected returns the selected status of given row index
func (sv *SliceView) RowIsSelected(row int) bool {
if _, ok := sv.SelectedRows[row]; ok {
return true
}
return false
}
// SelectedRowsList returns list of selected rows, sorted either ascending or descending
func (sv *SliceView) SelectedRowsList(descendingSort bool) []int {
rws := make([]int, len(sv.SelectedRows))
i := 0
for r, _ := range sv.SelectedRows {
rws[i] = r
i++
}
if descendingSort {
sort.Slice(rws, func(i, j int) bool {
return rws[i] > rws[j]
})
} else {
sort.Slice(rws, func(i, j int) bool {
return rws[i] < rws[j]
})
}
return rws
}
// SelectRow selects given row (if not already selected) -- updates select
// status of index label
func (sv *SliceView) SelectRow(row int) {
sv.SelectedRows[row] = struct{}{}
sv.SelectRowWidgets(row, true)
}
// UnselectRow unselects given row (if selected)
func (sv *SliceView) UnselectRow(row int) {
if sv.RowIsSelected(row) {
delete(sv.SelectedRows, row)
}
sv.SelectRowWidgets(row, false)
}
// UnselectAllRows unselects all selected rows
func (sv *SliceView) UnselectAllRows() {
win := sv.Viewport.Win
updt := false
if win != nil {
updt = win.UpdateStart()
}
for r, _ := range sv.SelectedRows {
sv.SelectRowWidgets(r, false)
}
sv.SelectedRows = make(map[int]struct{}, 10)
if win != nil {
win.UpdateEnd(updt)
}
}
// SelectAllRows selects all rows
func (sv *SliceView) SelectAllRows() {
win := sv.Viewport.Win
updt := false
if win != nil {
updt = win.UpdateStart()
}
sv.UnselectAllRows()
sv.SelectedRows = make(map[int]struct{}, sv.BuiltSize)
for row := 0; row < sv.BuiltSize; row++ {
sv.SelectedRows[row] = struct{}{}
sv.SelectRowWidgets(row, true)
}
if win != nil {
win.UpdateEnd(updt)
}
}
// SelectRowAction is called when a select action has been received (e.g., a
// mouse click) -- translates into selection updates -- gets selection mode
// from mouse event (ExtendContinuous, ExtendOne)
func (sv *SliceView) SelectRowAction(row int, mode mouse.SelectModes) {
if mode == mouse.NoSelect {
return
}
row = ints.MinInt(row, sv.BuiltSize-1)
if row < 0 {
row = 0
}
win := sv.Viewport.Win
updt := false
if win != nil {
updt = win.UpdateStart()
}
switch mode {
case mouse.SelectOne:
if sv.RowIsSelected(row) {
if len(sv.SelectedRows) > 1 {
sv.UnselectAllRows()
}
sv.SelectedIdx = row
sv.SelectRow(row)
sv.RowGrabFocus(row)
} else {
sv.UnselectAllRows()
sv.SelectedIdx = row
sv.SelectRow(row)
sv.RowGrabFocus(row)
}
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), sv.SelectedIdx)
case mouse.ExtendContinuous:
if len(sv.SelectedRows) == 0 {
sv.SelectedIdx = row
sv.SelectRow(row)
sv.RowGrabFocus(row)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), sv.SelectedIdx)
} else {
minIdx := -1
maxIdx := 0
for r, _ := range sv.SelectedRows {
if minIdx < 0 {
minIdx = r
} else {
minIdx = ints.MinInt(minIdx, r)
}
maxIdx = ints.MaxInt(maxIdx, r)
}
cidx := row
sv.SelectedIdx = row
sv.SelectRow(row)
if row < minIdx {
for cidx < minIdx {
r := sv.MoveDown(mouse.SelectQuiet) // just select
cidx = r
}
} else if row > maxIdx {
for cidx > maxIdx {
r := sv.MoveUp(mouse.SelectQuiet) // just select
cidx = r
}
}
sv.RowGrabFocus(row)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), sv.SelectedIdx)
}
case mouse.ExtendOne:
if sv.RowIsSelected(row) {
sv.UnselectRowAction(row)
} else {
sv.SelectedIdx = row
sv.SelectRow(row)
sv.RowGrabFocus(row)
sv.WidgetSig.Emit(sv.This(), int64(gi.WidgetSelected), sv.SelectedIdx)
}
case mouse.Unselect:
sv.SelectedIdx = row
sv.UnselectRowAction(row)
case mouse.SelectQuiet:
sv.SelectedIdx = row
sv.SelectRow(row)
case mouse.UnselectQuiet:
sv.SelectedIdx = row
sv.UnselectRow(row)
}
if win != nil {
win.UpdateEnd(updt)
}
}
// UnselectRowAction unselects this row (if selected) -- and emits a signal
func (sv *SliceView) UnselectRowAction(row int) {
if sv.RowIsSelected(row) {
sv.UnselectRow(row)
}
}
//////////////////////////////////////////////////////////////////////////////
// Copy / Cut / Paste
// MimeDataRow adds mimedata for given row: an application/json of the struct
func (sv *SliceView) MimeDataRow(md *mimedata.Mimes, row int) {
val := sv.RowVal(row)