-
Notifications
You must be signed in to change notification settings - Fork 7
/
node.go
1329 lines (1201 loc) · 43 KB
/
node.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 ki
//go:generate goki generate
import (
"errors"
"fmt"
"log/slog"
"strconv"
"log"
"strings"
"goki.dev/enums"
"goki.dev/glop/elide"
"goki.dev/gti"
)
// StringElideMax is the Max width for String() path printout of Ki nodes.
var StringElideMax = 38
// The Node implements the Ki interface and provides the core functionality
// for the GoKi tree -- use the Node as an embedded struct or as a struct
// field -- the embedded version supports full JSON save / load.
//
// The desc: key for fields is used by the GoGi GUI viewer for help / tooltip
// info -- add these to all your derived struct's fields. See relevant docs
// for other such tags controlling a wide range of GUI and other functionality
// -- Ki makes extensive use of such tags.
type Node struct {
// Ki.Name() user-supplied name of this node -- can be empty or non-unique
Nm string `copy:"-" set:"-" label:"Name"`
// bit flags for internal node state -- can extend this using enums package
Flags Flags `tableview:"-" copy:"-" json:"-" xml:"-" set:"-" max-width:"80" height:"3"`
// Ki.Properties() property map for arbitrary extensible properties, including style properties
Props Props `tableview:"-" xml:"-" copy:"-" set:"-" label:"Properties"`
// Ki.Parent() parent of this node -- set automatically when this node is added as a child of parent
Par Ki `tableview:"-" copy:"-" json:"-" xml:"-" view:"-" set:"-" label:"Parent"`
// Ki.Children() list of children of this node -- all are set to have this node as their parent -- can reorder etc but generally use Ki Node methods to Add / Delete to ensure proper usage
Kids Slice `tableview:"-" copy:"-" set:"-" label:"Children"`
// we need a pointer to ourselves as a Ki, which can always be used to extract the true underlying type of object when Node is embedded in other structs -- function receivers do not have this ability so this is necessary. This is set to nil when deleted. Typically use This() convenience accessor which protects against concurrent access.
Ths Ki `copy:"-" json:"-" xml:"-" view:"-" set:"-"`
// the number of children that have ever been added to this node, which is used for unique naming
NumLifetimeKids uint64 `copy:"-" json:"-" xml:"-" view:"-" set:"-"`
// last value of our index -- used as a starting point for finding us in our parent next time -- is not guaranteed to be accurate! use IndexInParent() method
index int `copy:"-" json:"-" xml:"-" view:"-" set:"-"`
// optional depth parameter of this node -- only valid during specific contexts, not generally -- e.g., used in WalkBreadth function
depth int `copy:"-" json:"-" xml:"-" view:"-" set:"-"`
}
// check implementation of [Ki] interface
var _ = Ki(&Node{})
// EnumTypeFlag is a [Props] property name that
// indicates what enum type to use as the type for
// the flags field in GUI views. Its value should be
// of the type [reflect.Type]
const EnumTypeFlag string = "EnumType:Flag"
//////////////////////////////////////////////////////////////////////////
// fmt.Stringer
// String implements the fmt.stringer interface -- returns the Path of the node
func (n *Node) String() string {
return elide.Middle(n.This().Path(), StringElideMax)
}
//////////////////////////////////////////////////////////////////////////
// Basic Ki fields
// This returns the Ki interface that guarantees access to the Ki
// interface in a way that always reveals the underlying type
// (e.g., in reflect calls). Returns nil if node is nil,
// has been destroyed, or is improperly constructed.
func (n *Node) This() Ki {
if n == nil || n.Is(Destroyed) {
return nil
}
return n.Ths
}
// AsNode returns the *ki.Node base type for this node.
func (n *Node) AsKi() *Node {
return n
}
// InitName initializes this node to given actual object as a Ki interface
// and sets its name. The names should be unique among children of a node.
// This is needed for root nodes -- automatically done for other nodes
// when they are added to the Ki tree. If the name is unspecified, it
// defaults to the ID (kebab-case) name of the type.
// Even though this is a method and gets the method receiver, it needs
// an "external" version of itself passed as the first arg, from which
// the proper Ki interface pointer will be obtained. This is the only
// way to get virtual functional calling to work within the Go language.
func (n *Node) InitName(k Ki, name ...string) {
InitNode(k)
if len(name) > 0 {
n.SetName(name[0])
}
}
// BaseType returns the base node type for all elements within this tree.
// Used e.g., for determining what types of children can be created.
func (n *Node) BaseType() *gti.Type {
return NodeType
}
// Name returns the user-defined name of the object (Node.Nm),
// for finding elements, generating paths, IO, etc.
func (n *Node) Name() string {
return n.Nm
}
// SetName sets the name of this node.
// Names should generally be unique across children of each node.
// See Unique* functions to check / fix.
// If node requires non-unique names, add a separate Label field.
// Does NOT wrap in UpdateStart / End.
func (n *Node) SetName(name string) {
n.Nm = name
}
// OnInit is a placeholder implementation of
// [Ki.OnInit] that does nothing.
func (n *Node) OnInit() {}
// OnAdd is a placeholder implementation of
// [Ki.OnAdd] that does nothing.
func (n *Node) OnAdd() {}
// OnChildAdded is a placeholder implementation of
// [Ki.OnChildAdded] that does nothing.
func (n *Node) OnChildAdded(child Ki) {}
// OnDelete is a placeholder implementation of
// [Ki.OnDelete] that does nothing.
func (n *Node) OnDelete() {}
// OnChildDeleting is a placeholder implementation of
// [Ki.OnChildDeleting] that does nothing.
func (n *Node) OnChildDeleting(child Ki) {}
// OnChildrenDeleting is a placeholder implementation of
// [Ki.OnChildrenDeleting] that does nothing.
func (n *Node) OnChildrenDeleting() {}
// OnUpdated is a placeholder implementation of
// [Ki.OnUpdated] that does nothing.
func (n *Node) OnUpdated() {}
//////////////////////////////////////////////////////////////////////////
// Parents
// Parent returns the parent of this Ki (Node.Par) -- Ki has strict
// one-parent, no-cycles structure -- see SetParent.
func (n *Node) Parent() Ki {
return n.Par
}
// IndexInParent returns our index within our parent object -- caches the
// last value and uses that for an optimized search so subsequent calls
// are typically quite fast. Returns false if we don't have a parent.
func (n *Node) IndexInParent() (int, bool) {
if n.Par == nil {
return -1, false
}
idx, ok := n.Par.Children().IndexOf(n.This(), n.index) // very fast if index is close..
if ok {
n.index = idx
}
return idx, ok
}
// ParentLevel finds a given potential parent node recursively up the
// hierarchy, returning level above current node that the parent was
// found, and -1 if not found.
func (n *Node) ParentLevel(par Ki) int {
parLev := -1
level := 0
n.WalkUpParent(func(k Ki) bool {
if k == par {
parLev = level
return Break
}
level++
return Continue
})
return parLev
}
// ParentByName finds first parent recursively up hierarchy that matches
// given name -- returns nil if not found.
func (n *Node) ParentByName(name string) Ki {
if IsRoot(n) {
return nil
}
if n.Par.Name() == name {
return n.Par
}
return n.Par.ParentByName(name)
}
// ParentByNameTry finds first parent recursively up hierarchy that matches
// given name -- returns error if not found.
func (n *Node) ParentByNameTry(name string) (Ki, error) {
par := n.ParentByName(name)
if par != nil {
return par, nil
}
return nil, fmt.Errorf("ki %v: Parent name: %v not found", n.Nm, name)
}
// ParentByType finds parent recursively up hierarchy, by type, and
// returns nil if not found. If embeds is true, then it looks for any
// type that embeds the given type at any level of anonymous embedding.
func (n *Node) ParentByType(t *gti.Type, embeds bool) Ki {
if IsRoot(n) {
return nil
}
if embeds {
if n.Par.KiType().HasEmbed(t) {
return n.Par
}
} else {
if n.Par.KiType() == t {
return n.Par
}
}
return n.Par.ParentByType(t, embeds)
}
// ParentByTypeTry finds parent recursively up hierarchy, by type, and
// returns error if not found. If embeds is true, then it looks for any
// type that embeds the given type at any level of anonymous embedding.
func (n *Node) ParentByTypeTry(t *gti.Type, embeds bool) (Ki, error) {
par := n.ParentByType(t, embeds)
if par != nil {
return par, nil
}
return nil, fmt.Errorf("ki %v: Parent of type: %v not found", n.Nm, t)
}
//////////////////////////////////////////////////////////////////////////
// Children
// HasChildren tests whether this node has children (i.e., non-terminal).
func (n *Node) HasChildren() bool {
return len(n.Kids) > 0
}
// NumChildren returns the number of children of this node.
func (n *Node) NumChildren() int {
return len(n.Kids)
}
func (n *Node) NumLifetimeChildren() uint64 {
return n.NumLifetimeKids
}
// Children returns a pointer to the slice of children (Node.Kids) -- use
// methods on ki.Slice for further ways to access (ByName, ByType, etc).
// Slice can be modified directly (e.g., sort, reorder) but Add* / Delete*
// methods on parent node should be used to ensure proper tracking.
func (n *Node) Children() *Slice {
return &n.Kids
}
// IsValidIndex returns error if given index is not valid for accessing children
// nil otherwise.
func (n *Node) IsValidIndex(idx int) error {
sz := len(n.Kids)
if idx >= 0 && idx < sz {
return nil
}
return fmt.Errorf("ki %v: invalid index: %v -- len = %v", n.Nm, idx, sz)
}
// Child returns the child at given index -- will panic if index is invalid.
// See methods on ki.Slice for more ways to access.
func (n *Node) Child(idx int) Ki {
return n.Kids[idx]
}
// ChildTry returns the child at given index. Try version returns error if index is invalid.
// See methods on ki.Slice for more ways to access.
func (n *Node) ChildTry(idx int) (Ki, error) {
if err := n.IsValidIndex(idx); err != nil {
return nil, err
}
return n.Kids[idx], nil
}
// ChildByName returns the first element that has given name, and nil
// if no such element is found. startIdx arg allows for optimized
// bidirectional find if you have an idea where it might be, which
// can be a key speedup for large lists. If no value is specified for
// startIdx, it starts in the middle, which is a good default.
func (n *Node) ChildByName(name string, startIdx ...int) Ki {
return n.Kids.ElemByName(name, startIdx...)
}
// ChildByNameTry returns the first element that has given name, and an error
// if no such element is found. startIdx arg allows for optimized
// bidirectional find if you have an idea where it might be, which
// can be a key speedup for large lists. If no value is specified for
// startIdx, it starts in the middle, which is a good default.
func (n *Node) ChildByNameTry(name string, startIdx ...int) (Ki, error) {
idx, ok := n.Kids.IndexByName(name, startIdx...)
if !ok {
return nil, fmt.Errorf("ki %v: child named: %v not found", n.Nm, name)
}
return n.Kids[idx], nil
}
// ChildByType returns the first element that has the given type, and nil
// if not found. If embeds is true, then it also looks for any type that
// embeds the given type at any level of anonymous embedding.
// startIdx arg allows for optimized bidirectional find if you have an
// idea where it might be, which can be a key speedup for large lists. If
// no value is specified for startIdx, it starts in the middle, which is a
// good default.
func (n *Node) ChildByType(t *gti.Type, embeds bool, startIdx ...int) Ki {
return n.Kids.ElemByType(t, embeds, startIdx...)
}
// ChildByTypeTry returns the first element that has the given type, and an
// error if not found. If embeds is true, then it also looks for any type that
// embeds the given type at any level of anonymous embedding.
// startIdx arg allows for optimized bidirectional find if you have an
// idea where it might be, which can be a key speedup for large lists. If
// no value is specified for startIdx, it starts in the middle, which is a
// good default.
func (n *Node) ChildByTypeTry(t *gti.Type, embeds bool, startIdx ...int) (Ki, error) {
idx, ok := n.Kids.IndexByType(t, embeds, startIdx...)
if !ok {
return nil, fmt.Errorf("ki %v: child of type: %s not found", n.Nm, t.Name)
}
return n.Kids[idx], nil
}
//////////////////////////////////////////////////////////////////////////
// Paths
// TODO: is this the best way to escape paths?
// EscapePathName returns a name that replaces any path delimiter symbols
// . or / with \, and \\ escaped versions.
func EscapePathName(name string) string {
return strings.Replace(strings.Replace(name, ".", `\,`, -1), "/", `\\`, -1)
}
// UnescapePathName returns a name that replaces any escaped path delimiter symbols
// \, or \\ with . and / unescaped versions.
func UnescapePathName(name string) string {
return strings.Replace(strings.Replace(name, `\,`, ".", -1), `\\`, "/", -1)
}
// Path returns path to this node from the tree root, using node Names
// separated by / and fields by .
// Node names escape any existing / and . characters to \\ and \,
// Path is only valid when child names are unique (see Unique* functions)
func (n *Node) Path() string {
if n.Par != nil {
if n.Is(Field) {
return n.Par.Path() + "." + EscapePathName(n.Nm)
}
return n.Par.Path() + "/" + EscapePathName(n.Nm)
}
return "/" + EscapePathName(n.Nm)
}
// PathFrom returns path to this node from given parent node, using
// node Names separated by / and fields by .
// Node names escape any existing / and . characters to \\ and \,
// Path is only valid for finding items when child names are unique
// (see Unique* functions). The paths that it returns exclude the
// name of the parent and the leading slash; for example, in the tree
// a/b/c/d/e, the result of d.PathFrom(b) would be c/d. PathFrom
// automatically gets the [Ki.This] version of the given parent,
// so a base type can be passed in without manually calling [Ki.This].
func (n *Node) PathFrom(par Ki) string {
// critical to get "This"
par = par.This()
// we bail a level below the parent so it isn't in the path
if n.Par == nil || n.Par == par {
return n.Nm
}
ppath := ""
if n.Par == par {
ppath = "/" + EscapePathName(par.Name())
} else {
ppath = n.Par.PathFrom(par)
}
if n.Is(Field) {
return ppath + "." + EscapePathName(n.Nm)
}
return ppath + "/" + EscapePathName(n.Nm)
}
// find the child on the path
func findPathChild(k Ki, child string) (int, bool) {
if child[0] == '[' && child[len(child)-1] == ']' {
idx, err := strconv.Atoi(child[1 : len(child)-1])
if err != nil {
return idx, false
}
if idx < 0 { // from end
idx = len(*k.Children()) + idx
}
if k.Children().IsValidIndex(idx) != nil {
return idx, false
}
return idx, true
}
return k.Children().IndexByName(child, 0)
}
// FindPath returns Ki object at given path, starting from this node
// (e.g., the root). If this node is not the root, then the path
// to this node is subtracted from the start of the path if present there.
// FindPath only works correctly when names are unique.
// Path has node Names separated by / and fields by .
// Node names escape any existing / and . characters to \\ and \,
// There is also support for [idx] index-based access for any given path
// element, for cases when indexes are more useful than names.
// Returns nil if not found.
func (n *Node) FindPath(path string) Ki {
if n.Par != nil { // we are not root..
myp := n.Path()
path = strings.TrimPrefix(path, myp)
}
curn := Ki(n)
pels := strings.Split(strings.Trim(strings.TrimSpace(path), "\""), "/")
for i, pe := range pels {
if len(pe) == 0 {
continue
}
if i <= 1 && curn.Name() == UnescapePathName(pe) {
continue
}
if strings.Contains(pe, ".") { // has fields
fels := strings.Split(pe, ".")
// find the child first, then the fields
idx, ok := findPathChild(curn, UnescapePathName(fels[0]))
if !ok {
return nil
}
curn = (*(curn.Children()))[idx]
for i := 1; i < len(fels); i++ {
fe := UnescapePathName(fels[i])
fk, err := curn.FieldByName(fe)
if err != nil {
slog.Debug("ki.FindPath: %v", err)
return nil
}
curn = fk
}
} else {
idx, ok := findPathChild(curn, UnescapePathName(pe))
if !ok {
return nil
}
curn = (*(curn.Children()))[idx]
}
}
return curn
}
// FindPathTry returns Ki object at given path, starting from this node
// (e.g., the root). If this node is not the root, then the path
// to this node is subtracted from the start of the path if present there.
// FindPath only works correctly when names are unique.
// Path has node Names separated by / and fields by .
// Node names escape any existing / and . characters to \\ and \,
// There is also support for [idx] index-based access for any given path
// element, for cases when indexes are more useful than names.
// Returns error if not found.
func (n *Node) FindPathTry(path string) (Ki, error) {
fk := n.This().FindPath(path)
if fk != nil {
return fk, nil
}
return nil, fmt.Errorf("ki %v: element at path: %v not found", n.Nm, path)
}
func (n *Node) FieldByName(field string) (Ki, error) {
return nil, errors.New("ki.FieldByName: no Ki fields defined for this node")
}
//////////////////////////////////////////////////////////////////////////
// Adding, Inserting Children
// AddChild adds given child at end of children list.
// The kid node is assumed to not be on another tree (see MoveToParent)
// and the existing name should be unique among children.
// No UpdateStart / End wrapping is done: do that externally as needed.
// Can also call SetFlag(ki.ChildAdded) if notification is needed.
func (n *Node) AddChild(kid Ki) error {
if err := ThisCheck(n); err != nil {
return err
}
InitNode(kid)
n.Kids = append(n.Kids, kid)
SetParent(kid, n.This()) // key to set new parent before deleting: indicates move instead of delete
return nil
}
// NewChild creates a new child of the given type and adds it at end
// of children list. The name should be unique among children. If the
// name is unspecified, it defaults to the ID (kebab-case) name of the
// type, plus the [Ki.NumLifetimeChildren] of its parent.
// No UpdateStart / End wrapping is done: do that externally as needed.
// Can also call SetFlag(ki.ChildAdded) if notification is needed.
func (n *Node) NewChild(typ *gti.Type, name ...string) Ki {
if err := ThisCheck(n); err != nil {
return nil
}
kid := NewOfType(typ)
InitNode(kid)
n.Kids = append(n.Kids, kid)
if len(name) > 0 {
kid.SetName(name[0])
}
SetParent(kid, n.This())
return kid
}
// SetChild sets child at given index to be the given item; if it is passed
// a name, then it sets the name of the child as well; just calls Init
// (or InitName) on the child, and SetParent. Names should be unique
// among children. No UpdateStart / End wrapping is done: do that
// externally as needed. Can also call SetFlag(ki.ChildAdded) if
// notification is needed.
func (n *Node) SetChild(kid Ki, idx int, name ...string) error {
if err := n.Kids.IsValidIndex(idx); err != nil {
return err
}
if len(name) > 0 {
kid.InitName(kid, name[0])
} else {
InitNode(kid)
}
n.Kids[idx] = kid
SetParent(kid, n.This())
return nil
}
// InsertChild adds given child at position in children list.
// The kid node is assumed to not be on another tree (see MoveToParent)
// and the existing name should be unique among children.
// No UpdateStart / End wrapping is done: do that externally as needed.
// Can also call SetChildAdded() if notification is needed.
func (n *Node) InsertChild(kid Ki, at int) error {
if err := ThisCheck(n); err != nil {
return err
}
InitNode(kid)
n.Kids.Insert(kid, at)
SetParent(kid, n.This())
return nil
}
// InsertNewChild creates a new child of given type and add at position
// in children list. The name should be unique among children. If the
// name is unspecified, it defaults to the ID (kebab-case) name of the
// type, plus the [Ki.NumLifetimeChildren] of its parent. No
// UpdateStart / End wrapping is done: do that externally as needed.
// Can also call SetFlag(ki.ChildAdded) if notification is needed.
func (n *Node) InsertNewChild(typ *gti.Type, at int, name ...string) Ki {
if err := ThisCheck(n); err != nil {
return nil
}
kid := NewOfType(typ)
InitNode(kid)
n.Kids.Insert(kid, at)
if len(name) > 0 {
kid.SetName(name[0])
}
SetParent(kid, n.This())
return kid
}
// SetNChildren ensures that there are exactly n children, deleting any
// extra, and creating any new ones, using NewChild with given type and
// naming according to nameStubX where X is the index of the child.
// If nameStub is not specified, it defaults to the ID (kebab-case)
// name of the type.
//
// IMPORTANT: returns whether any modifications were made (mods) AND if
// that is true, the result from the corresponding UpdateStart call --
// UpdateEnd is NOT called, allowing for further subsequent updates before
// you call UpdateEnd(updt)
//
// Note that this does not ensure existing children are of given type, or
// change their names, or call UniquifyNames -- use ConfigChildren for
// those cases -- this function is for simpler cases where a parent uses
// this function consistently to manage children all of the same type.
func (n *Node) SetNChildren(trgn int, typ *gti.Type, nameStub ...string) (mods, updt bool) {
mods, updt = false, false
sz := len(n.Kids)
if trgn == sz {
return
}
for sz > trgn {
if !mods {
mods = true
updt = n.This().UpdateStart()
}
sz--
n.DeleteChildAtIndex(sz, true)
}
ns := typ.IDName
if len(nameStub) > 0 {
ns = nameStub[0]
}
for sz < trgn {
if !mods {
mods = true
updt = n.This().UpdateStart()
}
nm := fmt.Sprintf("%s%d", ns, sz)
n.InsertNewChild(typ, sz, nm)
sz++
}
return
}
// ConfigChildren configures children according to given list of
// type-and-name's -- attempts to have minimal impact relative to existing
// items that fit the type and name constraints (they are moved into the
// corresponding positions), and any extra children are removed, and new
// ones added, to match the specified config. If uniqNm, then names
// represent UniqueNames (this results in Name == UniqueName for created
// children).
//
// IMPORTANT: returns whether any modifications were made (mods) AND if
// that is true, the result from the corresponding UpdateStart call --
// UpdateEnd is NOT called, allowing for further subsequent updates before
// you call UpdateEnd(updt).
func (n *Node) ConfigChildren(config Config) (mods, updt bool) {
return n.Kids.Config(n.This(), config)
}
//////////////////////////////////////////////////////////////////////////
// Deleting Children
// DeleteChildAtIndex deletes child at given index (returns error for
// invalid index).
// Wraps delete in UpdateStart / End and sets ChildDeleted flag.
func (n *Node) DeleteChildAtIndex(idx int, destroy bool) error {
child, err := n.ChildTry(idx)
if err != nil {
return err
}
updt := n.This().UpdateStart()
n.SetFlag(true, ChildDeleted)
if child.Parent() == n.This() {
// only deleting if we are still parent -- change parent first to
// signal move delete is always sent live to affected node without
// update blocking note: children of child etc will not send a signal
// at this point -- only later at destroy -- up to this parent to
// manage all that
DeleteFromParent(child)
}
n.Kids.DeleteAtIndex(idx)
if destroy {
DelMgr.Add(child)
}
UpdateReset(child) // it won't get the UpdateEnd from us anymore -- init fresh in any case
n.This().UpdateEnd(updt)
return nil
}
// DeleteChild deletes child node, returning error if not found in
// Children.
// Wraps delete in UpdateStart / End and sets ChildDeleted flag.
func (n *Node) DeleteChild(child Ki, destroy bool) error {
if child == nil {
return errors.New("ki DeleteChild: child is nil")
}
idx, ok := n.Kids.IndexOf(child, 0)
if !ok {
return fmt.Errorf("ki %v: child: %v not found", n.Nm, child.Path())
}
return n.DeleteChildAtIndex(idx, destroy)
}
// DeleteChildByName deletes child node by name -- returns child, error
// if not found.
// Wraps delete in UpdateStart / End and sets ChildDeleted flag.
func (n *Node) DeleteChildByName(name string, destroy bool) (Ki, error) {
idx, ok := n.Kids.IndexByName(name, 0)
if !ok {
return nil, fmt.Errorf("ki %v: child named: %v not found", n.Nm, name)
}
child := n.Kids[idx]
return child, n.DeleteChildAtIndex(idx, destroy)
}
// DeleteChildren deletes all children nodes -- destroy will add removed
// children to deleted list, to be destroyed later -- otherwise children
// remain intact but parent is nil -- could be inserted elsewhere, but you
// better have kept a slice of them before calling this.
func (n *Node) DeleteChildren(destroy bool) {
updt := n.This().UpdateStart()
n.SetFlag(true, ChildrenDeleted)
DeletingChildren(n.This())
kids := n.Kids
n.Kids = n.Kids[:0] // preserves capacity of list
for _, kid := range kids {
if kid == nil {
continue
}
kid.SetFlag(true, Deleted)
kid.This().OnDelete()
SetParent(kid, nil)
UpdateReset(kid)
}
if destroy {
DelMgr.Add(kids...)
}
n.This().UpdateEnd(updt)
}
// Delete deletes this node from its parent children list -- destroy will
// add removed child to deleted list, to be destroyed later -- otherwise
// child remains intact but parent is nil -- could be inserted elsewhere.
func (n *Node) Delete(destroy bool) {
if n.Par == nil {
if destroy {
n.This().Destroy()
}
} else {
n.Par.DeleteChild(n.This(), destroy)
}
}
// Destroy calls DisconnectAll to cut all pointers and signal connections,
// and remove all children and their childrens-children, etc.
func (n *Node) Destroy() {
// fmt.Printf("Destroying: %v %T %p Kids: %v\n", n.Nm, n.This(), n.This(), len(n.Kids))
if n.This() == nil { // already dead!
return
}
n.DeleteChildren(true) // first delete all my children
// and destroy all my fields
//
// n.FuncFields(0, nil, func(k Ki) bool {
// k.Destroy()
// return true
// })
DelMgr.DestroyDeleted() // then destroy all those kids
n.SetFlag(true, Destroyed)
n.Ths = nil // last gasp: lose our own sense of self..
// note: above is thread-safe because This() accessor checks Destroyed
}
//////////////////////////////////////////////////////////////////////////
// Flags
// Is checks if flag is set, using atomic, safe for concurrent access
func (n *Node) Is(f enums.BitFlag) bool {
return n.Flags.HasFlag(f)
}
// SetFlag sets the given flag(s) to given state
// using atomic, safe for concurrent access
func (n *Node) SetFlag(on bool, f ...enums.BitFlag) {
n.Flags.SetFlag(on, f...)
}
// SetChildAdded sets the ChildAdded flag -- set when notification is needed
// for Add, Insert methods
func (n *Node) SetChildAdded() {
n.SetFlag(true, ChildAdded)
}
// ClearUpdateFlags resets all structure update related flags:
// ChildAdded, ChildDeleted, ChildrenDeleted, Deleted
// automatically called on StartUpdate to reset any old state.
func (n *Node) ClearUpdateFlags() {
n.SetFlag(false, ChildAdded, ChildDeleted, ChildrenDeleted, Deleted)
}
// FlagType is the base implementation of [Ki.FlagType] that returns a
// value of type [Flags].
func (n *Node) FlagType() enums.BitFlagSetter {
return &n.Flags
}
//////////////////////////////////////////////////////////////////////////
// Property interface with inheritance -- nodes can inherit props from parents
// Properties (Node.Props) tell the GoGi GUI or other frameworks operating
// on Trees about special features of each node -- functions below support
// inheritance up Tree.
func (n *Node) Properties() *Props {
return &n.Props
}
// SetProp sets given property key to value val.
// initializes property map if nil.
func (n *Node) SetProp(key string, val any) {
if n.Props == nil {
n.Props = make(Props)
}
n.Props[key] = val
}
// SetProps sets a whole set of properties
func (n *Node) SetProps(props Props) {
if n.Props == nil {
n.Props = make(Props, len(props))
}
for key, val := range props {
n.Props[key] = val
}
}
// Prop returns property value for key that is known to exist.
// Returns nil if it actually doesn't -- this version allows
// direct conversion of return. See PropTry for version with
// error message if uncertain if property exists.
func (n *Node) Prop(key string) any {
return n.Props[key]
}
// PropTry returns property value for key. Returns error message
// if property with that key does not exist.
func (n *Node) PropTry(key string) (any, error) {
v, ok := n.Props[key]
if !ok {
return v, fmt.Errorf("ki.PropTry, could not find property with key %v on node %v", key, n.Nm)
}
return v, nil
}
// PropInherit gets property value from key with options for inheriting
// property from parents. If inherit, then checks all parents.
// Returns false if not set anywhere.
func (n *Node) PropInherit(key string, inherit bool) (any, bool) {
// pr := prof.Start("PropInherit")
// defer pr.End()
v, ok := n.Props[key]
if ok {
return v, ok
}
if inherit && n.Par != nil {
v, ok = n.Par.PropInherit(key, inherit)
if ok {
return v, ok
}
}
return nil, false
}
// DeleteProp deletes property key on this node.
func (n *Node) DeleteProp(key string) {
if n.Props == nil {
return
}
delete(n.Props, key)
}
// PropTag returns the name to look for in type properties, for types
// that are valid options for values that can be set in Props. For example
// in GoGi, it is "style-props" which is then set for all types that can
// be used in a style (colors, enum options, etc)
func (n *Node) PropTag() string {
return ""
}
//////////////////////////////////////////////////////////////////////////
// Tree walking and state updating
// WalkUp calls function on given node and all the way up to its parents,
// and so on -- sequentially all in current go routine (generally
// necessary for going up, which is typically quite fast anyway) -- level
// is incremented after each step (starts at 0, goes up), and passed to
// function -- returns false if fun aborts with false, else true.
func (n *Node) WalkUp(fun func(k Ki) bool) bool {
cur := n.This()
for {
if !fun(cur) { // false return means stop
return false
}
par := cur.Parent()
if par == nil || par == cur { // prevent loops
return true
}
cur = par
}
}
// WalkUpParent calls function on parent of node and all the way up to its
// parents, and so on -- sequentially all in current go routine (generally
// necessary for going up, which is typically quite fast anyway) -- level
// is incremented after each step (starts at 0, goes up), and passed to
// function -- returns false if fun aborts with false, else true.
func (n *Node) WalkUpParent(fun func(k Ki) bool) bool {
if IsRoot(n) {
return true
}
cur := n.Parent()
for {
if !fun(cur) { // false return means stop
return false
}
par := cur.Parent()
if par == nil || par == cur { // prevent loops
return true
}
cur = par
}
}
////////////////////////////////////////////////////////////////////////
// FuncDown -- Traversal records
// TravMap is a map for recording the traversal of nodes
type TravMap map[Ki]int
// Start is called at start of traversal
func (tm TravMap) Start(k Ki) {
tm[k] = -1
}
// End deletes node once done at end of traversal
func (tm TravMap) End(k Ki) {
delete(tm, k)
}
// Set updates traversal state
func (tm TravMap) Set(k Ki, curChild int) {
tm[k] = curChild
}
// Get retrieves current traversal state
func (tm TravMap) Get(k Ki) int {
return tm[k]
}
// strategy -- same as used in TreeView:
// https://stackoverflow.com/questions/5278580/non-recursive-depth-first-search-algorithm
// WalkPre calls function on this node (MeFirst) and then iterates
// in a depth-first manner over all the children.
// The [WalkPreNode] method is called for every node, after the given function,
// which e.g., enables nodes to also traverse additional Ki Trees (e.g., Fields),
// including for the basic UpdateStart / End and other such infrastructure calls
// which use WalkPre (otherwise it could just be done in the given fun).
// The node traversal is non-recursive and uses locally-allocated state -- safe
// for concurrent calling (modulo conflict management in function call itself).
// Function calls are sequential all in current go routine.
// If fun returns false then any further traversal of that branch of the tree is
// aborted, but other branches continue -- i.e., if fun on current node
// returns false, children are not processed further.
func (n *Node) WalkPre(fun func(Ki) bool) {
if n.This() == nil || n.Is(Deleted) {
return
}
tm := TravMap{} // not significantly faster to pre-allocate larger size
start := n.This()
cur := start
tm.Start(cur)
outer:
for {
if cur.This() != nil && !cur.Is(Deleted) && fun(cur) { // false return means stop
n.This().WalkPreNode(fun)
if cur.HasChildren() {
tm.Set(cur, 0) // 0 for no fields
nxt := cur.Child(0)
if nxt != nil && nxt.This() != nil && !nxt.Is(Deleted) {
cur = nxt.This()
tm.Start(cur)
continue
}
}
} else {
tm.Set(cur, cur.NumChildren())
}
// if we get here, we're in the ascent branch -- move to the right and then up
for {
curChild := tm.Get(cur)
if (curChild + 1) < cur.NumChildren() {