001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005
006import java.awt.Color;
007import java.awt.FontMetrics;
008import java.awt.Graphics2D;
009import java.awt.Font;
010import java.util.Arrays;
011import java.time.ZoneId;
012import java.time.Instant;
013import java.time.ZonedDateTime;
014import java.time.format.DateTimeFormatter;
015import java.util.Objects;
016
017import org.openstreetmap.josm.data.preferences.NamedColorProperty;
018
019import javax.swing.UIManager;
020
021/**
022 * Utility class that helps to work with color scale for coloring GPX tracks etc.
023 * @since 7319
024 */
025public final class ColorScale {
026    private static final Color LEGEND_BACKGROUND = new NamedColorProperty(marktr("gpx legend background"), new Color(180, 180, 180, 160)).get();
027    private static final Color LEGEND_TEXT_OUTLINE_DARK = new NamedColorProperty(marktr("gpx legend text outline dark"),
028            new Color(102, 102, 102)).get();
029    private static final Color LEGEND_TEXT_OUTLINE_BRIGHT = new NamedColorProperty(marktr("gpx legend text outline bright"),
030            new Color(204, 204, 204)).get();
031    private static final Color LEGEND_TITLE = new NamedColorProperty(marktr("gpx legend title color"), new Color(0, 0, 0)).get();
032
033    private static final String DAY_TIME_FORMAT = "yyyy-MM-dd      HH:mm";
034    private static final String TIME_FORMAT = "HH:mm:ss";
035    /** Padding for the legend (from the text to the edge of the rectangle) */
036    private static final byte PADDING = 19;
037
038    private double min, max;
039    private Color noDataColor;
040    private Color belowMinColor;
041    private Color aboveMaxColor;
042
043    private Color[] colors;
044    private String[] colorBarTitles;
045    private String title = "";
046    private int intervalCount = 5;
047
048    private ColorScale() {
049
050    }
051
052    /**
053     * Gets a fixed color range.
054     * @param colors the fixed colors list
055     * @return The scale
056     * @since 15247
057     */
058    public static ColorScale createFixedScale(Color[] colors) {
059        ColorScale sc = new ColorScale();
060        sc.colors = Utils.copyArray(colors);
061        sc.setRange(0, colors.length - 1d);
062        sc.addBounds();
063        return sc;
064    }
065
066    /**
067     * Gets a HSB color range.
068     * @param count The number of colors the scale should have
069     * @return The scale
070     */
071    public static ColorScale createHSBScale(int count) {
072        ColorScale sc = new ColorScale();
073        sc.colors = new Color[count];
074        for (int i = 0; i < count; i++) {
075            sc.colors[i] = Color.getHSBColor(i / 300.0f, 1, 1);
076        }
077        sc.setRange(0, 255);
078        sc.addBounds();
079        return sc;
080    }
081
082    /**
083     * Creates a cyclic color scale (red  yellow  green   blue    red)
084     * @param count The number of colors the scale should have
085     * @return The scale
086     */
087    public static ColorScale createCyclicScale(int count) {
088        ColorScale sc = new ColorScale();
089        // CHECKSTYLE.OFF: SingleSpaceSeparator
090        //                   red  yellow  green   blue    red
091        int[] h = {0,    59,     127,    244,   360};
092        int[] s = {100,  84,     99,     100};
093        int[] b = {90,   93,     74,     83};
094        // CHECKSTYLE.ON: SingleSpaceSeparator
095
096        sc.colors = new Color[count];
097        for (int i = 0; i < sc.colors.length; i++) {
098
099            float angle = i * 4f / count;
100            int quadrant = (int) angle;
101            angle -= quadrant;
102            quadrant = Utils.mod(quadrant+1, 4);
103
104            float vh = h[quadrant] * weighted(angle) + h[quadrant+1] * (1 - weighted(angle));
105            float vs = s[quadrant] * weighted(angle) + s[Utils.mod(quadrant+1, 4)] * (1 - weighted(angle));
106            float vb = b[quadrant] * weighted(angle) + b[Utils.mod(quadrant+1, 4)] * (1 - weighted(angle));
107
108            sc.colors[i] = Color.getHSBColor(vh/360f, vs/100f, vb/100f);
109        }
110        sc.setRange(0, 2*Math.PI);
111        sc.addBounds();
112        return sc;
113    }
114
115    /**
116     * transition function:
117     *  w(0)=1, w(1)=0, 0&lt;=w(x)&lt;=1
118     * @param x number: 0&lt;=x&lt;=1
119     * @return the weighted value
120     */
121    private static float weighted(float x) {
122        if (x < 0.5)
123            return 1 - 2*x*x;
124        else
125            return 2*(1-x)*(1-x);
126    }
127
128    /**
129     * Sets the hint on the range this scale is for
130     * @param min The minimum value
131     * @param max The maximum value
132     */
133    public void setRange(double min, double max) {
134        this.min = min;
135        this.max = max;
136    }
137
138    /**
139     * Add standard colors for values below min or above max value
140     */
141    public void addBounds() {
142        aboveMaxColor = colors[colors.length-1];
143        belowMinColor = colors[0];
144    }
145
146    /**
147     * Gets a color for the given value.
148     * @param value The value
149     * @return The color for this value, this may be a special color if the value is outside the range but never null.
150     */
151    public Color getColor(double value) {
152        if (value < min) return belowMinColor;
153        if (value > max) return aboveMaxColor;
154        if (Double.isNaN(value)) return noDataColor;
155        final int n = colors.length;
156        int idx = (int) ((value-min)*colors.length / (max-min));
157        if (idx < colors.length) {
158            return colors[idx];
159        } else {
160            return colors[n-1]; // this happens when value==max
161        }
162    }
163
164    /**
165     * Gets a color for the given value.
166     * @param value The value, may be <code>null</code>
167     * @return The color for this value, this may be a special color if the value is outside the range or the value is null but never null.
168     */
169    public Color getColor(Number value) {
170        return (value == null) ? noDataColor : getColor(value.doubleValue());
171    }
172
173    /**
174     * Get the color to use if there is no data
175     * @return The color
176     */
177    public Color getNoDataColor() {
178        return noDataColor;
179    }
180
181    /**
182     * Sets the color to use if there is no data
183     * @param noDataColor The color
184     */
185    public void setNoDataColor(Color noDataColor) {
186        this.noDataColor = noDataColor;
187    }
188
189    /**
190     * Make all colors transparent
191     * @param alpha The alpha value all colors in the range should have, range 0..255
192     * @return This scale, for chaining
193     */
194    public ColorScale makeTransparent(int alpha) {
195        for (int i = 0; i < colors.length; i++) {
196            colors[i] = new Color((colors[i].getRGB() & 0xFFFFFF) | ((alpha & 0xFF) << 24), true);
197        }
198        return this;
199    }
200
201    /**
202     * Adds a title to this scale
203     * @param title The new title
204     * @return This scale, for chaining
205     */
206    public ColorScale addTitle(String title) {
207        Objects.requireNonNull(title);
208        this.title = title;
209        return this;
210    }
211
212    /**
213     * Adds titles to the color bar for a fixed scale
214     * @param titles Array of String, same length as the colors array
215     * @return This scale, for chaining
216     * @since 18396
217     */
218    public ColorScale addColorBarTitles(String[] titles) {
219        this.intervalCount = titles.length - 1;
220        this.colorBarTitles = titles;
221        return this;
222    }
223
224    /**
225     * Sets the interval count for this scale
226     * @param intervalCount The interval count hint
227     * @return This scale, for chaining
228     */
229    public ColorScale setIntervalCount(int intervalCount) {
230        this.intervalCount = intervalCount;
231        return this;
232    }
233
234    /**
235     * Reverses this scale
236     * @return This scale, for chaining
237     */
238    public ColorScale makeReversed() {
239        int n = colors.length;
240        Color tmp;
241        for (int i = 0; i < n/2; i++) {
242            tmp = colors[i];
243            colors[i] = colors[n-1-i];
244            colors[n-1-i] = tmp;
245        }
246        tmp = belowMinColor;
247        belowMinColor = aboveMaxColor;
248        aboveMaxColor = tmp;
249        return this;
250    }
251
252    /**
253     * draws an outline for the legend texts
254     * @param g The graphics to draw on
255     * @param txt The text to draw the outline
256     * @param x Text x
257     * @param y Text y
258     * @param color The color of the text
259     */
260    private void drawOutline(final Graphics2D g, final String txt, final int x, final int y, final Color color) {
261        if (ColorHelper.calculateContrastRatio(color, LEGEND_TEXT_OUTLINE_DARK) >=
262            ColorHelper.calculateContrastRatio(color, LEGEND_TEXT_OUTLINE_BRIGHT)) {
263            g.setColor(LEGEND_TEXT_OUTLINE_DARK);
264        } else {
265            g.setColor(LEGEND_TEXT_OUTLINE_BRIGHT);
266        }
267
268        g.drawString(txt, x -1, y -1);
269        g.drawString(txt, x +1, y -1);
270        g.drawString(txt, x -1, y +1);
271        g.drawString(txt, x +1, y +1);
272        g.setColor(color);
273    }
274
275    /**
276     * Draws a color bar representing this scale on the given graphics
277     * @param g The graphics to draw on
278     * @param x Rect x
279     * @param y Rect y
280     * @param w Rect width
281     * @param h Rect height
282     * @param valueScale The scale factor of the values
283     */
284    public void drawColorBar(final Graphics2D g, final int x, final int y, final int w, final int h, final double valueScale) {
285        final int n = colors.length;
286
287        final FontMetrics fm = calculateFontMetrics(g);
288
289        g.setColor(LEGEND_BACKGROUND);
290
291        // color bar texts width & height
292        final int fw;
293        final int fh = fm.getHeight() / 2;
294
295        // calculates the width of the color bar texts
296        if (colorBarTitles != null && colorBarTitles.length > 0) {
297            fw = Arrays.stream(colorBarTitles).mapToInt(fm::stringWidth).max().orElse(50);
298        } else {
299            fw = fm.stringWidth(
300                    String.valueOf(Math.max((int) Math.abs(max * valueScale), (int) Math.abs(min * valueScale))))
301                    + fm.stringWidth("0.123");
302        }
303
304        // background rectangle
305        final int[] t = drawBackgroundRectangle(g, x, y, w, h, fw, fh, fm.stringWidth(title));
306        final int xRect = t[0];
307        final int rectWidth = t[1];
308        final int xText = t[2];
309        final int titleWidth = t[3];
310
311        // colorbar
312        for (int i = 0; i < n; i++) {
313            g.setColor(colors[i]);
314            if (w < h) {
315                double factor = n == 6 ? 1.2 : 1.07 + (0.045 * Math.log(n));
316                if (n < 200) {
317                    g.fillRect(xText + fw + PADDING / 3, y - PADDING / 2 + i * (int) ((double) h / n * factor),
318                            w, (int) ((double) h / n * factor));
319                } else {
320                    g.fillRect(xText + fw + PADDING / 3, y - PADDING / 2 + i * h / (int) (n * 0.875), w, (h / n + 1));
321                }
322            } else {
323                g.fillRect(xText + fw + 7 + i * w / n, y, w / n, h + 1);
324            }
325        }
326
327        // legend title
328        g.setColor(LEGEND_TITLE);
329        g.drawString(title, xRect + rectWidth / 2 - titleWidth / 2, y - fh * 3 / 2 - 10);
330
331        // legend texts
332        drawLegend(g, y, w, h, valueScale, fh, fw, xText);
333
334        g.setColor(noDataColor);
335    }
336
337    /**
338     * Draws a color bar representing the time scale on the given graphics
339     * @param g The graphics to draw on
340     * @param x Rect x
341     * @param y Rect y
342     * @param w Color bar width
343     * @param h Color bar height
344     * @param minVal start time of the track
345     * @param maxVal end time of the track
346     */
347    public void drawColorBarTime(final Graphics2D g, final int x, final int y, final int w, final int h,
348                                 final double minVal, final double maxVal) {
349        final int n = colors.length;
350
351        final FontMetrics fm = calculateFontMetrics(g);
352
353        g.setColor(LEGEND_BACKGROUND);
354
355        final int padding = PADDING;
356
357        // color bar texts width & height
358        final int fw;
359        final int fh = fm.getHeight() / 2;
360
361        // calculates the width of the colorbar texts
362        if (maxVal - minVal > 86400) {
363            fw = fm.stringWidth(DAY_TIME_FORMAT);
364        } else {
365            fw = fm.stringWidth(TIME_FORMAT);
366        }
367
368        // background rectangle
369        final int[] t = drawBackgroundRectangle(g, x, y, w, h, fw, fh, fm.stringWidth(title));
370        final int xRect = t[0];
371        final int rectWidth = t[1];
372        final int xText = t[2];
373        final int titleWidth = t[3];
374
375        // colorbar
376        for (int i = 0; i < n; i++) {
377            g.setColor(colors[i]);
378            if (w < h) {
379                g.fillRect(xText + fw + padding / 3, y - padding / 2 + i * h / (int) (n * 0.875), w, (h / n + 1));
380            } else {
381                g.fillRect(xText + fw + padding / 3 + i * w / n, y, w / n + 1, h);
382            }
383        }
384
385        // legend title
386        g.setColor(LEGEND_TITLE);
387        g.drawString(title, xRect + rectWidth / 2 - titleWidth / 2, y - fh * 3 / 2 - padding / 2);
388
389        // legend texts
390        drawTimeLegend(g, y, x, h, minVal, maxVal, fh, fw, xText);
391
392        g.setColor(noDataColor);
393    }
394
395    private static FontMetrics calculateFontMetrics(final Graphics2D g) {
396        final Font newFont = UIManager.getFont("PopupMenu.font");
397        g.setFont(newFont);
398        return g.getFontMetrics();
399    }
400
401    /**
402     * Draw the background rectangle
403     * @param g The graphics to draw on
404     * @param x Rect x
405     * @param y Rect y
406     * @param w Color bar width
407     * @param h Color bar height
408     * @param fw The font width
409     * @param fh The font height
410     * @param titleWidth The width of the title
411     * @return an @{code int[]} of [xRect, rectWidth, xText, titleWidth] TODO investigate using records in Java 17
412     */
413    private int[] drawBackgroundRectangle(final Graphics2D g, final int x, final int y,
414                                          final int w, final int h, final int fw, final int fh,
415                                          int titleWidth) {
416        final int xRect;
417        final int rectWidth;
418        final int xText;
419        final int arcWidth = 20;
420        final int arcHeight = 20;
421        if (fw + w > titleWidth) {
422            rectWidth = w + fw + PADDING * 2;
423            xRect = x - rectWidth;
424            xText = xRect + (int) (PADDING / 1.2);
425            g.fillRoundRect(xRect, (fh * 3 / 2), rectWidth, h + y - (fh * 3 / 2) + (int) (PADDING / 1.5), arcWidth, arcHeight);
426        } else {
427            if (titleWidth >= 120) {
428                titleWidth = 120;
429            }
430            rectWidth = w + titleWidth + PADDING + PADDING / 2;
431            xRect = x - rectWidth;
432            xText = xRect + PADDING / 2 + rectWidth / 2 - fw;
433            g.fillRoundRect(xRect, (fh * 3 / 2), rectWidth, h + y - (fh * 3 / 2) + (int) (PADDING / 1.5), arcWidth, arcHeight);
434        }
435        return new int[] {xRect, rectWidth, xText, titleWidth};
436    }
437
438    /**
439     * Draws the legend for the color bar representing the time scale on the given graphics
440     * @param g The graphics to draw on
441     * @param y Rect y
442     * @param w Color bar width
443     * @param h Color bar height
444     * @param fw The font width
445     * @param fh The font height
446     * @param valueScale The scale factor of the values
447     * @param xText The location to start drawing the text (x-axis)
448     */
449    private void drawLegend(final Graphics2D g, final int y, final int w, final int h, final double valueScale,
450                            final int fh, final int fw, final int xText) {
451        for (int i = 0; i <= intervalCount; i++) {
452            final String txt;
453            final Color color = colors[(int) (1.0 * i * colors.length / intervalCount - 1e-10)];
454            g.setColor(color);
455
456            if (colorBarTitles != null && i < colorBarTitles.length) {
457                txt = colorBarTitles[i];
458            } else {
459                final double val = min+i*(max-min)/intervalCount;
460                txt = String.format("%.3f", val*valueScale);
461            }
462            drawLegendText(g, y, w, h, fh, fw, xText, i, color, txt);
463        }
464    }
465
466    /**
467     * Draws the legend for the color bar representing the time scale on the given graphics
468     * @param g The graphics to draw on
469     * @param y Rect y
470     * @param w Color bar width
471     * @param h Color bar height
472     * @param minVal start time of the track
473     * @param maxVal end time of the track
474     * @param fw The font width
475     * @param fh The font height
476     * @param xText The location to start drawing the text (x-axis)
477     */
478    private void drawTimeLegend(final Graphics2D g, final int y, final int w, final int h,
479                                final double minVal, final double maxVal,
480                                final int fh, final int fw, final int xText) {
481        for (int i = 0; i <= intervalCount; i++) {
482            final String txt;
483            final Color color = colors[(int) (1.0 * i * colors.length / intervalCount - 1e-10)];
484            g.setColor(color);
485
486            if (colorBarTitles != null && i < colorBarTitles.length) {
487                txt = colorBarTitles[i];
488            } else {
489                final double val = minVal + i * (maxVal - minVal) / intervalCount;
490                final Instant dateInst = Instant.ofEpochSecond((long) val);
491
492                final ZoneId gmt = ZoneId.of("GMT");
493                final ZonedDateTime zonedDateTime = dateInst.atZone(gmt);
494
495                String formatted;
496
497                if (maxVal-minVal > 86400) {
498                    final DateTimeFormatter day = DateTimeFormatter.ofPattern(DAY_TIME_FORMAT);
499                    formatted = zonedDateTime.format(day);
500                } else {
501                    final DateTimeFormatter time = DateTimeFormatter.ofPattern(TIME_FORMAT);
502                    formatted = zonedDateTime.format(time);
503                }
504
505                txt = formatted;
506            }
507            drawLegendText(g, y, w, h, fh, fw, xText, i, color, txt);
508        }
509    }
510
511    /**
512     * Draws the legend for the color bar representing the time scale on the given graphics
513     * @param g The graphics to draw on
514     * @param y Rect y
515     * @param w Color bar width
516     * @param h Color bar height
517     * @param fw The font width
518     * @param fh The font height
519     * @param xText The location to start drawing the text (x-axis)
520     * @param color The color of the text to draw
521     * @param txt The text string to draw
522     * @param i The index of the legend (so we can calculate the y location)
523     */
524    private void drawLegendText(Graphics2D g, int y, int w, int h, int fh, int fw, int xText,
525                                int i, Color color, String txt) {
526
527        if (intervalCount == 0) {
528            drawOutline(g, txt, xText, y + h / 2 + fh / 2, color);
529            g.drawString(txt, xText, y + h / 2 + fh / 2);
530        } else if (w < h) {
531            drawOutline(g, txt, xText, y + i * h / intervalCount + fh / 2, color);
532            g.drawString(txt, xText, y + i * h / intervalCount + fh / 2);
533        } else {
534            final int xLoc = xText + i * w / intervalCount - fw / 2 - (int) (PADDING / 1.3);
535            final int yLoc = y + fh - 5;
536            drawOutline(g, txt, xLoc, yLoc, color);
537            g.drawString(txt, xLoc, yLoc);
538        }
539    }
540}