001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.preferences.display;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005import static org.openstreetmap.josm.tools.I18n.trc;
006
007import java.awt.Component;
008import java.awt.Dimension;
009import java.awt.GridBagLayout;
010import java.awt.event.ActionListener;
011import java.util.Collections;
012import java.util.Enumeration;
013import java.util.HashMap;
014import java.util.List;
015import java.util.Map;
016import java.util.Optional;
017
018import javax.swing.AbstractButton;
019import javax.swing.BorderFactory;
020import javax.swing.Box;
021import javax.swing.ButtonGroup;
022import javax.swing.JCheckBox;
023import javax.swing.JComboBox;
024import javax.swing.JLabel;
025import javax.swing.JOptionPane;
026import javax.swing.JPanel;
027import javax.swing.JRadioButton;
028import javax.swing.JSlider;
029
030import org.apache.commons.jcs3.access.exception.InvalidArgumentException;
031import org.openstreetmap.josm.actions.ExpertToggleAction;
032import org.openstreetmap.josm.data.gpx.GpxData;
033import org.openstreetmap.josm.data.gpx.IGpxLayerPrefs;
034import org.openstreetmap.josm.gui.MainApplication;
035import org.openstreetmap.josm.gui.layer.GpxLayer;
036import org.openstreetmap.josm.gui.layer.gpx.GpxDrawHelper;
037import org.openstreetmap.josm.gui.layer.markerlayer.Marker;
038import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane.ValidationListener;
039import org.openstreetmap.josm.gui.widgets.JosmComboBox;
040import org.openstreetmap.josm.gui.widgets.JosmTextField;
041import org.openstreetmap.josm.spi.preferences.Config;
042import org.openstreetmap.josm.tools.GBC;
043import org.openstreetmap.josm.tools.Logging;
044import org.openstreetmap.josm.tools.Utils;
045import org.openstreetmap.josm.tools.template_engine.ParseError;
046import org.openstreetmap.josm.tools.template_engine.TemplateParser;
047
048/**
049 * Panel for GPX settings.
050 */
051public class GPXSettingsPanel extends JPanel implements ValidationListener {
052
053    private static final int WAYPOINT_LABEL_CUSTOM = 6;
054    private static final String[] LABEL_PATTERN_TEMPLATE = {Marker.LABEL_PATTERN_AUTO, Marker.LABEL_PATTERN_NAME,
055        Marker.LABEL_PATTERN_DESC, "{special:everything}", "?{ '{name}' | '{desc}' | '{formattedWaypointOffset}' }", " "};
056    private static final String[] LABEL_PATTERN_DESC = {tr("Auto"), /* gpx data field name */ trc("gpx_field", "Name"),
057        /* gpx data field name */ trc("gpx_field", "Desc(ription)"), tr("Everything"), tr("Name or offset"), tr("None"), tr("Custom")};
058
059    private final JRadioButton drawRawGpsLinesGlobal = new JRadioButton(tr("Use global settings"));
060    private final JRadioButton drawRawGpsLinesAll = new JRadioButton(tr("All"));
061    private final JRadioButton drawRawGpsLinesLocal = new JRadioButton(tr("Local files"));
062    private final JRadioButton drawRawGpsLinesNone = new JRadioButton(tr("None"));
063    private transient ActionListener drawRawGpsLinesActionListener;
064    private final JosmTextField drawRawGpsMaxLineLength = new JosmTextField(8);
065    private final JosmTextField drawRawGpsMaxLineLengthLocal = new JosmTextField(8);
066    private final JosmTextField drawLineWidth = new JosmTextField(2);
067    private final JCheckBox forceRawGpsLines = new JCheckBox(tr("Force lines if no segments imported"));
068    private final JCheckBox largeGpsPoints = new JCheckBox(tr("Draw large GPS points"));
069    private final JCheckBox circleGpsPoints = new JCheckBox(tr("Draw a circle from value"));
070    private final JComboBox<String> circleDataSource = new JosmComboBox<>(new String[] {
071        tr("HDOP"),
072        tr("Horizontal deviation estimate"),
073        tr("Age of correction data")}); 
074    private final JRadioButton colorTypeVelocity = new JRadioButton(tr("Velocity (red = slow, green = fast)"));
075    private final JRadioButton colorTypeDirection = new JRadioButton(tr("Direction (red = west, yellow = north, green = east, blue = south)"));
076    private final JRadioButton colorTypeDilution = new JRadioButton(tr("Dilution of Position (red = high, green = low, if available)"));
077    private final JRadioButton colorTypeQuality = new JRadioButton(tr("Quality (RTKLib only, if available)"));
078    private final JRadioButton colorTypeFix = new JRadioButton(tr("GPS fix value"));
079    private final JRadioButton colorTypeRef = new JRadioButton(tr("GPS reference ID"));
080    private final JRadioButton colorTypeTime = new JRadioButton(tr("Track date"));
081    private final JRadioButton colorTypeHeatMap = new JRadioButton(tr("Heat Map (dark = few, bright = many)"));
082    private final JRadioButton colorTypeNone = new JRadioButton(tr("Single Color (can be customized in the layer manager)"));
083    private final JRadioButton colorTypeGlobal = new JRadioButton(tr("Use global settings"));
084    private final JosmComboBox<String> colorTypeVelocityTune = new JosmComboBox<>(new String[] {tr("Car"), tr("Bicycle"), tr("Foot")});
085    private final JosmComboBox<String> colorTypeHeatMapTune = new JosmComboBox<>(new String[] {
086        trc("Heat map", "User Normal"),
087        trc("Heat map", "User Light"),
088        trc("Heat map", "Traffic Lights"),
089        trc("Heat map", "Inferno"),
090        trc("Heat map", "Viridis"),
091        trc("Heat map", "Wood"),
092        trc("Heat map", "Heat")});
093    private final JCheckBox colorTypeHeatMapPoints = new JCheckBox(tr("Use points instead of lines for heat map"));
094    private final JSlider colorTypeHeatMapGain = new JSlider();
095    private final JSlider colorTypeHeatMapLowerLimit = new JSlider();
096    private final JCheckBox makeAutoMarkers = new JCheckBox(tr("Create markers when reading GPX"));
097    private final JCheckBox drawGpsArrows = new JCheckBox(tr("Draw Direction Arrows"));
098    private final JCheckBox drawGpsArrowsFast = new JCheckBox(tr("Fast drawing (looks uglier)"));
099    private final JosmTextField drawGpsArrowsMinDist = new JosmTextField(8);
100    private final JCheckBox colorDynamic = new JCheckBox(tr("Dynamic color range based on data limits"));
101    private final JosmComboBox<String> waypointLabel = new JosmComboBox<>(LABEL_PATTERN_DESC);
102    private final JosmTextField waypointLabelPattern = new JosmTextField();
103    private final JosmComboBox<String> audioWaypointLabel = new JosmComboBox<>(LABEL_PATTERN_DESC);
104    private final JosmTextField audioWaypointLabelPattern = new JosmTextField();
105    private final JCheckBox useGpsAntialiasing = new JCheckBox(tr("Smooth GPX graphics (antialiasing)"));
106    private final JCheckBox drawLineWithAlpha = new JCheckBox(tr("Draw with Opacity (alpha blending) "));
107
108    private final List<GpxLayer> layers;
109    private final GpxLayer firstLayer;
110    private final boolean global; // global settings vs. layer specific settings
111    private final boolean hasLocalFile; // flag to display LocalOnly checkbooks
112    private final boolean hasNonLocalFile; // flag to display AllLines checkbox
113
114    private static final Map<String, Object> DEFAULT_PREFS = getDefaultPrefs();
115
116    private static Map<String, Object> getDefaultPrefs() {
117        HashMap<String, Object> m = new HashMap<>();
118        m.put("colormode", -1);
119        m.put("colormode.dynamic-range", false);
120        m.put("colormode.heatmap.colormap", 0);
121        m.put("colormode.heatmap.gain", 0);
122        m.put("colormode.heatmap.line-extra", false); //Expert mode only
123        m.put("colormode.heatmap.lower-limit", 0);
124        m.put("colormode.heatmap.use-points", false);
125        m.put("colormode.time.min-distance", 60); //Expert mode only
126        m.put("colormode.velocity.tune", 45);
127        m.put("lines", -1);
128        m.put("lines.alpha-blend", false);
129        m.put("lines.arrows", false);
130        m.put("lines.arrows.fast", false);
131        m.put("lines.arrows.min-distance", 40);
132        m.put("lines.force", false);
133        m.put("lines.max-length", 200);
134        m.put("lines.max-length.local", -1);
135        m.put("lines.width", 0);
136        m.put("markers.color", "");
137        m.put("markers.show-text", true);
138        m.put("markers.pattern", Marker.LABEL_PATTERN_AUTO);
139        m.put("markers.audio.pattern", "?{ '{name}' | '{desc}' | '{" + Marker.MARKER_FORMATTED_OFFSET + "}' }");
140        m.put("points.circle", false);
141        m.put("points.circle.data.source", 0);
142        m.put("points.large", false);
143        m.put("points.large.alpha", -1); //Expert mode only
144        m.put("points.large.size", 3); //Expert mode only
145        return Collections.unmodifiableMap(m);
146    }
147
148    /**
149     * Constructs a new {@code GPXSettingsPanel} for the given layers.
150     * @param layers the GPX layers
151     */
152    public GPXSettingsPanel(List<GpxLayer> layers) {
153        super(new GridBagLayout());
154        this.layers = layers;
155        if (Utils.isEmpty(layers)) {
156            throw new InvalidArgumentException("At least one layer required");
157        }
158        firstLayer = layers.get(0);
159        global = false;
160        hasLocalFile = layers.stream().anyMatch(l -> !l.data.fromServer);
161        hasNonLocalFile = layers.stream().anyMatch(l -> l.data.fromServer);
162        initComponents();
163        loadPreferences();
164    }
165
166    /**
167     * Constructs a new {@code GPXSettingsPanel}.
168     */
169    public GPXSettingsPanel() {
170        super(new GridBagLayout());
171        layers = null;
172        firstLayer = null;
173        global = hasLocalFile = hasNonLocalFile = true;
174        initComponents();
175        loadPreferences(); // preferences -> controls
176    }
177
178    /**
179     * Reads the preference for the given layer or the default preference if not available
180     * @param layer the GpxLayer. Can be <code>null</code>, default preference will be returned then
181     * @param key the drawing key to be read, without "draw.rawgps."
182     * @return the value
183     */
184    public static String getLayerPref(GpxLayer layer, String key) {
185        GpxData data = layer != null ? layer.data : null;
186        return getDataPref(data, key);
187    }
188
189    /**
190     * Reads the preference for the given layer or the default preference if not available
191     * @param data the data. Can be <code>null</code>, default preference will be returned then
192     * @param key the drawing key to be read, without "draw.rawgps."
193     * @return the value
194     * @since 18287
195     */
196    public static String getDataPref(IGpxLayerPrefs data, String key) {
197        Object d = DEFAULT_PREFS.get(key);
198        String ds;
199        if (d != null) {
200            ds = d.toString();
201        } else {
202            Logging.warn("No default value found for layer preference \"" + key + "\".");
203            ds = null;
204        }
205        return Optional.ofNullable(tryGetDataPrefLocal(data, key)).orElse(Config.getPref().get("draw.rawgps." + key, ds));
206    }
207
208    /**
209     * Reads the integer preference for the given layer or the default preference if not available
210     * @param layer the GpxLayer. Can be <code>null</code>, default preference will be returned then
211     * @param key the drawing key to be read, without "draw.rawgps."
212     * @return the integer value
213     */
214    public static int getLayerPrefInt(GpxLayer layer, String key) {
215        GpxData data = layer != null ? layer.data : null;
216        return getDataPrefInt(data, key);
217    }
218
219    /**
220     * Reads the integer preference for the given data or the default preference if not available
221     * @param data the data. Can be <code>null</code>, default preference will be returned then
222     * @param key the drawing key to be read, without "draw.rawgps."
223     * @return the integer value
224     * @since 18287
225     */
226    public static int getDataPrefInt(IGpxLayerPrefs data, String key) {
227        String s = getDataPref(data, key);
228        if (s != null) {
229            try {
230                return Integer.parseInt(s);
231            } catch (NumberFormatException ex) {
232                Object d = DEFAULT_PREFS.get(key);
233                if (d instanceof Integer) {
234                    return (int) d;
235                } else {
236                    Logging.warn("No valid default value found for layer preference \"" + key + "\".");
237                }
238            }
239        }
240        return 0;
241    }
242
243    /**
244     * Try to read the preference for the given layer
245     * @param layer the GpxLayer
246     * @param key the drawing key to be read, without "draw.rawgps."
247     * @return the value or <code>null</code> if not found
248     */
249    public static String tryGetLayerPrefLocal(GpxLayer layer, String key) {
250        return layer != null ? tryGetDataPrefLocal(layer.data, key) : null;
251    }
252
253    /**
254     * Try to read the preference for the given GpxData
255     * @param data the GpxData
256     * @param key the drawing key to be read, without "draw.rawgps."
257     * @return the value or <code>null</code> if not found
258     */
259    public static String tryGetDataPrefLocal(IGpxLayerPrefs data, String key) {
260        return data != null ? data.getLayerPrefs().get(key) : null;
261    }
262
263    /**
264     * Puts the preference for the given layers or the default preference if layers is <code>null</code>
265     * @param layers List of <code>GpxLayer</code> to put the drawingOptions
266     * @param key the drawing key to be written, without "draw.rawgps."
267     * @param value (can be <code>null</code> to remove option)
268     */
269    public static void putLayerPref(List<GpxLayer> layers, String key, Object value) {
270        String v = value == null ? null : value.toString();
271        if (layers != null) {
272            for (GpxLayer l : layers) {
273                putDataPrefLocal(l.data, key, v);
274            }
275        } else {
276            Config.getPref().put("draw.rawgps." + key, v);
277        }
278    }
279
280    /**
281     * Puts the preference for the given layer
282     * @param layer <code>GpxLayer</code> to put the drawingOptions
283     * @param key the drawing key to be written, without "draw.rawgps."
284     * @param value the value or <code>null</code> to remove key
285     */
286    public static void putLayerPrefLocal(GpxLayer layer, String key, String value) {
287        if (layer == null || layer.data == null) return;
288        putDataPrefLocal(layer.data, key, value);
289    }
290
291    /**
292     * Puts the preference for the given layer
293     * @param data <code>GpxData</code> to put the drawingOptions. Must not be <code>null</code>
294     * @param key the drawing key to be written, without "draw.rawgps."
295     * @param value the value or <code>null</code> to remove key
296     * @since 18287
297     */
298    public static void putDataPrefLocal(IGpxLayerPrefs data, String key, String value) {
299        if (data == null) return;
300        data.setModified(true);
301        if (Utils.isStripEmpty(value) ||
302                (getLayerPref(null, key).equals(value) && DEFAULT_PREFS.get(key) != null && DEFAULT_PREFS.get(key).toString().equals(value))) {
303            data.getLayerPrefs().remove(key);
304        } else {
305            data.getLayerPrefs().put(key, value);
306        }
307    }
308
309    private String pref(String key) {
310        return getLayerPref(firstLayer, key);
311    }
312
313    private boolean prefBool(String key) {
314        return Boolean.parseBoolean(pref(key));
315    }
316
317    private int prefInt(String key) {
318        return getLayerPrefInt(firstLayer, key);
319    }
320
321    private int prefIntLocal(String key) {
322        try {
323            return Integer.parseInt(tryGetLayerPrefLocal(firstLayer, key));
324        } catch (NumberFormatException ex) {
325            return -1;
326        }
327
328    }
329
330    private void putPref(String key, Object value) {
331        putLayerPref(layers, key, value);
332    }
333
334    // CHECKSTYLE.OFF: ExecutableStatementCountCheck
335    private void initComponents() {
336        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
337
338        if (global) {
339            // makeAutoMarkers
340            makeAutoMarkers.setToolTipText(tr("Automatically make a marker layer from any waypoints when opening a GPX layer."));
341            ExpertToggleAction.addVisibilitySwitcher(makeAutoMarkers);
342            add(makeAutoMarkers, GBC.eol().insets(20, 0, 0, 5));
343        }
344
345        // drawRawGpsLines
346        ButtonGroup gpsLinesGroup = new ButtonGroup();
347        if (!global) {
348            gpsLinesGroup.add(drawRawGpsLinesGlobal);
349        }
350        gpsLinesGroup.add(drawRawGpsLinesNone);
351        gpsLinesGroup.add(drawRawGpsLinesLocal);
352        gpsLinesGroup.add(drawRawGpsLinesAll);
353
354        /* ensure that default is in data base */
355
356        JLabel label = new JLabel(tr("Draw lines between raw GPS points"));
357        add(label, GBC.eol().insets(20, 0, 0, 0));
358        if (!global) {
359            add(drawRawGpsLinesGlobal, GBC.eol().insets(40, 0, 0, 0));
360        }
361        add(drawRawGpsLinesNone, GBC.eol().insets(40, 0, 0, 0));
362        if (hasLocalFile) {
363            add(drawRawGpsLinesLocal, GBC.eol().insets(40, 0, 0, 0));
364        }
365        if (hasNonLocalFile) {
366            add(drawRawGpsLinesAll, GBC.eol().insets(40, 0, 0, 0));
367        }
368        ExpertToggleAction.addVisibilitySwitcher(label);
369        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsLinesGlobal);
370        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsLinesNone);
371        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsLinesLocal);
372        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsLinesAll);
373
374        drawRawGpsLinesActionListener = e -> {
375            boolean f = drawRawGpsLinesNone.isSelected() || drawRawGpsLinesGlobal.isSelected();
376            forceRawGpsLines.setEnabled(!f);
377            drawRawGpsMaxLineLength.setEnabled(!(f || drawRawGpsLinesLocal.isSelected()));
378            drawRawGpsMaxLineLengthLocal.setEnabled(!f);
379            drawGpsArrows.setEnabled(!f);
380            drawGpsArrowsFast.setEnabled(drawGpsArrows.isSelected() && drawGpsArrows.isEnabled());
381            drawGpsArrowsMinDist.setEnabled(drawGpsArrows.isSelected() && drawGpsArrows.isEnabled());
382        };
383
384        drawRawGpsLinesGlobal.addActionListener(drawRawGpsLinesActionListener);
385        drawRawGpsLinesNone.addActionListener(drawRawGpsLinesActionListener);
386        drawRawGpsLinesLocal.addActionListener(drawRawGpsLinesActionListener);
387        drawRawGpsLinesAll.addActionListener(drawRawGpsLinesActionListener);
388
389        // drawRawGpsMaxLineLengthLocal
390        drawRawGpsMaxLineLengthLocal.setToolTipText(
391                tr("Maximum length (in meters) to draw lines for local files. Set to ''-1'' to draw all lines."));
392        label = new JLabel(tr("Maximum length for local files (meters)"));
393        add(label, GBC.std().insets(40, 0, 0, 0));
394        add(drawRawGpsMaxLineLengthLocal, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
395        ExpertToggleAction.addVisibilitySwitcher(label);
396        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsMaxLineLengthLocal);
397
398        // drawRawGpsMaxLineLength
399        drawRawGpsMaxLineLength.setToolTipText(tr("Maximum length (in meters) to draw lines. Set to ''-1'' to draw all lines."));
400        label = new JLabel(tr("Maximum length (meters)"));
401        add(label, GBC.std().insets(40, 0, 0, 0));
402        add(drawRawGpsMaxLineLength, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
403        ExpertToggleAction.addVisibilitySwitcher(label);
404        ExpertToggleAction.addVisibilitySwitcher(drawRawGpsMaxLineLength);
405
406        // forceRawGpsLines
407        forceRawGpsLines.setToolTipText(tr("Force drawing of lines if the imported data contain no line information."));
408        add(forceRawGpsLines, GBC.eop().insets(40, 0, 0, 0));
409        ExpertToggleAction.addVisibilitySwitcher(forceRawGpsLines);
410
411        // drawGpsArrows
412        drawGpsArrows.addActionListener(e -> {
413            drawGpsArrowsFast.setEnabled(drawGpsArrows.isSelected() && drawGpsArrows.isEnabled());
414            drawGpsArrowsMinDist.setEnabled(drawGpsArrows.isSelected() && drawGpsArrows.isEnabled());
415        });
416        drawGpsArrows.setToolTipText(tr("Draw direction arrows for lines, connecting GPS points."));
417        add(drawGpsArrows, GBC.eop().insets(20, 0, 0, 0));
418
419        // drawGpsArrowsFast
420        drawGpsArrowsFast.setToolTipText(tr("Draw the direction arrows using table lookups instead of complex math."));
421        add(drawGpsArrowsFast, GBC.eop().insets(40, 0, 0, 0));
422        ExpertToggleAction.addVisibilitySwitcher(drawGpsArrowsFast);
423
424        // drawGpsArrowsMinDist
425        drawGpsArrowsMinDist.setToolTipText(tr("Do not draw arrows if they are not at least this distance away from the last one."));
426        add(new JLabel(tr("Minimum distance (pixels)")), GBC.std().insets(40, 0, 0, 0));
427        add(drawGpsArrowsMinDist, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
428
429        // circleGpsPoints
430        circleGpsPoints.addItemListener(e -> {
431            circleDataSource.setEnabled(circleGpsPoints.isSelected());
432        });
433        circleGpsPoints.setToolTipText(tr("Draw a circle from value"));
434        circleDataSource.setToolTipText(tr("Source of the circle size"));
435        circleDataSource.setEnabled(false);
436
437        add(circleGpsPoints, GBC.std().insets(20, 0, 0, 0));
438        add(circleDataSource, GBC.eop().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
439        ExpertToggleAction.addVisibilitySwitcher(circleGpsPoints);
440        ExpertToggleAction.addVisibilitySwitcher(circleDataSource);
441
442        // largeGpsPoints
443        largeGpsPoints.setToolTipText(tr("Draw larger dots for the GPS points."));
444        add(largeGpsPoints, GBC.eop().insets(20, 0, 0, 0));
445
446        // drawLineWidth
447        drawLineWidth.setToolTipText(tr("Width of drawn GPX line (0 for default)"));
448        add(new JLabel(tr("Drawing width of GPX lines")), GBC.std().insets(20, 0, 0, 0));
449        add(drawLineWidth, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
450
451        // antialiasing
452        useGpsAntialiasing.setToolTipText(tr("Apply antialiasing to the GPX lines resulting in a smoother appearance."));
453        add(useGpsAntialiasing, GBC.eop().insets(20, 0, 0, 0));
454        ExpertToggleAction.addVisibilitySwitcher(useGpsAntialiasing);
455
456        // alpha blending
457        drawLineWithAlpha.setToolTipText(tr("Apply dynamic alpha-blending and adjust width based on zoom level for all GPX lines."));
458        add(drawLineWithAlpha, GBC.eop().insets(20, 0, 0, 0));
459        ExpertToggleAction.addVisibilitySwitcher(drawLineWithAlpha);
460
461        // colorTracks
462        ButtonGroup colorGroup = new ButtonGroup();
463        if (!global) {
464            colorGroup.add(colorTypeGlobal);
465        }
466        colorGroup.add(colorTypeNone);
467        colorGroup.add(colorTypeVelocity);
468        colorGroup.add(colorTypeDirection);
469        colorGroup.add(colorTypeDilution);
470        colorGroup.add(colorTypeQuality);
471        colorGroup.add(colorTypeFix);
472        colorGroup.add(colorTypeRef);
473        colorGroup.add(colorTypeTime);
474        colorGroup.add(colorTypeHeatMap);
475
476        colorTypeNone.setToolTipText(tr("All points and track segments will have their own color. Can be customized in Layer Manager."));
477        colorTypeVelocity.setToolTipText(tr("Colors points and track segments by velocity."));
478        colorTypeDirection.setToolTipText(tr("Colors points and track segments by direction."));
479        colorTypeDilution.setToolTipText(
480                tr("Colors points and track segments by dilution of position (HDOP). Your capture device needs to log that information."));
481        colorTypeQuality.setToolTipText(
482                tr("Colors points and track segments by RTKLib quality flag (Q). Your capture device needs to log that information."));
483        colorTypeFix.setToolTipText(tr("Colors points and track segments by GPS fix value."));
484        colorTypeRef.setToolTipText(tr("Colors points and track segments by GPS reference ID."));
485        colorTypeTime.setToolTipText(tr("Colors points and track segments by its timestamp."));
486        colorTypeHeatMap.setToolTipText(tr("Collected points and track segments for a position and displayed as heat map."));
487
488        // color Tracks by Velocity Tune
489        colorTypeVelocityTune.setToolTipText(tr("Allows to tune the track coloring for different average speeds."));
490
491        colorTypeHeatMapTune.setToolTipText(tr("Selects the color schema for heat map."));
492        JLabel colorTypeHeatIconLabel = new JLabel();
493
494        add(Box.createVerticalGlue(), GBC.eol().insets(0, 20, 0, 0));
495
496        add(new JLabel(tr("Track and Point Coloring")), GBC.eol().insets(20, 0, 0, 0));
497        if (!global) {
498            add(colorTypeGlobal, GBC.eol().insets(40, 0, 0, 0));
499        }
500        add(colorTypeNone, GBC.eol().insets(40, 0, 0, 0));
501        add(colorTypeVelocity, GBC.std().insets(40, 0, 0, 0));
502        add(colorTypeVelocityTune, GBC.eop().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
503        add(colorTypeDirection, GBC.eol().insets(40, 0, 0, 0));
504        add(colorTypeDilution, GBC.eol().insets(40, 0, 0, 0));
505        add(colorTypeQuality, GBC.eol().insets(40, 0, 0, 0));
506        add(colorTypeFix, GBC.eol().insets(40, 0, 0, 0));
507        add(colorTypeRef, GBC.eol().insets(40, 0, 0, 0));
508        add(colorTypeTime, GBC.eol().insets(40, 0, 0, 0));
509        add(colorTypeHeatMap, GBC.std().insets(40, 0, 0, 0));
510        add(colorTypeHeatIconLabel, GBC.std().insets(5, 0, 0, 5));
511        add(colorTypeHeatMapTune, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
512
513        JLabel colorTypeHeatMapGainLabel = new JLabel(tr("Overlay gain adjustment"));
514        JLabel colorTypeHeatMapLowerLimitLabel = new JLabel(tr("Lower limit of visibility"));
515        add(colorTypeHeatMapGainLabel, GBC.std().insets(80, 0, 0, 0));
516        add(colorTypeHeatMapGain, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
517        add(colorTypeHeatMapLowerLimitLabel, GBC.std().insets(80, 0, 0, 0));
518        add(colorTypeHeatMapLowerLimit, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
519        add(colorTypeHeatMapPoints, GBC.eol().insets(60, 0, 0, 0));
520
521        colorTypeHeatMapGain.setToolTipText(tr("Adjust the gain of overlay blending."));
522        colorTypeHeatMapGain.setOrientation(JSlider.HORIZONTAL);
523        colorTypeHeatMapGain.setPaintLabels(true);
524        colorTypeHeatMapGain.setMinimum(-10);
525        colorTypeHeatMapGain.setMaximum(+10);
526        colorTypeHeatMapGain.setMinorTickSpacing(1);
527        colorTypeHeatMapGain.setMajorTickSpacing(5);
528
529        colorTypeHeatMapLowerLimit.setToolTipText(tr("Draw all GPX traces that exceed this threshold."));
530        colorTypeHeatMapLowerLimit.setOrientation(JSlider.HORIZONTAL);
531        colorTypeHeatMapLowerLimit.setMinimum(0);
532        colorTypeHeatMapLowerLimit.setMaximum(254);
533        colorTypeHeatMapLowerLimit.setPaintLabels(true);
534        colorTypeHeatMapLowerLimit.setMinorTickSpacing(10);
535        colorTypeHeatMapLowerLimit.setMajorTickSpacing(100);
536
537        colorTypeHeatMapPoints.setToolTipText(tr("Render engine uses points with simulated position error instead of lines. "));
538
539        // iterate over the buttons, add change listener to any change event
540        for (Enumeration<AbstractButton> button = colorGroup.getElements(); button.hasMoreElements();) {
541            button.nextElement().addChangeListener(e -> {
542                colorTypeVelocityTune.setEnabled(colorTypeVelocity.isSelected());
543                colorTypeHeatMapTune.setEnabled(colorTypeHeatMap.isSelected());
544                colorTypeHeatMapPoints.setEnabled(colorTypeHeatMap.isSelected());
545                colorTypeHeatMapGain.setEnabled(colorTypeHeatMap.isSelected());
546                colorTypeHeatMapLowerLimit.setEnabled(colorTypeHeatMap.isSelected());
547                colorTypeHeatMapGainLabel.setEnabled(colorTypeHeatMap.isSelected());
548                colorTypeHeatMapLowerLimitLabel.setEnabled(colorTypeHeatMap.isSelected());
549                colorDynamic.setEnabled(colorTypeVelocity.isSelected() || colorTypeDilution.isSelected());
550            });
551        }
552
553        colorTypeHeatMapTune.addActionListener(e -> {
554            final Dimension dim = colorTypeHeatMapTune.getPreferredSize();
555            if (null != dim) {
556                // get image size of environment
557                final int iconSize = (int) dim.getHeight();
558                colorTypeHeatIconLabel.setIcon(GpxDrawHelper.getColorMapImageIcon(
559                        GpxDrawHelper.DEFAULT_COLOR_PROPERTY.get(),
560                        colorTypeHeatMapTune.getSelectedIndex(),
561                        iconSize));
562            }
563        });
564
565        ExpertToggleAction.addVisibilitySwitcher(colorTypeDirection);
566        ExpertToggleAction.addVisibilitySwitcher(colorTypeDilution);
567        ExpertToggleAction.addVisibilitySwitcher(colorTypeQuality);
568        ExpertToggleAction.addVisibilitySwitcher(colorTypeHeatMapLowerLimit);
569        ExpertToggleAction.addVisibilitySwitcher(colorTypeHeatMapLowerLimitLabel);
570
571        colorDynamic.setToolTipText(tr("Colors points and track segments by data limits."));
572        add(colorDynamic, GBC.eop().insets(40, 0, 0, 0));
573        ExpertToggleAction.addVisibilitySwitcher(colorDynamic);
574
575        if (global) {
576            // Setting waypoints for gpx layer does not make sense - waypoints are shown in marker layer that has
577            // different name - so show this only for global config
578
579            // waypointLabel
580            label = new JLabel(tr("Waypoint labelling"));
581            add(label, GBC.std().insets(20, 0, 0, 0));
582            label.setLabelFor(waypointLabel);
583            add(waypointLabel, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
584            waypointLabel.addActionListener(e -> updateWaypointPattern(waypointLabel, waypointLabelPattern));
585            add(waypointLabelPattern, GBC.eol().fill(GBC.HORIZONTAL).insets(20, 0, 0, 5));
586            ExpertToggleAction.addVisibilitySwitcher(label);
587            ExpertToggleAction.addVisibilitySwitcher(waypointLabel);
588            ExpertToggleAction.addVisibilitySwitcher(waypointLabelPattern);
589
590            // audioWaypointLabel
591            Component glue = Box.createVerticalGlue();
592            add(glue, GBC.eol().insets(0, 20, 0, 0));
593            ExpertToggleAction.addVisibilitySwitcher(glue);
594
595            label = new JLabel(tr("Audio waypoint labelling"));
596            add(label, GBC.std().insets(20, 0, 0, 0));
597            label.setLabelFor(audioWaypointLabel);
598            add(audioWaypointLabel, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 0, 0, 5));
599            audioWaypointLabel.addActionListener(e -> updateWaypointPattern(audioWaypointLabel, audioWaypointLabelPattern));
600            add(audioWaypointLabelPattern, GBC.eol().fill(GBC.HORIZONTAL).insets(20, 0, 0, 5));
601            ExpertToggleAction.addVisibilitySwitcher(label);
602            ExpertToggleAction.addVisibilitySwitcher(audioWaypointLabel);
603            ExpertToggleAction.addVisibilitySwitcher(audioWaypointLabelPattern);
604        }
605
606        add(Box.createVerticalGlue(), GBC.eol().fill(GBC.BOTH));
607    }
608    // CHECKSTYLE.ON: ExecutableStatementCountCheck
609
610    /**
611     * Loads preferences to UI controls
612     */
613    public final void loadPreferences() {
614        makeAutoMarkers.setSelected(Config.getPref().getBoolean("marker.makeautomarkers", true));
615        int lines = global ? prefInt("lines") : prefIntLocal("lines");
616        // -1 = global (default: all)
617        //  0 = none
618        //  1 = local
619        //  2 = all
620        if ((lines == 2 && hasNonLocalFile) || (lines == -1 && global)) {
621            drawRawGpsLinesAll.setSelected(true);
622        } else if (lines == 1 && hasLocalFile) {
623            drawRawGpsLinesLocal.setSelected(true);
624        } else if (lines == 0) {
625            drawRawGpsLinesNone.setSelected(true);
626        } else if (lines == -1) {
627            drawRawGpsLinesGlobal.setSelected(true);
628        } else {
629            Logging.warn("Unknown line type: " + lines);
630        }
631        drawRawGpsMaxLineLengthLocal.setText(pref("lines.max-length.local"));
632        drawRawGpsMaxLineLength.setText(pref("lines.max-length"));
633        drawLineWidth.setText(pref("lines.width"));
634        drawLineWithAlpha.setSelected(prefBool("lines.alpha-blend"));
635        forceRawGpsLines.setSelected(prefBool("lines.force"));
636        drawGpsArrows.setSelected(prefBool("lines.arrows"));
637        drawGpsArrowsFast.setSelected(prefBool("lines.arrows.fast"));
638        drawGpsArrowsMinDist.setText(pref("lines.arrows.min-distance"));
639        circleGpsPoints.setSelected(prefBool("points.circle"));
640        circleDataSource.setSelectedIndex(prefInt("points.circle.data.source"));
641        largeGpsPoints.setSelected(prefBool("points.large"));
642        useGpsAntialiasing.setSelected(Config.getPref().getBoolean("mappaint.gpx.use-antialiasing", false));
643
644        drawRawGpsLinesActionListener.actionPerformed(null);
645        if (!global && prefIntLocal("colormode") == -1) {
646            colorTypeGlobal.setSelected(true);
647            colorDynamic.setSelected(false);
648            colorDynamic.setEnabled(false);
649            colorTypeHeatMapPoints.setSelected(false);
650            colorTypeHeatMapGain.setValue(0);
651            colorTypeHeatMapLowerLimit.setValue(0);
652        } else {
653            int colorType = prefInt("colormode");
654            switch (colorType) {
655            case -1: case 0: colorTypeNone.setSelected(true); break;
656            case 1: colorTypeVelocity.setSelected(true); break;
657            case 2: colorTypeDilution.setSelected(true); break;
658            case 3: colorTypeDirection.setSelected(true); break;
659            case 4: colorTypeTime.setSelected(true); break;
660            case 5: colorTypeHeatMap.setSelected(true); break;
661            case 6: colorTypeQuality.setSelected(true); break;
662            case 7: colorTypeFix.setSelected(true); break;
663            case 8: colorTypeRef.setSelected(true); break;
664            default: Logging.warn("Unknown color type: " + colorType);
665            }
666            int ccts = prefInt("colormode.velocity.tune");
667            colorTypeVelocityTune.setSelectedIndex(ccts == 10 ? 2 : (ccts == 20 ? 1 : 0));
668            colorTypeHeatMapTune.setSelectedIndex(prefInt("colormode.heatmap.colormap"));
669            colorDynamic.setSelected(prefBool("colormode.dynamic-range"));
670            colorTypeHeatMapPoints.setSelected(prefBool("colormode.heatmap.use-points"));
671            colorTypeHeatMapGain.setValue(prefInt("colormode.heatmap.gain"));
672            colorTypeHeatMapLowerLimit.setValue(prefInt("colormode.heatmap.lower-limit"));
673        }
674        updateWaypointLabelCombobox(waypointLabel, waypointLabelPattern, pref("markers.pattern"));
675        updateWaypointLabelCombobox(audioWaypointLabel, audioWaypointLabelPattern, pref("markers.audio.pattern"));
676
677    }
678
679    /**
680     * Save preferences from UI controls, globally or for the specified layers.
681     * @return {@code true} when restart is required, {@code false} otherwise
682     */
683    public boolean savePreferences() {
684        if (global) {
685            Config.getPref().putBoolean("marker.makeautomarkers", makeAutoMarkers.isSelected());
686            putPref("markers.pattern", waypointLabelPattern.getText());
687            putPref("markers.audio.pattern", audioWaypointLabelPattern.getText());
688        }
689        boolean g;
690        if (!global && ((g = drawRawGpsLinesGlobal.isSelected()) || drawRawGpsLinesNone.isSelected())) {
691            if (g) {
692                putPref("lines", null);
693            } else {
694                putPref("lines", 0);
695            }
696            putPref("lines.max-length", null);
697            putPref("lines.max-length.local", null);
698            putPref("lines.force", null);
699            putPref("lines.arrows", null);
700            putPref("lines.arrows.fast", null);
701            putPref("lines.arrows.min-distance", null);
702        } else {
703            if (drawRawGpsLinesLocal.isSelected()) {
704                putPref("lines", 1);
705            } else if (drawRawGpsLinesAll.isSelected()) {
706                putPref("lines", 2);
707            }
708            putPref("lines.max-length", drawRawGpsMaxLineLength.getText());
709            putPref("lines.max-length.local", drawRawGpsMaxLineLengthLocal.getText());
710            putPref("lines.force", forceRawGpsLines.isSelected());
711            putPref("lines.arrows", drawGpsArrows.isSelected());
712            putPref("lines.arrows.fast", drawGpsArrowsFast.isSelected());
713            putPref("lines.arrows.min-distance", drawGpsArrowsMinDist.getText());
714        }
715
716        putPref("points.circle", circleGpsPoints.isSelected());
717        putPref("points.circle.data.source", circleDataSource.getSelectedIndex());
718        putPref("points.large", largeGpsPoints.isSelected());
719        putPref("lines.width", drawLineWidth.getText());
720        putPref("lines.alpha-blend", drawLineWithAlpha.isSelected());
721
722        Config.getPref().putBoolean("mappaint.gpx.use-antialiasing", useGpsAntialiasing.isSelected());
723
724        if (colorTypeGlobal.isSelected()) {
725            putPref("colormode", null);
726            putPref("colormode.dynamic-range", null);
727            putPref("colormode.velocity.tune", null);
728            return false;
729        } else if (colorTypeVelocity.isSelected()) {
730            putPref("colormode", 1);
731        } else if (colorTypeDilution.isSelected()) {
732            putPref("colormode", 2);
733        } else if (colorTypeDirection.isSelected()) {
734            putPref("colormode", 3);
735        } else if (colorTypeTime.isSelected()) {
736            putPref("colormode", 4);
737        } else if (colorTypeHeatMap.isSelected()) {
738            putPref("colormode", 5);
739        } else if (colorTypeQuality.isSelected()) {
740            putPref("colormode", 6);
741        } else if (colorTypeFix.isSelected()) {
742            putPref("colormode", 7);
743        } else if (colorTypeRef.isSelected()) {
744            putPref("colormode", 8);
745        } else {
746            putPref("colormode", 0);
747        }
748        putPref("colormode.dynamic-range", colorDynamic.isSelected());
749        int ccti = colorTypeVelocityTune.getSelectedIndex();
750        putPref("colormode.velocity.tune", ccti == 2 ? 10 : (ccti == 1 ? 20 : 45));
751        putPref("colormode.heatmap.colormap", colorTypeHeatMapTune.getSelectedIndex());
752        putPref("colormode.heatmap.use-points", colorTypeHeatMapPoints.isSelected());
753        putPref("colormode.heatmap.gain", colorTypeHeatMapGain.getValue());
754        putPref("colormode.heatmap.lower-limit", colorTypeHeatMapLowerLimit.getValue());
755
756        if (!global && !Utils.isEmpty(layers)) {
757            layers.forEach(l -> l.data.invalidate());
758        }
759
760        return false;
761    }
762
763    private static void updateWaypointLabelCombobox(JosmComboBox<String> cb, JosmTextField tf, String labelPattern) {
764        boolean found = false;
765        for (int i = 0; i < LABEL_PATTERN_TEMPLATE.length; i++) {
766            if (LABEL_PATTERN_TEMPLATE[i].equals(labelPattern)) {
767                cb.setSelectedIndex(i);
768                found = true;
769                break;
770            }
771        }
772        if (!found) {
773            cb.setSelectedIndex(WAYPOINT_LABEL_CUSTOM);
774            tf.setEnabled(true);
775            tf.setText(labelPattern);
776        }
777    }
778
779    private static void updateWaypointPattern(JosmComboBox<String> cb, JosmTextField tf) {
780        if (cb.getSelectedIndex() == WAYPOINT_LABEL_CUSTOM) {
781            tf.setEnabled(true);
782        } else {
783            tf.setEnabled(false);
784            tf.setText(LABEL_PATTERN_TEMPLATE[cb.getSelectedIndex()]);
785        }
786    }
787
788    @Override
789    public boolean validatePreferences() {
790        TemplateParser parser = new TemplateParser(waypointLabelPattern.getText());
791        try {
792            parser.parse();
793        } catch (ParseError e) {
794            Logging.warn(e);
795            JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
796                    tr("Incorrect waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE);
797            waypointLabelPattern.requestFocus();
798            return false;
799        }
800        parser = new TemplateParser(audioWaypointLabelPattern.getText());
801        try {
802            parser.parse();
803        } catch (ParseError e) {
804            Logging.warn(e);
805            JOptionPane.showMessageDialog(MainApplication.getMainFrame(),
806                    tr("Incorrect audio waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE);
807            audioWaypointLabelPattern.requestFocus();
808            return false;
809        }
810        return true;
811    }
812}