1 package net.miginfocom.layout;
3 //import java.beans.Beans;
4 //import java.beans.ExceptionListener;
5 //import java.beans.Introspector;
6 //import java.beans.PersistenceDelegate;
7 //import java.beans.XMLDecoder;
8 //import java.beans.XMLEncoder;
9 //import java.io.ByteArrayInputStream;
10 //import java.io.ByteArrayOutputStream;
11 import java.io.EOFException;
12 import java.io.IOException;
13 //import java.io.ObjectInput;
14 //import java.io.ObjectOutput;
15 //import java.io.OutputStream;
16 import java.util.IdentityHashMap;
17 import java.util.TreeSet;
18 import java.util.WeakHashMap;
23 * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com)
24 * All rights reserved.
26 * Redistribution and use in source and binary forms, with or without modification,
27 * are permitted provided that the following conditions are met:
28 * Redistributions of source code must retain the above copyright notice, this list
29 * of conditions and the following disclaimer.
30 * Redistributions in binary form must reproduce the above copyright notice, this
31 * list of conditions and the following disclaimer in the documentation and/or other
32 * materials provided with the distribution.
33 * Neither the name of the MiG InfoCom AB nor the names of its contributors may be
34 * used to endorse or promote products derived from this software without specific
35 * prior written permission.
37 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
39 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
40 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
41 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
42 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
43 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
44 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
49 * @author Mikael Grev, MiG InfoCom AB
53 /** A utility class that has only static helper methods.
55 public final class LayoutUtil
57 /** A substitute value for a really large value. Integer.MAX_VALUE is not used since that means a lot of defensive code
58 * for potential overflow must exist in many places. This value is large enough for being unreasonable yet it is hard to
61 public static final int INF = (Integer.MAX_VALUE >> 10) - 100; // To reduce likelihood of overflow errors when calculating.
63 /** Tag int for a value that in considered "not set". Used as "null" element in int arrays.
65 static final int NOT_SET = Integer.MIN_VALUE + 12346; // Magic value...
67 // Index for the different sizes
68 public static final int MIN = 0;
69 public static final int PREF = 1;
70 public static final int MAX = 2;
72 public static final int HORIZONTAL = 0;
73 public static final int VERTICAL = 1;
75 private static volatile WeakHashMap<Object, String> CR_MAP = null;
76 private static volatile WeakHashMap<Object, Boolean> DT_MAP = null; // The Containers that have design time. Value not used.
77 private static int eSz = 0;
78 private static int globalDebugMillis = 0;
80 // public static final boolean HAS_BEANS = hasBeans();
82 // private static boolean hasBeans()
85 // LayoutUtil.class.getClassLoader().loadClass("java.beans.Beans");
87 // } catch (Throwable e) {
96 /** Returns the current version of MiG Layout.
97 * @return The current version of MiG Layout. E.g. "3.6.3" or "4.0"
99 public static String getVersion()
104 /** If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
106 * @return The current debug milliseconds.
107 * @see LC#setDebugMillis(int)
109 public static int getGlobalDebugMillis()
111 return globalDebugMillis;
114 /** If global debug should be on or off. If > 0 then debug is turned on for all MigLayout
117 * Note! This is a passive value and will be read by panels when the needed, which is normally
118 * when they repaint/layout.
119 * @param millis The new debug milliseconds. 0 turns of global debug and leaves debug up to every
121 * @see LC#setDebugMillis(int)
123 public static void setGlobalDebugMillis(int millis)
125 globalDebugMillis = millis;
128 /** Sets if design time is turned on for a Container in {@link ContainerWrapper}.
129 * @param cw The container to set design time for. <code>null</code> is legal and can be used as
130 * a key to turn on/off design time "in general". Note though that design time "in general" is
131 * always on as long as there is at least one ContainerWrapper with design time.
133 * <strong>If this method has not ever been called it will default to what
134 * <code>Beans.isDesignTime()</code> returns.</strong> This means that if you call
135 * this method you indicate that you will take responsibility for the design time value.
136 * @param b <code>true</code> means design time on.
138 public static void setDesignTime(ContainerWrapper cw, boolean b)
141 DT_MAP = new WeakHashMap<Object, Boolean>();
143 DT_MAP.put((cw != null ? cw.getComponent() : null), b);
146 /** Returns if design time is turned on for a Container in {@link ContainerWrapper}.
147 * @param cw The container to set design time for. <code>null</code> is legal will return <code>true</code>
148 * if there is at least one <code>ContainerWrapper</code> (or <code>null</code>) that have design time
150 * @return If design time is set for <code>cw</code>.
152 public static boolean isDesignTime(ContainerWrapper cw)
155 return false;// BH 2018 //HAS_BEANS && Beans.isDesignTime();
157 // assume design time "in general" (cw is null) if there is at least one container with design time
158 // (for storing constraints creation strings in method putCCString())
159 if (cw == null && DT_MAP != null && !DT_MAP.isEmpty() )
162 if (cw != null && DT_MAP.containsKey(cw.getComponent()) == false)
165 Boolean b = DT_MAP.get(cw != null ? cw.getComponent() : null);
166 return b != null && b;
169 /** The size of an empty row or columns in a grid during design time.
170 * @return The number of pixels. Default is 15.
172 public static int getDesignTimeEmptySize()
177 /** The size of an empty row or columns in a grid during design time.
178 * @param pixels The number of pixels. Default is 0 (it was 15 prior to v3.7.2, but since that meant different behaviour
179 * 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
180 * get the old behaviour.
182 public static void setDesignTimeEmptySize(int pixels)
187 /** Associates <code>con</code> with the creation string <code>s</code>. The <code>con</code> object should
188 * probably have an equals method that compares identities or <code>con</code> objects that .equals() will only
189 * be able to have <b>one</b> creation string.
191 * If {@link LayoutUtil#isDesignTime(ContainerWrapper)} returns <code>false</code> the method does nothing.
192 * @param con The object. if <code>null</code> the method does nothing.
193 * @param s The creation string. if <code>null</code> the method does nothing.
195 static void putCCString(Object con, String s)
197 if (s != null && con != null && isDesignTime(null)) {
199 CR_MAP = new WeakHashMap<Object, String>(64);
205 // /** Sets/add the persistence delegates to be used for a class.
206 // * @param c The class to set the registered delegate for.
207 // * @param del The new delegate or <code>null</code> to erase to old one.
209 // static synchronized void setDelegate(Class<?> c, PersistenceDelegate del)
212 // Introspector.getBeanInfo(c, Introspector.IGNORE_ALL_BEANINFO).getBeanDescriptor().setValue("persistenceDelegate", del);
213 // } catch (Exception ignored) {
217 /** Returns strings set with {@link #putCCString(Object, String)} or <code>null</code> if nothing is associated or
218 * {@link LayoutUtil#isDesignTime(ContainerWrapper)} returns <code>false</code>.
219 * @param con The constrain object.
220 * @return The creation string or <code>null</code> if nothing is registered with the <code>con</code> object.
222 static String getCCString(Object con)
224 return CR_MAP != null ? CR_MAP.get(con) : null;
227 static void throwCC()
229 throw new IllegalStateException("setStoreConstraintData(true) must be set for strings to be saved.");
232 /** 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
233 * will actually equal <code>bounds</code> is dependent on the pref/max sizes and resize constraints.
234 * @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)
235 * but if the array itself is null it will not get any size.
236 * @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.
237 * Can have length less than <code>sizes</code> in which case the last element should be used for the elements missing.
238 * @param defPushWeights If there is no grow weight for a resConstr the corresponding value of this array is used.
239 * These forced resConstr will be grown last though and only if needed to fill to the bounds.
240 * @param startSizeType The initial size to use. E.g. {@link net.miginfocom.layout.LayoutUtil#MIN}.
241 * @param bounds To use for relative sizes.
242 * @return The sizes. Array length will match <code>sizes</code>.
244 static int[] calculateSerial(int[][] sizes, ResizeConstraint[] resConstr, Float[] defPushWeights, int startSizeType, int bounds)
246 float[] lengths = new float[sizes.length]; // heights/widths that are set
247 float usedLength = 0.0f;
249 // Give all preferred size to start with
250 for (int i = 0; i < sizes.length; i++) {
251 if (sizes[i] != null) {
252 float len = sizes[i][startSizeType] != NOT_SET ? sizes[i][startSizeType] : 0;
253 int newSizeBounded = getBrokenBoundary(len, sizes[i][MIN], sizes[i][MAX]);
254 if (newSizeBounded != NOT_SET)
255 len = newSizeBounded;
262 int useLengthI = Math.round(usedLength);
263 if (useLengthI != bounds && resConstr != null) {
264 boolean isGrow = useLengthI < bounds;
266 // Create a Set with the available priorities
267 TreeSet<Integer> prioList = new TreeSet<Integer>();
268 for (int i = 0; i < sizes.length; i++) {
269 ResizeConstraint resC = (ResizeConstraint) getIndexSafe(resConstr, i);
271 prioList.add(isGrow ? resC.growPrio : resC.shrinkPrio);
273 Integer[] prioIntegers = prioList.toArray(new Integer[prioList.size()]);
275 for (int force = 0; force <= ((isGrow && defPushWeights != null) ? 1 : 0); force++) { // Run twice if defGrow and the need for growing.
276 for (int pr = prioIntegers.length - 1; pr >= 0; pr--) {
277 int curPrio = prioIntegers[pr];
279 float totWeight = 0f;
280 Float[] resizeWeight = new Float[sizes.length];
281 for (int i = 0; i < sizes.length; i++) {
282 if (sizes[i] == null) // if no min/pref/max size at all do not grow or shrink.
285 ResizeConstraint resC = (ResizeConstraint) getIndexSafe(resConstr, i);
287 int prio = isGrow ? resC.growPrio : resC.shrinkPrio;
289 if (curPrio == prio) {
291 resizeWeight[i] = (force == 0 || resC.grow != null) ? resC.grow : (defPushWeights[i < defPushWeights.length ? i : defPushWeights.length - 1]);
293 resizeWeight[i] = resC.shrink;
295 if (resizeWeight[i] != null)
296 totWeight += resizeWeight[i];
301 if (totWeight > 0f) {
304 float toChange = bounds - usedLength;
306 float changedWeight = 0f;
307 for (int i = 0; i < sizes.length && totWeight > 0.0001f; i++) {
309 Float weight = resizeWeight[i];
310 if (weight != null) {
311 float sizeDelta = toChange * weight / totWeight;
312 float newSize = lengths[i] + sizeDelta;
314 if (sizes[i] != null) {
315 int newSizeBounded = getBrokenBoundary(newSize, sizes[i][MIN], sizes[i][MAX]);
316 if (newSizeBounded != NOT_SET) {
317 resizeWeight[i] = null;
319 changedWeight += weight;
320 newSize = newSizeBounded;
321 sizeDelta = newSize - lengths[i];
325 lengths[i] = newSize;
326 usedLength += sizeDelta;
329 totWeight -= changedWeight;
335 return roundSizes(lengths);
338 static Object getIndexSafe(Object[] arr, int ix)
340 return arr != null ? arr[ix < arr.length ? ix : arr.length - 1] : null;
343 /** Returns the broken boundary if <code>sz</code> is outside the boundaries <code>lower</code> or <code>upper</code>. If both boundaries
344 * 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
346 * @param sz The size to check
347 * @param lower The lower boundary (or <code>null</code> for no boundary).
348 * @param upper The upper boundary (or <code>null</code> for no boundary).
349 * @return The broken boundary.
351 private static int getBrokenBoundary(float sz, int lower, int upper)
353 if (lower != NOT_SET) {
356 } else if (sz < 0f) {
360 if (upper != NOT_SET && sz > upper)
367 static int sum(int[] terms, int start, int len)
370 for (int i = start, iSz = start + len; i < iSz; i++)
375 static int sum(int[] terms)
377 return sum(terms, 0, terms.length);
380 /** Keeps f within min and max. Min is of higher priority if min is larger than max.
381 * @param f The value to clamp
384 * @return The clamped value, between min and max.
386 static float clamp(float f, float min, float max)
388 return Math.max(min, Math.min(f, max));
391 /** Keeps i within min and max. Min is of higher priority if min is larger than max.
392 * @param i The value to clamp
395 * @return The clamped value, between min and max.
397 static int clamp(int i, int min, int max)
399 return Math.max(min, Math.min(i, max));
402 public static int getSizeSafe(int[] sizes, int sizeType)
404 if (sizes == null || sizes[sizeType] == NOT_SET)
405 return sizeType == MAX ? LayoutUtil.INF : 0;
406 return sizes[sizeType];
409 static BoundSize derive(BoundSize bs, UnitValue min, UnitValue pref, UnitValue max)
411 if (bs == null || bs.isUnset())
412 return new BoundSize(min, pref, max, null);
414 return new BoundSize(
415 min != null ? min : bs.getMin(),
416 pref != null ? pref : bs.getPreferred(),
417 max != null ? max : bs.getMax(),
422 /** Returns if left-to-right orientation is used. If not set explicitly in the layout constraints the Locale
423 * of the <code>parent</code> is used.
424 * @param lc The constraint if there is one. Can be <code>null</code>.
425 * @param container The parent that may be used to get the left-to-right if lc does not specify this.
426 * @return If left-to-right orientation is currently used.
428 public static boolean isLeftToRight(LC lc, ContainerWrapper container)
430 if (lc != null && lc.getLeftToRight() != null)
431 return lc.getLeftToRight();
433 return container == null || container.isLeftToRight();
436 /** Round a number of float sizes into int sizes so that the total length match up
437 * @param sizes The sizes to round
438 * @return An array of equal length as <code>sizes</code>.
440 static int[] roundSizes(float[] sizes)
442 int[] retInts = new int[sizes.length];
445 for (int i = 0; i < retInts.length; i++) {
446 int posI = (int) (posD + 0.5f);
450 retInts[i] = (int) (posD + 0.5f) - posI;
456 /** Safe equals. null == null, but null never equals anything else.
457 * @param o1 The first object. May be <code>null</code>.
458 * @param o2 The second object. May be <code>null</code>.
459 * @return Returns <code>true</code> if <code>o1</code> and <code>o2</code> are equal (using .equals()) or both are <code>null</code>.
461 static boolean equals(Object o1, Object o2)
463 return o1 == o2 || (o1 != null && o2 != null && o1.equals(o2));
466 // static int getBaselineCorrect(Component comp)
468 // Dimension pSize = comp.getPreferredSize();
469 // int baseline = comp.getBaseline(pSize.width, pSize.height);
470 // int nextBaseline = comp.getBaseline(pSize.width, pSize.height + 1);
472 // // Amount to add to height when calculating where baseline
473 // // lands for a particular height:
476 // // Where the baseline is relative to the mid point
477 // int baselineOffset = baseline - pSize.height / 2;
478 // if (pSize.height % 2 == 0 && baseline != nextBaseline) {
480 // } else if (pSize.height % 2 == 1 && baseline == nextBaseline) {
485 // // The following calculates where the baseline lands for
487 // return (pSize.height + padding) / 2 + baselineOffset;
491 /** Returns the insets for the side.
492 * @param side top == 0, left == 1, bottom = 2, right = 3.
493 * @param getDefault If <code>true</code> the default insets will get retrieved if <code>lc</code> has none set.
494 * @return The insets for the side. Never <code>null</code>.
496 static UnitValue getInsets(LC lc, int side, boolean getDefault)
498 UnitValue[] i = lc.getInsets();
499 return (i != null && i[side] != null) ? i[side] : (getDefault ? PlatformDefaults.getPanelInsets(side) : UnitValue.ZERO);
502 // /** Writes the object and CLOSES the stream. Uses the persistence delegate registered in this class.
503 // * @param os The stream to write to. Will be closed.
504 // * @param o The object to be serialized.
505 // * @param listener The listener to receive the exceptions if there are any. If <code>null</code> not used.
507 // static void writeXMLObject(OutputStream os, Object o, ExceptionListener listener)
509 // ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
510 // Thread.currentThread().setContextClassLoader(LayoutUtil.class.getClassLoader());
512 // XMLEncoder encoder = new XMLEncoder(os);
514 // if (listener != null)
515 // encoder.setExceptionListener(listener);
517 // encoder.writeObject(o);
518 // encoder.close(); // Must be closed to write.
520 // Thread.currentThread().setContextClassLoader(oldClassLoader);
523 // private static ByteArrayOutputStream writeOutputStream = null;
524 // /** Writes an object to XML.
525 // * @param out The object out to write to. Will not be closed.
526 // * @param o The object to write.
528 // public static synchronized void writeAsXML(ObjectOutput out, Object o) throws IOException
530 // if (writeOutputStream == null)
531 // writeOutputStream = new ByteArrayOutputStream(16384);
533 // writeOutputStream.reset();
535 // writeXMLObject(writeOutputStream, o, new ExceptionListener() {
537 // public void exceptionThrown(Exception e) {
538 // e.printStackTrace();
541 // byte[] buf = writeOutputStream.toByteArray();
543 // out.writeInt(buf.length);
547 // private static byte[] readBuf = null;
548 // /** Reads an object from <code>in</code> using the
549 // * @param in The object input to read from.
550 // * @return The object. Never <code>null</code>.
551 // * @throws IOException If there was a problem saving as XML
553 // public static synchronized Object readAsXML(ObjectInput in) throws IOException
555 // if (readBuf == null)
556 // readBuf = new byte[16384];
558 // Thread cThread = Thread.currentThread();
559 // ClassLoader oldCL = null;
562 // oldCL = cThread.getContextClassLoader();
563 // cThread.setContextClassLoader(LayoutUtil.class.getClassLoader());
564 // } catch(SecurityException ignored) {
569 // int length = in.readInt();
570 // if (length > readBuf.length)
571 // readBuf = new byte[length];
573 // in.readFully(readBuf, 0, length);
575 // o = new XMLDecoder(new ByteArrayInputStream(readBuf, 0, length)).readObject();
577 // } catch(EOFException ignored) {
580 // if (oldCL != null)
581 // cThread.setContextClassLoader(oldCL);
586 private static final IdentityHashMap<Object, Object> SER_MAP = new IdentityHashMap<Object, Object>(2);
588 /** Sets the serialized object and associates it with <code>caller</code>.
589 * @param caller The object created <code>o</code>
590 * @param o The just serialized object.
592 public static void setSerializedObject(Object caller, Object o)
594 synchronized(SER_MAP) {
595 SER_MAP.put(caller, o);
599 /** Returns the serialized object that are associated with <code>caller</code>. It also removes it from the list.
600 * @param caller The original creator of the object.
601 * @return The object.
603 public static Object getSerializedObject(Object caller)
605 synchronized(SER_MAP) {
606 return SER_MAP.remove(caller);