001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.preferences.display;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Component;
007import java.awt.GridBagConstraints;
008import java.awt.GridBagLayout;
009import java.text.DecimalFormat;
010import java.text.DecimalFormatSymbols;
011import java.text.ParseException;
012import java.util.Locale;
013import java.util.function.Function;
014
015import javax.swing.DefaultListCellRenderer;
016import javax.swing.JCheckBox;
017import javax.swing.JLabel;
018import javax.swing.JList;
019import javax.swing.JPanel;
020
021import org.openstreetmap.josm.data.preferences.DoubleProperty;
022import org.openstreetmap.josm.gui.draw.BlendComposite;
023import org.openstreetmap.josm.gui.help.HelpUtil;
024import org.openstreetmap.josm.gui.layer.MapGridPaintable;
025import org.openstreetmap.josm.gui.layer.MapGridPaintable.GridType;
026import org.openstreetmap.josm.gui.preferences.DefaultTabPreferenceSetting;
027import org.openstreetmap.josm.gui.preferences.PreferenceSetting;
028import org.openstreetmap.josm.gui.preferences.PreferenceSettingFactory;
029import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane;
030import org.openstreetmap.josm.gui.widgets.JosmComboBox;
031import org.openstreetmap.josm.gui.widgets.JosmTextField;
032import org.openstreetmap.josm.tools.GBC;
033import org.openstreetmap.josm.tools.Logging;
034
035/**
036 * Settings of the grid drawn over the map, see {@link MapGridPaintable}.
037 * @since 19640
038 */
039public class GridPreference extends DefaultTabPreferenceSetting {
040
041    /**
042     * Factory used to create a new {@code GridPreference}.
043     */
044    public static class Factory implements PreferenceSettingFactory {
045        @Override
046        public PreferenceSetting createPreferenceSetting() {
047            return new GridPreference();
048        }
049    }
050
051    private static final DecimalFormat FORMAT = new DecimalFormat("0.#########", DecimalFormatSymbols.getInstance(Locale.ROOT));
052
053    private final JCheckBox enabled = new JCheckBox(tr("Show grid"));
054    private final JosmComboBox<GridType> type = new JosmComboBox<>(GridType.values());
055    private final JosmTextField spacingX = new JosmTextField(10);
056    private final JosmTextField spacingY = new JosmTextField(10);
057    private final JosmTextField rotation = new JosmTextField(10);
058    private final JosmTextField originX = new JosmTextField(10);
059    private final JosmTextField originY = new JosmTextField(10);
060    private final JosmTextField minPixelSpacing = new JosmTextField(10);
061    private final JosmTextField lineWidth = new JosmTextField(10);
062    private final JosmComboBox<BlendComposite.Mode> blendMode = new JosmComboBox<>(BlendComposite.Mode.values());
063    private final JLabel spacingXLabel = new JLabel();
064    private final JLabel spacingYLabel = new JLabel();
065    private final JLabel originXLabel = new JLabel();
066    private final JLabel originYLabel = new JLabel();
067
068    GridPreference() {
069        super("preferences/grid", tr("Grid"), tr("Settings of the grid drawn over the map."));
070    }
071
072    @Override
073    public void addGui(PreferenceTabbedPane gui) {
074        JPanel panel = new JPanel(new GridBagLayout());
075
076        enabled.setSelected(Boolean.TRUE.equals(MapGridPaintable.ENABLED.get()));
077        enabled.setToolTipText(tr("Draw a grid over the map (View menu: Show grid). "
078                + "The grid is a visual aid only, there is no snapping to it."));
079        type.setSelectedItem(MapGridPaintable.TYPE.get());
080        type.setRenderer(new TranslatedRenderer<>(t -> t == GridType.PROJECTED ? tr("Projected coordinates") : tr("Latitude/longitude")));
081        type.setToolTipText("<html>" + tr("Latitude/longitude: lines of constant latitude and longitude, spacing in degrees.<br>"
082                + "Projected: lines of constant east/north coordinate of the map projection, "
083                + "spacing in metres, optionally rotated.") + "</html>");
084        type.addActionListener(e -> updateLabels());
085        set(spacingX, MapGridPaintable.SPACING_X);
086        set(spacingY, MapGridPaintable.SPACING_Y);
087        set(rotation, MapGridPaintable.ROTATION);
088        rotation.setToolTipText(tr("Rotation of a projected grid in degrees, counter clockwise. Ignored for a latitude/longitude grid."));
089        set(originX, MapGridPaintable.ORIGIN_X);
090        set(originY, MapGridPaintable.ORIGIN_Y);
091        set(minPixelSpacing, MapGridPaintable.MIN_PIXEL_SPACING);
092        set(lineWidth, MapGridPaintable.LINE_WIDTH);
093        lineWidth.setToolTipText(tr("Width of the grid lines in pixels. The colors of the east and north lines are set in the Colors tab."));
094        minPixelSpacing.setToolTipText(tr("When the grid lines get closer than this on screen, the spacing is multiplied by 10 "
095                + "so that the grid stays readable when zooming out."));
096        blendMode.setSelectedItem(MapGridPaintable.BLEND_MODE.get());
097        blendMode.setRenderer(new TranslatedRenderer<>(GridPreference::blendModeName));
098        blendMode.setToolTipText(tr("How the lines are combined with the map: normal transparency, multiply (darkens), "
099                + "burn, hard light, difference (visible on any background) or divide. The colors are set in the Colors tab."));
100        updateLabels();
101
102        panel.add(enabled, GBC.eol().insets(0, 0, 0, 10));
103        panel.add(new JLabel(tr("Grid type")), GBC.std().insets(5, 0, 5, 5));
104        panel.add(type, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 5));
105        panel.add(spacingXLabel, GBC.std().insets(5, 0, 5, 5));
106        panel.add(spacingX, GBC.eol().insets(0, 0, 0, 5));
107        panel.add(spacingYLabel, GBC.std().insets(5, 0, 5, 5));
108        panel.add(spacingY, GBC.eol().insets(0, 0, 0, 5));
109        panel.add(new JLabel(tr("Rotation (degrees)")), GBC.std().insets(5, 0, 5, 5));
110        panel.add(rotation, GBC.eol().insets(0, 0, 0, 5));
111        panel.add(originXLabel, GBC.std().insets(5, 0, 5, 5));
112        panel.add(originX, GBC.eol().insets(0, 0, 0, 5));
113        panel.add(originYLabel, GBC.std().insets(5, 0, 5, 5));
114        panel.add(originY, GBC.eol().insets(0, 0, 0, 5));
115        panel.add(new JLabel(tr("Minimum line distance on screen (pixels)")), GBC.std().insets(5, 0, 5, 5));
116        panel.add(minPixelSpacing, GBC.eol().insets(0, 0, 0, 5));
117        panel.add(new JLabel(tr("Line width (pixels)")), GBC.std().insets(5, 0, 5, 5));
118        panel.add(lineWidth, GBC.eol().insets(0, 0, 0, 5));
119        panel.add(new JLabel(tr("Blend mode")), GBC.std().insets(5, 0, 5, 5));
120        panel.add(blendMode, GBC.eol().fill(GridBagConstraints.HORIZONTAL).insets(0, 0, 0, 5));
121        panel.add(GBC.glue(0, 0), GBC.eol().fill(GridBagConstraints.BOTH));
122
123        createPreferenceTabWithScrollPane(gui, panel);
124    }
125
126    private static String blendModeName(BlendComposite.Mode mode) {
127        switch (mode) {
128        case MULTIPLY:
129            return tr("Multiply");
130        case BURN:
131            return tr("Burn");
132        case HARD_LIGHT:
133            return tr("Hard light");
134        case DIFFERENCE:
135            return tr("Difference");
136        case DIVIDE:
137            return tr("Divide");
138        case NORMAL:
139        default:
140            return tr("Normal");
141        }
142    }
143
144    /** Renders enum values with a translated name */
145    private static final class TranslatedRenderer<T> extends DefaultListCellRenderer {
146        private final transient Function<T, String> name;
147
148        TranslatedRenderer(Function<T, String> name) {
149            this.name = name;
150        }
151
152        @Override
153        @SuppressWarnings("unchecked")
154        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
155            String text = value == null ? "" : name.apply((T) value);
156            return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
157        }
158    }
159
160    private void updateLabels() {
161        boolean latlon = type.getSelectedItem() != GridType.PROJECTED;
162        spacingXLabel.setText(latlon ? tr("Longitude spacing (degrees)") : tr("East spacing (metres)"));
163        spacingYLabel.setText(latlon ? tr("Latitude spacing (degrees)") : tr("North spacing (metres)"));
164        String spacingTip = latlon
165                ? tr("Distance between the grid lines in degrees.")
166                : tr("Distance between the grid lines as a true distance in metres (as measured by the parallel way tool "
167                        + "and the status bar), measured at the grid origin. Place the origin in the area of interest.");
168        spacingX.setToolTipText(spacingTip);
169        spacingY.setToolTipText(spacingTip);
170        originXLabel.setText(latlon ? tr("Origin longitude") : tr("Origin east"));
171        originYLabel.setText(latlon ? tr("Origin latitude") : tr("Origin north"));
172        rotation.setEnabled(!latlon);
173    }
174
175    private static void set(JosmTextField field, DoubleProperty property) {
176        field.setText(FORMAT.format(property.get()));
177    }
178
179    private static void save(JosmTextField field, DoubleProperty property, boolean positive) {
180        try {
181            double value = FORMAT.parse(field.getText().trim()).doubleValue();
182            if (positive && (Double.isNaN(value) || value <= 0)) {
183                Logging.warn("Ignoring invalid grid setting {0}: {1}", property.getKey(), field.getText());
184                return;
185            }
186            property.put(value);
187        } catch (ParseException e) {
188            Logging.warn("Ignoring invalid grid setting {0}: {1}", property.getKey(), field.getText());
189            Logging.trace(e);
190        }
191    }
192
193    @Override
194    public boolean ok() {
195        MapGridPaintable.ENABLED.put(enabled.isSelected());
196        MapGridPaintable.TYPE.put((GridType) type.getSelectedItem());
197        save(spacingX, MapGridPaintable.SPACING_X, true);
198        save(spacingY, MapGridPaintable.SPACING_Y, true);
199        save(rotation, MapGridPaintable.ROTATION, false);
200        save(originX, MapGridPaintable.ORIGIN_X, false);
201        save(originY, MapGridPaintable.ORIGIN_Y, false);
202        save(minPixelSpacing, MapGridPaintable.MIN_PIXEL_SPACING, true);
203        save(lineWidth, MapGridPaintable.LINE_WIDTH, true);
204        MapGridPaintable.BLEND_MODE.put((BlendComposite.Mode) blendMode.getSelectedItem());
205        return false;
206    }
207
208    @Override
209    public boolean isExpert() {
210        return false;
211    }
212
213    @Override
214    public String getHelpContext() {
215        return HelpUtil.ht("/Preferences/Grid");
216    }
217}