/
SpaceTreeLayoutAlgorithm.java
1130 lines (1046 loc) · 36.3 KB
/
SpaceTreeLayoutAlgorithm.java
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) 2005, 2016 The Chisel Group and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: Ian Bull (The Chisel Group) - initial API and implementation
* Mateusz Matela - "Tree Views for Zest" contribution, Google Summer of Code 2009
* Matthias Wienand (itemis AG) - refactorings
* Alexaner Nyßen (itemis AG) - refactorings (bug #469472)
******************************************************************************/
package org.eclipse.gef4.layout.algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.gef4.geometry.planar.Dimension;
import org.eclipse.gef4.geometry.planar.Point;
import org.eclipse.gef4.geometry.planar.Rectangle;
import org.eclipse.gef4.graph.Node;
import org.eclipse.gef4.layout.ILayoutAlgorithm;
import org.eclipse.gef4.layout.LayoutContext;
import org.eclipse.gef4.layout.LayoutProperties;
import org.eclipse.gef4.layout.algorithms.TreeLayoutObserver.TreeNode;
/**
* Layout algorithm implementing SpaceTree. It assumes that nodes in the layout
* context make a tree structure.
*
* It expands and collapses nodes to optimize use of available space. In order
* to keep the tree structure clearly visible, it also keeps track of the nodes'
* positions to makes sure they stay in their current layer and don't overlap
* with each other.
*
* @author Ian Bull
* @author Mateusz Matela
* @author mwienand
*/
public class SpaceTreeLayoutAlgorithm implements ILayoutAlgorithm {
/**
* Tree direction constant for which root is placed at the top and branches
* spread downwards
*/
public final static int TOP_DOWN = 1;
/**
* Tree direction constant for which root is placed at the bottom and
* branches spread upwards
*/
public final static int BOTTOM_UP = 2;
/**
* Tree direction constant for which root is placed at the left and branches
* spread to the right
*/
public final static int LEFT_RIGHT = 3;
/**
* Tree direction constant for which root is placed at the right and
* branches spread to the left
*/
public final static int RIGHT_LEFT = 4;
private class SpaceTreeNode extends TreeLayoutObserver.TreeNode {
public boolean expanded = true;
public double positionInLayer;
public SpaceTreeNode(Node node, TreeLayoutObserver owner) {
super(node, owner);
}
protected void addChild(TreeLayoutObserver.TreeNode child) {
super.addChild(child);
SpaceTreeNode child2 = (SpaceTreeNode) child;
child2.expanded = false;
if (child.depth >= 0)
spaceTreeLayers.get(child.depth).removeNode(child2);
if (expanded) {
child.depth = this.depth + 1;
SpaceTreeLayer childLayer;
if (child.depth < spaceTreeLayers.size())
childLayer = spaceTreeLayers.get(child.depth);
else
spaceTreeLayers
.add(childLayer = new SpaceTreeLayer(child.depth));
if (childLayer.nodes.isEmpty())
child.order = 0;
else
child.order = childLayer.nodes
.get(childLayer.nodes.size() - 1).order + 1;
childLayer.addNodes(Arrays.asList(child));
}
}
public void precomputeTree() {
super.precomputeTree();
if (this == owner.getSuperRoot()) {
expanded = true;
while (spaceTreeLayers.size() <= this.height)
spaceTreeLayers
.add(new SpaceTreeLayer(spaceTreeLayers.size()));
}
}
/**
* Moves the node back to its layer, as close as possible to given
* preferred location.
*
* @param preferredLocation
* The location to which the node should be moved.
*/
public void adjustPosition(Point preferredLocation) { // !
protectedNode = (SpaceTreeNode) owner.getSuperRoot();
double newPositionInLayer = (direction == BOTTOM_UP
|| direction == TOP_DOWN) ? preferredLocation.x
: preferredLocation.y;
if (((SpaceTreeNode) parent).expanded) {
spaceTreeLayers.get(depth).moveNode(this, newPositionInLayer);
centerParentsTopDown();
}
}
public double spaceRequiredForNode() {
if (node == null)
return 0;
switch (direction) {
case TOP_DOWN:
case BOTTOM_UP:
return LayoutProperties.getSize(node).width;
case LEFT_RIGHT:
case RIGHT_LEFT:
return LayoutProperties.getSize(node).height;
}
throw new RuntimeException("invalid direction");
}
public double spaceRequiredForChildren() {
if (children.isEmpty())
return 0;
double result = 0;
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
SpaceTreeNode child = (SpaceTreeNode) iterator.next();
result += child.spaceRequiredForNode();
}
result += leafGap * (children.size() - 1);
return result;
}
/**
* Checks if nodes in given list have proper positions according to
* their children (a parent's position cannot be smaller than its first
* child's position nor bigger than its last child's position). If not,
* it tries to fix them.
*
* @param nodesToCheck
* An {@link ArrayList} of the {@link TreeNode}s that are
* checked for proper positions.
* @return true if all locations are correct or could be corrected while
* checking.
*/
public boolean childrenPositionsOK(ArrayList<TreeNode> nodesToCheck) {
for (Iterator<TreeNode> iterator = nodesToCheck.iterator(); iterator
.hasNext();) {
SpaceTreeNode node = (SpaceTreeNode) iterator.next();
if (node.depth < 0 || node.children.isEmpty())
continue;
SpaceTreeNode child = ((SpaceTreeNode) node.children.get(0));
if (child.positionInLayer > node.positionInLayer) {
spaceTreeLayers.get(node.depth).moveNode(node,
child.positionInLayer);
if (child.positionInLayer > node.positionInLayer) {
spaceTreeLayers.get(child.depth).moveNode(child,
node.positionInLayer);
if (child.positionInLayer > node.positionInLayer) {
return false;
}
}
}
child = ((SpaceTreeNode) node.children
.get(node.children.size() - 1));
if (child.positionInLayer < node.positionInLayer) {
spaceTreeLayers.get(node.depth).moveNode(node,
child.positionInLayer);
if (child.positionInLayer < node.positionInLayer) {
spaceTreeLayers.get(child.depth).moveNode(child,
node.positionInLayer);
if (child.positionInLayer < node.positionInLayer) {
return false;
}
}
}
}
return true;
}
public void centerParentsBottomUp() {
if (!children.isEmpty() && expanded) {
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
((SpaceTreeNode) iterator.next()).centerParentsBottomUp();
}
if (depth >= 0) {
SpaceTreeNode firstChild = (SpaceTreeNode) children.get(0);
SpaceTreeNode lastChild = (SpaceTreeNode) children
.get(children.size() - 1);
SpaceTreeLayer layer = spaceTreeLayers.get(depth);
layer.moveNode(this, (firstChild.positionInLayer
+ lastChild.positionInLayer) / 2);
}
}
}
public void centerParentsTopDown() {
if (this == owner.getSuperRoot()) {
this.positionInLayer = getAvailableSpace() / 2;
}
if (!children.isEmpty() && expanded) {
SpaceTreeNode firstChild = (SpaceTreeNode) children.get(0);
SpaceTreeNode lastChild = (SpaceTreeNode) children
.get(children.size() - 1);
double offset = this.positionInLayer
- (firstChild.positionInLayer
+ lastChild.positionInLayer) / 2;
if (firstChild.positionInLayer
- firstChild.spaceRequiredForNode() / 2 + offset < 0)
offset = -firstChild.positionInLayer
+ firstChild.spaceRequiredForNode() / 2;
double availableSpace = getAvailableSpace();
if (lastChild.positionInLayer
+ lastChild.spaceRequiredForNode() / 2
+ offset > availableSpace) {
offset = availableSpace - lastChild.positionInLayer
- lastChild.spaceRequiredForNode() / 2;
}
SpaceTreeLayer layer = spaceTreeLayers.get(depth + 1);
layer.fitNodesWithinBounds(children,
firstChild.positionInLayer + offset,
lastChild.positionInLayer + offset);
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
((SpaceTreeNode) iterator.next()).centerParentsTopDown();
}
}
}
public void flushExpansionChanges() {
if (this.expanded) {
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
((SpaceTreeNode) iterator.next()).flushExpansionChanges();
}
}
}
/**
* Sets locations of nodes in the graph depending on their current layer
* and position in layer.
*
* @param thicknessSoFar
* sum of thicknesses and gaps for all layers 'above' this
* node (should be 0 if called on superRoot)
* @return true if location of at least one node has changed
*/
public boolean flushLocationChanges(double thicknessSoFar) {
Rectangle bounds = LayoutProperties.getBounds(context.getGraph());
boolean madeChanges = false;
if (node != null) {
Dimension nodeSize = LayoutProperties.getSize(node);
double x = 0, y = 0;
switch (direction) {
case TOP_DOWN:
x = bounds.getX() + positionInLayer;
y = thicknessSoFar + nodeSize.height / 2;
break;
case BOTTOM_UP:
x = bounds.getX() + positionInLayer;
y = bounds.getY() + bounds.getHeight() - thicknessSoFar
- nodeSize.height / 2;
break;
case LEFT_RIGHT:
x = thicknessSoFar + nodeSize.height / 2;
y = bounds.getY() + positionInLayer;
break;
case RIGHT_LEFT:
x = bounds.getX() + bounds.getWidth() - thicknessSoFar
- nodeSize.height / 2;
y = bounds.getY() + positionInLayer;
break;
}
Point currentLocation = LayoutProperties.getLocation(node);
if (currentLocation.x != x || currentLocation.y != y) {
LayoutProperties.setLocation(node, new Point(x, y));
SpaceTreeNode spaceTreeNode = (SpaceTreeNode) treeObserver
.getTreeNode(node);
spaceTreeNode
.adjustPosition(LayoutProperties.getLocation(node));
spaceTreeLayers.get(depth).refreshThickness();
madeChanges = true;
}
}
if (expanded) {
thicknessSoFar += (depth >= 0
? spaceTreeLayers.get(depth).thickness : 0) + layerGap;
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
SpaceTreeNode child = (SpaceTreeNode) iterator.next();
madeChanges = child.flushLocationChanges(thicknessSoFar)
|| madeChanges;
}
}
return madeChanges;
}
public String toString() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < depth; i++)
sb.append(" ");
if (node != null)
sb.append(node.toString());
sb.append("|" + this.order);
sb.append('\n');
for (Iterator<TreeNode> iterator = children.iterator(); iterator
.hasNext();) {
SpaceTreeNode child = (SpaceTreeNode) iterator.next();
sb.append(child.toString());
}
return sb.toString();
}
}
private TreeLayoutObserver.TreeNodeFactory spaceTreeNodeFactory = new TreeLayoutObserver.TreeNodeFactory() {
public TreeLayoutObserver.TreeNode createTreeNode(Node nodeLayout,
TreeLayoutObserver observer) {
return new SpaceTreeNode(nodeLayout, observer);
};
};
private class SpaceTreeLayer {
public ArrayList<SpaceTreeNode> nodes = new ArrayList<>();
private final int depth;
public double thickness = 0;
public SpaceTreeLayer(int depth) {
this.depth = depth;
}
public void addNodes(List<TreeNode> nodesToAdd) {
ListIterator<SpaceTreeNode> layerIterator = nodes.listIterator();
SpaceTreeNode previousNode = null;
for (Iterator<TreeNode> iterator = nodesToAdd.iterator(); iterator
.hasNext();) {
SpaceTreeNode nodeToAdd = (SpaceTreeNode) iterator.next();
SpaceTreeNode nodeInLayer = null;
while (layerIterator.hasNext()) {
nodeInLayer = layerIterator.next();
if (nodeInLayer.order >= nodeToAdd.order)
break;
double expectedPostion = (previousNode == null) ? 0
: previousNode.positionInLayer + expectedDistance(
previousNode, nodeInLayer);
nodeInLayer.positionInLayer = Math
.max(nodeInLayer.positionInLayer, expectedPostion);
previousNode = nodeInLayer;
}
if (nodeInLayer == null) {
layerIterator.add(nodeToAdd);
} else if (nodeInLayer.order == nodeToAdd.order) {
layerIterator.set(nodeToAdd);
} else {
if (nodeInLayer.order > nodeToAdd.order)
layerIterator.previous();
layerIterator.add(nodeToAdd);
}
layerIterator.previous();
}
// move the rest of nodes so that they don't overlap
while (layerIterator.hasNext()) {
SpaceTreeNode nodeInLayer = layerIterator.next();
double expectedPostion = (previousNode == null) ? 0
: previousNode.positionInLayer
+ expectedDistance(previousNode, nodeInLayer);
nodeInLayer.positionInLayer = Math
.max(nodeInLayer.positionInLayer, expectedPostion);
previousNode = nodeInLayer;
}
refreshThickness();
}
public void removeNode(SpaceTreeNode node) {
if (nodes.remove(node)) {
spaceTreeLayers.get(depth + 1).removeNodes(node.children);
refreshThickness();
}
}
public void removeNodes(List<TreeNode> nodesToRemove) {
if (this.nodes.removeAll(nodesToRemove)) {
SpaceTreeLayer nextLayer = spaceTreeLayers.get(depth + 1);
for (Iterator<TreeNode> iterator = nodesToRemove
.iterator(); iterator.hasNext();) {
SpaceTreeNode nodeToRemove = (SpaceTreeNode) iterator
.next();
nextLayer.removeNodes(nodeToRemove.children);
}
refreshThickness();
}
}
public void checkThickness(SpaceTreeNode node) {
double nodeThickness = 0;
Dimension size = LayoutProperties.getSize(node.node);
nodeThickness = (direction == TOP_DOWN || direction == BOTTOM_UP)
? size.height : size.width;
this.thickness = Math.max(this.thickness, nodeThickness);
}
public void refreshThickness() {
this.thickness = 0;
for (Iterator<SpaceTreeNode> iterator = nodes.iterator(); iterator
.hasNext();) {
checkThickness(iterator.next());
}
}
public void fitNodesWithinBounds(List<TreeNode> nodeList,
double startPosition, double endPosition) {
NodeSnapshot[][] snapShot = takeSnapShot();
SpaceTreeNode[] nodes = nodeList
.toArray(new SpaceTreeNode[nodeList.size()]);
double initialStartPosition = nodes[0].positionInLayer;
double initialNodesBredth = nodes[nodes.length - 1].positionInLayer
- initialStartPosition;
double[] desiredPositions = new double[nodes.length];
// calculate desired positions for every node, regarding their
// initial initial proportions
for (int i = 0; i < nodes.length; i++) {
double initialPositionAsPercent = (initialNodesBredth > 0)
? (nodes[i].positionInLayer - initialStartPosition)
/ initialNodesBredth
: 0;
desiredPositions[i] = initialPositionAsPercent
* (endPosition - startPosition);
}
// make sure there's proper distance between each pair of
// consecutive nodes
for (int i = 1; i < nodes.length; i++) {
SpaceTreeNode node = nodes[i];
SpaceTreeNode previousNode = nodes[i - 1];
double expectedDistance = expectedDistance(previousNode, node);
if (desiredPositions[i]
- desiredPositions[i - 1] < expectedDistance) {
desiredPositions[i] = desiredPositions[i - 1]
+ expectedDistance;
}
}
// if the above operation caused some nodes to fall out of requested
// bounds, push them back
if (desiredPositions[nodes.length - 1] > (endPosition
- startPosition)) {
desiredPositions[nodes.length - 1] = (endPosition
- startPosition);
for (int i = nodes.length - 1; i > 0; i--) {
SpaceTreeNode node = nodes[i];
SpaceTreeNode previousNode = nodes[i - 1];
double expectedDistance = expectedDistance(previousNode,
node);
if (desiredPositions[i]
- desiredPositions[i - 1] < expectedDistance) {
desiredPositions[i - 1] = desiredPositions[i]
- expectedDistance;
} else
break;
}
}
for (int i = 0; i < nodeList.size(); i++) {
SpaceTreeNode node = (SpaceTreeNode) nodeList.get(i);
double desiredPosition = startPosition + desiredPositions[i];
moveNode(node, desiredPosition);
if (Math.abs(node.positionInLayer - desiredPosition) > 0.5) {
startPosition += (node.positionInLayer - desiredPosition);
i = -1;
revertToSnapshot(snapShot);
}
}
}
public void moveNode(SpaceTreeNode node, double newPosition) {
Collections.sort(nodes, new Comparator<SpaceTreeNode>() {
public int compare(SpaceTreeNode arg0, SpaceTreeNode arg1) {
return arg0.order - arg1.order;
}
});
double positionInLayerAtStart = node.positionInLayer;
if (newPosition >= positionInLayerAtStart)
moveNodeForward(node, newPosition);
if (newPosition <= positionInLayerAtStart)
moveNodeBackward(node, newPosition);
}
/**
* Tries to increase node's position in layer. It can move a node only
* if it doesn't cause nodes to fall out of available space (see
* {@link SpaceTreeLayoutAlgorithm#getAvailableSpace()}. If there's not
* enough space available, some nodes may be collapsed to increase it as
* long as it doesn't cause
* {@link SpaceTreeLayoutAlgorithm#protectedNode} or any of its
* descendants to be collapsed.
*
* @param nodeToMove
* @param newPosition
*/
private void moveNodeForward(SpaceTreeNode nodeToMove,
double newPosition) {
int nodeIndex = nodes.indexOf(nodeToMove);
if (nodeIndex == -1)
throw new IllegalArgumentException("node not on this layer");
// move forward -> check space to the 'right'
NodeSnapshot[][] snapShot = takeSnapShot();
boolean firstRun = true;
mainLoop: while (firstRun
|| nodeToMove.positionInLayer < newPosition) {
firstRun = false;
double requiredSpace = 0;
SpaceTreeNode previousNode = nodeToMove;
for (int i = nodeIndex + 1; i < nodes.size(); i++) {
SpaceTreeNode nextNode = nodes.get(i);
requiredSpace += expectedDistance(previousNode, nextNode);
previousNode = nextNode;
}
requiredSpace += previousNode.spaceRequiredForNode() / 2;
if (requiredSpace > getAvailableSpace() - newPosition) {
// find nodes to remove
boolean removed = false;
for (int i = nodeIndex; i < nodes.size(); i++) {
SpaceTreeNode nextNode = nodes.get(i);
if (protectedNode == null
|| (!protectedNode.isAncestorOf(nextNode)
&& !nextNode.parent
.isAncestorOf(protectedNode))) {
collapseNode((SpaceTreeNode) nextNode.parent);
if (nextNode.parent == nodeToMove.parent)
break mainLoop;
removed = true;
break;
}
}
if (!removed) {
// not enough space, but we can't collapse anything...
newPosition = getAvailableSpace() - requiredSpace;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
// move the node and all its neighbors to the 'right'
SpaceTreeNode currentNodeToMove = nodeToMove;
double newPositionForCurrent = newPosition;
for (int i = nodeIndex; i < nodes.size(); i++) {
currentNodeToMove.positionInLayer = newPositionForCurrent;
// move parent if moved node is its first child
if (currentNodeToMove.firstChild) {
SpaceTreeNode parent = (SpaceTreeNode) currentNodeToMove.parent;
if (depth > 0
&& parent.positionInLayer <= newPositionForCurrent) {
SpaceTreeLayer parentLayer = spaceTreeLayers
.get(depth - 1);
parentLayer.moveNodeForward(parent,
newPositionForCurrent);
if (parent.positionInLayer < newPositionForCurrent) {
double delta = newPositionForCurrent
- parent.positionInLayer;
newPosition -= delta;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
}
// move children if necessary
if (currentNodeToMove.expanded
&& !currentNodeToMove.children.isEmpty()) {
SpaceTreeNode lastChild = (SpaceTreeNode) currentNodeToMove.children
.get(currentNodeToMove.children.size() - 1);
if (lastChild.positionInLayer < newPositionForCurrent) {
// try to move all the children, that is move the
// first child and the rest will be pushed
SpaceTreeNode firstChild = (SpaceTreeNode) currentNodeToMove.children
.get(0);
SpaceTreeLayer childLayer = spaceTreeLayers
.get(depth + 1);
double expectedDistanceBetweenChildren = currentNodeToMove
.spaceRequiredForChildren()
- firstChild.spaceRequiredForNode() / 2
- lastChild.spaceRequiredForNode() / 2;
childLayer.moveNodeForward(firstChild,
newPositionForCurrent
- expectedDistanceBetweenChildren);
if (currentNodeToMove.expanded
&& lastChild.positionInLayer < newPositionForCurrent) {
// the previous attempt failed -> try to move
// only the last child
childLayer.moveNodeForward(lastChild,
newPositionForCurrent);
if (lastChild.positionInLayer < newPositionForCurrent) {
// child couldn't be moved as far as needed
// -> move current node back to the position
// over the child
double delta = newPositionForCurrent
- lastChild.positionInLayer;
newPosition -= delta;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
}
}
if (i < nodes.size() - 1) {
SpaceTreeNode nextNode = nodes.get(i + 1);
newPositionForCurrent += expectedDistance(
currentNodeToMove, nextNode);
currentNodeToMove = nextNode;
if (currentNodeToMove.positionInLayer > newPositionForCurrent)
break;
}
}
}
}
/**
* Method complementary to
* {@link #moveNodeForward(SpaceTreeNode, double)}. Decreases node's
* position in layer.
*
* @param nodeToMove
* @param newPosition
*/
private void moveNodeBackward(SpaceTreeNode nodeToMove,
double newPosition) {
int nodeIndex = nodes.indexOf(nodeToMove);
if (nodeIndex == -1)
throw new IllegalArgumentException("node not on this layer");
// move backward -> check space to the 'left'
// move and collapse until there's enough space
NodeSnapshot[][] snapShot = takeSnapShot();
boolean firstRun = true;
mainLoop: while (firstRun
|| nodeToMove.positionInLayer > newPosition) {
firstRun = false;
double requiredSpace = 0;
SpaceTreeNode previousNode = nodeToMove;
for (int i = nodeIndex - 1; i >= 0; i--) {
SpaceTreeNode nextNode = nodes.get(i);
requiredSpace += expectedDistance(previousNode, nextNode);
previousNode = nextNode;
}
requiredSpace += previousNode.spaceRequiredForNode() / 2;
if (requiredSpace > newPosition) {
// find nodes to remove
boolean removed = false;
for (int i = nodeIndex; i >= 0; i--) {
SpaceTreeNode nextNode = nodes.get(i);
if (protectedNode == null
|| (!protectedNode.isAncestorOf(nextNode)
&& !nextNode.parent
.isAncestorOf(protectedNode))) {
collapseNode((SpaceTreeNode) nextNode.parent);
if (nextNode.parent == nodeToMove.parent)
break mainLoop;
nodeIndex -= nextNode.parent.children.size();
removed = true;
break;
}
}
if (!removed) {
// not enough space, but we can't collapse anything...
newPosition = requiredSpace;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
// move the node and all its neighbors to the 'left'
SpaceTreeNode currentNodeToMove = nodeToMove;
double newPositionForCurrent = newPosition;
for (int i = nodeIndex; i >= 0; i--) {
currentNodeToMove.positionInLayer = newPositionForCurrent;
// move parent if moved node is its last child
if (currentNodeToMove.lastChild) {
SpaceTreeNode parent = (SpaceTreeNode) currentNodeToMove.parent;
if (depth > 0
&& parent.positionInLayer >= newPositionForCurrent) {
SpaceTreeLayer parentLayer = spaceTreeLayers
.get(depth - 1);
parentLayer.moveNodeBackward(parent,
newPositionForCurrent);
if (parent.positionInLayer > newPositionForCurrent) {
double delta = parent.positionInLayer
- newPositionForCurrent;
newPosition += delta;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
}
// move children if necessary
if (currentNodeToMove.expanded
&& !currentNodeToMove.children.isEmpty()) {
SpaceTreeNode firstChild = (SpaceTreeNode) currentNodeToMove.children
.get(0);
if (firstChild.positionInLayer > newPositionForCurrent) {
// try to move all the children, that is move the
// last child and the rest will be pushed
SpaceTreeNode lastChild = (SpaceTreeNode) currentNodeToMove.children
.get(currentNodeToMove.children.size() - 1);
SpaceTreeLayer childLayer = spaceTreeLayers
.get(depth + 1);
double expectedDistanceBetweenChildren = currentNodeToMove
.spaceRequiredForChildren()
- firstChild.spaceRequiredForNode() / 2
- lastChild.spaceRequiredForNode() / 2;
childLayer.moveNodeBackward(lastChild,
newPositionForCurrent
+ expectedDistanceBetweenChildren);
if (currentNodeToMove.expanded
&& firstChild.positionInLayer > newPositionForCurrent) {
// the previous attempt failed -> try to move
// only the first child
childLayer.moveNodeBackward(firstChild,
newPositionForCurrent);
if (firstChild.positionInLayer > newPositionForCurrent) {
// child couldn't be moved as far as needed
// -> move current node back to the position
// over the child
double delta = firstChild.positionInLayer
- newPositionForCurrent;
newPosition += delta;
revertToSnapshot(snapShot);
continue mainLoop;
}
}
}
}
if (i > 0) {
SpaceTreeNode nextNode = nodes.get(i - 1);
newPositionForCurrent -= expectedDistance(
currentNodeToMove, nextNode);
currentNodeToMove = nextNode;
if (currentNodeToMove.positionInLayer < newPositionForCurrent)
break;
}
}
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Layer ").append(depth).append(": ");
for (Iterator<SpaceTreeNode> iterator = nodes.iterator(); iterator
.hasNext();) {
SpaceTreeNode node = iterator.next();
buffer.append(node.node).append(", ");
}
return buffer.toString();
}
private void collapseNode(SpaceTreeNode node) {
node.expanded = false;
SpaceTreeLayer layer = spaceTreeLayers.get(node.depth + 1);
layer.removeNodes(node.children);
for (Iterator<TreeNode> iterator = node.children
.iterator(); iterator.hasNext();) {
SpaceTreeNode child = (SpaceTreeNode) iterator.next();
if (child.expanded)
collapseNode(child);
}
}
}
private int direction = TOP_DOWN;
private double leafGap = 15;
private double branchGap = leafGap + 5;
private double layerGap = 20;
/**
* Sets the distance between leaf nodes to the given value. Default value is
* 15.
*
* @param value
* The new distance between leaf nodes.
*
*/
public void setLeafGap(double value) {
this.leafGap = value;
}
/**
* Sets the distance between branches to the given value. Default value is
* 20.
*
* @param value
* The new distance between branches.
*
*/
public void setBranchGap(double value) {
this.branchGap = value;
}
/**
* Sets the distance between layers to the given value. Default value is 20.
*
* @param value
* The new distance between layers.
*
*/
public void setLayerGap(double value) {
this.layerGap = value;
}
/**
* Returns the distance between leaf nodes. Default value is 15.
*
* @return The distance between leaf nodes.
*/
public double getLeafGap() {
return this.leafGap;
}
/**
* Returns the distance between branches. Default value is 20.
*
* @return The distance between branches.
*/
public double getBranchGap() {
return this.branchGap;
}
/**
* Returns the distance between layers. Default value is 20.
*
* @return The distance between layers.
*/
public double getLayerGap() {
return this.layerGap;
}
private LayoutContext context;
private TreeLayoutObserver treeObserver;
private double availableSpace;
private ArrayList<SpaceTreeLayer> spaceTreeLayers = new ArrayList<>();
/**
* If not null, this node and all of its children shall not be collapsed
* during node movements.
*/
private SpaceTreeNode protectedNode = null;
/**
* Constructs an instance of <code>SpaceTreeLayoutAlgorithm</code> that
* places the root of a tree at the top of the graph.
*/
public SpaceTreeLayoutAlgorithm() {
}
/**
* Constructs an instance of <code>SpaceTreeLayoutAlgorithm</code> that
* places the root of a tree according to given direction
*
* @param direction
* direction of the tree, sould be one of the following:
* {@link #TOP_DOWN}, {@link #BOTTOM_UP}, {@link #LEFT_RIGHT},
* {@link #RIGHT_LEFT}.
*/
public SpaceTreeLayoutAlgorithm(int direction) {
setDirection(direction);
}
/**
*
* @return current direction (placement) of the tree
*/
public int getDirection() {
return direction;
}
/**
* Sets direction (placement) of the tree
*
* @param direction
* direction of the tree, sould be one of the following:
* {@link #TOP_DOWN}, {@link #BOTTOM_UP}, {@link #LEFT_RIGHT},
* {@link #RIGHT_LEFT}.
*/
public void setDirection(int direction) {
if (direction == this.direction)
return;
if (direction == TOP_DOWN || direction == BOTTOM_UP
|| direction == LEFT_RIGHT || direction == RIGHT_LEFT) {
this.direction = direction;
} else
throw new IllegalArgumentException(
"Invalid direction: " + direction);
}
public void applyLayout(boolean clean) {
Rectangle bounds = LayoutProperties.getBounds(context.getGraph());
if (bounds.isEmpty()) {
return;
}
if (clean) {
treeObserver.recomputeTree();
maximizeExpansion((SpaceTreeNode) treeObserver.getSuperRoot());
}
SpaceTreeNode superRoot = ((SpaceTreeNode) treeObserver.getSuperRoot());
superRoot.flushExpansionChanges();
superRoot.flushLocationChanges(0);
}
private void maximizeExpansion(SpaceTreeNode nodeToExpand) {
protectedNode = nodeToExpand;
double availableSpace = getAvailableSpace();
double requiredSpace = 0;
spaceTreeLayers.get(nodeToExpand.depth + 1)
.removeNodes(nodeToExpand.children);
ArrayList<TreeNode> nodesInThisLayer = null;
ArrayList<TreeNode> nodesInNextLayer = new ArrayList<>();
nodesInNextLayer.add(nodeToExpand);
double spaceRequiredInNextLayer = nodeToExpand.spaceRequiredForNode();
for (int layer = 0; !nodesInNextLayer.isEmpty(); layer++) {
NodeSnapshot[][] snapShot = takeSnapShot();
requiredSpace = Math.max(requiredSpace, spaceRequiredInNextLayer);
spaceRequiredInNextLayer = 0;
nodesInThisLayer = nodesInNextLayer;
nodesInNextLayer = new ArrayList<>();
int numOfNodesWithChildren = 0;
for (Iterator<TreeNode> iterator = nodesInThisLayer
.iterator(); iterator.hasNext();) {
SpaceTreeNode node = (SpaceTreeNode) iterator.next();
if (!node.children.isEmpty()) {
node.expanded = true;
spaceRequiredInNextLayer += node.spaceRequiredForChildren();
nodesInNextLayer.addAll(node.children);
numOfNodesWithChildren++;
}
}
for (Iterator<TreeNode> iterator = nodesInNextLayer
.iterator(); iterator.hasNext();) {
SpaceTreeNode node = (SpaceTreeNode) iterator.next();
node.expanded = false;
}
if (numOfNodesWithChildren == 0)
break;
spaceRequiredInNextLayer += branchGap
* (numOfNodesWithChildren - 1);
boolean addedNewLayer = false;
if ((spaceRequiredInNextLayer <= requiredSpace
|| spaceRequiredInNextLayer <= availableSpace
|| (layer < 1 && nodeToExpand.depth + layer < 1))
&& !nodesInNextLayer.isEmpty()) {
// add next layer and center its nodes
SpaceTreeLayer childLayer = spaceTreeLayers
.get(nodeToExpand.depth + layer + 1);
childLayer.addNodes(nodesInNextLayer);
SpaceTreeNode firstChild = ((SpaceTreeNode) nodesInNextLayer
.get(0));
SpaceTreeNode lastChild = ((SpaceTreeNode) nodesInNextLayer
.get(nodesInNextLayer.size() - 1));
double boundsWidth = spaceRequiredInNextLayer