-
Notifications
You must be signed in to change notification settings - Fork 0
/
treeview.go
2251 lines (2089 loc) · 64.7 KB
/
treeview.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 (
"bytes"
"fmt"
"image"
"image/color"
"log"
"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/bitflag"
"github.com/goki/ki/ints"
"github.com/goki/ki/ki"
"github.com/goki/ki/kit"
"github.com/goki/mat32"
"github.com/goki/pi/filecat"
)
////////////////////////////////////////////////////////////////////////////////////////
// TreeView -- a widget that graphically represents / manipulates a Ki Tree
// TreeView provides a graphical representation of source tree structure
// (which can be any type of Ki nodes), providing full manipulation abilities
// of that source tree (move, cut, add, etc) through drag-n-drop and
// cut/copy/paste and menu actions.
//
// There are special style Props interpreted by these nodes:
// * no-templates -- if present (assumed to be true) then style templates are
// not used to optimize rendering speed. Set this for nodes that have
// styling applied differentially to individual nodes (e.g., FileNode).
type TreeView struct {
gi.PartsWidgetBase
SrcNode ki.Ki `copy:"-" json:"-" xml:"-" desc:"Ki Node that this widget is viewing in the tree -- the source"`
ShowViewCtxtMenu bool `desc:"if the object we're viewing has its own CtxtMenu property defined, should we also still show the view's own context menu?"`
ViewIdx int `desc:"linear index of this node within the entire tree -- updated on full rebuilds and may sometimes be off, but close enough for expected uses"`
Indent units.Value `xml:"indent" desc:"styled amount to indent children relative to this node"`
OpenDepth int `xml:"open-depth" desc:"styled depth for nodes be initialized as open -- nodes beyond this depth will be initialized as closed. initial default is 4."`
TreeViewSig ki.Signal `json:"-" xml:"-" desc:"signal for TreeView -- all are emitted from the root tree view widget, with data = affected node -- see TreeViewSignals for the types"`
StateStyles [TreeViewStatesN]gi.Style `json:"-" xml:"-" desc:"styles for different states of the widget -- everything inherits from the base Style which is styled first according to the user-set styles, and then subsequent style settings can override that"`
WidgetSize mat32.Vec2 `desc:"just the size of our widget -- our alloc includes all of our children, but we only draw us"`
Icon gi.IconName `json:"-" xml:"icon" view:"show-name" desc:"optional icon, displayed to the the left of the text label"`
RootView *TreeView `json:"-" xml:"-" desc:"cached root of the view"`
}
var KiT_TreeView = kit.Types.AddType(&TreeView{}, nil)
// AddNewTreeView adds a new treeview to given parent node, with given name.
func AddNewTreeView(parent ki.Ki, name string) *TreeView {
tv := parent.AddNewChild(KiT_TreeView, name).(*TreeView)
tv.OpenDepth = 4
return tv
}
func (tv *TreeView) Disconnect() {
tv.PartsWidgetBase.Disconnect()
tv.TreeViewSig.DisconnectAll()
}
func init() {
kit.Types.SetProps(KiT_TreeView, TreeViewProps)
}
//////////////////////////////////////////////////////////////////////////////
// End-User API
// SetRootNode sets the root view to the root of the source node that we are
// viewing, and builds-out the view of its tree
func (tv *TreeView) SetRootNode(sk ki.Ki) {
updt := false
if tv.SrcNode != sk {
updt = tv.UpdateStart()
tv.SrcNode = sk
sk.NodeSignal().Connect(tv.This(), SrcNodeSignalFunc) // we recv signals from source
}
tv.RootView = tv
tvIdx := 0
tv.SyncToSrc(&tvIdx, true, 0)
tv.UpdateEnd(updt)
}
// SetSrcNode sets the source node that we are viewing,
// and builds-out the view of its tree. It is called routinely
// via SyncToSrc during tree updating.
func (tv *TreeView) SetSrcNode(sk ki.Ki, tvIdx *int, init bool, depth int) {
updt := false
if tv.SrcNode != sk {
updt = tv.UpdateStart()
tv.SrcNode = sk
sk.NodeSignal().Connect(tv.This(), SrcNodeSignalFunc) // we recv signals from source
}
tv.SyncToSrc(tvIdx, init, depth)
tv.UpdateEnd(updt)
}
// SyncToSrc updates the view tree to match the source tree, using
// ConfigChildren to maximally preserve existing tree elements.
// init means we are doing initial build, and depth tracks depth
// (only during init).
func (tv *TreeView) SyncToSrc(tvIdx *int, init bool, depth int) {
// pr := prof.Start("TreeView.SyncToSrc")
// defer pr.End()
sk := tv.SrcNode
nm := "tv_" + sk.UniqueName()
tv.SetNameRaw(nm) // guaranteed to be unique
tv.SetUniqueName(nm)
tv.ViewIdx = *tvIdx
(*tvIdx)++
tvPar := tv.TreeViewParent()
if tvPar != nil {
tv.RootView = tvPar.RootView
if init && depth >= tv.RootView.OpenDepth {
tv.SetClosed()
}
}
vcprop := "view-closed"
skids := *sk.Children()
tnl := make(kit.TypeAndNameList, 0, len(skids))
typ := tv.This().Type() // always make our type
flds := make([]ki.Ki, 0)
fldClosed := make([]bool, 0)
sk.FuncFields(0, nil, func(k ki.Ki, level int, d interface{}) bool {
flds = append(flds, k)
tnl.Add(typ, "tv_"+k.Name())
ft := sk.FieldTag(k.Name(), vcprop)
cls := false
if vc, ok := kit.ToBool(ft); ok && vc {
cls = true
} else {
if vcp, ok := k.PropInherit(vcprop, ki.NoInherit, ki.TypeProps); ok {
if vc, ok := kit.ToBool(vcp); vc && ok {
cls = true
}
}
}
fldClosed = append(fldClosed, cls)
return true
})
for _, skid := range skids {
tnl.Add(typ, "tv_"+skid.UniqueName())
}
mods, updt := tv.ConfigChildren(tnl, ki.NonUniqueNames) // false = don't use unique names -- needs to!
if mods {
tv.SetFullReRender()
// fmt.Printf("got mod on %v\n", tv.PathUnique())
}
idx := 0
for i, fld := range flds {
vk := tv.Kids[idx].Embed(KiT_TreeView).(*TreeView)
vk.SetSrcNode(fld, tvIdx, init, depth+1)
if mods {
vk.SetClosedState(fldClosed[i])
}
idx++
}
for _, skid := range *sk.Children() {
vk := tv.Kids[idx].Embed(KiT_TreeView).(*TreeView)
vk.SetSrcNode(skid, tvIdx, init, depth+1)
if mods {
if vcp, ok := skid.PropInherit(vcprop, ki.NoInherit, ki.TypeProps); ok {
if vc, ok := kit.ToBool(vcp); vc && ok {
vk.SetClosed()
}
}
}
idx++
}
if !sk.HasChildren() {
tv.SetClosed()
}
tv.UpdateEnd(updt)
}
// SrcNodeSignalFunc is the function for receiving node signals from our SrcNode
func SrcNodeSignalFunc(tvki, send ki.Ki, sig int64, data interface{}) {
tv := tvki.Embed(KiT_TreeView).(*TreeView)
if data != nil {
dflags := data.(int64)
if gi.Update2DTrace {
fmt.Printf("treeview: %v got signal: %v from node: %v data: %v flags %v\n", tv.PathUnique(), ki.NodeSignals(sig), send.PathUnique(), kit.BitFlagsToString(dflags, ki.FlagsN), kit.BitFlagsToString(send.Flags(), ki.FlagsN))
}
if tv.This() == tv.RootView.This() {
// fmt.Printf("root full rerender\n")
tv.SetFullReRender() // re-render for any updates on root node
}
if bitflag.HasAnyMask(dflags, int64(ki.StruUpdateFlagsMask)) {
tvIdx := tv.ViewIdx
// fmt.Printf("full sync, idx: %v %v", tvIdx, tv.PathUnique())
tv.SyncToSrc(&tvIdx, false, 0)
} else {
tv.UpdateSig()
}
}
}
// IsClosed returns whether this node itself closed?
func (tv *TreeView) IsClosed() bool {
return tv.HasFlag(int(TreeViewFlagClosed))
}
// SetClosed sets the closed flag for this node -- call Close() method to
// close a node and update view
func (tv *TreeView) SetClosed() {
tv.SetFlag(int(TreeViewFlagClosed))
}
// SetOpen clears the closed flag for this node -- call Open() method to open
// a node and update view
func (tv *TreeView) SetOpen() {
tv.ClearFlag(int(TreeViewFlagClosed))
}
// SetClosedState sets the closed state based on arg
func (tv *TreeView) SetClosedState(closed bool) {
tv.SetFlagState(closed, int(TreeViewFlagClosed))
}
// IsChanged returns whether this node has the changed flag set? Only updated
// on the root note by GUI actions.
func (tv *TreeView) IsChanged() bool {
return tv.HasFlag(int(TreeViewFlagChanged))
}
// SetChanged is called whenever a gui action updates the tree -- sets Changed
// flag on root node and emits signal
func (tv *TreeView) SetChanged() {
if tv.RootView == nil {
return
}
tv.RootView.SetFlag(int(TreeViewFlagChanged))
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewChanged), tv.This())
}
// HasClosedParent returns whether this node have a closed parent? if so, don't render!
func (tv *TreeView) HasClosedParent() bool {
pcol := false
tv.FuncUpParent(0, tv.This(), func(k ki.Ki, level int, d interface{}) bool {
_, pg := gi.KiToNode2D(k)
if pg == nil {
return false
}
if pg.TypeEmbeds(KiT_TreeView) {
// nw := pg.Embed(KiT_TreeView).(*TreeView)
if pg.HasFlag(int(TreeViewFlagClosed)) {
pcol = true
return false
}
}
return true
})
return pcol
}
// Label returns the display label for this node, satisfying the Labeler interface
func (tv *TreeView) Label() string {
if lbl, has := gi.ToLabeler(tv.SrcNode); has {
return lbl
}
return tv.SrcNode.Name()
}
// UpdateInactive updates the Inactive state based on SrcNode -- returns true if
// inactive. The inactivity of individual nodes only affects display properties
// typically, and not overall functional behavior, which is controlled by
// inactivity of the root node (i.e, make the root inactive to make entire tree
// read-only and non-modifiable)
func (tv *TreeView) UpdateInactive() bool {
tv.ClearInactive()
if tv.SrcNode == nil {
tv.SetInactive()
} else {
if inact, err := tv.SrcNode.PropTry("inactive"); err == nil {
if bo, ok := kit.ToBool(inact); bo && ok {
tv.SetInactive()
}
}
}
return tv.IsInactive()
}
// RootIsInactive returns the inactive status of the root node, which is what
// controls the functional inactivity of the tree -- if individual nodes
// are inactive that only affects display typically.
func (tv *TreeView) RootIsInactive() bool {
if tv.RootView == nil {
return true
}
return tv.RootView.IsInactive()
}
//////////////////////////////////////////////////////////////////////////////
// Signals etc
// TreeViewSignals are signals that treeview can send -- these are all sent
// from the root tree view widget node, with data being the relevant node
// widget
type TreeViewSignals int64
const (
// node was selected
TreeViewSelected TreeViewSignals = iota
// TreeView unselected
TreeViewUnselected
// TreeView all items were selected
TreeViewAllSelected
// TreeView all items were unselected
TreeViewAllUnselected
// closed TreeView was opened
TreeViewOpened
// open TreeView was closed -- children not visible
TreeViewClosed
// TreeViewChanged means that some kind of edit operation has taken place
// by the user via the gui -- we don't track the details, just that
// changes have happened
TreeViewChanged
TreeViewSignalsN
)
//go:generate stringer -type=TreeViewSignals
// TreeViewFlags extend NodeBase NodeFlags to hold TreeView state
type TreeViewFlags int
//go:generate stringer -type=TreeViewFlags
var KiT_TreeViewFlags = kit.Enums.AddEnumExt(gi.KiT_NodeFlags, TreeViewFlagsN, kit.BitFlag, nil)
const (
// TreeViewFlagClosed means node is toggled closed (children not visible)
TreeViewFlagClosed TreeViewFlags = TreeViewFlags(gi.NodeFlagsN) + iota
// TreeViewFlagChanged is updated on the root node whenever a gui edit is
// made through the tree view on the tree -- this does not track any other
// changes that might have occurred in the tree itself.
// Also emits a TreeViewChanged signal on the root node.
TreeViewFlagChanged
// TreeViewFlagNoTemplate -- this node is not using a style template -- should
// be restyled on any full re-render change
TreeViewFlagNoTemplate
TreeViewFlagsN
)
// TreeViewStates are mutually-exclusive tree view states -- determines appearance
type TreeViewStates int32
const (
// TreeViewActive is normal state -- there but not being interacted with
TreeViewActive TreeViewStates = iota
// TreeViewSel is selected
TreeViewSel
// TreeViewFocus is in focus -- will respond to keyboard input
TreeViewFocus
// TreeViewInactive is inactive -- if SrcNode is nil, or source has "inactive" property
// set, or treeview node has inactive property set directly
TreeViewInactive
TreeViewStatesN
)
//go:generate stringer -type=TreeViewStates
// TreeViewSelectors are Style selector names for the different states:
var TreeViewSelectors = []string{":active", ":selected", ":focus", ":inactive"}
// These are special properties established on the RootView for maintaining
// overall tree state
const (
// TreeViewSelProp is a slice of tree views that are currently selected
// -- much more efficient to update the list rather than regenerate it,
// especially for a large tree
TreeViewSelProp = "__SelectedList"
// TreeViewSelModeProp is a bool that, if true, automatically selects nodes
// when nodes are moved to via keyboard actions
TreeViewSelModeProp = "__SelectMode"
)
//////////////////////////////////////////////////////////////////////////////
// Selection
// SelectMode returns true if keyboard movements should automatically select nodes
func (tv *TreeView) SelectMode() bool {
smp, err := tv.RootView.PropTry(TreeViewSelModeProp)
if err != nil {
tv.SetSelectMode(false)
return false
} else {
return smp.(bool)
}
}
// SetSelectMode updates the select mode
func (tv *TreeView) SetSelectMode(selMode bool) {
tv.RootView.SetProp(TreeViewSelModeProp, selMode)
}
// SelectModeToggle toggles the SelectMode
func (tv *TreeView) SelectModeToggle() {
if tv.SelectMode() {
tv.SetSelectMode(false)
} else {
tv.SetSelectMode(true)
}
}
// SelectedViews returns a slice of the currently-selected TreeViews within
// the entire tree, using a list maintained by the root node
func (tv *TreeView) SelectedViews() []*TreeView {
if tv.RootView == nil {
return nil
}
var sl []*TreeView
slp, err := tv.RootView.PropTry(TreeViewSelProp)
if err != nil {
sl = make([]*TreeView, 0)
tv.SetSelectedViews(sl)
} else {
sl = slp.([]*TreeView)
}
return sl
}
// SetSelectedViews updates the selected views to given list
func (tv *TreeView) SetSelectedViews(sl []*TreeView) {
if tv.RootView != nil {
tv.RootView.SetProp(TreeViewSelProp, sl)
}
}
// SelectedSrcNodes returns a slice of the currently-selected source nodes
// in the entire tree view
func (tv *TreeView) SelectedSrcNodes() ki.Slice {
sn := make(ki.Slice, 0)
sl := tv.SelectedViews()
for _, v := range sl {
sn = append(sn, v.SrcNode)
}
return sn
}
// Select selects this node (if not already selected) -- must use this method
// to update global selection list
func (tv *TreeView) Select() {
if !tv.IsSelected() {
tv.SetSelected()
sl := tv.SelectedViews()
sl = append(sl, tv)
tv.SetSelectedViews(sl)
tv.UpdateSig()
}
}
// Unselect unselects this node (if selected) -- must use this method
// to update global selection list
func (tv *TreeView) Unselect() {
if tv.IsSelected() {
tv.ClearSelected()
sl := tv.SelectedViews()
sz := len(sl)
for i := 0; i < sz; i++ {
if sl[i] == tv {
sl = append(sl[:i], sl[i+1:]...)
break
}
}
tv.SetSelectedViews(sl)
tv.UpdateSig()
}
}
// UnselectAll unselects all selected items in the view
func (tv *TreeView) UnselectAll() {
if tv.Viewport == nil {
return
}
wupdt := tv.TopUpdateStart()
sl := tv.SelectedViews()
tv.SetSelectedViews(nil) // clear in advance
for _, v := range sl {
v.ClearSelected()
v.UpdateSig()
}
tv.TopUpdateEnd(wupdt)
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewAllUnselected), tv.This())
}
// SelectAll all items in view
func (tv *TreeView) SelectAll() {
if tv.Viewport == nil {
return
}
wupdt := tv.TopUpdateStart()
tv.UnselectAll()
nn := tv.RootView
nn.Select()
for nn != nil {
nn = nn.MoveDown(mouse.SelectQuiet)
}
tv.TopUpdateEnd(wupdt)
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewAllSelected), tv.This())
}
// SelectUpdate updates selection to include this node, using selectmode
// from mouse event (ExtendContinuous, ExtendOne). Returns true if this node selected
func (tv *TreeView) SelectUpdate(mode mouse.SelectModes) bool {
if mode == mouse.NoSelect {
return false
}
wupdt := tv.TopUpdateStart()
sel := false
switch mode {
case mouse.SelectOne:
if tv.IsSelected() {
sl := tv.SelectedViews()
if len(sl) > 1 {
tv.UnselectAll()
tv.Select()
tv.GrabFocus()
sel = true
}
} else {
tv.UnselectAll()
tv.Select()
tv.GrabFocus()
sel = true
}
case mouse.ExtendContinuous:
sl := tv.SelectedViews()
if len(sl) == 0 {
tv.Select()
tv.GrabFocus()
sel = true
} else {
minIdx := -1
maxIdx := 0
for _, v := range sl {
if minIdx < 0 {
minIdx = v.ViewIdx
} else {
minIdx = ints.MinInt(minIdx, v.ViewIdx)
}
maxIdx = ints.MaxInt(maxIdx, v.ViewIdx)
}
cidx := tv.ViewIdx
nn := tv
tv.Select()
if tv.ViewIdx < minIdx {
for cidx < minIdx {
nn = nn.MoveDown(mouse.SelectQuiet) // just select
cidx = nn.ViewIdx
}
} else if tv.ViewIdx > maxIdx {
for cidx > maxIdx {
nn = nn.MoveUp(mouse.SelectQuiet) // just select
cidx = nn.ViewIdx
}
}
}
case mouse.ExtendOne:
if tv.IsSelected() {
tv.UnselectAction()
} else {
tv.Select()
tv.GrabFocus()
sel = true
}
case mouse.SelectQuiet:
tv.Select()
// not sel -- no signal..
case mouse.UnselectQuiet:
tv.Unselect()
// not sel -- no signal..
}
tv.TopUpdateEnd(wupdt)
return sel
}
// SelectAction updates selection to include this node, using selectmode
// from mouse event (ExtendContinuous, ExtendOne), and emits selection signal
// returns true if signal emitted
func (tv *TreeView) SelectAction(mode mouse.SelectModes) bool {
sel := tv.SelectUpdate(mode)
if sel {
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), tv.This())
}
return sel
}
// UnselectAction unselects this node (if selected) -- and emits a signal
func (tv *TreeView) UnselectAction() {
if tv.IsSelected() {
tv.Unselect()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewUnselected), tv.This())
}
}
//////////////////////////////////////////////////////////////////////////////
// Moving
// MoveDown moves the selection down to next element in the tree, using given
// select mode (from keyboard modifiers) -- returns newly selected node
func (tv *TreeView) MoveDown(selMode mouse.SelectModes) *TreeView {
if tv.Par == nil {
return nil
}
if tv.IsClosed() || !tv.HasChildren() { // next sibling
return tv.MoveDownSibling(selMode)
} else {
if tv.HasChildren() {
nn := tv.Child(0).Embed(KiT_TreeView).(*TreeView)
if nn != nil {
nn.SelectUpdate(selMode)
return nn
}
}
}
return nil
}
// MoveDownAction moves the selection down to next element in the tree, using given
// select mode (from keyboard modifiers) -- and emits select event for newly selected item
func (tv *TreeView) MoveDownAction(selMode mouse.SelectModes) *TreeView {
nn := tv.MoveDown(selMode)
if nn != nil && nn != tv {
nn.GrabFocus()
nn.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), nn.This())
}
return nn
}
// MoveDownSibling moves down only to siblings, not down into children, using
// given select mode (from keyboard modifiers)
func (tv *TreeView) MoveDownSibling(selMode mouse.SelectModes) *TreeView {
if tv.Par == nil {
return nil
}
if tv == tv.RootView {
return nil
}
myidx, ok := tv.IndexInParent()
if ok && myidx < len(*tv.Par.Children())-1 {
nn := tv.Par.Child(myidx + 1).Embed(KiT_TreeView).(*TreeView)
if nn != nil {
nn.SelectUpdate(selMode)
return nn
}
} else {
return tv.Par.Embed(KiT_TreeView).(*TreeView).MoveDownSibling(selMode) // try up
}
return nil
}
// MoveUp moves selection up to previous element in the tree, using given
// select mode (from keyboard modifiers) -- returns newly selected node
func (tv *TreeView) MoveUp(selMode mouse.SelectModes) *TreeView {
if tv.Par == nil || tv == tv.RootView {
return nil
}
myidx, ok := tv.IndexInParent()
if ok && myidx > 0 {
nn := tv.Par.Child(myidx - 1).Embed(KiT_TreeView).(*TreeView)
if nn != nil {
return nn.MoveToLastChild(selMode)
}
} else {
if tv.Par != nil {
nn := tv.Par.Embed(KiT_TreeView).(*TreeView)
if nn != nil {
nn.SelectUpdate(selMode)
return nn
}
}
}
return nil
}
// MoveUpAction moves the selection up to previous element in the tree, using given
// select mode (from keyboard modifiers) -- and emits select event for newly selected item
func (tv *TreeView) MoveUpAction(selMode mouse.SelectModes) *TreeView {
nn := tv.MoveUp(selMode)
if nn != nil && nn != tv {
nn.GrabFocus()
nn.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), nn.This())
}
return nn
}
// TreeViewPageSteps is the number of steps to take in PageUp / Down events
var TreeViewPageSteps = 10
// MovePageUpAction moves the selection up to previous TreeViewPageSteps elements in the tree,
// using given select mode (from keyboard modifiers) -- and emits select event for newly selected item
func (tv *TreeView) MovePageUpAction(selMode mouse.SelectModes) *TreeView {
wupdt := tv.TopUpdateStart()
mvMode := selMode
if selMode == mouse.SelectOne {
mvMode = mouse.NoSelect
} else if selMode == mouse.ExtendContinuous || selMode == mouse.ExtendOne {
mvMode = mouse.SelectQuiet
}
fnn := tv.MoveUp(mvMode)
if fnn != nil && fnn != tv {
for i := 1; i < TreeViewPageSteps; i++ {
nn := fnn.MoveUp(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == mouse.SelectOne {
fnn.SelectUpdate(selMode)
}
fnn.GrabFocus()
fnn.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), fnn.This())
}
tv.TopUpdateEnd(wupdt)
return fnn
}
// MovePageDownAction moves the selection up to previous TreeViewPageSteps elements in the tree,
// using given select mode (from keyboard modifiers) -- and emits select event for newly selected item
func (tv *TreeView) MovePageDownAction(selMode mouse.SelectModes) *TreeView {
wupdt := tv.TopUpdateStart()
mvMode := selMode
if selMode == mouse.SelectOne {
mvMode = mouse.NoSelect
} else if selMode == mouse.ExtendContinuous || selMode == mouse.ExtendOne {
mvMode = mouse.SelectQuiet
}
fnn := tv.MoveDown(mvMode)
if fnn != nil && fnn != tv {
for i := 1; i < TreeViewPageSteps; i++ {
nn := fnn.MoveDown(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == mouse.SelectOne {
fnn.SelectUpdate(selMode)
}
fnn.GrabFocus()
fnn.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), fnn.This())
}
tv.TopUpdateEnd(wupdt)
return fnn
}
// MoveToLastChild moves to the last child under me, using given select mode
// (from keyboard modifiers)
func (tv *TreeView) MoveToLastChild(selMode mouse.SelectModes) *TreeView {
if tv.Par == nil || tv == tv.RootView {
return nil
}
if !tv.IsClosed() && tv.HasChildren() {
nnk, err := tv.Children().ElemFromEndTry(0)
if err == nil {
nn := nnk.Embed(KiT_TreeView).(*TreeView)
return nn.MoveToLastChild(selMode)
}
} else {
tv.SelectUpdate(selMode)
return tv
}
return nil
}
// MoveHomeAction moves the selection up to top of the tree,
// using given select mode (from keyboard modifiers)
// and emits select event for newly selected item
func (tv *TreeView) MoveHomeAction(selMode mouse.SelectModes) *TreeView {
tv.RootView.SelectUpdate(selMode)
tv.RootView.GrabFocus()
tv.RootView.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), tv.RootView.This())
return tv.RootView
}
// MoveEndAction moves the selection to the very last node in the tree
// using given select mode (from keyboard modifiers) -- and emits select event
// for newly selected item
func (tv *TreeView) MoveEndAction(selMode mouse.SelectModes) *TreeView {
wupdt := tv.TopUpdateStart()
mvMode := selMode
if selMode == mouse.SelectOne {
mvMode = mouse.NoSelect
} else if selMode == mouse.ExtendContinuous || selMode == mouse.ExtendOne {
mvMode = mouse.SelectQuiet
}
fnn := tv.MoveDown(mvMode)
if fnn != nil && fnn != tv {
for {
nn := fnn.MoveDown(mvMode)
if nn == nil || nn == fnn {
break
}
fnn = nn
}
if selMode == mouse.SelectOne {
fnn.SelectUpdate(selMode)
}
fnn.GrabFocus()
fnn.ScrollToMe()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewSelected), fnn.This())
}
tv.TopUpdateEnd(wupdt)
return fnn
}
// Close closes the given node and updates the view accordingly (if it is not already closed)
func (tv *TreeView) Close() {
if !tv.IsClosed() {
updt := tv.UpdateStart()
if tv.HasChildren() {
tv.SetFullReRender()
}
tv.SetClosed()
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewClosed), tv.This())
tv.UpdateEnd(updt)
}
}
// Open opens the given node and updates the view accordingly (if it is not already opened)
func (tv *TreeView) Open() {
if tv.IsClosed() {
updt := tv.UpdateStart()
if tv.HasChildren() {
tv.SetFullReRender()
}
if tv.HasChildren() {
tv.SetClosedState(false)
}
// send signal in any case -- dynamic trees can open a node here!
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewOpened), tv.This())
tv.UpdateEnd(updt)
}
}
// ToggleClose toggles the close / open status: if closed, opens, and vice-versa
func (tv *TreeView) ToggleClose() {
if tv.IsClosed() {
tv.Open()
} else {
tv.Close()
}
}
// OpenAll opens the given node and all of its sub-nodes
func (tv *TreeView) OpenAll() {
wupdt := tv.TopUpdateStart()
updt := tv.UpdateStart()
tv.SetFullReRender()
tv.FuncDownMeFirst(0, tv.This(), func(k ki.Ki, level int, d interface{}) bool {
tvki := k.Embed(KiT_TreeView)
if tvki != nil {
tvki.(*TreeView).SetClosedState(false)
}
return ki.Continue
})
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewOpened), tv.This())
tv.UpdateEnd(updt)
tv.TopUpdateEnd(wupdt)
}
// CloseAll closes the given node and all of its sub-nodes
func (tv *TreeView) CloseAll() {
wupdt := tv.TopUpdateStart()
updt := tv.UpdateStart()
tv.SetFullReRender()
tv.FuncDownMeFirst(0, tv.This(), func(k ki.Ki, level int, d interface{}) bool {
tvki := k.Embed(KiT_TreeView)
if tvki != nil {
tvki.(*TreeView).SetClosedState(true)
}
return ki.Continue
})
tv.RootView.TreeViewSig.Emit(tv.RootView.This(), int64(TreeViewClosed), tv.This())
tv.UpdateEnd(updt)
tv.TopUpdateEnd(wupdt)
}
//////////////////////////////////////////////////////////////////////////////
// Modifying Source Tree
func (tv *TreeView) ContextMenuPos() (pos image.Point) {
pos.X = tv.WinBBox.Min.X + int(tv.Indent.Dots)
pos.Y = (tv.WinBBox.Min.Y + tv.WinBBox.Max.Y) / 2
return
}
func (tv *TreeView) MakeContextMenu(m *gi.Menu) {
// derived types put native menu code here
if tv.CtxtMenuFunc != nil {
tv.CtxtMenuFunc(tv.This().(gi.Node2D), m)
}
// note: root inactivity is relevant factor here..
if CtxtMenuView(tv.SrcNode, tv.RootIsInactive(), tv.Viewport, m) { // our viewed obj's menu
if tv.ShowViewCtxtMenu {
m.AddSeparator("sep-tvmenu")
CtxtMenuView(tv.This(), tv.RootIsInactive(), tv.Viewport, m)
}
} else {
CtxtMenuView(tv.This(), tv.RootIsInactive(), tv.Viewport, m)
}
}
// IsRootOrField returns true if given node is either the root of the
// tree or a field -- various operations can not be performed on these -- if
// string is passed, then a prompt dialog is presented with that as the name
// of the operation being attempted -- otherwise it silently returns (suitable
// for context menu UpdateFunc).
func (tv *TreeView) IsRootOrField(op string) bool {
sk := tv.SrcNode
if sk == nil {
log.Printf("TreeView IsRootOrField nil SrcNode in: %v\n", tv.PathUnique())
return false
}
if sk.IsField() {
if op != "" {
gi.PromptDialog(tv.Viewport, gi.DlgOpts{Title: "TreeView " + op, Prompt: fmt.Sprintf("Cannot %v fields", op)}, gi.AddOk, gi.NoCancel, nil, nil)
}
return true
}
if tv.This() == tv.RootView.This() {
if op != "" {
gi.PromptDialog(tv.Viewport, gi.DlgOpts{Title: "TreeView " + op, Prompt: fmt.Sprintf("Cannot %v the root of the tree", op)}, gi.AddOk, gi.NoCancel, nil, nil)
}
return true
}
return false
}
// SrcInsertAfter inserts a new node in the source tree after this node, at
// the same (sibling) level, prompting for the type of node to insert
func (tv *TreeView) SrcInsertAfter() {
tv.SrcInsertAt(1, "Insert After")
}
// SrcInsertBefore inserts a new node in the source tree before this node, at
// the same (sibling) level, prompting for the type of node to insert
func (tv *TreeView) SrcInsertBefore() {
tv.SrcInsertAt(0, "Insert Before")
}
// SrcInsertAt inserts a new node in the source tree at given relative offset
// from this node, at the same (sibling) level, prompting for the type of node to insert
func (tv *TreeView) SrcInsertAt(rel int, actNm string) {
if tv.IsRootOrField(actNm) {
return
}
sk := tv.SrcNode
if sk == nil {
log.Printf("TreeView %v nil SrcNode in: %v\n", actNm, tv.PathUnique())
return
}
myidx, ok := sk.IndexInParent()
if !ok {
return
}
myidx += rel
gi.NewKiDialog(tv.Viewport, sk.BaseIface(),
gi.DlgOpts{Title: actNm, Prompt: "Number and Type of Items to Insert:"},
tv.Par.This(), func(recv, send ki.Ki, sig int64, data interface{}) {
if sig == int64(gi.DialogAccepted) {
tvv, _ := recv.Embed(KiT_TreeView).(*TreeView)
par := tvv.SrcNode
dlg, _ := send.(*gi.Dialog)
n, typ := gi.NewKiDialogValues(dlg)
updt := par.UpdateStart()
var ski ki.Ki
for i := 0; i < n; i++ {
nm := fmt.Sprintf("New%v%v", typ.Name(), myidx+rel+i)
nki := par.InsertNewChild(typ, myidx+i, nm)
if i == n-1 {