1/*
2 * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25package javax.swing;
26
27import java.awt.Component;
28
29/**
30 *  An instance of the <code>Spring</code> class holds three properties that
31 *  characterize its behavior: the <em>minimum</em>, <em>preferred</em>, and
32 *  <em>maximum</em> values. Each of these properties may be involved in
33 *  defining its fourth, <em>value</em>, property based on a series of rules.
34 *  <p>
35 *  An instance of the <code>Spring</code> class can be visualized as a
36 *  mechanical spring that provides a corrective force as the spring is compressed
37 *  or stretched away from its preferred value. This force is modelled
38 *  as linear function of the distance from the preferred value, but with
39 *  two different constants -- one for the compressional force and one for the
40 *  tensional one. Those constants are specified by the minimum and maximum
41 *  values of the spring such that a spring at its minimum value produces an
42 *  equal and opposite force to that which is created when it is at its
43 *  maximum value. The difference between the <em>preferred</em> and
44 *  <em>minimum</em> values, therefore, represents the ease with which the
45 *  spring can be compressed and the difference between its <em>maximum</em>
46 *  and <em>preferred</em> values, indicates the ease with which the
47 *  <code>Spring</code> can be extended.
48 *  See the {@link #sum} method for details.
49 *
50 *  <p>
51 *  By defining simple arithmetic operations on <code>Spring</code>s,
52 *  the behavior of a collection of <code>Spring</code>s
53 *  can be reduced to that of an ordinary (non-compound) <code>Spring</code>. We define
54 *  the "+", "-", <em>max</em>, and <em>min</em> operators on
55 *  <code>Spring</code>s so that, in each case, the result is a <code>Spring</code>
56 *  whose characteristics bear a useful mathematical relationship to its constituent
57 *  springs.
58 *
59 *  <p>
60 *  A <code>Spring</code> can be treated as a pair of intervals
61 *  with a single common point: the preferred value.
62 *  The following rules define some of the
63 *  arithmetic operators that can be applied to intervals
64 *  (<code>[a, b]</code> refers to the interval
65 *  from <code>a</code>
66 *  to <code>b</code>,
67 *  where <code>a &lt;= b</code>).
68 *
69 *  <pre>
70 *          [a1, b1] + [a2, b2] = [a1 + a2, b1 + b2]
71 *
72 *                      -[a, b] = [-b, -a]
73 *
74 *      max([a1, b1], [a2, b2]) = [max(a1, a2), max(b1, b2)]
75 *  </pre>
76 *  <p>
77 *
78 *  If we denote <code>Spring</code>s as <code>[a, b, c]</code>,
79 *  where <code>a &lt;= b &lt;= c</code>, we can define the same
80 *  arithmetic operators on <code>Spring</code>s:
81 *
82 *  <pre>
83 *          [a1, b1, c1] + [a2, b2, c2] = [a1 + a2, b1 + b2, c1 + c2]
84 *
85 *                           -[a, b, c] = [-c, -b, -a]
86 *
87 *      max([a1, b1, c1], [a2, b2, c2]) = [max(a1, a2), max(b1, b2), max(c1, c2)]
88 *  </pre>
89 *  <p>
90 *  With both intervals and <code>Spring</code>s we can define "-" and <em>min</em>
91 *  in terms of negation:
92 *
93 *  <pre>
94 *      X - Y = X + (-Y)
95 *
96 *      min(X, Y) = -max(-X, -Y)
97 *  </pre>
98 *  <p>
99 *  For the static methods in this class that embody the arithmetic
100 *  operators, we do not actually perform the operation in question as
101 *  that would snapshot the values of the properties of the method's arguments
102 *  at the time the static method is called. Instead, the static methods
103 *  create a new <code>Spring</code> instance containing references to
104 *  the method's arguments so that the characteristics of the new spring track the
105 *  potentially changing characteristics of the springs from which it
106 *  was made. This is a little like the idea of a <em>lazy value</em>
107 *  in a functional language.
108 * <p>
109 * If you are implementing a <code>SpringLayout</code> you
110 * can find further information and examples in
111 * <a
112 href="http://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html">How to Use SpringLayout</a>,
113 * a section in <em>The Java Tutorial.</em>
114 * <p>
115 * <strong>Warning:</strong>
116 * Serialized objects of this class will not be compatible with
117 * future Swing releases. The current serialization support is
118 * appropriate for short term storage or RMI between applications running
119 * the same version of Swing.  As of 1.4, support for long term storage
120 * of all JavaBeans&trade;
121 * has been added to the <code>java.beans</code> package.
122 * Please see {@link java.beans.XMLEncoder}.
123 *
124 * @see SpringLayout
125 * @see SpringLayout.Constraints
126 *
127 * @author      Philip Milne
128 * @since       1.4
129 */
130@SuppressWarnings("serial") // Same-version serialization only
131public abstract class Spring {
132
133    /**
134     * An integer value signifying that a property value has not yet been calculated.
135     */
136    public static final int UNSET = Integer.MIN_VALUE;
137
138    /**
139     * Used by factory methods to create a <code>Spring</code>.
140     *
141     * @see #constant(int)
142     * @see #constant(int, int, int)
143     * @see #max
144     * @see #minus
145     * @see #sum
146     * @see SpringLayout.Constraints
147     */
148    protected Spring() {}
149
150    /**
151     * Returns the <em>minimum</em> value of this <code>Spring</code>.
152     *
153     * @return the <code>minimumValue</code> property of this <code>Spring</code>
154     */
155    public abstract int getMinimumValue();
156
157    /**
158     * Returns the <em>preferred</em> value of this <code>Spring</code>.
159     *
160     * @return the <code>preferredValue</code> of this <code>Spring</code>
161     */
162    public abstract int getPreferredValue();
163
164    /**
165     * Returns the <em>maximum</em> value of this <code>Spring</code>.
166     *
167     * @return the <code>maximumValue</code> property of this <code>Spring</code>
168     */
169    public abstract int getMaximumValue();
170
171    /**
172     * Returns the current <em>value</em> of this <code>Spring</code>.
173     *
174     * @return  the <code>value</code> property of this <code>Spring</code>
175     *
176     * @see #setValue
177     */
178    public abstract int getValue();
179
180    /**
181     * Sets the current <em>value</em> of this <code>Spring</code> to <code>value</code>.
182     *
183     * @param   value the new setting of the <code>value</code> property
184     *
185     * @see #getValue
186     */
187    public abstract void setValue(int value);
188
189    private double range(boolean contract) {
190        return contract ? (getPreferredValue() - getMinimumValue()) :
191                          (getMaximumValue() - getPreferredValue());
192    }
193
194    /*pp*/ double getStrain() {
195        double delta = (getValue() - getPreferredValue());
196        return delta/range(getValue() < getPreferredValue());
197    }
198
199    /*pp*/ void setStrain(double strain) {
200        setValue(getPreferredValue() + (int)(strain * range(strain < 0)));
201    }
202
203    /*pp*/ boolean isCyclic(SpringLayout l) {
204        return false;
205    }
206
207    /*pp*/ static abstract class AbstractSpring extends Spring {
208        protected int size = UNSET;
209
210        public int getValue() {
211            return size != UNSET ? size : getPreferredValue();
212        }
213
214        public final void setValue(int size) {
215            if (this.size == size) {
216                return;
217            }
218            if (size == UNSET) {
219                clear();
220            } else {
221                setNonClearValue(size);
222            }
223        }
224
225        protected void clear() {
226            size = UNSET;
227        }
228
229        protected void setNonClearValue(int size) {
230            this.size = size;
231        }
232    }
233
234    private static class StaticSpring extends AbstractSpring {
235        protected int min;
236        protected int pref;
237        protected int max;
238
239        public StaticSpring(int pref) {
240            this(pref, pref, pref);
241        }
242
243        public StaticSpring(int min, int pref, int max) {
244            this.min = min;
245            this.pref = pref;
246            this.max = max;
247        }
248
249         public String toString() {
250             return "StaticSpring [" + min + ", " + pref + ", " + max + "]";
251         }
252
253         public int getMinimumValue() {
254            return min;
255        }
256
257        public int getPreferredValue() {
258            return pref;
259        }
260
261        public int getMaximumValue() {
262            return max;
263        }
264    }
265
266    private static class NegativeSpring extends Spring {
267        private Spring s;
268
269        public NegativeSpring(Spring s) {
270            this.s = s;
271        }
272
273// Note the use of max value rather than minimum value here.
274// See the opening preamble on arithmetic with springs.
275
276        public int getMinimumValue() {
277            return -s.getMaximumValue();
278        }
279
280        public int getPreferredValue() {
281            return -s.getPreferredValue();
282        }
283
284        public int getMaximumValue() {
285            return -s.getMinimumValue();
286        }
287
288        public int getValue() {
289            return -s.getValue();
290        }
291
292        public void setValue(int size) {
293            // No need to check for UNSET as
294            // Integer.MIN_VALUE == -Integer.MIN_VALUE.
295            s.setValue(-size);
296        }
297
298        /*pp*/ boolean isCyclic(SpringLayout l) {
299            return s.isCyclic(l);
300        }
301    }
302
303    private static class ScaleSpring extends Spring {
304        private Spring s;
305        private float factor;
306
307        private ScaleSpring(Spring s, float factor) {
308            this.s = s;
309            this.factor = factor;
310        }
311
312        public int getMinimumValue() {
313            return Math.round((factor < 0 ? s.getMaximumValue() : s.getMinimumValue()) * factor);
314        }
315
316        public int getPreferredValue() {
317            return Math.round(s.getPreferredValue() * factor);
318        }
319
320        public int getMaximumValue() {
321            return Math.round((factor < 0 ? s.getMinimumValue() : s.getMaximumValue()) * factor);
322        }
323
324        public int getValue() {
325            return Math.round(s.getValue() * factor);
326        }
327
328        public void setValue(int value) {
329            if (value == UNSET) {
330                s.setValue(UNSET);
331            } else {
332                s.setValue(Math.round(value / factor));
333            }
334        }
335
336        /*pp*/ boolean isCyclic(SpringLayout l) {
337            return s.isCyclic(l);
338        }
339    }
340
341    /*pp*/ static class WidthSpring extends AbstractSpring {
342        /*pp*/ Component c;
343
344        public WidthSpring(Component c) {
345            this.c = c;
346        }
347
348        public int getMinimumValue() {
349            return c.getMinimumSize().width;
350        }
351
352        public int getPreferredValue() {
353            return c.getPreferredSize().width;
354        }
355
356        public int getMaximumValue() {
357            // We will be doing arithmetic with the results of this call,
358            // so if a returned value is Integer.MAX_VALUE we will get
359            // arithmetic overflow. Truncate such values.
360            return Math.min(Short.MAX_VALUE, c.getMaximumSize().width);
361        }
362    }
363
364     /*pp*/  static class HeightSpring extends AbstractSpring {
365        /*pp*/ Component c;
366
367        public HeightSpring(Component c) {
368            this.c = c;
369        }
370
371        public int getMinimumValue() {
372            return c.getMinimumSize().height;
373        }
374
375        public int getPreferredValue() {
376            return c.getPreferredSize().height;
377        }
378
379        public int getMaximumValue() {
380            return Math.min(Short.MAX_VALUE, c.getMaximumSize().height);
381        }
382    }
383
384   /*pp*/ static abstract class SpringMap extends Spring {
385       private Spring s;
386
387       public SpringMap(Spring s) {
388           this.s = s;
389       }
390
391       protected abstract int map(int i);
392
393       protected abstract int inv(int i);
394
395       public int getMinimumValue() {
396           return map(s.getMinimumValue());
397       }
398
399       public int getPreferredValue() {
400           return map(s.getPreferredValue());
401       }
402
403       public int getMaximumValue() {
404           return Math.min(Short.MAX_VALUE, map(s.getMaximumValue()));
405       }
406
407       public int getValue() {
408           return map(s.getValue());
409       }
410
411       public void setValue(int value) {
412           if (value == UNSET) {
413               s.setValue(UNSET);
414           } else {
415               s.setValue(inv(value));
416           }
417       }
418
419       /*pp*/ boolean isCyclic(SpringLayout l) {
420           return s.isCyclic(l);
421       }
422   }
423
424// Use the instance variables of the StaticSpring superclass to
425// cache values that have already been calculated.
426    /*pp*/ static abstract class CompoundSpring extends StaticSpring {
427        protected Spring s1;
428        protected Spring s2;
429
430        public CompoundSpring(Spring s1, Spring s2) {
431            super(UNSET);
432            this.s1 = s1;
433            this.s2 = s2;
434        }
435
436        public String toString() {
437            return "CompoundSpring of " + s1 + " and " + s2;
438        }
439
440        protected void clear() {
441            super.clear();
442            min = pref = max = UNSET;
443            s1.setValue(UNSET);
444            s2.setValue(UNSET);
445        }
446
447        protected abstract int op(int x, int y);
448
449        public int getMinimumValue() {
450            if (min == UNSET) {
451                min = op(s1.getMinimumValue(), s2.getMinimumValue());
452            }
453            return min;
454        }
455
456        public int getPreferredValue() {
457            if (pref == UNSET) {
458                pref = op(s1.getPreferredValue(), s2.getPreferredValue());
459            }
460            return pref;
461        }
462
463        public int getMaximumValue() {
464            if (max == UNSET) {
465                max = op(s1.getMaximumValue(), s2.getMaximumValue());
466            }
467            return max;
468        }
469
470        public int getValue() {
471            if (size == UNSET) {
472                size = op(s1.getValue(), s2.getValue());
473            }
474            return size;
475        }
476
477        /*pp*/ boolean isCyclic(SpringLayout l) {
478            return l.isCyclic(s1) || l.isCyclic(s2);
479        }
480    };
481
482     private static class SumSpring extends CompoundSpring {
483         public SumSpring(Spring s1, Spring s2) {
484             super(s1, s2);
485         }
486
487         protected int op(int x, int y) {
488             return x + y;
489         }
490
491         protected void setNonClearValue(int size) {
492             super.setNonClearValue(size);
493             s1.setStrain(this.getStrain());
494             s2.setValue(size - s1.getValue());
495         }
496     }
497
498    private static class MaxSpring extends CompoundSpring {
499
500        public MaxSpring(Spring s1, Spring s2) {
501            super(s1, s2);
502        }
503
504        protected int op(int x, int y) {
505            return Math.max(x, y);
506        }
507
508        protected void setNonClearValue(int size) {
509            super.setNonClearValue(size);
510            s1.setValue(size);
511            s2.setValue(size);
512        }
513    }
514
515    /**
516     * Returns a strut -- a spring whose <em>minimum</em>, <em>preferred</em>, and
517     * <em>maximum</em> values each have the value <code>pref</code>.
518     *
519     * @param  pref the <em>minimum</em>, <em>preferred</em>, and
520     *         <em>maximum</em> values of the new spring
521     * @return a spring whose <em>minimum</em>, <em>preferred</em>, and
522     *         <em>maximum</em> values each have the value <code>pref</code>
523     *
524     * @see Spring
525     */
526     public static Spring constant(int pref) {
527         return constant(pref, pref, pref);
528     }
529
530    /**
531     * Returns a spring whose <em>minimum</em>, <em>preferred</em>, and
532     * <em>maximum</em> values have the values: <code>min</code>, <code>pref</code>,
533     * and <code>max</code> respectively.
534     *
535     * @param  min the <em>minimum</em> value of the new spring
536     * @param  pref the <em>preferred</em> value of the new spring
537     * @param  max the <em>maximum</em> value of the new spring
538     * @return a spring whose <em>minimum</em>, <em>preferred</em>, and
539     *         <em>maximum</em> values have the values: <code>min</code>, <code>pref</code>,
540     *         and <code>max</code> respectively
541     *
542     * @see Spring
543     */
544     public static Spring constant(int min, int pref, int max) {
545         return new StaticSpring(min, pref, max);
546     }
547
548
549    /**
550     * Returns {@code -s}: a spring running in the opposite direction to {@code s}.
551     *
552     * @param s a {@code Spring} object
553     * @return {@code -s}: a spring running in the opposite direction to {@code s}
554     *
555     * @see Spring
556     */
557    public static Spring minus(Spring s) {
558        return new NegativeSpring(s);
559    }
560
561    /**
562     * Returns <code>s1+s2</code>: a spring representing <code>s1</code> and <code>s2</code>
563     * in series. In a sum, <code>s3</code>, of two springs, <code>s1</code> and <code>s2</code>,
564     * the <em>strains</em> of <code>s1</code>, <code>s2</code>, and <code>s3</code> are maintained
565     * at the same level (to within the precision implied by their integer <em>value</em>s).
566     * The strain of a spring in compression is:
567     * <pre>
568     *         value - pref
569     *         ------------
570     *          pref - min
571     * </pre>
572     * and the strain of a spring in tension is:
573     * <pre>
574     *         value - pref
575     *         ------------
576     *          max - pref
577     * </pre>
578     * When <code>setValue</code> is called on the sum spring, <code>s3</code>, the strain
579     * in <code>s3</code> is calculated using one of the formulas above. Once the strain of
580     * the sum is known, the <em>value</em>s of <code>s1</code> and <code>s2</code> are
581     * then set so that they are have a strain equal to that of the sum. The formulas are
582     * evaluated so as to take rounding errors into account and ensure that the sum of
583     * the <em>value</em>s of <code>s1</code> and <code>s2</code> is exactly equal to
584     * the <em>value</em> of <code>s3</code>.
585     *
586     * @param s1 a {@code Spring} object
587     * @param s2 a {@code Spring} object
588     * @return <code>s1+s2</code>: a spring representing <code>s1</code> and <code>s2</code> in series
589     *
590     * @see Spring
591     */
592     public static Spring sum(Spring s1, Spring s2) {
593         return new SumSpring(s1, s2);
594     }
595
596    /**
597     * Returns {@code max(s1, s2)}: a spring whose value is always greater than (or equal to)
598     *         the values of both {@code s1} and {@code s2}.
599     *
600     * @param s1 a {@code Spring} object
601     * @param s2 a {@code Spring} object
602     * @return {@code max(s1, s2)}: a spring whose value is always greater than (or equal to)
603     *         the values of both {@code s1} and {@code s2}
604     * @see Spring
605     */
606    public static Spring max(Spring s1, Spring s2) {
607        return new MaxSpring(s1, s2);
608    }
609
610    // Remove these, they're not used often and can be created using minus -
611    // as per these implementations.
612
613    /*pp*/ static Spring difference(Spring s1, Spring s2) {
614        return sum(s1, minus(s2));
615    }
616
617    /*
618    public static Spring min(Spring s1, Spring s2) {
619        return minus(max(minus(s1), minus(s2)));
620    }
621    */
622
623    /**
624     * Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
625     * and <em>value</em> properties are each multiples of the properties of the
626     * argument spring, <code>s</code>. Minimum and maximum properties are
627     * swapped when <code>factor</code> is negative (in accordance with the
628     * rules of interval arithmetic).
629     * <p>
630     * When factor is, for example, 0.5f the result represents 'the mid-point'
631     * of its input - an operation that is useful for centering components in
632     * a container.
633     *
634     * @param s the spring to scale
635     * @param factor amount to scale by.
636     * @return  a spring whose properties are those of the input spring <code>s</code>
637     * multiplied by <code>factor</code>
638     * @throws NullPointerException if <code>s</code> is null
639     * @since 1.5
640     */
641    public static Spring scale(Spring s, float factor) {
642        checkArg(s);
643        return new ScaleSpring(s, factor);
644    }
645
646    /**
647     * Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
648     * and <em>value</em> properties are defined by the widths of the <em>minimumSize</em>,
649     * <em>preferredSize</em>, <em>maximumSize</em> and <em>size</em> properties
650     * of the supplied component. The returned spring is a 'wrapper' implementation
651     * whose methods call the appropriate size methods of the supplied component.
652     * The minimum, preferred, maximum and value properties of the returned spring
653     * therefore report the current state of the appropriate properties in the
654     * component and track them as they change.
655     *
656     * @param c Component used for calculating size
657     * @return  a spring whose properties are defined by the horizontal component
658     * of the component's size methods.
659     * @throws NullPointerException if <code>c</code> is null
660     * @since 1.5
661     */
662    public static Spring width(Component c) {
663        checkArg(c);
664        return new WidthSpring(c);
665    }
666
667    /**
668     * Returns a spring whose <em>minimum</em>, <em>preferred</em>, <em>maximum</em>
669     * and <em>value</em> properties are defined by the heights of the <em>minimumSize</em>,
670     * <em>preferredSize</em>, <em>maximumSize</em> and <em>size</em> properties
671     * of the supplied component. The returned spring is a 'wrapper' implementation
672     * whose methods call the appropriate size methods of the supplied component.
673     * The minimum, preferred, maximum and value properties of the returned spring
674     * therefore report the current state of the appropriate properties in the
675     * component and track them as they change.
676     *
677     * @param c Component used for calculating size
678     * @return  a spring whose properties are defined by the vertical component
679     * of the component's size methods.
680     * @throws NullPointerException if <code>c</code> is null
681     * @since 1.5
682     */
683    public static Spring height(Component c) {
684        checkArg(c);
685        return new HeightSpring(c);
686    }
687
688
689    /**
690     * If <code>s</code> is null, this throws an NullPointerException.
691     */
692    private static void checkArg(Object s) {
693        if (s == null) {
694            throw new NullPointerException("Argument must not be null");
695        }
696    }
697}
698