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