001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions.mapmode;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.marktr;
006import static org.openstreetmap.josm.tools.I18n.tr;
007
008import java.awt.BasicStroke;
009import java.awt.Color;
010import java.awt.Cursor;
011import java.awt.Graphics2D;
012import java.awt.Point;
013import java.awt.event.KeyEvent;
014import java.awt.event.MouseEvent;
015import java.awt.event.WindowAdapter;
016import java.awt.event.WindowEvent;
017import java.awt.event.WindowFocusListener;
018import java.util.ArrayList;
019import java.util.Collection;
020import java.util.Collections;
021import java.util.EnumMap;
022import java.util.EnumSet;
023import java.util.LinkedHashSet;
024import java.util.List;
025import java.util.Map;
026import java.util.Optional;
027import java.util.Set;
028import java.util.stream.Stream;
029
030import javax.swing.JOptionPane;
031
032import org.openstreetmap.josm.data.Bounds;
033import org.openstreetmap.josm.data.SystemOfMeasurement;
034import org.openstreetmap.josm.data.coor.EastNorth;
035import org.openstreetmap.josm.data.coor.ILatLon;
036import org.openstreetmap.josm.data.osm.OsmPrimitive;
037import org.openstreetmap.josm.data.osm.Way;
038import org.openstreetmap.josm.data.osm.WaySegment;
039import org.openstreetmap.josm.data.preferences.AbstractToStringProperty;
040import org.openstreetmap.josm.data.preferences.BooleanProperty;
041import org.openstreetmap.josm.data.preferences.CachingProperty;
042import org.openstreetmap.josm.data.preferences.DoubleProperty;
043import org.openstreetmap.josm.data.preferences.IntegerProperty;
044import org.openstreetmap.josm.data.preferences.NamedColorProperty;
045import org.openstreetmap.josm.data.preferences.StrokeProperty;
046import org.openstreetmap.josm.gui.MainApplication;
047import org.openstreetmap.josm.gui.MapFrame;
048import org.openstreetmap.josm.gui.MapView;
049import org.openstreetmap.josm.gui.Notification;
050import org.openstreetmap.josm.gui.draw.MapViewPath;
051import org.openstreetmap.josm.gui.layer.AbstractMapViewPaintable;
052import org.openstreetmap.josm.gui.layer.Layer;
053import org.openstreetmap.josm.gui.util.ModifierExListener;
054import org.openstreetmap.josm.tools.CheckParameterUtil;
055import org.openstreetmap.josm.tools.ImageProvider;
056import org.openstreetmap.josm.tools.Logging;
057import org.openstreetmap.josm.tools.Shortcut;
058
059/**
060 * MapMode for making parallel ways.
061 * <p>
062 * All calculations are done in projected coordinates.
063 * <p>
064 * TODO:
065 * <p>
066 * == Functionality ==
067 * <ol>
068 * <li>Use selected nodes as split points for the selected ways.
069 * <p>
070 * The ways containing the selected nodes will be split and only the "inner"
071 * parts will be copied</li>
072 * <li>Enter exact offset</li>
073 * <li>Improve snapping</li>
074 * <li>Visual cues could be better</li>
075 * <li>(long term) Parallelize and adjust offsets of existing ways</li>
076 * </ol>
077 * == Code quality ==
078 * <ol type="a">
079 * <li>The mode, flags, and modifiers might be updated more than necessary.
080 * <p>
081 * Not a performance problem, but better if they where more centralized</li>
082 * <li>Extract generic MapMode services into a super class and/or utility class</li>
083 * <li>Maybe better to simply draw our own source way highlighting?</li>
084 * </ol>
085 * Current code doesn't not take into account that ways might been highlighted
086 * by other than us. Don't think that situation should ever happen though.
087 *
088 * @author Ole Jørgen Brønner (olejorgenb)
089 */
090public class ParallelWayAction extends MapMode implements ModifierExListener {
091
092    private static final CachingProperty<BasicStroke> HELPER_LINE_STROKE = new StrokeProperty(prefKey("stroke.hepler-line"), "1").cached();
093    private static final CachingProperty<BasicStroke> REF_LINE_STROKE = new StrokeProperty(prefKey("stroke.ref-line"), "2 2 3").cached();
094
095    // @formatter:off
096    // CHECKSTYLE.OFF: SingleSpaceSeparator
097    private static final CachingProperty<Double> SNAP_THRESHOLD         = new DoubleProperty(prefKey("snap-threshold-percent"), 0.70).cached();
098    private static final CachingProperty<Boolean> SNAP_DEFAULT          = new BooleanProperty(prefKey("snap-default"),      true).cached();
099    private static final CachingProperty<Boolean> COPY_TAGS_DEFAULT     = new BooleanProperty(prefKey("copy-tags-default"), true).cached();
100    private static final CachingProperty<Integer> INITIAL_MOVE_DELAY    = new IntegerProperty(prefKey("initial-move-delay"), 200).cached();
101    private static final CachingProperty<Double> SNAP_DISTANCE_METRIC   = new DoubleProperty(prefKey("snap-distance-metric"), 0.5).cached();
102    private static final CachingProperty<Double> SNAP_DISTANCE_IMPERIAL = new DoubleProperty(prefKey("snap-distance-imperial"), 1).cached();
103    private static final CachingProperty<Double> SNAP_DISTANCE_CHINESE  = new DoubleProperty(prefKey("snap-distance-chinese"), 1).cached();
104    private static final CachingProperty<Double> SNAP_DISTANCE_NAUTICAL = new DoubleProperty(prefKey("snap-distance-nautical"), 0.1).cached();
105    private static final CachingProperty<Double> ARC_STEP_DEGREES
106            = new DoubleProperty(prefKey("arc-step-degrees"), ParallelWays.DEFAULT_ARC_STEP_DEGREES).cached();
107    private static final CachingProperty<BasicStroke> PREVIEW_STROKE = new StrokeProperty(prefKey("stroke.preview"), "2").cached();
108    private static final CachingProperty<Color> MAIN_COLOR = new NamedColorProperty(marktr("make parallel helper line"), Color.RED).cached();
109
110    private static final CachingProperty<Map<Modifier, Boolean>> SNAP_MODIFIER_COMBO
111            = new KeyboardModifiersProperty(prefKey("snap-modifier-combo"),             "?sC").cached();
112    private static final CachingProperty<Map<Modifier, Boolean>> COPY_TAGS_MODIFIER_COMBO
113            = new KeyboardModifiersProperty(prefKey("copy-tags-modifier-combo"),        "As?").cached();
114    private static final CachingProperty<Map<Modifier, Boolean>> ADD_TO_SELECTION_MODIFIER_COMBO
115            = new KeyboardModifiersProperty(prefKey("add-to-selection-modifier-combo"), "aSc").cached();
116    private static final CachingProperty<Map<Modifier, Boolean>> TOGGLE_SELECTED_MODIFIER_COMBO
117            = new KeyboardModifiersProperty(prefKey("toggle-selection-modifier-combo"), "asC").cached();
118    private static final CachingProperty<Map<Modifier, Boolean>> SET_SELECTED_MODIFIER_COMBO
119            = new KeyboardModifiersProperty(prefKey("set-selection-modifier-combo"),    "asc").cached();
120    // CHECKSTYLE.ON: SingleSpaceSeparator
121    // @formatter:on
122
123    enum Mode {
124        DRAGGING, NORMAL
125    }
126
127    //// Preferences and flags
128    // See updateModeLocalPreferences for defaults
129    private Mode mode;
130    private boolean copyTags;
131
132    private boolean snap;
133
134    private final MapView mv;
135
136    // Mouse tracking state
137    private Point mousePressedPos;
138    private boolean mouseIsDown;
139    private long mousePressedTime;
140    private boolean mouseHasBeenDragged;
141
142    private transient WaySegment referenceSegment;
143    private transient ParallelWays pWays;
144    private transient Set<Way> sourceWays;
145    private EastNorth helperLineStart;
146    private EastNorth helperLineEnd;
147    /** the source segment the current offset relates to (the one closest to the mouse) */
148    private transient ParallelWays.ClosestPoint helperSegment;
149
150    private final ParallelWayLayer temporaryLayer = new ParallelWayLayer();
151
152    /** #25012: a drag cannot continue once JOSM loses the focus, as the mouse release may go to another window */
153    private transient final WindowFocusListener focusListener = new WindowAdapter() {
154        @Override
155        public void windowLostFocus(WindowEvent e) {
156            cancelDrag();
157        }
158    };
159
160    /**
161     * Constructs a new {@code ParallelWayAction}.
162     * @param mapFrame Map frame
163     */
164    public ParallelWayAction(MapFrame mapFrame) {
165        super(tr("Parallel"), "parallel", tr("Make parallel copies of ways"),
166            Shortcut.registerShortcut("mapmode:parallel", tr("Mode: {0}",
167                tr("Parallel")), KeyEvent.VK_P, Shortcut.SHIFT),
168            ImageProvider.getCursor("normal", "parallel"));
169        setHelpId(ht("/Action/Parallel"));
170        mv = mapFrame.mapView;
171    }
172
173    @Override
174    public void enterMode() {
175        // super.enterMode() updates the status line and cursor so we need our state to be set correctly
176        setMode(Mode.NORMAL);
177        pWays = null;
178        super.enterMode();
179
180        // #19887: overwrite default: we want to show the distance to the original way
181        MainApplication.getMap().statusLine.setAutoLength(false);
182
183        mv.addMouseListener(this);
184        mv.addMouseMotionListener(this);
185        mv.addTemporaryLayer(temporaryLayer);
186
187        // Needed to update the mouse cursor if modifiers are changed when the mouse is motionless
188        MainApplication.getMap().keyDetector.addModifierExListener(this);
189        if (MainApplication.getMainFrame() != null) {
190            MainApplication.getMainFrame().addWindowFocusListener(focusListener);
191        }
192        sourceWays = new LinkedHashSet<>(getLayerManager().getEditDataSet().getSelectedWays());
193        for (Way w : sourceWays) {
194            w.setHighlighted(true);
195        }
196    }
197
198    @Override
199    public void exitMode() {
200        super.exitMode();
201        mv.removeMouseListener(this);
202        mv.removeMouseMotionListener(this);
203        mv.removeTemporaryLayer(temporaryLayer);
204        MapFrame map = MainApplication.getMap();
205        map.statusLine.setDist(-1);
206        map.keyDetector.removeModifierExListener(this);
207        if (MainApplication.getMainFrame() != null) {
208            MainApplication.getMainFrame().removeWindowFocusListener(focusListener);
209        }
210        removeWayHighlighting(sourceWays);
211        pWays = null;
212        sourceWays = null;
213        referenceSegment = null;
214        helperSegment = null;
215    }
216
217    @Override
218    public String getModeHelpText() {
219        // TODO: add more detailed feedback based on modifier state.
220        // TODO: dynamic messages based on preferences. (Could be problematic translation wise)
221        if (mode == Mode.NORMAL) {
222            // CHECKSTYLE.OFF: LineLength
223            return tr("Select ways as in Select mode. Drag selected ways or a single way to create a parallel copy (Alt toggles tag preservation)");
224            // CHECKSTYLE.ON: LineLength
225        } else { // mode == DRAGGING
226            return tr("Hold Ctrl to toggle snapping");
227        }
228    }
229
230    @Override
231    public boolean layerIsSupported(Layer l) {
232        return isEditableDataLayer(l);
233    }
234
235    @Override
236    public void modifiersExChanged(int modifiers) {
237        if (MainApplication.getMap() == null || mv == null || !mv.isActiveLayerDrawable())
238            return;
239
240        // Should only get InputEvents due to the mask in enterMode
241        if (updateModifiersState(modifiers)) {
242            updateStatusLine();
243            updateCursor();
244        }
245    }
246
247    private boolean updateModifiersState(int modifiers) {
248        boolean oldAlt = alt;
249        boolean oldShift = shift;
250        boolean oldCtrl = ctrl;
251        updateKeyModifiersEx(modifiers);
252        return oldAlt != alt || oldShift != shift || oldCtrl != ctrl;
253    }
254
255    private void updateCursor() {
256        Cursor newCursor = null;
257        switch (mode) {
258        case NORMAL:
259            if (matchesCurrentModifiers(SET_SELECTED_MODIFIER_COMBO)) {
260                newCursor = ImageProvider.getCursor("normal", "parallel");
261            } else if (matchesCurrentModifiers(ADD_TO_SELECTION_MODIFIER_COMBO)) {
262                newCursor = ImageProvider.getCursor("normal", "parallel_add");
263            } else if (matchesCurrentModifiers(TOGGLE_SELECTED_MODIFIER_COMBO)) {
264                newCursor = ImageProvider.getCursor("normal", "parallel_remove");
265            }
266            break;
267        case DRAGGING:
268            newCursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
269            break;
270        }
271        if (newCursor != null) {
272            mv.setNewCursor(newCursor, this);
273        }
274    }
275
276    private void setMode(Mode mode) {
277        this.mode = mode;
278        updateCursor();
279        updateStatusLine();
280    }
281
282    private boolean sanityCheck() {
283        // @formatter:off
284        boolean areWeSane =
285            mv.isActiveLayerVisible() &&
286            mv.isActiveLayerDrawable() &&
287            ((Boolean) this.getValue("active"));
288        // @formatter:on
289        assert areWeSane; // mad == bad
290        return areWeSane;
291    }
292
293    @Override
294    public void mousePressed(MouseEvent e) {
295        requestFocusInMapView();
296        updateModifiersState(e.getModifiersEx());
297        // Other buttons are off limit, but we still get events.
298        if (e.getButton() != MouseEvent.BUTTON1)
299            return;
300
301        // #25012: the release ending the previous drag never arrived, drop that drag and start afresh
302        cancelDrag();
303
304        if (!sanityCheck())
305            return;
306
307        updateFlagsOnlyChangeableOnPress();
308        updateFlagsChangeableAlways();
309
310        // Since the created way is left selected, we need to unselect again here
311        if (pWays != null && pWays.getWays() != null) {
312            final List<Way> ways = new ArrayList<>(pWays.getWays());
313            ways.removeIf(w -> w.getDataSet() == null);
314            getLayerManager().getEditDataSet().clearSelection(ways);
315            pWays = null;
316        }
317
318        mouseIsDown = true;
319        mousePressedPos = e.getPoint();
320        mousePressedTime = System.currentTimeMillis();
321
322    }
323
324    @Override
325    public void mouseReleased(MouseEvent e) {
326        updateModifiersState(e.getModifiersEx());
327        // Other buttons are off limit, but we still get events.
328        // Ignore the release of a press that was not accepted or whose drag was cancelled.
329        if (e.getButton() != MouseEvent.BUTTON1 || !mouseIsDown)
330            return;
331
332        if (!mouseHasBeenDragged) {
333            // use point from press or click event? (or are these always the same)
334            Way nearestWay = mv.getNearestWay(e.getPoint(), OsmPrimitive::isSelectable);
335            if (nearestWay == null) {
336                if (matchesCurrentModifiers(SET_SELECTED_MODIFIER_COMBO)) {
337                    clearSourceWays();
338                }
339                resetMouseTrackingState();
340                return;
341            }
342            boolean isSelected = nearestWay.isSelected();
343            if (matchesCurrentModifiers(ADD_TO_SELECTION_MODIFIER_COMBO)) {
344                if (!isSelected) {
345                    addSourceWay(nearestWay);
346                }
347            } else if (matchesCurrentModifiers(TOGGLE_SELECTED_MODIFIER_COMBO)) {
348                if (isSelected) {
349                    removeSourceWay(nearestWay);
350                } else {
351                    addSourceWay(nearestWay);
352                }
353            } else if (matchesCurrentModifiers(SET_SELECTED_MODIFIER_COMBO)) {
354                clearSourceWays();
355                addSourceWay(nearestWay);
356            } // else -> invalid modifier combination
357        } else if (mode == Mode.DRAGGING) {
358            clearSourceWays();
359            if (pWays != null) {
360                // The nodes and ways are only created now, since their number depends on the offset
361                pWays.commit();
362                List<Way> newWays = pWays.getWays();
363                if (newWays.isEmpty()) {
364                    new Notification(tr("Parallel Way:\n" +
365                            "The offset is too large, nothing remains of the parallel way(s)"))
366                            .setIcon(JOptionPane.INFORMATION_MESSAGE)
367                            .show();
368                    pWays = null;
369                } else {
370                    getLayerManager().getEditDataSet().setSelected(newWays);
371                    MainApplication.getMap().statusLine.setDist(newWays);
372                }
373            }
374        }
375
376        setMode(Mode.NORMAL);
377        resetMouseTrackingState();
378        temporaryLayer.invalidate();
379    }
380
381    private static void removeWayHighlighting(Collection<Way> ways) {
382        if (ways == null)
383            return;
384        for (Way w : ways) {
385            w.setHighlighted(false);
386        }
387    }
388
389    @Override
390    public void mouseDragged(MouseEvent e) {
391        // WTF... the event passed here doesn't have button info?
392        // Since we get this event from other buttons too, we must check that
393        // _BUTTON1_ is down.
394        if (!mouseIsDown)
395            return;
396
397        boolean modifiersChanged = updateModifiersState(e.getModifiersEx());
398        updateFlagsChangeableAlways();
399
400        if (modifiersChanged) {
401            // Since this could be remotely slow, do it conditionally
402            updateStatusLine();
403            updateCursor();
404        }
405
406        if ((System.currentTimeMillis() - mousePressedTime) < INITIAL_MOVE_DELAY.get())
407            return;
408        // Assuming this event only is emitted when the mouse has moved
409        // Setting this after the check above means we tolerate clicks with some movement
410        mouseHasBeenDragged = true;
411
412        if (mode == Mode.NORMAL) {
413            // Should we ensure that the copyTags modifiers are still valid?
414
415            // Important to use mouse position from the press, since the drag
416            // event can come quite late
417            if (!isModifiersValidForDragMode())
418                return;
419            if (!initParallelWays(mousePressedPos, copyTags))
420                return;
421            setMode(Mode.DRAGGING);
422        }
423
424        // Calculate the distance to the source path: the offset relates to the part of the path closest to the
425        // mouse, so that the helper line stays meaningful when the mouse moves along the way.
426        Point p = e.getPoint();
427        EastNorth enp = mv.getEastNorth((int) p.getX(), (int) p.getY());
428        ParallelWays.ClosestPoint closest = pWays.closestPoint(enp);
429        EastNorth nearestPointOnPath = closest.point;
430
431        // Note: d is the distance in _projected units_
432        double d = Math.abs(closest.signedDistance);
433        double realD = mv.getProjection().eastNorth2latlon(enp).greatCircleDistance(
434                (ILatLon) mv.getProjection().eastNorth2latlon(nearestPointOnPath));
435        double snappedRealD = realD;
436
437        boolean toTheRight = closest.signedDistance < 0;
438
439        if (snap) {
440            // TODO: Very simple snapping
441            // - Snap steps relative to the distance?
442            double snapDistance;
443            SystemOfMeasurement som = SystemOfMeasurement.getSystemOfMeasurement();
444            if (som.equals(SystemOfMeasurement.CHINESE)) {
445                snapDistance = SNAP_DISTANCE_CHINESE.get() * SystemOfMeasurement.CHINESE.aValue;
446            } else if (som.equals(SystemOfMeasurement.IMPERIAL)) {
447                snapDistance = SNAP_DISTANCE_IMPERIAL.get() * SystemOfMeasurement.IMPERIAL.aValue;
448            } else if (som.equals(SystemOfMeasurement.NAUTICAL_MILE)) {
449                snapDistance = SNAP_DISTANCE_NAUTICAL.get() * SystemOfMeasurement.NAUTICAL_MILE.aValue;
450            } else {
451                snapDistance = SNAP_DISTANCE_METRIC.get(); // Metric system by default
452            }
453            double closestWholeUnit;
454            double modulo = realD % snapDistance;
455            if (modulo < snapDistance/2.0) {
456                closestWholeUnit = realD - modulo;
457            } else {
458                closestWholeUnit = realD + (snapDistance-modulo);
459            }
460            if (Math.abs(closestWholeUnit - realD) < (SNAP_THRESHOLD.get() * snapDistance)) {
461                snappedRealD = closestWholeUnit;
462            } else {
463                snappedRealD = closestWholeUnit + Math.signum(realD - closestWholeUnit) * snapDistance;
464            }
465        }
466        if (realD > 0) {
467            d = snappedRealD * (d/realD); // convert back to projected distance. (probably ok on small scales)
468        }
469        helperLineStart = nearestPointOnPath;
470        helperLineEnd = enp;
471        helperSegment = closest;
472        if (toTheRight) {
473            d = -d;
474        }
475        pWays.changeOffset(d);
476
477        MapFrame map = MainApplication.getMap();
478        map.statusLine.setDist(Math.abs(snappedRealD));
479        map.statusLine.repaint();
480        temporaryLayer.invalidate();
481    }
482
483    private boolean matchesCurrentModifiers(CachingProperty<Map<Modifier, Boolean>> spec) {
484        return matchesCurrentModifiers(spec.get());
485    }
486
487    @SuppressWarnings("PMD.UnusedPrivateMethod")
488    private boolean matchesCurrentModifiers(Map<Modifier, Boolean> spec) {
489        EnumSet<Modifier> modifiers = EnumSet.noneOf(Modifier.class);
490        if (ctrl) {
491            modifiers.add(Modifier.CTRL);
492        }
493        if (alt) {
494            modifiers.add(Modifier.ALT);
495        }
496        if (shift) {
497            modifiers.add(Modifier.SHIFT);
498        }
499        return spec.entrySet().stream().allMatch(entry -> modifiers.contains(entry.getKey()) == entry.getValue());
500    }
501
502    private boolean isModifiersValidForDragMode() {
503        return (!alt && !shift && !ctrl) || matchesCurrentModifiers(SNAP_MODIFIER_COMBO)
504                || matchesCurrentModifiers(COPY_TAGS_MODIFIER_COMBO);
505    }
506
507    private void updateFlagsOnlyChangeableOnPress() {
508        copyTags = COPY_TAGS_DEFAULT.get() != matchesCurrentModifiers(COPY_TAGS_MODIFIER_COMBO);
509    }
510
511    private void updateFlagsChangeableAlways() {
512        snap = SNAP_DEFAULT.get() != matchesCurrentModifiers(SNAP_MODIFIER_COMBO);
513    }
514
515    // We keep the source ways and the selection in sync so the user can see the source way's tags
516    private void addSourceWay(Way w) {
517        assert sourceWays != null;
518        getLayerManager().getEditDataSet().addSelected(w);
519        w.setHighlighted(true);
520        sourceWays.add(w);
521    }
522
523    private void removeSourceWay(Way w) {
524        assert sourceWays != null;
525        getLayerManager().getEditDataSet().clearSelection(w);
526        w.setHighlighted(false);
527        sourceWays.remove(w);
528    }
529
530    private void clearSourceWays() {
531        assert sourceWays != null;
532        getLayerManager().getEditDataSet().clearSelection(sourceWays);
533        for (Way w : sourceWays) {
534            w.setHighlighted(false);
535        }
536        sourceWays.clear();
537    }
538
539    /**
540     * Cancels the drag in progress, if any. Nothing has been changed yet, since the parallel ways are only created
541     * when the mouse is released.
542     */
543    private void cancelDrag() {
544        if (mode == Mode.DRAGGING) {
545            pWays = null;
546            helperSegment = null;
547            setMode(Mode.NORMAL);
548            MainApplication.getMap().statusLine.setDist(-1);
549            temporaryLayer.invalidate();
550        }
551        resetMouseTrackingState();
552    }
553
554    private void resetMouseTrackingState() {
555        mouseIsDown = false;
556        mousePressedPos = null;
557        mouseHasBeenDragged = false;
558    }
559
560    // TODO: rename
561    private boolean initParallelWays(Point p, boolean copyTags) {
562        referenceSegment = mv.getNearestWaySegment(p, OsmPrimitive::isUsable, true);
563        if (referenceSegment == null)
564            return false;
565
566        sourceWays.removeIf(w -> w.isIncomplete() || w.isEmpty());
567
568        // The selection may have been changed by other means while in this mode (e.g. Selection > Non-branching way
569        // sequences): if it contains the way under the mouse, the selected ways are the source ways.
570        Set<Way> selectedWays = new LinkedHashSet<>(getLayerManager().getEditDataSet().getSelectedWays());
571        selectedWays.removeIf(w -> w.isIncomplete() || w.isEmpty());
572        if (selectedWays.contains(referenceSegment.getWay()) && !selectedWays.equals(sourceWays)) {
573            clearSourceWays();
574            for (Way w : selectedWays) {
575                addSourceWay(w);
576            }
577        }
578
579        if (!sourceWays.contains(referenceSegment.getWay())) {
580            clearSourceWays();
581            addSourceWay(referenceSegment.getWay());
582        }
583
584        try {
585            int referenceWayIndex = -1;
586            int i = 0;
587            for (Way w : sourceWays) {
588                if (w == referenceSegment.getWay()) {
589                    referenceWayIndex = i;
590                    break;
591                }
592                i++;
593            }
594            pWays = new ParallelWays(sourceWays, copyTags, referenceWayIndex, ARC_STEP_DEGREES.get());
595            return true;
596        } catch (IllegalArgumentException e) {
597            Logging.debug(e);
598            new Notification(tr("Parallel Way:\n" +
599                    "The ways selected must form a simple branchless path"))
600                    .setIcon(JOptionPane.INFORMATION_MESSAGE)
601                    .show();
602            // The error dialog prevents us from getting the mouseReleased event
603            resetMouseTrackingState();
604            pWays = null;
605            return false;
606        }
607    }
608
609    private static String prefKey(String subKey) {
610        return "edit.make-parallel-way-action." + subKey;
611    }
612
613    /**
614     * A property that holds the keyboard modifiers.
615     * @author Michael Zangl
616     * @since 10869
617     */
618    private static class KeyboardModifiersProperty extends AbstractToStringProperty<Map<Modifier, Boolean>> {
619
620        KeyboardModifiersProperty(String key, String defaultValue) {
621            this(key, createFromString(defaultValue));
622        }
623
624        KeyboardModifiersProperty(String key, Map<Modifier, Boolean> defaultValue) {
625            super(key, defaultValue);
626        }
627
628        @Override
629        protected String toString(Map<Modifier, Boolean> t) {
630            StringBuilder sb = new StringBuilder();
631            for (Modifier mod : Modifier.values()) {
632                Boolean val = t.get(mod);
633                if (val == null) {
634                    sb.append('?');
635                } else if (val) {
636                    sb.append(Character.toUpperCase(mod.shortChar));
637                } else {
638                    sb.append(mod.shortChar);
639                }
640            }
641            return sb.toString();
642        }
643
644        @Override
645        protected Map<Modifier, Boolean> fromString(String string) {
646            return createFromString(string);
647        }
648
649        private static Map<Modifier, Boolean> createFromString(String string) {
650            Map<Modifier, Boolean> ret = new EnumMap<>(Modifier.class);
651            for (int i = 0; i < string.length(); i++) {
652                char c = string.charAt(i);
653                if (c == '?') {
654                    continue;
655                }
656                Optional<Modifier> mod = Modifier.findWithShortCode(c);
657                if (mod.isPresent()) {
658                    ret.put(mod.get(), Character.isUpperCase(c));
659                } else {
660                    Logging.debug("Ignoring unknown modifier {0}", c);
661                }
662            }
663            return Collections.unmodifiableMap(ret);
664        }
665    }
666
667    enum Modifier {
668        CTRL('c'),
669        ALT('a'),
670        SHIFT('s');
671
672        private final char shortChar;
673
674        Modifier(char shortChar) {
675            this.shortChar = Character.toLowerCase(shortChar);
676        }
677
678        /**
679         * Find the modifier with the given short code
680         * @param charCode The short code
681         * @return The modifier
682         */
683        public static Optional<Modifier> findWithShortCode(int charCode) {
684            return Stream.of(values()).filter(m -> m.shortChar == Character.toLowerCase(charCode)).findAny();
685        }
686    }
687
688    private final class ParallelWayLayer extends AbstractMapViewPaintable {
689        @Override
690        public void paint(Graphics2D g, MapView mv, Bounds bbox) {
691            if (mode == Mode.DRAGGING) {
692                CheckParameterUtil.ensureParameterNotNull(mv, "mv");
693
694                Color mainColor = MAIN_COLOR.get();
695                g.setStroke(REF_LINE_STROKE.get());
696                g.setColor(mainColor);
697                MapViewPath line = new MapViewPath(mv);
698                if (helperSegment != null) {
699                    line.moveTo(helperSegment.segmentStart);
700                    line.lineTo(helperSegment.segmentEnd);
701                } else {
702                    line.moveTo(referenceSegment.getFirstNode());
703                    line.lineTo(referenceSegment.getSecondNode());
704                }
705                g.draw(line.computeClippedLine(g.getStroke()));
706
707                g.setStroke(HELPER_LINE_STROKE.get());
708                g.setColor(mainColor);
709                line = new MapViewPath(mv);
710                line.moveTo(helperLineStart);
711                line.lineTo(helperLineEnd);
712                g.draw(line.computeClippedLine(g.getStroke()));
713
714                // Preview of the parallel way(s)
715                if (pWays != null) {
716                    List<EastNorth> pts = pWays.getOffsetPoints();
717                    if (pts.size() > 1) {
718                        g.setStroke(PREVIEW_STROKE.get());
719                        line = new MapViewPath(mv);
720                        line.moveTo(pts.get(0));
721                        for (int i = 1; i < pts.size(); i++) {
722                            line.lineTo(pts.get(i));
723                        }
724                        if (pWays.isResultClosed()) {
725                            line.lineTo(pts.get(0));
726                        }
727                        g.draw(line.computeClippedLine(g.getStroke()));
728                    }
729                }
730            }
731        }
732    }
733}