-
Notifications
You must be signed in to change notification settings - Fork 0
/
tableview.go
1912 lines (1769 loc) · 54.8 KB
/
tableview.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"
"strings"
"github.com/goki/gi/gi"
"github.com/goki/gi/oswin"
"github.com/goki/gi/oswin/cursor"
"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"
"github.com/goki/ki/ints"
"github.com/goki/ki/kit"
)
// todo:
// * search option, both as a search field and as simple type-to-search
// * popup menu option -- when user does right-mouse on item, a provided func is called
// -- use in fileview
// * could have a native context menu for add / delete etc.
// * emit TableViewSigs
// TableViewWaitCursorSize is the length of the slice above which a wait
// cursor will be displayed while updating the table
var TableViewWaitCursorSize = 5000
// TableView represents a slice-of-structs as a table, where the fields are
// the columns, within an overall frame. It has two modes, determined by
// Inactive flag: if Inactive, it functions as a mutually-exclusive item
// selector, highlighting the selected row and emitting a WidgetSig
// WidgetSelected signal, and TableViewDoubleClick for double clicks (can be
// used for closing dialogs). If !Inactive, it is a full-featured editor with
// multiple-selection, cut-and-paste, and drag-and-drop, reporting each action
// taken using the TableViewSig signals
type TableView struct {
gi.Frame
Slice interface{} `view:"-" json:"-" xml:"-" 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"`
StyleFunc TableViewStyleFunc `view:"-" json:"-" xml:"-" desc:"optional styling function"`
ShowViewCtxtMenu bool `desc:"if the object 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 table been edited?"`
Values [][]ValueView `json:"-" xml:"-" desc:"ValueView representations of the slice field values -- outer dimension is fields, inner is rows (generally more rows than fields, so this minimizes number of slices allocated)"`
ShowIndex bool `xml:"index" desc:"whether to show index or not (default true) -- 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"`
SelField string `view:"-" json:"-" xml:"-" desc:"current selection field -- initially select value in this field"`
SelVal interface{} `view:"-" json:"-" xml:"-" desc:"current selection value -- initially select this value in SelField"`
SelectedIdx int `json:"-" xml:"-" desc:"index (row) of currently-selected item (-1 if none) -- see SelectedRows for full set of selected rows in active editing mode"`
SortIdx int `desc:"current sort index"`
SortDesc bool `desc:"whether current sort order is descending"`
SelectMode bool `desc:"editing-mode select rows mode"`
SelectedRows map[int]bool `desc:"list of currently-selected rows"`
DraggedRows []int `desc:"list of currently-dragged rows"`
TableViewSig ki.Signal `json:"-" xml:"-" desc:"table 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"`
StruType reflect.Type
NVisFields int
VisFields []reflect.StructField `view:"-" json:"-" xml:"-" desc:"the visible fields"`
inFocusGrab bool
curRow int // temp row variable used e.g., in Drop method
}
var KiT_TableView = kit.Types.AddType(&TableView{}, TableViewProps)
// Note: the overall strategy here is similar to Dialog, where we provide lots
// of flexible configuration elements that can be easily extended and modified
// TableViewStyleFunc is a styling function for custom styling /
// configuration of elements in the view
type TableViewStyleFunc func(tv *TableView, slice interface{}, widg gi.Node2D, row, col int, vv ValueView)
// SetSlice sets the source slice that we are viewing -- rebuilds the children
// to represent this slice
func (tv *TableView) SetSlice(sl interface{}, tmpSave ValueView) {
updt := false
if kit.IfaceIsNil(sl) {
return
}
if tv.Slice != sl {
if !tv.IsInactive() {
tv.SelectedIdx = -1
}
tv.SortIdx = -1
tv.SortDesc = false
slpTyp := reflect.TypeOf(sl)
if slpTyp.Kind() != reflect.Ptr {
log.Printf("TableView requires that you pass a pointer to a slice of struct elements -- type is not a Ptr: %v\n", slpTyp.String())
return
}
if slpTyp.Elem().Kind() != reflect.Slice {
log.Printf("TableView requires that you pass a pointer to a slice of struct elements -- ptr doesn't point to a slice: %v\n", slpTyp.Elem().String())
return
}
tv.Slice = sl
struTyp := tv.StructType()
if struTyp.Kind() != reflect.Struct {
log.Printf("TableView requires that you pass a slice of struct elements -- type is not a Struct: %v\n", struTyp.String())
return
}
updt = tv.UpdateStart()
tv.SelectedRows = make(map[int]bool, 10)
tv.SelectMode = false
tv.SetFullReRender()
}
tv.ShowIndex = true
if sidxp, ok := tv.Prop("index"); ok {
tv.ShowIndex, _ = kit.ToBool(sidxp)
}
tv.InactKeyNav = true
if siknp, ok := tv.Prop("inact-key-nav"); ok {
tv.InactKeyNav, _ = kit.ToBool(siknp)
}
tv.TmpSave = tmpSave
tv.UpdateFromSlice()
tv.UpdateEnd(updt)
}
var TableViewProps = ki.Props{
"background-color": &gi.Prefs.Colors.Background,
"color": &gi.Prefs.Colors.Font,
"max-width": -1,
"max-height": -1,
}
// TableViewSignals are signals that tableview can send, mostly for editing
// mode. Selection events are sent on WidgetSig WidgetSelected signals in
// both modes.
type TableViewSignals int64
const (
// TableViewDoubleClicked emitted during inactive mode when item
// double-clicked -- can be used for accepting dialog.
TableViewDoubleClicked TableViewSignals = iota
// todo: add more signals as needed
TableViewSignalsN
)
//go:generate stringer -type=TableViewSignals
// UpdateFromSlice does full update from current slice
func (tv *TableView) UpdateFromSlice() {
mods, updt := tv.StdConfig()
tv.ConfigSliceGrid(true)
tv.ConfigToolbar()
if mods {
tv.SetFullReRender()
tv.UpdateEnd(updt)
}
}
// UpdateValues just updates rendered values
func (tv *TableView) UpdateValues() {
updt := tv.UpdateStart()
for _, vv := range tv.Values {
for _, vvf := range vv {
vvf.UpdateWidget()
}
}
tv.UpdateEnd(updt)
}
// StructType sets the StruType and returns the type of the struct within the
// slice -- this is a non-ptr type even if slice has pointers to structs
func (tv *TableView) StructType() reflect.Type {
tv.StruType = kit.NonPtrType(kit.SliceElType(tv.Slice))
return tv.StruType
}
// CacheVisFields computes the number of visible fields in nVisFields and
// caches those to skip in fieldSkip
func (tv *TableView) CacheVisFields() {
styp := tv.StructType()
tv.VisFields = make([]reflect.StructField, 0, 20)
kit.FlatFieldsTypeFunc(styp, func(typ reflect.Type, fld reflect.StructField) bool {
tvtag := fld.Tag.Get("tableview")
add := true
if tvtag != "" {
if tvtag == "-" {
add = false
} else if tvtag == "-select" && tv.IsInactive() {
add = false
} else if tvtag == "-edit" && !tv.IsInactive() {
add = false
}
}
if add {
tv.VisFields = append(tv.VisFields, fld)
}
return true
})
tv.NVisFields = len(tv.VisFields)
}
// StdFrameConfig returns a TypeAndNameList for configuring a standard Frame
// -- can modify as desired before calling ConfigChildren on Frame using this
func (tv *TableView) StdFrameConfig() kit.TypeAndNameList {
config := kit.TypeAndNameList{}
config.Add(gi.KiT_ToolBar, "toolbar")
config.Add(gi.KiT_Frame, "slice-frame")
return config
}
// StdConfig configures a standard setup of the overall Frame -- returns mods,
// updt from ConfigChildren and does NOT call UpdateEnd
func (tv *TableView) StdConfig() (mods, updt bool) {
tv.Lay = gi.LayoutVert
tv.SetProp("spacing", gi.StdDialogVSpaceUnits)
config := tv.StdFrameConfig()
mods, updt = tv.ConfigChildren(config, false)
return
}
// SliceFrame returns the outer frame widget, which contains all the header,
// fields and values, and its index, within frame -- nil, -1 if not found
func (tv *TableView) SliceFrame() (*gi.Frame, int) {
idx, ok := tv.Children().IndexByName("slice-frame", 0)
if !ok {
return nil, -1
}
return tv.KnownChild(idx).(*gi.Frame), idx
}
// SliceGrid returns the SliceGrid grid frame widget, which contains all the
// fields and values, within SliceFrame
func (tv *TableView) SliceGrid() *gi.Frame {
sf, _ := tv.SliceFrame()
if sf == nil {
return nil
}
return sf.KnownChild(1).(*gi.Frame)
}
// SliceHeader returns the Toolbar header for slice grid
func (tv *TableView) SliceHeader() *gi.ToolBar {
sf, _ := tv.SliceFrame()
if sf == nil {
return nil
}
return sf.KnownChild(0).(*gi.ToolBar)
}
// ToolBar returns the toolbar widget
func (tv *TableView) ToolBar() *gi.ToolBar {
idx, ok := tv.Children().IndexByName("toolbar", 0)
if !ok {
return nil
}
return tv.KnownChild(idx).(*gi.ToolBar)
}
// StdSliceFrameConfig returns a TypeAndNameList for configuring the slice-frame
func (tv *TableView) StdSliceFrameConfig() kit.TypeAndNameList {
config := kit.TypeAndNameList{}
config.Add(gi.KiT_ToolBar, "header")
config.Add(gi.KiT_Frame, "grid")
return config
}
// RowWidgetNs returns number of widgets per row and offset for index label
func (tv *TableView) RowWidgetNs() (nWidgPerRow, idxOff int) {
nWidgPerRow = 1 + tv.NVisFields
if !tv.IsInactive() {
nWidgPerRow += 2
}
idxOff = 1
if !tv.ShowIndex {
nWidgPerRow -= 1
idxOff = 0
}
return
}
// ConfigSliceGrid configures the SliceGrid for the current slice
func (tv *TableView) ConfigSliceGrid(forceUpdt bool) {
if kit.IfaceIsNil(tv.Slice) {
return
}
mv := reflect.ValueOf(tv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
if !forceUpdt && tv.BuiltSlice == tv.Slice && tv.BuiltSize == sz {
return
}
tv.BuiltSlice = tv.Slice
tv.BuiltSize = sz
tv.CacheVisFields()
nWidgPerRow, idxOff := tv.RowWidgetNs()
// always start fresh!
tv.Values = make([][]ValueView, tv.NVisFields)
for fli := 0; fli < tv.NVisFields; fli++ {
tv.Values[fli] = make([]ValueView, sz)
}
sg, _ := tv.SliceFrame()
if sg == nil {
return
}
sg.Lay = gi.LayoutVert
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
if sz > TableViewWaitCursorSize {
oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Push(cursor.Wait)
defer oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Pop()
}
sgcfg := tv.StdSliceFrameConfig()
modsg, updtg := sg.ConfigChildren(sgcfg, false)
if modsg {
sg.SetFullReRender()
} else {
updtg = sg.UpdateStart()
}
sgh := tv.SliceHeader()
sgh.Lay = gi.LayoutHoriz
sgh.SetProp("overflow", "hidden") // no scrollbars!
sgh.SetProp("spacing", 0)
// sgh.SetStretchMaxWidth()
sgf := tv.SliceGrid()
sgf.Lay = gi.LayoutGrid
sgf.Stripes = gi.RowStripes
// setting a pref here is key for giving it a scrollbar in larger context
sgf.SetMinPrefHeight(units.NewValue(10, units.Em))
sgf.SetStretchMaxHeight() // for this to work, ALL layers above need it too
sgf.SetStretchMaxWidth() // for this to work, ALL layers above need it too
sgf.SetProp("columns", nWidgPerRow)
// Configure Header
hcfg := kit.TypeAndNameList{}
if tv.ShowIndex {
hcfg.Add(gi.KiT_Label, "head-idx")
}
for fli := 0; fli < tv.NVisFields; fli++ {
fld := tv.VisFields[fli]
labnm := fmt.Sprintf("head-%v", fld.Name)
hcfg.Add(gi.KiT_Action, labnm)
}
if !tv.IsInactive() {
hcfg.Add(gi.KiT_Label, "head-add")
hcfg.Add(gi.KiT_Label, "head-del")
}
modsh, updth := sgh.ConfigChildren(hcfg, false)
if modsh {
tv.SetFullReRender()
} else {
updth = sgh.UpdateStart()
}
if tv.ShowIndex {
lbl := sgh.KnownChild(0).(*gi.Label)
lbl.Text = "Index"
}
for fli := 0; fli < tv.NVisFields; fli++ {
fld := tv.VisFields[fli]
hdr := sgh.KnownChild(idxOff + fli).(*gi.Action)
hdr.SetText(fld.Name)
if fli == tv.SortIdx {
if tv.SortDesc {
hdr.SetIcon("widget-wedge-down")
} else {
hdr.SetIcon("widget-wedge-up")
}
}
hdr.Data = fli
hdr.Tooltip = "click to sort / toggle sort direction by this column"
dsc := fld.Tag.Get("desc")
if dsc != "" {
hdr.Tooltip += ": " + dsc
}
hdr.ActionSig.ConnectOnly(tv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
tvv := recv.Embed(KiT_TableView).(*TableView)
act := send.(*gi.Action)
fldIdx := act.Data.(int)
tvv.SortSliceAction(fldIdx)
})
}
if !tv.IsInactive() {
lbl := sgh.KnownChild(tv.NVisFields + idxOff).(*gi.Label)
lbl.Text = "+"
lbl.Tooltip = "insert row"
lbl = sgh.KnownChild(tv.NVisFields + idxOff + 1).(*gi.Label)
lbl.Text = "-"
lbl.Tooltip = "delete row"
}
sgf.DeleteChildren(true)
sgf.Kids = make(ki.Slice, nWidgPerRow*sz)
if tv.SortIdx >= 0 {
rawIdx := tv.VisFields[tv.SortIdx].Index
kit.StructSliceSort(tv.Slice, rawIdx, !tv.SortDesc)
}
tv.ConfigSliceGridRows()
sg.SetFullReRender()
sgh.UpdateEnd(updth)
sg.UpdateEnd(updtg)
}
// 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 (tv *TableView) ConfigSliceGridRows() {
mv := reflect.ValueOf(tv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
if sz > TableViewWaitCursorSize {
oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Push(cursor.Wait)
defer oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Pop()
}
nWidgPerRow, idxOff := tv.RowWidgetNs()
sgf := tv.SliceGrid()
updt := sgf.UpdateStart()
defer sgf.UpdateEnd(updt)
for i := 0; i < sz; i++ {
ridx := i * nWidgPerRow
val := kit.OnePtrValue(mvnp.Index(i)) // deal with pointer lists
stru := val.Interface()
idxtxt := fmt.Sprintf("%05d", i)
labnm := fmt.Sprintf("index-%v", idxtxt)
if tv.ShowIndex {
var idxlab *gi.Label
if sgf.Kids[ridx] != nil {
idxlab = sgf.Kids[ridx].(*gi.Label)
} else {
idxlab = &gi.Label{}
sgf.SetChild(idxlab, ridx, labnm)
}
idxlab.Text = idxtxt
idxlab.SetProp("tv-index", i)
idxlab.Selectable = true
idxlab.WidgetSig.ConnectOnly(tv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.WidgetSelected) {
wbb := send.(gi.Node2D).AsWidget()
idx := wbb.KnownProp("tv-index").(int)
tvv := recv.Embed(KiT_TableView).(*TableView)
tvv.UpdateSelect(idx, wbb.IsSelected())
}
})
}
for fli := 0; fli < tv.NVisFields; fli++ {
field := tv.VisFields[fli]
fval := val.Elem().Field(field.Index[0])
vv := ToValueView(fval.Interface(), "")
if vv == nil { // shouldn't happen
continue
}
vv.SetStructValue(fval.Addr(), stru, &field, tv.TmpSave)
vtyp := vv.WidgetType()
valnm := fmt.Sprintf("value-%v.%v", fli, idxtxt)
cidx := ridx + idxOff + fli
var widg gi.Node2D
if sgf.Kids[cidx] != nil {
widg = sgf.Kids[cidx].(gi.Node2D)
} else {
tv.Values[fli][i] = vv
widg = ki.NewOfType(vtyp).(gi.Node2D)
sgf.SetChild(widg, cidx, valnm)
}
vv.ConfigWidget(widg)
wb := widg.AsWidget()
if wb != nil {
wb.SetProp("tv-index", i)
wb.ClearSelected()
wb.WidgetSig.ConnectOnly(tv.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.KnownProp("tv-index").(int)
tvv := recv.Embed(KiT_TableView).(*TableView)
if sig != int64(gi.WidgetFocused) || !tvv.inFocusGrab {
tvv.UpdateSelect(idx, wbb.IsSelected())
}
}
})
}
if tv.IsInactive() {
widg.AsNode2D().SetInactive()
} else {
vvb := vv.AsValueViewBase()
vvb.ViewSig.ConnectOnly(tv.This(), // todo: do we need this?
func(recv, send ki.Ki, sig int64, data interface{}) {
tvv, _ := recv.Embed(KiT_TableView).(*TableView)
tvv.SetChanged()
})
addnm := fmt.Sprintf("add-%v", idxtxt)
delnm := fmt.Sprintf("del-%v", idxtxt)
addact := gi.Action{}
delact := gi.Action{}
sgf.SetChild(&addact, ridx+1+tv.NVisFields, addnm)
sgf.SetChild(&delact, ridx+1+tv.NVisFields+1, delnm)
addact.SetIcon("plus")
addact.Tooltip = "insert a new element at this index"
addact.Data = i
addact.ActionSig.ConnectOnly(tv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
tvv := recv.Embed(KiT_TableView).(*TableView)
tvv.SliceNewAt(act.Data.(int)+1, true)
})
delact.SetIcon("minus")
delact.Tooltip = "delete this element"
delact.Data = i
delact.ActionSig.ConnectOnly(tv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
act := send.(*gi.Action)
tvv := recv.Embed(KiT_TableView).(*TableView)
tvv.SliceDelete(act.Data.(int), true)
})
}
if tv.StyleFunc != nil {
tv.StyleFunc(tv, mvnp.Interface(), widg, i, fli, vv)
}
}
}
if tv.SelField != "" && tv.SelVal != nil {
tv.SelectedIdx, _ = StructSliceRowByValue(tv.Slice, tv.SelField, tv.SelVal)
}
if tv.IsInactive() && tv.SelectedIdx >= 0 {
tv.SelectRow(tv.SelectedIdx)
}
}
// SetChanged sets the Changed flag and emits the ViewSig signal for the
// TableView, 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 (tv *TableView) SetChanged() {
tv.Changed = true
tv.ViewSig.Emit(tv.This(), 0, nil)
tv.ToolBar().UpdateActions() // nil safe
}
// SliceNewAt inserts a new blank element at given index in the slice -- -1
// means the end -- reconfig means call ConfigSliceGrid to update display
func (tv *TableView) SliceNewAt(idx int, reconfig bool) {
updt := tv.UpdateStart()
defer tv.UpdateEnd(updt)
kit.SliceNewAt(tv.Slice, idx)
if tv.TmpSave != nil {
tv.TmpSave.SaveTmp()
}
tv.SetChanged()
if reconfig {
tv.ConfigSliceGrid(true)
}
tv.ViewSig.Emit(tv.This(), 0, nil)
}
// SliceDelete deletes element at given index from slice -- reconfig means
// call ConfigSliceGrid to update display
func (tv *TableView) SliceDelete(idx int, reconfig bool) {
if idx < 0 {
return
}
updt := tv.UpdateStart()
defer tv.UpdateEnd(updt)
kit.SliceDeleteAt(tv.Slice, idx)
if tv.TmpSave != nil {
tv.TmpSave.SaveTmp()
}
tv.SetChanged()
if reconfig {
tv.ConfigSliceGrid(true)
}
tv.ViewSig.Emit(tv.This(), 0, nil)
}
// SortSliceAction sorts the slice for given field index -- toggles ascending
// vs. descending if already sorting on this dimension
func (tv *TableView) SortSliceAction(fldIdx int) {
oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Push(cursor.Wait)
defer oswin.TheApp.Cursor(tv.Viewport.Win.OSWin).Pop()
sgh := tv.SliceHeader()
sgh.SetFullReRender()
idxOff := 1
if !tv.ShowIndex {
idxOff = 0
}
ascending := true
for fli := 0; fli < tv.NVisFields; fli++ {
hdr := sgh.KnownChild(idxOff + fli).(*gi.Action)
if fli == fldIdx {
if tv.SortIdx == fli {
tv.SortDesc = !tv.SortDesc
ascending = !tv.SortDesc
} else {
tv.SortDesc = false
}
if ascending {
hdr.SetIcon("widget-wedge-up")
} else {
hdr.SetIcon("widget-wedge-down")
}
} else {
hdr.SetIcon("none")
}
}
tv.SortIdx = fldIdx
rawIdx := tv.VisFields[fldIdx].Index
sgf := tv.SliceGrid()
sgf.SetFullReRender()
kit.StructSliceSort(tv.Slice, rawIdx, !tv.SortDesc)
tv.ConfigSliceGridRows()
}
// ConfigToolbar configures the toolbar actions
func (tv *TableView) ConfigToolbar() {
if kit.IfaceIsNil(tv.Slice) || tv.IsInactive() {
return
}
if tv.ToolbarSlice == tv.Slice {
return
}
tb := tv.ToolBar()
if len(*tb.Children()) == 0 {
tb.SetStretchMaxWidth()
tb.AddAction(gi.ActOpts{Label: "Add", Icon: "plus"},
tv.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
tvv := recv.Embed(KiT_TableView).(*TableView)
tvv.SliceNewAt(-1, true)
})
}
sz := len(*tb.Children())
if sz > 1 {
for i := sz - 1; i >= 1; i-- {
tb.DeleteChildAtIndex(i, true)
}
}
if HasToolBarView(tv.Slice) {
ToolBarView(tv.Slice, tv.Viewport, tb)
}
tv.ToolbarSlice = tv.Slice
}
// SortFieldName returns the name of the field being sorted, along with :up or
// :down depending on descending
func (tv *TableView) SortFieldName() string {
if tv.SortIdx >= 0 && tv.SortIdx < tv.NVisFields {
nm := tv.VisFields[tv.SortIdx].Name
if tv.SortDesc {
nm += ":down"
} else {
nm += ":up"
}
return nm
}
return ""
}
// SetSortField sets sorting to happen on given field and direction -- see
// SortFieldName for details
func (tv *TableView) SetSortFieldName(nm string) {
if nm == "" {
return
}
spnm := strings.Split(nm, ":")
for fli := 0; fli < tv.NVisFields; fli++ {
fld := tv.VisFields[fli]
if fld.Name == spnm[0] {
tv.SortIdx = fli
}
}
if len(spnm) == 2 {
if spnm[1] == "down" {
tv.SortDesc = true
} else {
tv.SortDesc = false
}
}
}
func (tv *TableView) Style2D() {
if tv.Viewport != nil && tv.Viewport.IsDoingFullRender() {
tv.UpdateFromSlice()
}
tv.Frame.Style2D()
sg := tv.SliceGrid()
sg.StartFocus() // need to call this when window is actually active
}
func (tv *TableView) Layout2D(parBBox image.Rectangle, iter int) bool {
redo := tv.Frame.Layout2D(parBBox, iter)
sg, _ := tv.SliceFrame()
if sg == nil {
return redo
}
idxOff := 1
if !tv.ShowIndex {
idxOff = 0
}
nfld := tv.NVisFields + idxOff
sgh := tv.SliceHeader()
sgf := tv.SliceGrid()
if len(sgf.Kids) >= nfld {
sumwd := float32(0)
for fli := 0; fli < nfld; fli++ {
lbl := sgh.KnownChild(fli).(gi.Node2D).AsWidget()
wd := sgf.GridData[gi.Col][fli].AllocSize
lbl.SetMinPrefWidth(units.NewValue(wd-sgf.Spacing.Dots, units.Dot))
sumwd += wd
}
if !tv.IsInactive() {
for fli := nfld; fli < nfld+2; fli++ {
lbl := sgh.KnownChild(fli).(gi.Node2D).AsWidget()
wd := sgf.GridData[gi.Col][fli].AllocSize
lbl.SetMinPrefWidth(units.NewValue(wd-sgf.Spacing.Dots, units.Dot))
sumwd += wd
}
}
sgh.SetMinPrefWidth(units.NewValue(sumwd, units.Dot))
sgh.Layout2D(parBBox, iter)
}
return redo
}
func (tv *TableView) Render2D() {
tv.ToolBar().UpdateActions()
if win := tv.ParentWindow(); win != nil {
if !win.IsResizing() {
win.MainMenuUpdateActives()
}
}
if tv.FullReRenderIfNeeded() {
return
}
if tv.PushBounds() {
if tv.Sty.Font.Height > 0 {
tv.VisRows = (tv.VpBBox.Max.Y - tv.VpBBox.Min.Y) / int(1.8*tv.Sty.Font.Height)
} else {
tv.VisRows = 10
}
tv.FrameStdRender()
tv.This().(gi.Node2D).ConnectEvents2D()
tv.RenderScrolls()
tv.Render2DChildren()
tv.PopBounds()
if tv.SelectedIdx > -1 {
tv.ScrollToRow(tv.SelectedIdx)
}
} else {
tv.DisconnectAllEvents(gi.AllPris)
}
}
func (tv *TableView) ConnectEvents2D() {
tv.TableViewEvents()
}
func (tv *TableView) HasFocus2D() bool {
if tv.IsInactive() {
return tv.InactKeyNav
}
return tv.ContainsFocus() // anyone within us gives us focus..
}
//////////////////////////////////////////////////////////////////////////////
// Row access methods
// RowStruct returns struct interface at given row
func (tv *TableView) RowStruct(row int) interface{} {
mv := reflect.ValueOf(tv.Slice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
if row < 0 || row >= sz {
// fmt.Printf("giv.TableView: row index out of range: %v\n", row)
return nil
}
val := kit.OnePtrValue(mvnp.Index(row)) // deal with pointer lists
stru := val.Interface()
return stru
}
// RowFirstWidget returns the first widget for given row (could be index or
// not) -- false if out of range
func (tv *TableView) RowFirstWidget(row int) (*gi.WidgetBase, bool) {
if tv.RowStruct(row) == nil { // range check
return nil, false
}
nWidgPerRow, _ := tv.RowWidgetNs()
sg, _ := tv.SliceFrame()
if sg == nil {
return nil, false
}
sgf := tv.SliceGrid()
widg := sgf.Kids[row*nWidgPerRow].(gi.Node2D).AsWidget()
return widg, true
}
// RowFirstVisWidget returns the first visible widget for given row (could be
// index or not) -- false if out of range
func (tv *TableView) RowFirstVisWidget(row int) (*gi.WidgetBase, bool) {
if tv.RowStruct(row) == nil { // range check
return nil, false
}
nWidgPerRow, idxOff := tv.RowWidgetNs()
sg, _ := tv.SliceFrame()
if sg == nil {
return nil, false
}
sgf := tv.SliceGrid()
widg := sgf.Kids[row*nWidgPerRow].(gi.Node2D).AsWidget()
if widg.VpBBox != image.ZR {
return widg, true
}
ridx := nWidgPerRow * row
for fli := 0; fli < tv.NVisFields; fli++ {
widg := sgf.KnownChild(ridx + idxOff + fli).(gi.Node2D).AsWidget()
if widg.VpBBox != image.ZR {
return widg, true
}
}
return nil, false
}
// 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 (tv *TableView) RowGrabFocus(row int) *gi.WidgetBase {
if tv.RowStruct(row) == nil || tv.inFocusGrab { // range check
return nil
}
// fmt.Printf("grab row focus: %v\n", row)
nWidgPerRow, idxOff := tv.RowWidgetNs()
sg, _ := tv.SliceFrame()
if sg == nil {
return nil
}
ridx := nWidgPerRow * row
sgf := tv.SliceGrid()
// first check if we already have focus
for fli := 0; fli < tv.NVisFields; fli++ {
widg := sgf.KnownChild(ridx + idxOff + fli).(gi.Node2D).AsWidget()
if widg.HasFocus() {
return widg
}
}
tv.inFocusGrab = true
defer func() { tv.inFocusGrab = false }()
for fli := 0; fli < tv.NVisFields; fli++ {
widg := sgf.KnownChild(ridx + idxOff + fli).(gi.Node2D).AsWidget()
if widg.CanFocus() {
widg.GrabFocus()
return widg
}
}
return nil
}
// RowPos returns center of window position of index label for row (ContextMenuPos)
func (tv *TableView) RowPos(row int) image.Point {
var pos image.Point
widg, ok := tv.RowFirstVisWidget(row)
if ok {
pos = widg.ContextMenuPos()
}
return pos
}
// RowFromPos returns the row that contains given vertical position, false if not found
func (tv *TableView) RowFromPos(posY int) (int, bool) {
// todo: could optimize search to approx loc, and search up / down from there
for rw := 0; rw < tv.BuiltSize; rw++ {
widg, ok := tv.RowFirstWidget(rw)
if ok {
if widg.ObjBBox.Min.Y < posY && posY < widg.ObjBBox.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 (tv *TableView) ScrollToRow(row int) bool {
row = ints.MinInt(row, tv.BuiltSize-1)
sgf := tv.SliceGrid()
if widg, ok := tv.RowFirstWidget(row); ok {
return sgf.ScrollToItem(widg)
}
return false
}
// SelectFieldVal sets SelField and SelVal and attempts to find corresponding
// row, setting SelectedIdx and selecting row if found -- returns true if
// found, false otherwise
func (tv *TableView) SelectFieldVal(fld, val string) bool {
tv.SelField = fld
tv.SelVal = val
if tv.SelField != "" && tv.SelVal != nil {
idx, _ := StructSliceRowByValue(tv.Slice, tv.SelField, tv.SelVal)
if idx >= 0 {
tv.ScrollToRow(idx)
tv.UpdateSelect(idx, true)
return true
}
}
return false
}
// StructSliceRowByValue searches for first row that contains given value in field of
// given name.
func StructSliceRowByValue(struSlice interface{}, fldName string, fldVal interface{}) (int, error) {
mv := reflect.ValueOf(struSlice)
mvnp := kit.NonPtrValue(mv)
sz := mvnp.Len()
struTyp := kit.NonPtrType(reflect.TypeOf(struSlice).Elem().Elem())
fld, ok := struTyp.FieldByName(fldName)
if !ok {
err := fmt.Errorf("gi.StructSliceRowByValue: field name: %v not found\n", fldName)
log.Println(err)
return -1, err
}
fldIdx := fld.Index[0]
for row := 0; row < sz; row++ {
rval := kit.OnePtrValue(mvnp.Index(row))
fval := rval.Elem().Field(fldIdx)
if fval.Interface() == fldVal {
return row, nil
}
}
return -1, nil
}
/////////////////////////////////////////////////////////////////////////////
// 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 (tv *TableView) MoveDown(selMode mouse.SelectModes) int {
if selMode == mouse.NoSelectMode {
if tv.SelectMode {
selMode = mouse.ExtendContinuous
}
}
if tv.SelectedIdx >= tv.BuiltSize-1 {
tv.SelectedIdx = tv.BuiltSize - 1
return -1
}
tv.SelectedIdx++
tv.SelectRowAction(tv.SelectedIdx, selMode)
return tv.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 (tv *TableView) MoveDownAction(selMode mouse.SelectModes) int {
nrow := tv.MoveDown(selMode)
if nrow >= 0 {
tv.ScrollToRow(nrow)
tv.WidgetSig.Emit(tv.This(), int64(gi.WidgetSelected), nrow)
}
return nrow
}