1 package net.miginfocom.layout;
3 import java.io.IOException;
4 import java.io.ObjectInput;
5 import java.io.ObjectOutput;
6 import java.util.TreeSet;
7 import java.util.WeakHashMap;
12 * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com)
13 * All rights reserved.
15 * Redistribution and use in source and binary forms, with or without modification,
16 * are permitted provided that the following conditions are met:
17 * Redistributions of source code must retain the above copyright notice, this list
18 * of conditions and the following disclaimer.
19 * Redistributions in binary form must reproduce the above copyright notice, this
20 * list of conditions and the following disclaimer in the documentation and/or other
21 * materials provided with the distribution.
22 * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
23 * used to endorse or promote products derived from this software without specific
24 * prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
30 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
32 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
38 * @author Mikael Grev, MiG InfoCom AB
42 /** A utility class that has only static helper methods.
44 public final class LayoutUtil
46 /** A substitute value for a really large value. Integer.MAX_VALUE is not used since that means a lot of defensive code
47 * for potential overflow must exist in many places. This value is large enough for being unreasonable yet it is hard to
50 public static final int INF = (Integer.MAX_VALUE >> 10) - 100; // To reduce likelihood of overflow errors when calculating.
52 /** Tag int for a value that in considered "not set". Used as "null" element in int arrays.
54 static final int NOT_SET = Integer.MIN_VALUE + 12346; // Magic value...
56 // Index for the different sizes
57 public static final int MIN = 0;
58 public static final int PREF = 1;
59 public static final int MAX = 2;
61 public static final int HORIZONTAL = 0;
62 public static final int VERTICAL = 1;
64 private static volatile WeakHashMap<Object, String> CR_MAP = null;
65 private static volatile WeakHashMap<Object, Boolean> DT_MAP = null; // The Containers that have design time. Value not used.
66 private static int eSz = 0;
67 private static int globalDebugMillis = 0;
68 public static final boolean HAS_BEANS = hasBeans();
70 private static boolean hasBeans()
73 // LayoutUtil.class.getClassLoader().loadClass("java.beans.Beans");
75 // } catch (Throwable e) {
84 /** Returns the current version of MiG Layout.
85 * @return The current version of MiG Layout. E.g. "3.6.3" or "4.0"
87 public static String getVersion()
92 /** If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
94 * @return The current debug milliseconds.
95 * @see LC#setDebugMillis(int)
97 public static int getGlobalDebugMillis()
99 return globalDebugMillis;
102 /** If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
105 * Note! This is a passive value and will be read by panels when the needed, which is normally
106 * when they repaint/layout.
107 * @param millis The new debug milliseconds. 0 turns of global debug and leaves debug up to every
109 * @see LC#setDebugMillis(int)
111 public static void setGlobalDebugMillis(int millis)
113 globalDebugMillis = millis;
116 /** Sets if design time is turned on for a Container in {@link ContainerWrapper}.
117 * @param cw The container to set design time for. <code>null</code> is legal and can be used as
118 * a key to turn on/off design time "in general". Note though that design time "in general" is
119 * always on as long as there is at least one ContainerWrapper with design time.
121 * <strong>If this method has not ever been called it will default to what
122 * <code>Beans.isDesignTime()</code> returns.</strong> This means that if you call
123 * this method you indicate that you will take responsibility for the design time value.
124 * @param b <code>true</code> means design time on.
126 public static void setDesignTime(ContainerWrapper cw, boolean b)
129 DT_MAP = new WeakHashMap<Object, Boolean>();
131 DT_MAP.put((cw != null ? cw.getComponent() : null), b);
134 /** Returns if design time is turned on for a Container in {@link ContainerWrapper}.
135 * @param cw The container to set design time for. <code>null</code> is legal will return <code>true</code>
136 * if there is at least one <code>ContainerWrapper</code> (or <code>null</code>) that have design time
138 * @return If design time is set for <code>cw</code>.
140 public static boolean isDesignTime(ContainerWrapper cw)
143 return false;//HAS_BEANS && Beans.isDesignTime();
145 // assume design time "in general" (cw is null) if there is at least one container with design time
146 // (for storing constraints creation strings in method putCCString())
147 if (cw == null && DT_MAP != null && !DT_MAP.isEmpty() )
150 if (cw != null && DT_MAP.containsKey(cw.getComponent()) == false)
153 Boolean b = DT_MAP.get(cw != null ? cw.getComponent() : null);
154 return b != null && b;
157 /** The size of an empty row or columns in a grid during design time.
158 * @return The number of pixels. Default is 15.
160 public static int getDesignTimeEmptySize()
165 /** The size of an empty row or columns in a grid during design time.
166 * @param pixels The number of pixels. Default is 0 (it was 15 prior to v3.7.2, but since that meant different behaviour
167 * under design time by default it was changed to be 0, same as non-design time). IDE vendors can still set it to 15 to
168 * get the old behaviour.
170 public static void setDesignTimeEmptySize(int pixels)
175 /** Associates <code>con</code> with the creation string <code>s</code>. The <code>con</code> object should
176 * probably have an equals method that compares identities or <code>con</code> objects that .equals() will only
177 * be able to have <b>one</b> creation string.
179 * If {@link LayoutUtil#isDesignTime(ContainerWrapper)} returns <code>false</code> the method does nothing.
180 * @param con The object. if <code>null</code> the method does nothing.
181 * @param s The creation string. if <code>null</code> the method does nothing.
183 static void putCCString(Object con, String s)
185 if (s != null && con != null && isDesignTime(null)) {
187 CR_MAP = new WeakHashMap<Object, String>(64);
193 // /** Sets/add the persistence delegates to be used for a class.
194 // * @param c The class to set the registered delegate for.
195 // * @param del The new delegate or <code>null</code> to erase to old one.
197 // static synchronized void setDelegate(Class<?> c, PersistenceDelegate del)
200 // Introspector.getBeanInfo(c, Introspector.IGNORE_ALL_BEANINFO).getBeanDescriptor().setValue("persistenceDelegate", del);
201 // } catch (Exception ignored) {
205 /** Returns strings set with {@link #putCCString(Object, String)} or <code>null</code> if nothing is associated or
206 * {@link LayoutUtil#isDesignTime(ContainerWrapper)} returns <code>false</code>.
207 * @param con The constrain object.
208 * @return The creation string or <code>null</code> if nothing is registered with the <code>con</code> object.
210 static String getCCString(Object con)
212 return CR_MAP != null ? CR_MAP.get(con) : null;
215 static void throwCC()
217 throw new IllegalStateException("setStoreConstraintData(true) must be set for strings to be saved.");
220 /** Takes a number on min/preferred/max sizes and resize constraints and returns the calculated sizes which sum should add up to <code>bounds</code>. Whether the sum
221 * will actually equal <code>bounds</code> is dependent on the pref/max sizes and resize constraints.
222 * @param sizes [ix],[MIN][PREF][MAX]. Grid.CompWrap.NOT_SET will be treated as N/A or 0. A "[MIN][PREF][MAX]" array with null elements will be interpreted as very flexible (no bounds)
223 * but if the array itself is null it will not get any size.
224 * @param resConstr Elements can be <code>null</code> and the whole array can be <code>null</code>. <code>null</code> means that the size will not be flexible at all.
225 * Can have length less than <code>sizes</code> in which case the last element should be used for the elements missing.
226 * @param defPushWeights If there is no grow weight for a resConstr the corresponding value of this array is used.
227 * These forced resConstr will be grown last though and only if needed to fill to the bounds.
228 * @param startSizeType The initial size to use. E.g. {@link net.miginfocom.layout.LayoutUtil#MIN}.
229 * @param bounds To use for relative sizes.
230 * @return The sizes. Array length will match <code>sizes</code>.
232 static int[] calculateSerial(int[][] sizes, ResizeConstraint[] resConstr, Float[] defPushWeights, int startSizeType, int bounds)
234 float[] lengths = new float[sizes.length]; // heights/widths that are set
235 float usedLength = 0.0f;
237 // Give all preferred size to start with
238 for (int i = 0; i < sizes.length; i++) {
239 if (sizes[i] != null) {
240 float len = sizes[i][startSizeType] != NOT_SET ? sizes[i][startSizeType] : 0;
241 int newSizeBounded = getBrokenBoundary(len, sizes[i][MIN], sizes[i][MAX]);
242 if (newSizeBounded != NOT_SET)
243 len = newSizeBounded;
250 int useLengthI = Math.round(usedLength);
251 if (useLengthI != bounds && resConstr != null) {
252 boolean isGrow = useLengthI < bounds;
254 // Create a Set with the available priorities
255 TreeSet<Integer> prioList = new TreeSet<Integer>();
256 for (int i = 0; i < sizes.length; i++) {
257 ResizeConstraint resC = (ResizeConstraint) getIndexSafe(resConstr, i);
259 prioList.add(isGrow ? resC.growPrio : resC.shrinkPrio);
261 Integer[] prioIntegers = prioList.toArray(new Integer[prioList.size()]);
263 for (int force = 0; force <= ((isGrow && defPushWeights != null) ? 1 : 0); force++) { // Run twice if defGrow and the need for growing.
264 for (int pr = prioIntegers.length - 1; pr >= 0; pr--) {
265 int curPrio = prioIntegers[pr];
267 float totWeight = 0f;
268 Float[] resizeWeight = new Float[sizes.length];
269 for (int i = 0; i < sizes.length; i++) {
270 if (sizes[i] == null) // if no min/pref/max size at all do not grow or shrink.
273 ResizeConstraint resC = (ResizeConstraint) getIndexSafe(resConstr, i);
275 int prio = isGrow ? resC.growPrio : resC.shrinkPrio;
277 if (curPrio == prio) {
279 resizeWeight[i] = (force == 0 || resC.grow != null) ? resC.grow : (defPushWeights[i < defPushWeights.length ? i : defPushWeights.length - 1]);
281 resizeWeight[i] = resC.shrink;
283 if (resizeWeight[i] != null)
284 totWeight += resizeWeight[i];
289 if (totWeight > 0f) {
292 float toChange = bounds - usedLength;
294 float changedWeight = 0f;
295 for (int i = 0; i < sizes.length && totWeight > 0.0001f; i++) {
297 Float weight = resizeWeight[i];
298 if (weight != null) {
299 float sizeDelta = toChange * weight / totWeight;
300 float newSize = lengths[i] + sizeDelta;
302 if (sizes[i] != null) {
303 int newSizeBounded = getBrokenBoundary(newSize, sizes[i][MIN], sizes[i][MAX]);
304 if (newSizeBounded != NOT_SET) {
305 resizeWeight[i] = null;
307 changedWeight += weight;
308 newSize = newSizeBounded;
309 sizeDelta = newSize - lengths[i];
313 lengths[i] = newSize;
314 usedLength += sizeDelta;
317 totWeight -= changedWeight;
323 return roundSizes(lengths);
326 static Object getIndexSafe(Object[] arr, int ix)
328 return arr != null ? arr[ix < arr.length ? ix : arr.length - 1] : null;
331 /** Returns the broken boundary if <code>sz</code> is outside the boundaries <code>lower</code> or <code>upper</code>. If both boundaries
332 * are broken, the lower one is returned. If <code>sz</code> is < 0 then <code>new Float(0f)</code> is returned so that no sizes can be
334 * @param sz The size to check
335 * @param lower The lower boundary (or <code>null</code> for no boundary).
336 * @param upper The upper boundary (or <code>null</code> for no boundary).
337 * @return The broken boundary.
339 private static int getBrokenBoundary(float sz, int lower, int upper)
341 if (lower != NOT_SET) {
344 } else if (sz < 0f) {
348 if (upper != NOT_SET && sz > upper)
355 static int sum(int[] terms, int start, int len)
358 for (int i = start, iSz = start + len; i < iSz; i++)
363 static int sum(int[] terms)
365 return sum(terms, 0, terms.length);
368 /** Keeps f within min and max. Min is of higher priority if min is larger than max.
369 * @param f The value to clamp
372 * @return The clamped value, between min and max.
374 static float clamp(float f, float min, float max)
376 return Math.max(min, Math.min(f, max));
379 /** Keeps i within min and max. Min is of higher priority if min is larger than max.
380 * @param i The value to clamp
383 * @return The clamped value, between min and max.
385 static int clamp(int i, int min, int max)
387 return Math.max(min, Math.min(i, max));
390 public static int getSizeSafe(int[] sizes, int sizeType)
392 if (sizes == null || sizes[sizeType] == NOT_SET)
393 return sizeType == MAX ? LayoutUtil.INF : 0;
394 return sizes[sizeType];
397 static BoundSize derive(BoundSize bs, UnitValue min, UnitValue pref, UnitValue max)
399 if (bs == null || bs.isUnset())
400 return new BoundSize(min, pref, max, null);
402 return new BoundSize(
403 min != null ? min : bs.getMin(),
404 pref != null ? pref : bs.getPreferred(),
405 max != null ? max : bs.getMax(),
410 /** Returns if left-to-right orientation is used. If not set explicitly in the layout constraints the Locale
411 * of the <code>parent</code> is used.
412 * @param lc The constraint if there is one. Can be <code>null</code>.
413 * @param container The parent that may be used to get the left-to-right if lc does not specify this.
414 * @return If left-to-right orientation is currently used.
416 public static boolean isLeftToRight(LC lc, ContainerWrapper container)
418 if (lc != null && lc.getLeftToRight() != null)
419 return lc.getLeftToRight();
421 return container == null || container.isLeftToRight();
424 /** Round a number of float sizes into int sizes so that the total length match up
425 * @param sizes The sizes to round
426 * @return An array of equal length as <code>sizes</code>.
428 static int[] roundSizes(float[] sizes)
430 int[] retInts = new int[sizes.length];
433 for (int i = 0; i < retInts.length; i++) {
434 int posI = (int) (posD + 0.5f);
438 retInts[i] = (int) (posD + 0.5f) - posI;
444 /** Safe equals. null == null, but null never equals anything else.
445 * @param o1 The first object. May be <code>null</code>.
446 * @param o2 The second object. May be <code>null</code>.
447 * @return Returns <code>true</code> if <code>o1</code> and <code>o2</code> are equal (using .equals()) or both are <code>null</code>.
449 static boolean equals(Object o1, Object o2)
451 return o1 == o2 || (o1 != null && o2 != null && o1.equals(o2));
454 // static int getBaselineCorrect(Component comp)
456 // Dimension pSize = comp.getPreferredSize();
457 // int baseline = comp.getBaseline(pSize.width, pSize.height);
458 // int nextBaseline = comp.getBaseline(pSize.width, pSize.height + 1);
460 // // Amount to add to height when calculating where baseline
461 // // lands for a particular height:
464 // // Where the baseline is relative to the mid point
465 // int baselineOffset = baseline - pSize.height / 2;
466 // if (pSize.height % 2 == 0 && baseline != nextBaseline) {
468 // } else if (pSize.height % 2 == 1 && baseline == nextBaseline) {
473 // // The following calculates where the baseline lands for
475 // return (pSize.height + padding) / 2 + baselineOffset;
479 /** Returns the insets for the side.
480 * @param side top == 0, left == 1, bottom = 2, right = 3.
481 * @param getDefault If <code>true</code> the default insets will get retrieved if <code>lc</code> has none set.
482 * @return The insets for the side. Never <code>null</code>.
484 static UnitValue getInsets(LC lc, int side, boolean getDefault)
486 UnitValue[] i = lc.getInsets();
487 return (i != null && i[side] != null) ? i[side] : (getDefault ? PlatformDefaults.getPanelInsets(side) : UnitValue.ZERO);
490 // /** Writes the object and CLOSES the stream. Uses the persistence delegate registered in this class.
491 // * @param os The stream to write to. Will be closed.
492 // * @param o The object to be serialized.
493 // * @param listener The listener to receive the exceptions if there are any. If <code>null</code> not used.
495 // static void writeXMLObject(OutputStream os, Object o, ExceptionListener listener)
497 // ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
498 // Thread.currentThread().setContextClassLoader(LayoutUtil.class.getClassLoader());
500 // XMLEncoder encoder = new XMLEncoder(os);
502 // if (listener != null)
503 // encoder.setExceptionListener(listener);
505 // encoder.writeObject(o);
506 // encoder.close(); // Must be closed to write.
508 // Thread.currentThread().setContextClassLoader(oldClassLoader);
511 // private static ByteArrayOutputStream writeOutputStream = null;
512 // /** Writes an object to XML.
513 // * @param out The object out to write to. Will not be closed.
514 // * @param o The object to write.
516 public static synchronized void writeAsXML(ObjectOutput out, Object o) throws IOException
518 // if (writeOutputStream == null)
519 // writeOutputStream = new ByteArrayOutputStream(16384);
521 // writeOutputStream.reset();
523 // writeXMLObject(writeOutputStream, o, new ExceptionListener() {
525 // public void exceptionThrown(Exception e) {
526 // e.printStackTrace();
529 // byte[] buf = writeOutputStream.toByteArray();
531 // out.writeInt(buf.length);
535 // private static byte[] readBuf = null;
536 /** Reads an object from <code>in</code> using the
537 * @param in The object input to read from.
538 * @return The object. Never <code>null</code>.
539 * @throws IOException If there was a problem saving as XML
541 public static synchronized Object readAsXML(ObjectInput in) throws IOException
543 // if (readBuf == null)
544 // readBuf = new byte[16384];
546 // Thread f cThread = Thread.currentThread();
547 // ClassLoader oldCL = null;
550 // oldCL = cThread.getContextClassLoader();
551 // cThread.setContextClassLoader(LayoutUtil.class.getClassLoader());
552 // } catch(SecurityException ignored) {
557 // int length = in.readInt();
558 // if (length > readBuf.length)
559 // readBuf = new byte[length];
561 // in.readFully(readBuf, 0, length);
563 // o = new XMLDecoder(new ByteArrayInputStream(readBuf, 0, length)).readObject();
565 // } catch(EOFException ignored) {
568 // if (oldCL != null)
569 // cThread.setContextClassLoader(oldCL);
575 // private static final IdentityHashMap<Object, Object> SER_MAP = new IdentityHashMap<Object, Object>(2);
577 // /** Sets the serialized object and associates it with <code>caller</code>.
578 // * @param caller The object created <code>o</code>
579 // * @param o The just serialized object.
581 public static void setSerializedObject(Object caller, Object o)
583 // synchronized(SER_MAP) {
584 // SER_MAP.put(caller, o);
588 /** Returns the serialized object that are associated with <code>caller</code>. It also removes it from the list.
589 * @param caller The original creator of the object.
590 * @return The object.
592 public static Object getSerializedObject(Object caller)
595 // synchronized(SER_MAP) {
596 // return SER_MAP.remove(caller);