source: josm/trunk/src/org/openstreetmap/josm/gui/widgets/MultiSplitLayout.java@ 8470

Last change on this file since 8470 was 8470, checked in by Don-vip, 10 years ago

javadoc fixes. Removed one duplicated method in exception handling

  • Property svn:eol-style set to native
File size: 49.8 KB
Line 
1/*
2 * $Id: MultiSplitLayout.java,v 1.15 2005/10/26 14:29:54 hansmuller Exp $
3 *
4 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
5 * Santa Clara, California 95054, U.S.A. All rights reserved.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21package org.openstreetmap.josm.gui.widgets;
22
23import java.awt.Component;
24import java.awt.Container;
25import java.awt.Dimension;
26import java.awt.Insets;
27import java.awt.LayoutManager;
28import java.awt.Rectangle;
29import java.beans.PropertyChangeListener;
30import java.beans.PropertyChangeSupport;
31import java.io.Reader;
32import java.io.StreamTokenizer;
33import java.io.StringReader;
34import java.util.ArrayList;
35import java.util.Collections;
36import java.util.HashMap;
37import java.util.Iterator;
38import java.util.List;
39import java.util.ListIterator;
40import java.util.Locale;
41import java.util.Map;
42
43import javax.swing.UIManager;
44
45import org.openstreetmap.josm.Main;
46import org.openstreetmap.josm.tools.CheckParameterUtil;
47import org.openstreetmap.josm.tools.Utils;
48
49/**
50 * The MultiSplitLayout layout manager recursively arranges its
51 * components in row and column groups called "Splits". Elements of
52 * the layout are separated by gaps called "Dividers". The overall
53 * layout is defined with a simple tree model whose nodes are
54 * instances of MultiSplitLayout.Split, MultiSplitLayout.Divider,
55 * and MultiSplitLayout.Leaf. Named Leaf nodes represent the space
56 * allocated to a component that was added with a constraint that
57 * matches the Leaf's name. Extra space is distributed
58 * among row/column siblings according to their 0.0 to 1.0 weight.
59 * If no weights are specified then the last sibling always gets
60 * all of the extra space, or space reduction.
61 *
62 * <p>
63 * Although MultiSplitLayout can be used with any Container, it's
64 * the default layout manager for MultiSplitPane. MultiSplitPane
65 * supports interactively dragging the Dividers, accessibility,
66 * and other features associated with split panes.
67 *
68 * <p>
69 * All properties in this class are bound: when a properties value
70 * is changed, all PropertyChangeListeners are fired.
71 *
72 * @author Hans Muller - SwingX
73 * @see MultiSplitPane
74 */
75public class MultiSplitLayout implements LayoutManager {
76 private final Map<String, Component> childMap = new HashMap<>();
77 private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
78 private Node model;
79 private int dividerSize;
80 private boolean floatingDividers = true;
81
82 /**
83 * Create a MultiSplitLayout with a default model with a single
84 * Leaf node named "default".
85 *
86 * #see setModel
87 */
88 public MultiSplitLayout() {
89 this(new Leaf("default"));
90 }
91
92 /**
93 * Create a MultiSplitLayout with the specified model.
94 *
95 * #see setModel
96 */
97 public MultiSplitLayout(Node model) {
98 this.model = model;
99 this.dividerSize = UIManager.getInt("SplitPane.dividerSize");
100 if (this.dividerSize == 0) {
101 this.dividerSize = 7;
102 }
103 }
104
105 public void addPropertyChangeListener(PropertyChangeListener listener) {
106 if (listener != null) {
107 pcs.addPropertyChangeListener(listener);
108 }
109 }
110 public void removePropertyChangeListener(PropertyChangeListener listener) {
111 if (listener != null) {
112 pcs.removePropertyChangeListener(listener);
113 }
114 }
115 public PropertyChangeListener[] getPropertyChangeListeners() {
116 return pcs.getPropertyChangeListeners();
117 }
118
119 private void firePCS(String propertyName, Object oldValue, Object newValue) {
120 if (!(oldValue != null && newValue != null && oldValue.equals(newValue))) {
121 pcs.firePropertyChange(propertyName, oldValue, newValue);
122 }
123 }
124
125 /**
126 * Return the root of the tree of Split, Leaf, and Divider nodes
127 * that define this layout.
128 *
129 * @return the value of the model property
130 * @see #setModel
131 */
132 public Node getModel() {
133 return model;
134 }
135
136 /**
137 * Set the root of the tree of Split, Leaf, and Divider nodes
138 * that define this layout. The model can be a Split node
139 * (the typical case) or a Leaf. The default value of this
140 * property is a Leaf named "default".
141 *
142 * @param model the root of the tree of Split, Leaf, and Divider node
143 * @throws IllegalArgumentException if model is a Divider or null
144 * @see #getModel
145 */
146 public void setModel(Node model) {
147 if ((model == null) || (model instanceof Divider))
148 throw new IllegalArgumentException("invalid model");
149 Node oldModel = model;
150 this.model = model;
151 firePCS("model", oldModel, model);
152 }
153
154 /**
155 * Returns the width of Dividers in Split rows, and the height of
156 * Dividers in Split columns.
157 *
158 * @return the value of the dividerSize property
159 * @see #setDividerSize
160 */
161 public int getDividerSize() {
162 return dividerSize;
163 }
164
165 /**
166 * Sets the width of Dividers in Split rows, and the height of
167 * Dividers in Split columns. The default value of this property
168 * is the same as for JSplitPane Dividers.
169 *
170 * @param dividerSize the size of dividers (pixels)
171 * @throws IllegalArgumentException if dividerSize &lt; 0
172 * @see #getDividerSize
173 */
174 public void setDividerSize(int dividerSize) {
175 if (dividerSize < 0)
176 throw new IllegalArgumentException("invalid dividerSize");
177 int oldDividerSize = this.dividerSize;
178 this.dividerSize = dividerSize;
179 firePCS("dividerSize", oldDividerSize, dividerSize);
180 }
181
182 /**
183 * @return the value of the floatingDividers property
184 * @see #setFloatingDividers
185 */
186 public boolean getFloatingDividers() {
187 return floatingDividers;
188 }
189
190 /**
191 * If true, Leaf node bounds match the corresponding component's
192 * preferred size and Splits/Dividers are resized accordingly.
193 * If false then the Dividers define the bounds of the adjacent
194 * Split and Leaf nodes. Typically this property is set to false
195 * after the (MultiSplitPane) user has dragged a Divider.
196 *
197 * @see #getFloatingDividers
198 */
199 public void setFloatingDividers(boolean floatingDividers) {
200 boolean oldFloatingDividers = this.floatingDividers;
201 this.floatingDividers = floatingDividers;
202 firePCS("floatingDividers", oldFloatingDividers, floatingDividers);
203 }
204
205 /**
206 * Add a component to this MultiSplitLayout. The
207 * <code>name</code> should match the name property of the Leaf
208 * node that represents the bounds of <code>child</code>. After
209 * layoutContainer() recomputes the bounds of all of the nodes in
210 * the model, it will set this child's bounds to the bounds of the
211 * Leaf node with <code>name</code>. Note: if a component was already
212 * added with the same name, this method does not remove it from
213 * its parent.
214 *
215 * @param name identifies the Leaf node that defines the child's bounds
216 * @param child the component to be added
217 * @see #removeLayoutComponent
218 */
219 @Override
220 public void addLayoutComponent(String name, Component child) {
221 if (name == null)
222 throw new IllegalArgumentException("name not specified");
223 childMap.put(name, child);
224 }
225
226 /**
227 * Removes the specified component from the layout.
228 *
229 * @param child the component to be removed
230 * @see #addLayoutComponent
231 */
232 @Override
233 public void removeLayoutComponent(Component child) {
234 String name = child.getName();
235 if (name != null) {
236 childMap.remove(name);
237 }
238 }
239
240 private Component childForNode(Node node) {
241 if (node instanceof Leaf) {
242 Leaf leaf = (Leaf)node;
243 String name = leaf.getName();
244 return (name != null) ? childMap.get(name) : null;
245 }
246 return null;
247 }
248
249 private Dimension preferredComponentSize(Node node) {
250 Component child = childForNode(node);
251 return (child != null) ? child.getPreferredSize() : new Dimension(0, 0);
252
253 }
254
255 private Dimension preferredNodeSize(Node root) {
256 if (root instanceof Leaf)
257 return preferredComponentSize(root);
258 else if (root instanceof Divider) {
259 int dividerSize = getDividerSize();
260 return new Dimension(dividerSize, dividerSize);
261 } else {
262 Split split = (Split)root;
263 List<Node> splitChildren = split.getChildren();
264 int width = 0;
265 int height = 0;
266 if (split.isRowLayout()) {
267 for(Node splitChild : splitChildren) {
268 Dimension size = preferredNodeSize(splitChild);
269 width += size.width;
270 height = Math.max(height, size.height);
271 }
272 } else {
273 for(Node splitChild : splitChildren) {
274 Dimension size = preferredNodeSize(splitChild);
275 width = Math.max(width, size.width);
276 height += size.height;
277 }
278 }
279 return new Dimension(width, height);
280 }
281 }
282
283 private Dimension minimumNodeSize(Node root) {
284 if (root instanceof Leaf) {
285 Component child = childForNode(root);
286 return (child != null) ? child.getMinimumSize() : new Dimension(0, 0);
287 } else if (root instanceof Divider) {
288 int dividerSize = getDividerSize();
289 return new Dimension(dividerSize, dividerSize);
290 } else {
291 Split split = (Split)root;
292 List<Node> splitChildren = split.getChildren();
293 int width = 0;
294 int height = 0;
295 if (split.isRowLayout()) {
296 for(Node splitChild : splitChildren) {
297 Dimension size = minimumNodeSize(splitChild);
298 width += size.width;
299 height = Math.max(height, size.height);
300 }
301 } else {
302 for(Node splitChild : splitChildren) {
303 Dimension size = minimumNodeSize(splitChild);
304 width = Math.max(width, size.width);
305 height += size.height;
306 }
307 }
308 return new Dimension(width, height);
309 }
310 }
311
312 private Dimension sizeWithInsets(Container parent, Dimension size) {
313 Insets insets = parent.getInsets();
314 int width = size.width + insets.left + insets.right;
315 int height = size.height + insets.top + insets.bottom;
316 return new Dimension(width, height);
317 }
318
319 @Override
320 public Dimension preferredLayoutSize(Container parent) {
321 Dimension size = preferredNodeSize(getModel());
322 return sizeWithInsets(parent, size);
323 }
324
325 @Override
326 public Dimension minimumLayoutSize(Container parent) {
327 Dimension size = minimumNodeSize(getModel());
328 return sizeWithInsets(parent, size);
329 }
330
331 private Rectangle boundsWithYandHeight(Rectangle bounds, double y, double height) {
332 Rectangle r = new Rectangle();
333 r.setBounds((int)(bounds.getX()), (int)y, (int)(bounds.getWidth()), (int)height);
334 return r;
335 }
336
337 private Rectangle boundsWithXandWidth(Rectangle bounds, double x, double width) {
338 Rectangle r = new Rectangle();
339 r.setBounds((int)x, (int)(bounds.getY()), (int)width, (int)(bounds.getHeight()));
340 return r;
341 }
342
343 private void minimizeSplitBounds(Split split, Rectangle bounds) {
344 Rectangle splitBounds = new Rectangle(bounds.x, bounds.y, 0, 0);
345 List<Node> splitChildren = split.getChildren();
346 Node lastChild = splitChildren.get(splitChildren.size() - 1);
347 Rectangle lastChildBounds = lastChild.getBounds();
348 if (split.isRowLayout()) {
349 int lastChildMaxX = lastChildBounds.x + lastChildBounds.width;
350 splitBounds.add(lastChildMaxX, bounds.y + bounds.height);
351 } else {
352 int lastChildMaxY = lastChildBounds.y + lastChildBounds.height;
353 splitBounds.add(bounds.x + bounds.width, lastChildMaxY);
354 }
355 split.setBounds(splitBounds);
356 }
357
358 private void layoutShrink(Split split, Rectangle bounds) {
359 Rectangle splitBounds = split.getBounds();
360 ListIterator<Node> splitChildren = split.getChildren().listIterator();
361
362 if (split.isRowLayout()) {
363 int totalWidth = 0; // sum of the children's widths
364 int minWeightedWidth = 0; // sum of the weighted childrens' min widths
365 int totalWeightedWidth = 0; // sum of the weighted childrens' widths
366 for(Node splitChild : split.getChildren()) {
367 int nodeWidth = splitChild.getBounds().width;
368 int nodeMinWidth = Math.min(nodeWidth, minimumNodeSize(splitChild).width);
369 totalWidth += nodeWidth;
370 if (splitChild.getWeight() > 0.0) {
371 minWeightedWidth += nodeMinWidth;
372 totalWeightedWidth += nodeWidth;
373 }
374 }
375
376 double x = bounds.getX();
377 double extraWidth = splitBounds.getWidth() - bounds.getWidth();
378 double availableWidth = extraWidth;
379 boolean onlyShrinkWeightedComponents =
380 (totalWeightedWidth - minWeightedWidth) > extraWidth;
381
382 while(splitChildren.hasNext()) {
383 Node splitChild = splitChildren.next();
384 Rectangle splitChildBounds = splitChild.getBounds();
385 double minSplitChildWidth = minimumNodeSize(splitChild).getWidth();
386 double splitChildWeight = (onlyShrinkWeightedComponents)
387 ? splitChild.getWeight()
388 : (splitChildBounds.getWidth() / totalWidth);
389
390 if (!splitChildren.hasNext()) {
391 double newWidth = Math.max(minSplitChildWidth, bounds.getMaxX() - x);
392 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, newWidth);
393 layout2(splitChild, newSplitChildBounds);
394 } else if ((availableWidth > 0.0) && (splitChildWeight > 0.0)) {
395 double allocatedWidth = Math.rint(splitChildWeight * extraWidth);
396 double oldWidth = splitChildBounds.getWidth();
397 double newWidth = Math.max(minSplitChildWidth, oldWidth - allocatedWidth);
398 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, newWidth);
399 layout2(splitChild, newSplitChildBounds);
400 availableWidth -= (oldWidth - splitChild.getBounds().getWidth());
401 } else {
402 double existingWidth = splitChildBounds.getWidth();
403 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, existingWidth);
404 layout2(splitChild, newSplitChildBounds);
405 }
406 x = splitChild.getBounds().getMaxX();
407 }
408 } else {
409 int totalHeight = 0; // sum of the children's heights
410 int minWeightedHeight = 0; // sum of the weighted childrens' min heights
411 int totalWeightedHeight = 0; // sum of the weighted childrens' heights
412 for(Node splitChild : split.getChildren()) {
413 int nodeHeight = splitChild.getBounds().height;
414 int nodeMinHeight = Math.min(nodeHeight, minimumNodeSize(splitChild).height);
415 totalHeight += nodeHeight;
416 if (splitChild.getWeight() > 0.0) {
417 minWeightedHeight += nodeMinHeight;
418 totalWeightedHeight += nodeHeight;
419 }
420 }
421
422 double y = bounds.getY();
423 double extraHeight = splitBounds.getHeight() - bounds.getHeight();
424 double availableHeight = extraHeight;
425 boolean onlyShrinkWeightedComponents =
426 (totalWeightedHeight - minWeightedHeight) > extraHeight;
427
428 while(splitChildren.hasNext()) {
429 Node splitChild = splitChildren.next();
430 Rectangle splitChildBounds = splitChild.getBounds();
431 double minSplitChildHeight = minimumNodeSize(splitChild).getHeight();
432 double splitChildWeight = (onlyShrinkWeightedComponents)
433 ? splitChild.getWeight()
434 : (splitChildBounds.getHeight() / totalHeight);
435
436 if (!splitChildren.hasNext()) {
437 double oldHeight = splitChildBounds.getHeight();
438 double newHeight = Math.max(minSplitChildHeight, bounds.getMaxY() - y);
439 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, newHeight);
440 layout2(splitChild, newSplitChildBounds);
441 availableHeight -= (oldHeight - splitChild.getBounds().getHeight());
442 } else if ((availableHeight > 0.0) && (splitChildWeight > 0.0)) {
443 double allocatedHeight = Math.rint(splitChildWeight * extraHeight);
444 double oldHeight = splitChildBounds.getHeight();
445 double newHeight = Math.max(minSplitChildHeight, oldHeight - allocatedHeight);
446 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, newHeight);
447 layout2(splitChild, newSplitChildBounds);
448 availableHeight -= (oldHeight - splitChild.getBounds().getHeight());
449 } else {
450 double existingHeight = splitChildBounds.getHeight();
451 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, existingHeight);
452 layout2(splitChild, newSplitChildBounds);
453 }
454 y = splitChild.getBounds().getMaxY();
455 }
456 }
457
458 /* The bounds of the Split node root are set to be
459 * big enough to contain all of its children. Since
460 * Leaf children can't be reduced below their
461 * (corresponding java.awt.Component) minimum sizes,
462 * the size of the Split's bounds maybe be larger than
463 * the bounds we were asked to fit within.
464 */
465 minimizeSplitBounds(split, bounds);
466 }
467
468 private void layoutGrow(Split split, Rectangle bounds) {
469 Rectangle splitBounds = split.getBounds();
470 ListIterator<Node> splitChildren = split.getChildren().listIterator();
471 Node lastWeightedChild = split.lastWeightedChild();
472
473 if (split.isRowLayout()) {
474 /* Layout the Split's child Nodes' along the X axis. The bounds
475 * of each child will have the same y coordinate and height as the
476 * layoutGrow() bounds argument. Extra width is allocated to the
477 * to each child with a non-zero weight:
478 * newWidth = currentWidth + (extraWidth * splitChild.getWeight())
479 * Any extraWidth "left over" (that's availableWidth in the loop
480 * below) is given to the last child. Note that Dividers always
481 * have a weight of zero, and they're never the last child.
482 */
483 double x = bounds.getX();
484 double extraWidth = bounds.getWidth() - splitBounds.getWidth();
485 double availableWidth = extraWidth;
486
487 while(splitChildren.hasNext()) {
488 Node splitChild = splitChildren.next();
489 Rectangle splitChildBounds = splitChild.getBounds();
490 double splitChildWeight = splitChild.getWeight();
491
492 if (!splitChildren.hasNext()) {
493 double newWidth = bounds.getMaxX() - x;
494 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, newWidth);
495 layout2(splitChild, newSplitChildBounds);
496 } else if ((availableWidth > 0.0) && (splitChildWeight > 0.0)) {
497 double allocatedWidth = (splitChild.equals(lastWeightedChild))
498 ? availableWidth
499 : Math.rint(splitChildWeight * extraWidth);
500 double newWidth = splitChildBounds.getWidth() + allocatedWidth;
501 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, newWidth);
502 layout2(splitChild, newSplitChildBounds);
503 availableWidth -= allocatedWidth;
504 } else {
505 double existingWidth = splitChildBounds.getWidth();
506 Rectangle newSplitChildBounds = boundsWithXandWidth(bounds, x, existingWidth);
507 layout2(splitChild, newSplitChildBounds);
508 }
509 x = splitChild.getBounds().getMaxX();
510 }
511 } else {
512 /* Layout the Split's child Nodes' along the Y axis. The bounds
513 * of each child will have the same x coordinate and width as the
514 * layoutGrow() bounds argument. Extra height is allocated to the
515 * to each child with a non-zero weight:
516 * newHeight = currentHeight + (extraHeight * splitChild.getWeight())
517 * Any extraHeight "left over" (that's availableHeight in the loop
518 * below) is given to the last child. Note that Dividers always
519 * have a weight of zero, and they're never the last child.
520 */
521 double y = bounds.getY();
522 double extraHeight = bounds.getMaxY() - splitBounds.getHeight();
523 double availableHeight = extraHeight;
524
525 while(splitChildren.hasNext()) {
526 Node splitChild = splitChildren.next();
527 Rectangle splitChildBounds = splitChild.getBounds();
528 double splitChildWeight = splitChild.getWeight();
529
530 if (!splitChildren.hasNext()) {
531 double newHeight = bounds.getMaxY() - y;
532 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, newHeight);
533 layout2(splitChild, newSplitChildBounds);
534 } else if ((availableHeight > 0.0) && (splitChildWeight > 0.0)) {
535 double allocatedHeight = (splitChild.equals(lastWeightedChild))
536 ? availableHeight
537 : Math.rint(splitChildWeight * extraHeight);
538 double newHeight = splitChildBounds.getHeight() + allocatedHeight;
539 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, newHeight);
540 layout2(splitChild, newSplitChildBounds);
541 availableHeight -= allocatedHeight;
542 } else {
543 double existingHeight = splitChildBounds.getHeight();
544 Rectangle newSplitChildBounds = boundsWithYandHeight(bounds, y, existingHeight);
545 layout2(splitChild, newSplitChildBounds);
546 }
547 y = splitChild.getBounds().getMaxY();
548 }
549 }
550 }
551
552 /* Second pass of the layout algorithm: branch to layoutGrow/Shrink
553 * as needed.
554 */
555 private void layout2(Node root, Rectangle bounds) {
556 if (root instanceof Leaf) {
557 Component child = childForNode(root);
558 if (child != null) {
559 child.setBounds(bounds);
560 }
561 root.setBounds(bounds);
562 } else if (root instanceof Divider) {
563 root.setBounds(bounds);
564 } else if (root instanceof Split) {
565 Split split = (Split)root;
566 boolean grow = split.isRowLayout()
567 ? split.getBounds().width <= bounds.width
568 : (split.getBounds().height <= bounds.height);
569 if (grow) {
570 layoutGrow(split, bounds);
571 root.setBounds(bounds);
572 } else {
573 layoutShrink(split, bounds);
574 // split.setBounds() called in layoutShrink()
575 }
576 }
577 }
578
579 /* First pass of the layout algorithm.
580 *
581 * If the Dividers are "floating" then set the bounds of each
582 * node to accomodate the preferred size of all of the
583 * Leaf's java.awt.Components. Otherwise, just set the bounds
584 * of each Leaf/Split node so that it's to the left of (for
585 * Split.isRowLayout() Split children) or directly above
586 * the Divider that follows.
587 *
588 * This pass sets the bounds of each Node in the layout model. It
589 * does not resize any of the parent Container's
590 * (java.awt.Component) children. That's done in the second pass,
591 * see layoutGrow() and layoutShrink().
592 */
593 private void layout1(Node root, Rectangle bounds) {
594 if (root instanceof Leaf) {
595 root.setBounds(bounds);
596 } else if (root instanceof Split) {
597 Split split = (Split)root;
598 Iterator<Node> splitChildren = split.getChildren().iterator();
599 Rectangle childBounds = null;
600 int dividerSize = getDividerSize();
601
602 /* Layout the Split's child Nodes' along the X axis. The bounds
603 * of each child will have the same y coordinate and height as the
604 * layout1() bounds argument.
605 *
606 * Note: the column layout code - that's the "else" clause below
607 * this if, is identical to the X axis (rowLayout) code below.
608 */
609 if (split.isRowLayout()) {
610 double x = bounds.getX();
611 while(splitChildren.hasNext()) {
612 Node splitChild = splitChildren.next();
613 Divider dividerChild =
614 (splitChildren.hasNext()) ? (Divider)(splitChildren.next()) : null;
615
616 double childWidth = 0.0;
617 if (getFloatingDividers()) {
618 childWidth = preferredNodeSize(splitChild).getWidth();
619 } else {
620 if (dividerChild != null) {
621 childWidth = dividerChild.getBounds().getX() - x;
622 } else {
623 childWidth = split.getBounds().getMaxX() - x;
624 }
625 }
626 childBounds = boundsWithXandWidth(bounds, x, childWidth);
627 layout1(splitChild, childBounds);
628
629 if (getFloatingDividers() && (dividerChild != null)) {
630 double dividerX = childBounds.getMaxX();
631 Rectangle dividerBounds = boundsWithXandWidth(bounds, dividerX, dividerSize);
632 dividerChild.setBounds(dividerBounds);
633 }
634 if (dividerChild != null) {
635 x = dividerChild.getBounds().getMaxX();
636 }
637 }
638 } else {
639 /* Layout the Split's child Nodes' along the Y axis. The bounds
640 * of each child will have the same x coordinate and width as the
641 * layout1() bounds argument. The algorithm is identical to what's
642 * explained above, for the X axis case.
643 */
644 double y = bounds.getY();
645 while(splitChildren.hasNext()) {
646 Node splitChild = splitChildren.next();
647 Divider dividerChild =
648 (splitChildren.hasNext()) ? (Divider)(splitChildren.next()) : null;
649
650 double childHeight = 0.0;
651 if (getFloatingDividers()) {
652 childHeight = preferredNodeSize(splitChild).getHeight();
653 } else {
654 if (dividerChild != null) {
655 childHeight = dividerChild.getBounds().getY() - y;
656 } else {
657 childHeight = split.getBounds().getMaxY() - y;
658 }
659 }
660 childBounds = boundsWithYandHeight(bounds, y, childHeight);
661 layout1(splitChild, childBounds);
662
663 if (getFloatingDividers() && (dividerChild != null)) {
664 double dividerY = childBounds.getMaxY();
665 Rectangle dividerBounds = boundsWithYandHeight(bounds, dividerY, dividerSize);
666 dividerChild.setBounds(dividerBounds);
667 }
668 if (dividerChild != null) {
669 y = dividerChild.getBounds().getMaxY();
670 }
671 }
672 }
673 /* The bounds of the Split node root are set to be just
674 * big enough to contain all of its children, but only
675 * along the axis it's allocating space on. That's
676 * X for rows, Y for columns. The second pass of the
677 * layout algorithm - see layoutShrink()/layoutGrow()
678 * allocates extra space.
679 */
680 minimizeSplitBounds(split, bounds);
681 }
682 }
683
684 /**
685 * The specified Node is either the wrong type or was configured incorrectly.
686 */
687 public static class InvalidLayoutException extends RuntimeException {
688 private final transient Node node;
689 public InvalidLayoutException(String msg, Node node) {
690 super(msg);
691 this.node = node;
692 }
693 /**
694 * @return the invalid Node.
695 */
696 public Node getNode() {
697 return node;
698 }
699 }
700
701 private void throwInvalidLayout(String msg, Node node) {
702 throw new InvalidLayoutException(msg, node);
703 }
704
705 private void checkLayout(Node root) {
706 if (root instanceof Split) {
707 Split split = (Split)root;
708 if (split.getChildren().size() <= 2) {
709 throwInvalidLayout("Split must have > 2 children", root);
710 }
711 Iterator<Node> splitChildren = split.getChildren().iterator();
712 double weight = 0.0;
713 while(splitChildren.hasNext()) {
714 Node splitChild = splitChildren.next();
715 if (splitChild instanceof Divider) {
716 throwInvalidLayout("expected a Split or Leaf Node", splitChild);
717 }
718 if (splitChildren.hasNext()) {
719 Node dividerChild = splitChildren.next();
720 if (!(dividerChild instanceof Divider)) {
721 throwInvalidLayout("expected a Divider Node", dividerChild);
722 }
723 }
724 weight += splitChild.getWeight();
725 checkLayout(splitChild);
726 }
727 if (weight > 1.0 + 0.000000001) { /* add some epsilon to a double check */
728 throwInvalidLayout("Split children's total weight > 1.0", root);
729 }
730 }
731 }
732
733 /**
734 * Compute the bounds of all of the Split/Divider/Leaf Nodes in
735 * the layout model, and then set the bounds of each child component
736 * with a matching Leaf Node.
737 */
738 @Override
739 public void layoutContainer(Container parent) {
740 checkLayout(getModel());
741 Insets insets = parent.getInsets();
742 Dimension size = parent.getSize();
743 int width = size.width - (insets.left + insets.right);
744 int height = size.height - (insets.top + insets.bottom);
745 Rectangle bounds = new Rectangle(insets.left, insets.top, width, height);
746 layout1(getModel(), bounds);
747 layout2(getModel(), bounds);
748 }
749
750 private Divider dividerAt(Node root, int x, int y) {
751 if (root instanceof Divider) {
752 Divider divider = (Divider)root;
753 return (divider.getBounds().contains(x, y)) ? divider : null;
754 } else if (root instanceof Split) {
755 Split split = (Split)root;
756 for(Node child : split.getChildren()) {
757 if (child.getBounds().contains(x, y))
758 return dividerAt(child, x, y);
759 }
760 }
761 return null;
762 }
763
764 /**
765 * Return the Divider whose bounds contain the specified
766 * point, or null if there isn't one.
767 *
768 * @param x x coordinate
769 * @param y y coordinate
770 * @return the Divider at x,y
771 */
772 public Divider dividerAt(int x, int y) {
773 return dividerAt(getModel(), x, y);
774 }
775
776 private boolean nodeOverlapsRectangle(Node node, Rectangle r2) {
777 Rectangle r1 = node.getBounds();
778 return
779 (r1.x <= (r2.x + r2.width)) && ((r1.x + r1.width) >= r2.x) &&
780 (r1.y <= (r2.y + r2.height)) && ((r1.y + r1.height) >= r2.y);
781 }
782
783 private List<Divider> dividersThatOverlap(Node root, Rectangle r) {
784 if (nodeOverlapsRectangle(root, r) && (root instanceof Split)) {
785 List<Divider> dividers = new ArrayList<>();
786 for(Node child : ((Split)root).getChildren()) {
787 if (child instanceof Divider) {
788 if (nodeOverlapsRectangle(child, r)) {
789 dividers.add((Divider)child);
790 }
791 } else if (child instanceof Split) {
792 dividers.addAll(dividersThatOverlap(child, r));
793 }
794 }
795 return dividers;
796 } else
797 return Collections.emptyList();
798 }
799
800 /**
801 * Return the Dividers whose bounds overlap the specified
802 * Rectangle.
803 *
804 * @param r target Rectangle
805 * @return the Dividers that overlap r
806 * @throws IllegalArgumentException if the Rectangle is null
807 */
808 public List<Divider> dividersThatOverlap(Rectangle r) {
809 CheckParameterUtil.ensureParameterNotNull(r, "r");
810 return dividersThatOverlap(getModel(), r);
811 }
812
813 /**
814 * Base class for the nodes that model a MultiSplitLayout.
815 */
816 public abstract static class Node {
817 private Split parent = null;
818 private Rectangle bounds = new Rectangle();
819 private double weight = 0.0;
820
821 /**
822 * Returns the Split parent of this Node, or null.
823 *
824 * This method isn't called getParent(), in order to avoid problems
825 * with recursive object creation when using XmlDecoder.
826 *
827 * @return the value of the parent property.
828 * @see #parent_set
829 */
830 public Split parent_get() {
831 return parent;
832 }
833
834 /**
835 * Set the value of this Node's parent property. The default
836 * value of this property is null.
837 *
838 * This method isn't called setParent(), in order to avoid problems
839 * with recursive object creation when using XmlEncoder.
840 *
841 * @param parent a Split or null
842 * @see #parent_get
843 */
844 public void parent_set(Split parent) {
845 this.parent = parent;
846 }
847
848 /**
849 * Returns the bounding Rectangle for this Node.
850 *
851 * @return the value of the bounds property.
852 * @see #setBounds
853 */
854 public Rectangle getBounds() {
855 return new Rectangle(this.bounds);
856 }
857
858 /**
859 * Set the bounding Rectangle for this node. The value of
860 * bounds may not be null. The default value of bounds
861 * is equal to <code>new Rectangle(0,0,0,0)</code>.
862 *
863 * @param bounds the new value of the bounds property
864 * @throws IllegalArgumentException if bounds is null
865 * @see #getBounds
866 */
867 public void setBounds(Rectangle bounds) {
868 CheckParameterUtil.ensureParameterNotNull(bounds, "bounds");
869 this.bounds = new Rectangle(bounds);
870 }
871
872 /**
873 * Value between 0.0 and 1.0 used to compute how much space
874 * to add to this sibling when the layout grows or how
875 * much to reduce when the layout shrinks.
876 *
877 * @return the value of the weight property
878 * @see #setWeight
879 */
880 public double getWeight() {
881 return weight;
882 }
883
884 /**
885 * The weight property is a between 0.0 and 1.0 used to
886 * compute how much space to add to this sibling when the
887 * layout grows or how much to reduce when the layout shrinks.
888 * If rowLayout is true then this node's width grows
889 * or shrinks by (extraSpace * weight). If rowLayout is false,
890 * then the node's height is changed. The default value
891 * of weight is 0.0.
892 *
893 * @param weight a double between 0.0 and 1.0
894 * @throws IllegalArgumentException if weight is not between 0.0 and 1.0
895 * @see #getWeight
896 * @see MultiSplitLayout#layoutContainer
897 */
898 public void setWeight(double weight) {
899 if ((weight < 0.0)|| (weight > 1.0))
900 throw new IllegalArgumentException("invalid weight");
901 this.weight = weight;
902 }
903
904 private Node siblingAtOffset(int offset) {
905 Split parent = parent_get();
906 if (parent == null)
907 return null;
908 List<Node> siblings = parent.getChildren();
909 int index = siblings.indexOf(this);
910 if (index == -1)
911 return null;
912 index += offset;
913 return ((index > -1) && (index < siblings.size())) ? siblings.get(index) : null;
914 }
915
916 /**
917 * Return the Node that comes after this one in the parent's
918 * list of children, or null. If this node's parent is null,
919 * or if it's the last child, then return null.
920 *
921 * @return the Node that comes after this one in the parent's list of children.
922 * @see #previousSibling
923 * @see #parent_get
924 */
925 public Node nextSibling() {
926 return siblingAtOffset(+1);
927 }
928
929 /**
930 * Return the Node that comes before this one in the parent's
931 * list of children, or null. If this node's parent is null,
932 * or if it's the last child, then return null.
933 *
934 * @return the Node that comes before this one in the parent's list of children.
935 * @see #nextSibling
936 * @see #parent_get
937 */
938 public Node previousSibling() {
939 return siblingAtOffset(-1);
940 }
941 }
942
943 /**
944 * Defines a vertical or horizontal subdivision into two or more
945 * tiles.
946 */
947 public static class Split extends Node {
948 private List<Node> children = Collections.emptyList();
949 private boolean rowLayout = true;
950
951 /**
952 * Returns true if the this Split's children are to be
953 * laid out in a row: all the same height, left edge
954 * equal to the previous Node's right edge. If false,
955 * children are laid on in a column.
956 *
957 * @return the value of the rowLayout property.
958 * @see #setRowLayout
959 */
960 public boolean isRowLayout() {
961 return rowLayout;
962 }
963
964 /**
965 * Set the rowLayout property. If true, all of this Split's
966 * children are to be laid out in a row: all the same height,
967 * each node's left edge equal to the previous Node's right
968 * edge. If false, children are laid on in a column. Default value is true.
969 *
970 * @param rowLayout true for horizontal row layout, false for column
971 * @see #isRowLayout
972 */
973 public void setRowLayout(boolean rowLayout) {
974 this.rowLayout = rowLayout;
975 }
976
977 /**
978 * Returns this Split node's children. The returned value
979 * is not a reference to the Split's internal list of children
980 *
981 * @return the value of the children property.
982 * @see #setChildren
983 */
984 public List<Node> getChildren() {
985 return new ArrayList<>(children);
986 }
987
988 /**
989 * Set's the children property of this Split node. The parent
990 * of each new child is set to this Split node, and the parent
991 * of each old child (if any) is set to null. This method
992 * defensively copies the incoming List. Default value is an empty List.
993 *
994 * @param children List of children
995 * @throws IllegalArgumentException if children is null
996 * @see #getChildren
997 */
998 public void setChildren(List<Node> children) {
999 if (children == null)
1000 throw new IllegalArgumentException("children must be a non-null List");
1001 for(Node child : this.children) {
1002 child.parent_set(null);
1003 }
1004 this.children = new ArrayList<>(children);
1005 for(Node child : this.children) {
1006 child.parent_set(this);
1007 }
1008 }
1009
1010 /**
1011 * Convenience method that returns the last child whose weight
1012 * is &gt; 0.0.
1013 *
1014 * @return the last child whose weight is &gt; 0.0.
1015 * @see #getChildren
1016 * @see Node#getWeight
1017 */
1018 public final Node lastWeightedChild() {
1019 List<Node> children = getChildren();
1020 Node weightedChild = null;
1021 for(Node child : children) {
1022 if (child.getWeight() > 0.0) {
1023 weightedChild = child;
1024 }
1025 }
1026 return weightedChild;
1027 }
1028
1029 @Override
1030 public String toString() {
1031 int nChildren = getChildren().size();
1032 StringBuilder sb = new StringBuilder("MultiSplitLayout.Split");
1033 sb.append(isRowLayout() ? " ROW [" : " COLUMN [")
1034 .append(nChildren + ((nChildren == 1) ? " child" : " children"))
1035 .append("] ")
1036 .append(getBounds());
1037 return sb.toString();
1038 }
1039 }
1040
1041 /**
1042 * Models a java.awt Component child.
1043 */
1044 public static class Leaf extends Node {
1045 private String name = "";
1046
1047 /**
1048 * Create a Leaf node. The default value of name is "".
1049 */
1050 public Leaf() {
1051 // Name can be set later with setName()
1052 }
1053
1054 /**
1055 * Create a Leaf node with the specified name. Name can not be null.
1056 *
1057 * @param name value of the Leaf's name property
1058 * @throws IllegalArgumentException if name is null
1059 */
1060 public Leaf(String name) {
1061 CheckParameterUtil.ensureParameterNotNull(name, "name");
1062 this.name = name;
1063 }
1064
1065 /**
1066 * Return the Leaf's name.
1067 *
1068 * @return the value of the name property.
1069 * @see #setName
1070 */
1071 public String getName() {
1072 return name;
1073 }
1074
1075 /**
1076 * Set the value of the name property. Name may not be null.
1077 *
1078 * @param name value of the name property
1079 * @throws IllegalArgumentException if name is null
1080 */
1081 public void setName(String name) {
1082 CheckParameterUtil.ensureParameterNotNull(name, "name");
1083 this.name = name;
1084 }
1085
1086 @Override
1087 public String toString() {
1088 StringBuilder sb = new StringBuilder("MultiSplitLayout.Leaf");
1089 sb.append(" \"")
1090 .append(getName())
1091 .append("\" weight=")
1092 .append(getWeight())
1093 .append(' ')
1094 .append(getBounds());
1095 return sb.toString();
1096 }
1097 }
1098
1099 /**
1100 * Models a single vertical/horiztonal divider.
1101 */
1102 public static class Divider extends Node {
1103 /**
1104 * Convenience method, returns true if the Divider's parent
1105 * is a Split row (a Split with isRowLayout() true), false
1106 * otherwise. In other words if this Divider's major axis
1107 * is vertical, return true.
1108 *
1109 * @return true if this Divider is part of a Split row.
1110 */
1111 public final boolean isVertical() {
1112 Split parent = parent_get();
1113 return (parent != null) ? parent.isRowLayout() : false;
1114 }
1115
1116 /**
1117 * Dividers can't have a weight, they don't grow or shrink.
1118 * @throws UnsupportedOperationException always
1119 */
1120 @Override
1121 public void setWeight(double weight) {
1122 throw new UnsupportedOperationException();
1123 }
1124
1125 @Override
1126 public String toString() {
1127 return "MultiSplitLayout.Divider " + getBounds();
1128 }
1129 }
1130
1131 private static void throwParseException(StreamTokenizer st, String msg) throws Exception {
1132 throw new Exception("MultiSplitLayout.parseModel Error: " + msg);
1133 }
1134
1135 private static void parseAttribute(String name, StreamTokenizer st, Node node) throws Exception {
1136 if (st.nextToken() != '=') {
1137 throwParseException(st, "expected '=' after " + name);
1138 }
1139 if ("WEIGHT".equalsIgnoreCase(name)) {
1140 if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
1141 node.setWeight(st.nval);
1142 } else {
1143 throwParseException(st, "invalid weight");
1144 }
1145 } else if ("NAME".equalsIgnoreCase(name)) {
1146 if (st.nextToken() == StreamTokenizer.TT_WORD) {
1147 if (node instanceof Leaf) {
1148 ((Leaf)node).setName(st.sval);
1149 } else {
1150 throwParseException(st, "can't specify name for " + node);
1151 }
1152 } else {
1153 throwParseException(st, "invalid name");
1154 }
1155 } else {
1156 throwParseException(st, "unrecognized attribute \"" + name + "\"");
1157 }
1158 }
1159
1160 private static void addSplitChild(Split parent, Node child) {
1161 List<Node> children = new ArrayList<>(parent.getChildren());
1162 if (children.isEmpty()) {
1163 children.add(child);
1164 } else {
1165 children.add(new Divider());
1166 children.add(child);
1167 }
1168 parent.setChildren(children);
1169 }
1170
1171 private static void parseLeaf(StreamTokenizer st, Split parent) throws Exception {
1172 Leaf leaf = new Leaf();
1173 int token;
1174 while ((token = st.nextToken()) != StreamTokenizer.TT_EOF) {
1175 if (token == ')') {
1176 break;
1177 }
1178 if (token == StreamTokenizer.TT_WORD) {
1179 parseAttribute(st.sval, st, leaf);
1180 } else {
1181 throwParseException(st, "Bad Leaf: " + leaf);
1182 }
1183 }
1184 addSplitChild(parent, leaf);
1185 }
1186
1187 private static void parseSplit(StreamTokenizer st, Split parent) throws Exception {
1188 int token;
1189 while ((token = st.nextToken()) != StreamTokenizer.TT_EOF) {
1190 if (token == ')') {
1191 break;
1192 } else if (token == StreamTokenizer.TT_WORD) {
1193 if ("WEIGHT".equalsIgnoreCase(st.sval)) {
1194 parseAttribute(st.sval, st, parent);
1195 } else {
1196 addSplitChild(parent, new Leaf(st.sval));
1197 }
1198 } else if (token == '(') {
1199 if ((token = st.nextToken()) != StreamTokenizer.TT_WORD) {
1200 throwParseException(st, "invalid node type");
1201 }
1202 String nodeType = st.sval.toUpperCase(Locale.ENGLISH);
1203 if ("LEAF".equals(nodeType)) {
1204 parseLeaf(st, parent);
1205 } else if ("ROW".equals(nodeType) || "COLUMN".equals(nodeType)) {
1206 Split split = new Split();
1207 split.setRowLayout("ROW".equals(nodeType));
1208 addSplitChild(parent, split);
1209 parseSplit(st, split);
1210 } else {
1211 throwParseException(st, "unrecognized node type '" + nodeType + "'");
1212 }
1213 }
1214 }
1215 }
1216
1217 private static Node parseModel(Reader r) {
1218 StreamTokenizer st = new StreamTokenizer(r);
1219 try {
1220 Split root = new Split();
1221 parseSplit(st, root);
1222 return root.getChildren().get(0);
1223 } catch (Exception e) {
1224 Main.error(e);
1225 } finally {
1226 Utils.close(r);
1227 }
1228 return null;
1229 }
1230
1231 /**
1232 * A convenience method that converts a string to a
1233 * MultiSplitLayout model (a tree of Nodes) using a
1234 * a simple syntax. Nodes are represented by
1235 * parenthetical expressions whose first token
1236 * is one of ROW/COLUMN/LEAF. ROW and COLUMN specify
1237 * horizontal and vertical Split nodes respectively,
1238 * LEAF specifies a Leaf node. A Leaf's name and
1239 * weight can be specified with attributes,
1240 * name=<i>myLeafName</i> weight=<i>myLeafWeight</i>.
1241 * Similarly, a Split's weight can be specified with
1242 * weight=<i>mySplitWeight</i>.
1243 *
1244 * <p> For example, the following expression generates
1245 * a horizontal Split node with three children:
1246 * the Leafs named left and right, and a Divider in
1247 * between:
1248 * <pre>
1249 * (ROW (LEAF name=left) (LEAF name=right weight=1.0))
1250 * </pre>
1251 *
1252 * <p> Dividers should not be included in the string,
1253 * they're added automatcially as needed. Because
1254 * Leaf nodes often only need to specify a name, one
1255 * can specify a Leaf by just providing the name.
1256 * The previous example can be written like this:
1257 * <pre>
1258 * (ROW left (LEAF name=right weight=1.0))
1259 * </pre>
1260 *
1261 * <p>Here's a more complex example. One row with
1262 * three elements, the first and last of which are columns
1263 * with two leaves each:
1264 * <pre>
1265 * (ROW (COLUMN weight=0.5 left.top left.bottom)
1266 * (LEAF name=middle)
1267 * (COLUMN weight=0.5 right.top right.bottom))
1268 * </pre>
1269 *
1270 *
1271 * <p> This syntax is not intended for archiving or
1272 * configuration files . It's just a convenience for
1273 * examples and tests.
1274 *
1275 * @return the Node root of a tree based on s.
1276 */
1277 public static Node parseModel(String s) {
1278 return parseModel(new StringReader(s));
1279 }
1280}
Note: See TracBrowser for help on using the repository browser.