001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------------------
028 * CyclicNumberAxis.java
029 * ---------------------
030 * (C) Copyright 2003-2017, by Nicolas Brodu and Contributors.
031 *
032 * Original Author:  Nicolas Brodu;
033 * Contributor(s):   David Gilbert (for Object Refinery Limited);
034 *
035 * Changes
036 * -------
037 * 19-Nov-2003 : Initial import to JFreeChart from the JSynoptic project (NB);
038 * 16-Mar-2004 : Added plotState to draw() method (DG);
039 * 07-Apr-2004 : Modifed text bounds calculation (DG);
040 * 21-Apr-2005 : Replaced Insets with RectangleInsets, removed redundant
041 *               argument in selectAutoTickUnit() (DG);
042 * 22-Apr-2005 : Renamed refreshHorizontalTicks() --> refreshTicksHorizontal
043 *               (for consistency with other classes) and removed unused
044 *               parameters (DG);
045 * 08-Jun-2005 : Fixed equals() method to handle GradientPaint (DG);
046 * 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
047 * 02-Jul-2013 : Use ParamChecks (DG);
048 *
049 */
050
051package org.jfree.chart.axis;
052
053import java.awt.BasicStroke;
054import java.awt.Color;
055import java.awt.Font;
056import java.awt.FontMetrics;
057import java.awt.Graphics2D;
058import java.awt.Paint;
059import java.awt.Stroke;
060import java.awt.geom.Line2D;
061import java.awt.geom.Rectangle2D;
062import java.io.IOException;
063import java.io.ObjectInputStream;
064import java.io.ObjectOutputStream;
065import java.text.NumberFormat;
066import java.util.List;
067
068import org.jfree.chart.plot.Plot;
069import org.jfree.chart.plot.PlotRenderingInfo;
070import org.jfree.chart.text.TextUtils;
071import org.jfree.chart.ui.RectangleEdge;
072import org.jfree.chart.ui.TextAnchor;
073import org.jfree.chart.util.ObjectUtils;
074import org.jfree.chart.util.PaintUtils;
075import org.jfree.chart.util.Args;
076import org.jfree.chart.util.SerialUtils;
077import org.jfree.data.Range;
078/**
079This class extends NumberAxis and handles cycling.
080
081Traditional representation of data in the range x0..x1
082<pre>
083|-------------------------|
084x0                       x1
085</pre>
086
087Here, the range bounds are at the axis extremities.
088With cyclic axis, however, the time is split in
089"cycles", or "time frames", or the same duration : the period.
090
091A cycle axis cannot by definition handle a larger interval
092than the period : <pre>x1 - x0 &gt;= period</pre>. Thus, at most a full
093period can be represented with such an axis.
094
095The cycle bound is the number between x0 and x1 which marks
096the beginning of new time frame:
097<pre>
098|---------------------|----------------------------|
099x0                   cb                           x1
100&lt;---previous cycle---&gt;&lt;-------current cycle--------&gt;
101</pre>
102
103It is actually a multiple of the period, plus optionally
104a start offset: <pre>cb = n * period + offset</pre>
105
106Thus, by definition, two consecutive cycle bounds
107period apart, which is precisely why it is called a
108period.
109
110The visual representation of a cyclic axis is like that:
111<pre>
112|----------------------------|---------------------|
113cb                         x1|x0                  cb
114&lt;-------current cycle--------&gt;&lt;---previous cycle---&gt;
115</pre>
116
117The cycle bound is at the axis ends, then current
118cycle is shown, then the last cycle. When using
119dynamic data, the visual effect is the current cycle
120erases the last cycle as x grows. Then, the next cycle
121bound is reached, and the process starts over, erasing
122the previous cycle.
123
124A Cyclic item renderer is provided to do exactly this.
125
126 */
127public class CyclicNumberAxis extends NumberAxis {
128
129    /** For serialization. */
130    static final long serialVersionUID = -7514160997164582554L;
131
132    /** The default axis line stroke. */
133    public static Stroke DEFAULT_ADVANCE_LINE_STROKE = new BasicStroke(1.0f);
134
135    /** The default axis line paint. */
136    public static final Paint DEFAULT_ADVANCE_LINE_PAINT = Color.gray;
137
138    /** The offset. */
139    protected double offset;
140
141    /** The period.*/
142    protected double period;
143
144    /** ??. */
145    protected boolean boundMappedToLastCycle;
146
147    /** A flag that controls whether or not the advance line is visible. */
148    protected boolean advanceLineVisible;
149
150    /** The advance line stroke. */
151    protected transient Stroke advanceLineStroke = DEFAULT_ADVANCE_LINE_STROKE;
152
153    /** The advance line paint. */
154    protected transient Paint advanceLinePaint;
155
156    private transient boolean internalMarkerWhenTicksOverlap;
157    private transient Tick internalMarkerCycleBoundTick;
158
159    /**
160     * Creates a CycleNumberAxis with the given period.
161     *
162     * @param period  the period.
163     */
164    public CyclicNumberAxis(double period) {
165        this(period, 0.0);
166    }
167
168    /**
169     * Creates a CycleNumberAxis with the given period and offset.
170     *
171     * @param period  the period.
172     * @param offset  the offset.
173     */
174    public CyclicNumberAxis(double period, double offset) {
175        this(period, offset, null);
176    }
177
178    /**
179     * Creates a named CycleNumberAxis with the given period.
180     *
181     * @param period  the period.
182     * @param label  the label.
183     */
184    public CyclicNumberAxis(double period, String label) {
185        this(0, period, label);
186    }
187
188    /**
189     * Creates a named CycleNumberAxis with the given period and offset.
190     *
191     * @param period  the period.
192     * @param offset  the offset.
193     * @param label  the label.
194     */
195    public CyclicNumberAxis(double period, double offset, String label) {
196        super(label);
197        this.period = period;
198        this.offset = offset;
199        setFixedAutoRange(period);
200        this.advanceLineVisible = true;
201        this.advanceLinePaint = DEFAULT_ADVANCE_LINE_PAINT;
202    }
203
204    /**
205     * The advance line is the line drawn at the limit of the current cycle,
206     * when erasing the previous cycle.
207     *
208     * @return A boolean.
209     */
210    public boolean isAdvanceLineVisible() {
211        return this.advanceLineVisible;
212    }
213
214    /**
215     * The advance line is the line drawn at the limit of the current cycle,
216     * when erasing the previous cycle.
217     *
218     * @param visible  the flag.
219     */
220    public void setAdvanceLineVisible(boolean visible) {
221        this.advanceLineVisible = visible;
222    }
223
224    /**
225     * The advance line is the line drawn at the limit of the current cycle,
226     * when erasing the previous cycle.
227     *
228     * @return The paint (never {@code null}).
229     */
230    public Paint getAdvanceLinePaint() {
231        return this.advanceLinePaint;
232    }
233
234    /**
235     * The advance line is the line drawn at the limit of the current cycle,
236     * when erasing the previous cycle.
237     *
238     * @param paint  the paint ({@code null} not permitted).
239     */
240    public void setAdvanceLinePaint(Paint paint) {
241        Args.nullNotPermitted(paint, "paint");
242        this.advanceLinePaint = paint;
243    }
244
245    /**
246     * The advance line is the line drawn at the limit of the current cycle,
247     * when erasing the previous cycle.
248     *
249     * @return The stroke (never {@code null}).
250     */
251    public Stroke getAdvanceLineStroke() {
252        return this.advanceLineStroke;
253    }
254    /**
255     * The advance line is the line drawn at the limit of the current cycle,
256     * when erasing the previous cycle.
257     *
258     * @param stroke  the stroke ({@code null} not permitted).
259     */
260    public void setAdvanceLineStroke(Stroke stroke) {
261        Args.nullNotPermitted(stroke, "stroke");
262        this.advanceLineStroke = stroke;
263    }
264
265    /**
266     * The cycle bound can be associated either with the current or with the
267     * last cycle.  It's up to the user's choice to decide which, as this is
268     * just a convention.  By default, the cycle bound is mapped to the current
269     * cycle.
270     * <br>
271     * Note that this has no effect on visual appearance, as the cycle bound is
272     * mapped successively for both axis ends. Use this function for correct
273     * results in translateValueToJava2D.
274     *
275     * @return {@code true} if the cycle bound is mapped to the last
276     *         cycle, {@code false} if it is bound to the current cycle
277     *         (default)
278     */
279    public boolean isBoundMappedToLastCycle() {
280        return this.boundMappedToLastCycle;
281    }
282
283    /**
284     * The cycle bound can be associated either with the current or with the
285     * last cycle.  It's up to the user's choice to decide which, as this is
286     * just a convention. By default, the cycle bound is mapped to the current
287     * cycle.
288     * <br>
289     * Note that this has no effect on visual appearance, as the cycle bound is
290     * mapped successively for both axis ends. Use this function for correct
291     * results in valueToJava2D.
292     *
293     * @param boundMappedToLastCycle Set it to true to map the cycle bound to
294     *        the last cycle.
295     */
296    public void setBoundMappedToLastCycle(boolean boundMappedToLastCycle) {
297        this.boundMappedToLastCycle = boundMappedToLastCycle;
298    }
299
300    /**
301     * Selects a tick unit when the axis is displayed horizontally.
302     *
303     * @param g2  the graphics device.
304     * @param drawArea  the drawing area.
305     * @param dataArea  the data area.
306     * @param edge  the side of the rectangle on which the axis is displayed.
307     */
308    protected void selectHorizontalAutoTickUnit(Graphics2D g2,
309            Rectangle2D drawArea, Rectangle2D dataArea, RectangleEdge edge) {
310
311        double tickLabelWidth
312            = estimateMaximumTickLabelWidth(g2, getTickUnit());
313
314        // Compute number of labels
315        double n = getRange().getLength()
316                   * tickLabelWidth / dataArea.getWidth();
317
318        setTickUnit(
319                (NumberTickUnit) getStandardTickUnits().getCeilingTickUnit(n),
320                false, false);
321
322     }
323
324    /**
325     * Selects a tick unit when the axis is displayed vertically.
326     *
327     * @param g2  the graphics device.
328     * @param drawArea  the drawing area.
329     * @param dataArea  the data area.
330     * @param edge  the side of the rectangle on which the axis is displayed.
331     */
332    protected void selectVerticalAutoTickUnit(Graphics2D g2,
333            Rectangle2D drawArea, Rectangle2D dataArea, RectangleEdge edge) {
334
335        double tickLabelWidth
336            = estimateMaximumTickLabelWidth(g2, getTickUnit());
337
338        // Compute number of labels
339        double n = getRange().getLength()
340                   * tickLabelWidth / dataArea.getHeight();
341
342        setTickUnit(
343            (NumberTickUnit) getStandardTickUnits().getCeilingTickUnit(n),
344            false, false);
345     }
346
347    /**
348     * A special Number tick that also hold information about the cycle bound
349     * mapping for this tick.  This is especially useful for having a tick at
350     * each axis end with the cycle bound value.  See also
351     * isBoundMappedToLastCycle()
352     */
353    protected static class CycleBoundTick extends NumberTick {
354
355        /** Map to last cycle. */
356        public boolean mapToLastCycle;
357
358        /**
359         * Creates a new tick.
360         *
361         * @param mapToLastCycle  map to last cycle?
362         * @param number  the number.
363         * @param label  the label.
364         * @param textAnchor  the text anchor.
365         * @param rotationAnchor  the rotation anchor.
366         * @param angle  the rotation angle.
367         */
368        public CycleBoundTick(boolean mapToLastCycle, Number number,
369                              String label, TextAnchor textAnchor,
370                              TextAnchor rotationAnchor, double angle) {
371            super(number, label, textAnchor, rotationAnchor, angle);
372            this.mapToLastCycle = mapToLastCycle;
373        }
374    }
375
376    /**
377     * Calculates the anchor point for a tick.
378     *
379     * @param tick  the tick.
380     * @param cursor  the cursor.
381     * @param dataArea  the data area.
382     * @param edge  the side on which the axis is displayed.
383     *
384     * @return The anchor point.
385     */
386    @Override
387    protected float[] calculateAnchorPoint(ValueTick tick, double cursor,
388            Rectangle2D dataArea, RectangleEdge edge) {
389        if (tick instanceof CycleBoundTick) {
390            boolean mapsav = this.boundMappedToLastCycle;
391            this.boundMappedToLastCycle
392                = ((CycleBoundTick) tick).mapToLastCycle;
393            float[] ret = super.calculateAnchorPoint(
394                tick, cursor, dataArea, edge
395            );
396            this.boundMappedToLastCycle = mapsav;
397            return ret;
398        }
399        return super.calculateAnchorPoint(tick, cursor, dataArea, edge);
400    }
401
402
403
404    /**
405     * Builds a list of ticks for the axis.  This method is called when the
406     * axis is at the top or bottom of the chart (so the axis is "horizontal").
407     *
408     * @param g2  the graphics device.
409     * @param dataArea  the data area.
410     * @param edge  the edge.
411     *
412     * @return A list of ticks.
413     */
414    @Override
415    protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea,
416            RectangleEdge edge) {
417
418        List result = new java.util.ArrayList();
419
420        Font tickLabelFont = getTickLabelFont();
421        g2.setFont(tickLabelFont);
422
423        if (isAutoTickUnitSelection()) {
424            selectAutoTickUnit(g2, dataArea, edge);
425        }
426
427        double unit = getTickUnit().getSize();
428        double cycleBound = getCycleBound();
429        double currentTickValue = Math.ceil(cycleBound / unit) * unit;
430        double upperValue = getRange().getUpperBound();
431        boolean cycled = false;
432
433        boolean boundMapping = this.boundMappedToLastCycle;
434        this.boundMappedToLastCycle = false;
435
436        CycleBoundTick lastTick = null;
437        float lastX = 0.0f;
438
439        if (upperValue == cycleBound) {
440            currentTickValue = calculateLowestVisibleTickValue();
441            cycled = true;
442            this.boundMappedToLastCycle = true;
443        }
444
445        while (currentTickValue <= upperValue) {
446
447            // Cycle when necessary
448            boolean cyclenow = false;
449            if ((currentTickValue + unit > upperValue) && !cycled) {
450                cyclenow = true;
451            }
452
453            double xx = valueToJava2D(currentTickValue, dataArea, edge);
454            String tickLabel;
455            NumberFormat formatter = getNumberFormatOverride();
456            if (formatter != null) {
457                tickLabel = formatter.format(currentTickValue);
458            }
459            else {
460                tickLabel = getTickUnit().valueToString(currentTickValue);
461            }
462            float x = (float) xx;
463            TextAnchor anchor;
464            TextAnchor rotationAnchor;
465            double angle = 0.0;
466            if (isVerticalTickLabels()) {
467                if (edge == RectangleEdge.TOP) {
468                    angle = Math.PI / 2.0;
469                }
470                else {
471                    angle = -Math.PI / 2.0;
472                }
473                anchor = TextAnchor.CENTER_RIGHT;
474                // If tick overlap when cycling, update last tick too
475                if ((lastTick != null) && (lastX == x)
476                        && (currentTickValue != cycleBound)) {
477                    anchor = isInverted()
478                        ? TextAnchor.TOP_RIGHT : TextAnchor.BOTTOM_RIGHT;
479                    result.remove(result.size() - 1);
480                    result.add(new CycleBoundTick(
481                        this.boundMappedToLastCycle, lastTick.getNumber(),
482                        lastTick.getText(), anchor, anchor,
483                        lastTick.getAngle())
484                    );
485                    this.internalMarkerWhenTicksOverlap = true;
486                    anchor = isInverted()
487                        ? TextAnchor.BOTTOM_RIGHT : TextAnchor.TOP_RIGHT;
488                }
489                rotationAnchor = anchor;
490            }
491            else {
492                if (edge == RectangleEdge.TOP) {
493                    anchor = TextAnchor.BOTTOM_CENTER;
494                    if ((lastTick != null) && (lastX == x)
495                            && (currentTickValue != cycleBound)) {
496                        anchor = isInverted()
497                            ? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
498                        result.remove(result.size() - 1);
499                        result.add(new CycleBoundTick(
500                            this.boundMappedToLastCycle, lastTick.getNumber(),
501                            lastTick.getText(), anchor, anchor,
502                            lastTick.getAngle())
503                        );
504                        this.internalMarkerWhenTicksOverlap = true;
505                        anchor = isInverted()
506                            ? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
507                    }
508                    rotationAnchor = anchor;
509                }
510                else {
511                    anchor = TextAnchor.TOP_CENTER;
512                    if ((lastTick != null) && (lastX == x)
513                            && (currentTickValue != cycleBound)) {
514                        anchor = isInverted()
515                            ? TextAnchor.TOP_LEFT : TextAnchor.TOP_RIGHT;
516                        result.remove(result.size() - 1);
517                        result.add(new CycleBoundTick(
518                            this.boundMappedToLastCycle, lastTick.getNumber(),
519                            lastTick.getText(), anchor, anchor,
520                            lastTick.getAngle())
521                        );
522                        this.internalMarkerWhenTicksOverlap = true;
523                        anchor = isInverted()
524                            ? TextAnchor.TOP_RIGHT : TextAnchor.TOP_LEFT;
525                    }
526                    rotationAnchor = anchor;
527                }
528            }
529
530            CycleBoundTick tick = new CycleBoundTick(
531                this.boundMappedToLastCycle, currentTickValue, tickLabel, anchor,
532                rotationAnchor, angle
533            );
534            if (currentTickValue == cycleBound) {
535                this.internalMarkerCycleBoundTick = tick;
536            }
537            result.add(tick);
538            lastTick = tick;
539            lastX = x;
540
541            currentTickValue += unit;
542
543            if (cyclenow) {
544                currentTickValue = calculateLowestVisibleTickValue();
545                upperValue = cycleBound;
546                cycled = true;
547                this.boundMappedToLastCycle = true;
548            }
549
550        }
551        this.boundMappedToLastCycle = boundMapping;
552        return result;
553
554    }
555
556    /**
557     * Builds a list of ticks for the axis.  This method is called when the
558     * axis is at the left or right of the chart (so the axis is "vertical").
559     *
560     * @param g2  the graphics device.
561     * @param dataArea  the data area.
562     * @param edge  the edge.
563     *
564     * @return A list of ticks.
565     */
566    protected List refreshVerticalTicks(Graphics2D g2, Rectangle2D dataArea,
567            RectangleEdge edge) {
568
569        List result = new java.util.ArrayList();
570        result.clear();
571
572        Font tickLabelFont = getTickLabelFont();
573        g2.setFont(tickLabelFont);
574        if (isAutoTickUnitSelection()) {
575            selectAutoTickUnit(g2, dataArea, edge);
576        }
577
578        double unit = getTickUnit().getSize();
579        double cycleBound = getCycleBound();
580        double currentTickValue = Math.ceil(cycleBound / unit) * unit;
581        double upperValue = getRange().getUpperBound();
582        boolean cycled = false;
583
584        boolean boundMapping = this.boundMappedToLastCycle;
585        this.boundMappedToLastCycle = true;
586
587        NumberTick lastTick = null;
588        float lastY = 0.0f;
589
590        if (upperValue == cycleBound) {
591            currentTickValue = calculateLowestVisibleTickValue();
592            cycled = true;
593            this.boundMappedToLastCycle = true;
594        }
595
596        while (currentTickValue <= upperValue) {
597
598            // Cycle when necessary
599            boolean cyclenow = false;
600            if ((currentTickValue + unit > upperValue) && !cycled) {
601                cyclenow = true;
602            }
603
604            double yy = valueToJava2D(currentTickValue, dataArea, edge);
605            String tickLabel;
606            NumberFormat formatter = getNumberFormatOverride();
607            if (formatter != null) {
608                tickLabel = formatter.format(currentTickValue);
609            }
610            else {
611                tickLabel = getTickUnit().valueToString(currentTickValue);
612            }
613
614            float y = (float) yy;
615            TextAnchor anchor;
616            TextAnchor rotationAnchor;
617            double angle = 0.0;
618            if (isVerticalTickLabels()) {
619
620                if (edge == RectangleEdge.LEFT) {
621                    anchor = TextAnchor.BOTTOM_CENTER;
622                    if ((lastTick != null) && (lastY == y)
623                            && (currentTickValue != cycleBound)) {
624                        anchor = isInverted()
625                            ? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
626                        result.remove(result.size() - 1);
627                        result.add(new CycleBoundTick(
628                            this.boundMappedToLastCycle, lastTick.getNumber(),
629                            lastTick.getText(), anchor, anchor,
630                            lastTick.getAngle())
631                        );
632                        this.internalMarkerWhenTicksOverlap = true;
633                        anchor = isInverted()
634                            ? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
635                    }
636                    rotationAnchor = anchor;
637                    angle = -Math.PI / 2.0;
638                }
639                else {
640                    anchor = TextAnchor.BOTTOM_CENTER;
641                    if ((lastTick != null) && (lastY == y)
642                            && (currentTickValue != cycleBound)) {
643                        anchor = isInverted()
644                            ? TextAnchor.BOTTOM_RIGHT : TextAnchor.BOTTOM_LEFT;
645                        result.remove(result.size() - 1);
646                        result.add(new CycleBoundTick(
647                            this.boundMappedToLastCycle, lastTick.getNumber(),
648                            lastTick.getText(), anchor, anchor,
649                            lastTick.getAngle())
650                        );
651                        this.internalMarkerWhenTicksOverlap = true;
652                        anchor = isInverted()
653                            ? TextAnchor.BOTTOM_LEFT : TextAnchor.BOTTOM_RIGHT;
654                    }
655                    rotationAnchor = anchor;
656                    angle = Math.PI / 2.0;
657                }
658            }
659            else {
660                if (edge == RectangleEdge.LEFT) {
661                    anchor = TextAnchor.CENTER_RIGHT;
662                    if ((lastTick != null) && (lastY == y)
663                            && (currentTickValue != cycleBound)) {
664                        anchor = isInverted()
665                            ? TextAnchor.BOTTOM_RIGHT : TextAnchor.TOP_RIGHT;
666                        result.remove(result.size() - 1);
667                        result.add(new CycleBoundTick(
668                            this.boundMappedToLastCycle, lastTick.getNumber(),
669                            lastTick.getText(), anchor, anchor,
670                            lastTick.getAngle())
671                        );
672                        this.internalMarkerWhenTicksOverlap = true;
673                        anchor = isInverted()
674                            ? TextAnchor.TOP_RIGHT : TextAnchor.BOTTOM_RIGHT;
675                    }
676                    rotationAnchor = anchor;
677                }
678                else {
679                    anchor = TextAnchor.CENTER_LEFT;
680                    if ((lastTick != null) && (lastY == y)
681                            && (currentTickValue != cycleBound)) {
682                        anchor = isInverted()
683                            ? TextAnchor.BOTTOM_LEFT : TextAnchor.TOP_LEFT;
684                        result.remove(result.size() - 1);
685                        result.add(new CycleBoundTick(
686                            this.boundMappedToLastCycle, lastTick.getNumber(),
687                            lastTick.getText(), anchor, anchor,
688                            lastTick.getAngle())
689                        );
690                        this.internalMarkerWhenTicksOverlap = true;
691                        anchor = isInverted()
692                            ? TextAnchor.TOP_LEFT : TextAnchor.BOTTOM_LEFT;
693                    }
694                    rotationAnchor = anchor;
695                }
696            }
697
698            CycleBoundTick tick = new CycleBoundTick(
699                this.boundMappedToLastCycle, currentTickValue,
700                tickLabel, anchor, rotationAnchor, angle);
701            if (currentTickValue == cycleBound) {
702                this.internalMarkerCycleBoundTick = tick;
703            }
704            result.add(tick);
705            lastTick = tick;
706            lastY = y;
707
708            if (currentTickValue == cycleBound) {
709                this.internalMarkerCycleBoundTick = tick;
710            }
711
712            currentTickValue += unit;
713
714            if (cyclenow) {
715                currentTickValue = calculateLowestVisibleTickValue();
716                upperValue = cycleBound;
717                cycled = true;
718                this.boundMappedToLastCycle = false;
719            }
720
721        }
722        this.boundMappedToLastCycle = boundMapping;
723        return result;
724    }
725
726    /**
727     * Converts a coordinate from Java 2D space to data space.
728     *
729     * @param java2DValue  the coordinate in Java2D space.
730     * @param dataArea  the data area.
731     * @param edge  the edge.
732     *
733     * @return The data value.
734     */
735    @Override
736    public double java2DToValue(double java2DValue, Rectangle2D dataArea,
737            RectangleEdge edge) {
738        Range range = getRange();
739
740        double vmax = range.getUpperBound();
741        double vp = getCycleBound();
742
743        double jmin = 0.0;
744        double jmax = 0.0;
745        if (RectangleEdge.isTopOrBottom(edge)) {
746            jmin = dataArea.getMinX();
747            jmax = dataArea.getMaxX();
748        }
749        else if (RectangleEdge.isLeftOrRight(edge)) {
750            jmin = dataArea.getMaxY();
751            jmax = dataArea.getMinY();
752        }
753
754        if (isInverted()) {
755            double jbreak = jmax - (vmax - vp) * (jmax - jmin) / this.period;
756            if (java2DValue >= jbreak) {
757                return vp + (jmax - java2DValue) * this.period / (jmax - jmin);
758            }
759            else {
760                return vp - (java2DValue - jmin) * this.period / (jmax - jmin);
761            }
762        }
763        else {
764            double jbreak = (vmax - vp) * (jmax - jmin) / this.period + jmin;
765            if (java2DValue <= jbreak) {
766                return vp + (java2DValue - jmin) * this.period / (jmax - jmin);
767            }
768            else {
769                return vp - (jmax - java2DValue) * this.period / (jmax - jmin);
770            }
771        }
772    }
773
774    /**
775     * Translates a value from data space to Java 2D space.
776     *
777     * @param value  the data value.
778     * @param dataArea  the data area.
779     * @param edge  the edge.
780     *
781     * @return The Java 2D value.
782     */
783    @Override
784    public double valueToJava2D(double value, Rectangle2D dataArea,
785            RectangleEdge edge) {
786        Range range = getRange();
787
788        double vmin = range.getLowerBound();
789        double vmax = range.getUpperBound();
790        double vp = getCycleBound();
791
792        if ((value < vmin) || (value > vmax)) {
793            return Double.NaN;
794        }
795
796
797        double jmin = 0.0;
798        double jmax = 0.0;
799        if (RectangleEdge.isTopOrBottom(edge)) {
800            jmin = dataArea.getMinX();
801            jmax = dataArea.getMaxX();
802        }
803        else if (RectangleEdge.isLeftOrRight(edge)) {
804            jmax = dataArea.getMinY();
805            jmin = dataArea.getMaxY();
806        }
807
808        if (isInverted()) {
809            if (value == vp) {
810                return this.boundMappedToLastCycle ? jmin : jmax;
811            }
812            else if (value > vp) {
813                return jmax - (value - vp) * (jmax - jmin) / this.period;
814            }
815            else {
816                return jmin + (vp - value) * (jmax - jmin) / this.period;
817            }
818        }
819        else {
820            if (value == vp) {
821                return this.boundMappedToLastCycle ? jmax : jmin;
822            }
823            else if (value >= vp) {
824                return jmin + (value - vp) * (jmax - jmin) / this.period;
825            }
826            else {
827                return jmax - (vp - value) * (jmax - jmin) / this.period;
828            }
829        }
830    }
831
832    /**
833     * Centers the range about the given value.
834     *
835     * @param value  the data value.
836     */
837    @Override
838    public void centerRange(double value) {
839        setRange(value - this.period / 2.0, value + this.period / 2.0);
840    }
841
842    /**
843     * This function is nearly useless since the auto range is fixed for this
844     * class to the period.  The period is extended if necessary to fit the
845     * minimum size.
846     *
847     * @param size  the size.
848     * @param notify  notify?
849     *
850     * @see org.jfree.chart.axis.ValueAxis#setAutoRangeMinimumSize(double,
851     *      boolean)
852     */
853    @Override
854    public void setAutoRangeMinimumSize(double size, boolean notify) {
855        if (size > this.period) {
856            this.period = size;
857        }
858        super.setAutoRangeMinimumSize(size, notify);
859    }
860
861    /**
862     * The auto range is fixed for this class to the period by default.
863     * This function will thus set a new period.
864     *
865     * @param length  the length.
866     *
867     * @see org.jfree.chart.axis.ValueAxis#setFixedAutoRange(double)
868     */
869    @Override
870    public void setFixedAutoRange(double length) {
871        this.period = length;
872        super.setFixedAutoRange(length);
873    }
874
875    /**
876     * Sets a new axis range. The period is extended to fit the range size, if
877     * necessary.
878     *
879     * @param range  the range.
880     * @param turnOffAutoRange  switch off the auto range.
881     * @param notify notify?
882     *
883     * @see org.jfree.chart.axis.ValueAxis#setRange(Range, boolean, boolean)
884     */
885    @Override
886    public void setRange(Range range, boolean turnOffAutoRange,
887            boolean notify) {
888        double size = range.getUpperBound() - range.getLowerBound();
889        if (size > this.period) {
890            this.period = size;
891        }
892        super.setRange(range, turnOffAutoRange, notify);
893    }
894
895    /**
896     * The cycle bound is defined as the higest value x such that
897     * "offset + period * i = x", with i and integer and x &lt;
898     * range.getUpperBound() This is the value which is at both ends of the
899     * axis :  x...up|low...x
900     * The values from x to up are the valued in the current cycle.
901     * The values from low to x are the valued in the previous cycle.
902     *
903     * @return The cycle bound.
904     */
905    public double getCycleBound() {
906        return Math.floor(
907            (getRange().getUpperBound() - this.offset) / this.period
908        ) * this.period + this.offset;
909    }
910
911    /**
912     * The cycle bound is a multiple of the period, plus optionally a start
913     * offset.
914     * <pre>cb = n * period + offset</pre>
915     *
916     * @return The current offset.
917     *
918     * @see #getCycleBound()
919     */
920    public double getOffset() {
921        return this.offset;
922    }
923
924    /**
925     * The cycle bound is a multiple of the period, plus optionally a start
926     * offset.
927     * <pre>cb = n * period + offset</pre>
928     *
929     * @param offset The offset to set.
930     *
931     * @see #getCycleBound()
932     */
933    public void setOffset(double offset) {
934        this.offset = offset;
935    }
936
937    /**
938     * The cycle bound is a multiple of the period, plus optionally a start
939     * offset.
940     * <pre>cb = n * period + offset</pre>
941     *
942     * @return The current period.
943     *
944     * @see #getCycleBound()
945     */
946    public double getPeriod() {
947        return this.period;
948    }
949
950    /**
951     * The cycle bound is a multiple of the period, plus optionally a start
952     * offset.
953     * <pre>cb = n * period + offset</pre>
954     *
955     * @param period The period to set.
956     *
957     * @see #getCycleBound()
958     */
959    public void setPeriod(double period) {
960        this.period = period;
961    }
962
963    /**
964     * Draws the tick marks and labels.
965     *
966     * @param g2  the graphics device.
967     * @param cursor  the cursor.
968     * @param plotArea  the plot area.
969     * @param dataArea  the area inside the axes.
970     * @param edge  the side on which the axis is displayed.
971     *
972     * @return The axis state.
973     */
974    @Override
975    protected AxisState drawTickMarksAndLabels(Graphics2D g2, double cursor,
976            Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge) {
977        this.internalMarkerWhenTicksOverlap = false;
978        AxisState ret = super.drawTickMarksAndLabels(g2, cursor, plotArea,
979                dataArea, edge);
980
981        // continue and separate the labels only if necessary
982        if (!this.internalMarkerWhenTicksOverlap) {
983            return ret;
984        }
985
986        double ol;
987        FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
988        if (isVerticalTickLabels()) {
989            ol = fm.getMaxAdvance();
990        }
991        else {
992            ol = fm.getHeight();
993        }
994
995        double il = 0;
996        if (isTickMarksVisible()) {
997            float xx = (float) valueToJava2D(getRange().getUpperBound(),
998                    dataArea, edge);
999            Line2D mark = null;
1000            g2.setStroke(getTickMarkStroke());
1001            g2.setPaint(getTickMarkPaint());
1002            if (edge == RectangleEdge.LEFT) {
1003                mark = new Line2D.Double(cursor - ol, xx, cursor + il, xx);
1004            }
1005            else if (edge == RectangleEdge.RIGHT) {
1006                mark = new Line2D.Double(cursor + ol, xx, cursor - il, xx);
1007            }
1008            else if (edge == RectangleEdge.TOP) {
1009                mark = new Line2D.Double(xx, cursor - ol, xx, cursor + il);
1010            }
1011            else if (edge == RectangleEdge.BOTTOM) {
1012                mark = new Line2D.Double(xx, cursor + ol, xx, cursor - il);
1013            }
1014            g2.draw(mark);
1015        }
1016        return ret;
1017    }
1018
1019    /**
1020     * Draws the axis.
1021     *
1022     * @param g2  the graphics device ({@code null} not permitted).
1023     * @param cursor  the cursor position.
1024     * @param plotArea  the plot area ({@code null} not permitted).
1025     * @param dataArea  the data area ({@code null} not permitted).
1026     * @param edge  the edge ({@code null} not permitted).
1027     * @param plotState  collects information about the plot
1028     *                   ({@code null} permitted).
1029     *
1030     * @return The axis state (never {@code null}).
1031     */
1032    @Override
1033    public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
1034            Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) {
1035
1036        AxisState ret = super.draw(g2, cursor, plotArea, dataArea, edge, 
1037                plotState);
1038        if (isAdvanceLineVisible()) {
1039            double xx = valueToJava2D(getRange().getUpperBound(), dataArea, 
1040                    edge);
1041            Line2D mark = null;
1042            g2.setStroke(getAdvanceLineStroke());
1043            g2.setPaint(getAdvanceLinePaint());
1044            if (edge == RectangleEdge.LEFT) {
1045                mark = new Line2D.Double(cursor, xx, cursor 
1046                        + dataArea.getWidth(), xx);
1047            }
1048            else if (edge == RectangleEdge.RIGHT) {
1049                mark = new Line2D.Double(cursor - dataArea.getWidth(), xx, 
1050                        cursor, xx);
1051            }
1052            else if (edge == RectangleEdge.TOP) {
1053                mark = new Line2D.Double(xx, cursor + dataArea.getHeight(), xx, 
1054                        cursor);
1055            }
1056            else if (edge == RectangleEdge.BOTTOM) {
1057                mark = new Line2D.Double(xx, cursor, xx, 
1058                        cursor - dataArea.getHeight());
1059            }
1060            g2.draw(mark);
1061        }
1062        return ret;
1063    }
1064
1065    /**
1066     * Reserve some space on each axis side because we draw a centered label at
1067     * each extremity.
1068     *
1069     * @param g2  the graphics device.
1070     * @param plot  the plot.
1071     * @param plotArea  the plot area.
1072     * @param edge  the edge.
1073     * @param space  the space already reserved.
1074     *
1075     * @return The reserved space.
1076     */
1077    @Override
1078    public AxisSpace reserveSpace(Graphics2D g2, Plot plot,
1079            Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {
1080
1081        this.internalMarkerCycleBoundTick = null;
1082        AxisSpace ret = super.reserveSpace(g2, plot, plotArea, edge, space);
1083        if (this.internalMarkerCycleBoundTick == null) {
1084            return ret;
1085        }
1086
1087        FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
1088        Rectangle2D r = TextUtils.getTextBounds(
1089            this.internalMarkerCycleBoundTick.getText(), g2, fm
1090        );
1091
1092        if (RectangleEdge.isTopOrBottom(edge)) {
1093            if (isVerticalTickLabels()) {
1094                space.add(r.getHeight() / 2, RectangleEdge.RIGHT);
1095            }
1096            else {
1097                space.add(r.getWidth() / 2, RectangleEdge.RIGHT);
1098            }
1099        }
1100        else if (RectangleEdge.isLeftOrRight(edge)) {
1101            if (isVerticalTickLabels()) {
1102                space.add(r.getWidth() / 2, RectangleEdge.TOP);
1103            }
1104            else {
1105                space.add(r.getHeight() / 2, RectangleEdge.TOP);
1106            }
1107        }
1108
1109        return ret;
1110
1111    }
1112
1113    /**
1114     * Provides serialization support.
1115     *
1116     * @param stream  the output stream.
1117     *
1118     * @throws IOException  if there is an I/O error.
1119     */
1120    private void writeObject(ObjectOutputStream stream) throws IOException {
1121        stream.defaultWriteObject();
1122        SerialUtils.writePaint(this.advanceLinePaint, stream);
1123        SerialUtils.writeStroke(this.advanceLineStroke, stream);
1124    }
1125
1126    /**
1127     * Provides serialization support.
1128     *
1129     * @param stream  the input stream.
1130     *
1131     * @throws IOException  if there is an I/O error.
1132     * @throws ClassNotFoundException  if there is a classpath problem.
1133     */
1134    private void readObject(ObjectInputStream stream)
1135            throws IOException, ClassNotFoundException {
1136        stream.defaultReadObject();
1137        this.advanceLinePaint = SerialUtils.readPaint(stream);
1138        this.advanceLineStroke = SerialUtils.readStroke(stream);
1139    }
1140
1141
1142    /**
1143     * Tests the axis for equality with another object.
1144     *
1145     * @param obj  the object to test against.
1146     *
1147     * @return A boolean.
1148     */
1149    @Override
1150    public boolean equals(Object obj) {
1151        if (obj == this) {
1152            return true;
1153        }
1154        if (!(obj instanceof CyclicNumberAxis)) {
1155            return false;
1156        }
1157        if (!super.equals(obj)) {
1158            return false;
1159        }
1160        CyclicNumberAxis that = (CyclicNumberAxis) obj;
1161        if (this.period != that.period) {
1162            return false;
1163        }
1164        if (this.offset != that.offset) {
1165            return false;
1166        }
1167        if (!PaintUtils.equal(this.advanceLinePaint,
1168                that.advanceLinePaint)) {
1169            return false;
1170        }
1171        if (!ObjectUtils.equal(this.advanceLineStroke,
1172                that.advanceLineStroke)) {
1173            return false;
1174        }
1175        if (this.advanceLineVisible != that.advanceLineVisible) {
1176            return false;
1177        }
1178        if (this.boundMappedToLastCycle != that.boundMappedToLastCycle) {
1179            return false;
1180        }
1181        return true;
1182    }
1183}