source: josm/trunk/src/org/openstreetmap/josm/gui/NavigatableComponent.java@ 17318

Last change on this file since 17318 was 16671, checked in by stoecker, 4 years ago

fix #19402 - fix race condition in auto follow function

  • Property svn:eol-style set to native
File size: 64.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import java.awt.Cursor;
5import java.awt.Point;
6import java.awt.Rectangle;
7import java.awt.event.ComponentAdapter;
8import java.awt.event.ComponentEvent;
9import java.awt.event.HierarchyEvent;
10import java.awt.event.HierarchyListener;
11import java.awt.geom.AffineTransform;
12import java.awt.geom.Point2D;
13import java.nio.charset.StandardCharsets;
14import java.text.NumberFormat;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.Collections;
18import java.util.Date;
19import java.util.HashSet;
20import java.util.LinkedList;
21import java.util.List;
22import java.util.Map;
23import java.util.Map.Entry;
24import java.util.Set;
25import java.util.Stack;
26import java.util.TreeMap;
27import java.util.concurrent.CopyOnWriteArrayList;
28import java.util.function.Predicate;
29import java.util.stream.Collectors;
30import java.util.zip.CRC32;
31
32import javax.swing.JComponent;
33import javax.swing.SwingUtilities;
34
35import org.openstreetmap.josm.data.Bounds;
36import org.openstreetmap.josm.data.ProjectionBounds;
37import org.openstreetmap.josm.data.SystemOfMeasurement;
38import org.openstreetmap.josm.data.ViewportData;
39import org.openstreetmap.josm.data.coor.EastNorth;
40import org.openstreetmap.josm.data.coor.ILatLon;
41import org.openstreetmap.josm.data.coor.LatLon;
42import org.openstreetmap.josm.data.osm.BBox;
43import org.openstreetmap.josm.data.osm.DataSet;
44import org.openstreetmap.josm.data.osm.Node;
45import org.openstreetmap.josm.data.osm.OsmPrimitive;
46import org.openstreetmap.josm.data.osm.Relation;
47import org.openstreetmap.josm.data.osm.Way;
48import org.openstreetmap.josm.data.osm.WaySegment;
49import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
50import org.openstreetmap.josm.data.preferences.BooleanProperty;
51import org.openstreetmap.josm.data.preferences.DoubleProperty;
52import org.openstreetmap.josm.data.preferences.IntegerProperty;
53import org.openstreetmap.josm.data.projection.Projection;
54import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
55import org.openstreetmap.josm.data.projection.ProjectionRegistry;
56import org.openstreetmap.josm.gui.help.Helpful;
57import org.openstreetmap.josm.gui.layer.NativeScaleLayer;
58import org.openstreetmap.josm.gui.layer.NativeScaleLayer.Scale;
59import org.openstreetmap.josm.gui.layer.NativeScaleLayer.ScaleList;
60import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
61import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
62import org.openstreetmap.josm.gui.util.CursorManager;
63import org.openstreetmap.josm.gui.util.GuiHelper;
64import org.openstreetmap.josm.spi.preferences.Config;
65import org.openstreetmap.josm.tools.Logging;
66import org.openstreetmap.josm.tools.Utils;
67
68/**
69 * A component that can be navigated by a {@link MapMover}. Used as map view and for the
70 * zoomer in the download dialog.
71 *
72 * @author imi
73 * @since 41
74 */
75public class NavigatableComponent extends JComponent implements Helpful {
76
77 private static final double ALIGNMENT_EPSILON = 1e-3;
78
79 /**
80 * Interface to notify listeners of the change of the zoom area.
81 * @since 10600 (functional interface)
82 */
83 @FunctionalInterface
84 public interface ZoomChangeListener {
85 /**
86 * Method called when the zoom area has changed.
87 */
88 void zoomChanged();
89 }
90
91 /**
92 * To determine if a primitive is currently selectable.
93 */
94 public transient Predicate<OsmPrimitive> isSelectablePredicate = prim -> {
95 if (!prim.isSelectable()) return false;
96 // if it isn't displayed on screen, you cannot click on it
97 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().lock();
98 try {
99 return !MapPaintStyles.getStyles().get(prim, getDist100Pixel(), this).isEmpty();
100 } finally {
101 MapCSSStyleSource.STYLE_SOURCE_LOCK.readLock().unlock();
102 }
103 };
104
105 /** Snap distance */
106 public static final IntegerProperty PROP_SNAP_DISTANCE = new IntegerProperty("mappaint.node.snap-distance", 10);
107 /** Zoom steps to get double scale */
108 public static final DoubleProperty PROP_ZOOM_RATIO = new DoubleProperty("zoom.ratio", 2.0);
109 /** Divide intervals between native resolution levels to smaller steps if they are much larger than zoom ratio */
110 public static final BooleanProperty PROP_ZOOM_INTERMEDIATE_STEPS = new BooleanProperty("zoom.intermediate-steps", true);
111 /** scale follows native resolution of layer status when layer is created */
112 public static final BooleanProperty PROP_ZOOM_SCALE_FOLLOW_NATIVE_RES_AT_LOAD = new BooleanProperty(
113 "zoom.scale-follow-native-resolution-at-load", true);
114
115 /**
116 * The layer which scale is set to.
117 */
118 private transient NativeScaleLayer nativeScaleLayer;
119
120 /**
121 * the zoom listeners
122 */
123 private static final CopyOnWriteArrayList<ZoomChangeListener> zoomChangeListeners = new CopyOnWriteArrayList<>();
124
125 /**
126 * Removes a zoom change listener
127 *
128 * @param listener the listener. Ignored if null or already absent
129 */
130 public static void removeZoomChangeListener(ZoomChangeListener listener) {
131 zoomChangeListeners.remove(listener);
132 }
133
134 /**
135 * Adds a zoom change listener
136 *
137 * @param listener the listener. Ignored if null or already registered.
138 */
139 public static void addZoomChangeListener(ZoomChangeListener listener) {
140 if (listener != null) {
141 zoomChangeListeners.addIfAbsent(listener);
142 }
143 }
144
145 protected static void fireZoomChanged() {
146 GuiHelper.runInEDTAndWait(() -> {
147 for (ZoomChangeListener l : zoomChangeListeners) {
148 l.zoomChanged();
149 }
150 });
151 }
152
153 // The only events that may move/resize this map view are window movements or changes to the map view size.
154 // We can clean this up more by only recalculating the state on repaint.
155 private final transient HierarchyListener hierarchyListener = e -> {
156 long interestingFlags = HierarchyEvent.ANCESTOR_MOVED | HierarchyEvent.SHOWING_CHANGED;
157 if ((e.getChangeFlags() & interestingFlags) != 0) {
158 updateLocationState();
159 }
160 };
161
162 private final transient ComponentAdapter componentListener = new ComponentAdapter() {
163 @Override
164 public void componentShown(ComponentEvent e) {
165 updateLocationState();
166 }
167
168 @Override
169 public void componentResized(ComponentEvent e) {
170 updateLocationState();
171 }
172 };
173
174 protected transient ViewportData initialViewport;
175
176 protected final transient CursorManager cursorManager = new CursorManager(this);
177
178 /**
179 * The current state (scale, center, ...) of this map view.
180 */
181 private transient MapViewState state;
182
183 /**
184 * Main uses weak link to store this, so we need to keep a reference.
185 */
186 private final ProjectionChangeListener projectionChangeListener = (oldValue, newValue) -> fixProjection();
187
188 /**
189 * Constructs a new {@code NavigatableComponent}.
190 */
191 public NavigatableComponent() {
192 setLayout(null);
193 state = MapViewState.createDefaultState(getWidth(), getHeight());
194 ProjectionRegistry.addProjectionChangeListener(projectionChangeListener);
195 }
196
197 @Override
198 public void addNotify() {
199 updateLocationState();
200 addHierarchyListener(hierarchyListener);
201 addComponentListener(componentListener);
202 super.addNotify();
203 }
204
205 @Override
206 public void removeNotify() {
207 removeHierarchyListener(hierarchyListener);
208 removeComponentListener(componentListener);
209 super.removeNotify();
210 }
211
212 /**
213 * Choose a layer that scale will be snap to its native scales.
214 * @param nativeScaleLayer layer to which scale will be snapped
215 */
216 public void setNativeScaleLayer(NativeScaleLayer nativeScaleLayer) {
217 this.nativeScaleLayer = nativeScaleLayer;
218 zoomTo(getCenter(), scaleRound(getScale()));
219 repaint();
220 }
221
222 /**
223 * Replies the layer which scale is set to.
224 * @return the current scale layer (may be null)
225 */
226 public NativeScaleLayer getNativeScaleLayer() {
227 return nativeScaleLayer;
228 }
229
230 /**
231 * Get a new scale that is zoomed in from previous scale
232 * and snapped to selected native scale layer.
233 * @return new scale
234 */
235 public double scaleZoomIn() {
236 return scaleZoomManyTimes(-1);
237 }
238
239 /**
240 * Get a new scale that is zoomed out from previous scale
241 * and snapped to selected native scale layer.
242 * @return new scale
243 */
244 public double scaleZoomOut() {
245 return scaleZoomManyTimes(1);
246 }
247
248 /**
249 * Get a new scale that is zoomed in/out a number of times
250 * from previous scale and snapped to selected native scale layer.
251 * @param times count of zoom operations, negative means zoom in
252 * @return new scale
253 */
254 public double scaleZoomManyTimes(int times) {
255 if (nativeScaleLayer != null) {
256 ScaleList scaleList = nativeScaleLayer.getNativeScales();
257 if (scaleList != null) {
258 if (PROP_ZOOM_INTERMEDIATE_STEPS.get()) {
259 scaleList = scaleList.withIntermediateSteps(PROP_ZOOM_RATIO.get());
260 }
261 Scale s = scaleList.scaleZoomTimes(getScale(), PROP_ZOOM_RATIO.get(), times);
262 return s != null ? s.getScale() : 0;
263 }
264 }
265 return getScale() * Math.pow(PROP_ZOOM_RATIO.get(), times);
266 }
267
268 /**
269 * Get a scale snapped to native resolutions, use round method.
270 * It gives nearest step from scale list.
271 * Use round method.
272 * @param scale to snap
273 * @return snapped scale
274 */
275 public double scaleRound(double scale) {
276 return scaleSnap(scale, false);
277 }
278
279 /**
280 * Get a scale snapped to native resolutions.
281 * It gives nearest lower step from scale list, usable to fit objects.
282 * @param scale to snap
283 * @return snapped scale
284 */
285 public double scaleFloor(double scale) {
286 return scaleSnap(scale, true);
287 }
288
289 /**
290 * Get a scale snapped to native resolutions.
291 * It gives nearest lower step from scale list, usable to fit objects.
292 * @param scale to snap
293 * @param floor use floor instead of round, set true when fitting view to objects
294 * @return new scale
295 */
296 public double scaleSnap(double scale, boolean floor) {
297 if (nativeScaleLayer != null) {
298 ScaleList scaleList = nativeScaleLayer.getNativeScales();
299 if (scaleList != null) {
300 if (PROP_ZOOM_INTERMEDIATE_STEPS.get()) {
301 scaleList = scaleList.withIntermediateSteps(PROP_ZOOM_RATIO.get());
302 }
303 Scale snapscale = scaleList.getSnapScale(scale, PROP_ZOOM_RATIO.get(), floor);
304 return snapscale != null ? snapscale.getScale() : scale;
305 }
306 }
307 return scale;
308 }
309
310 /**
311 * Zoom in current view. Use configured zoom step and scaling settings.
312 */
313 public void zoomIn() {
314 zoomTo(state.getCenter().getEastNorth(), scaleZoomIn());
315 }
316
317 /**
318 * Zoom out current view. Use configured zoom step and scaling settings.
319 */
320 public void zoomOut() {
321 zoomTo(state.getCenter().getEastNorth(), scaleZoomOut());
322 }
323
324 protected void updateLocationState() {
325 if (isVisibleOnScreen()) {
326 state = state.usingLocation(this);
327 }
328 }
329
330 protected boolean isVisibleOnScreen() {
331 return SwingUtilities.getWindowAncestor(this) != null && isShowing();
332 }
333
334 /**
335 * Changes the projection settings used for this map view.
336 * <p>
337 * Made public temporarily, will be made private later.
338 */
339 public void fixProjection() {
340 state = state.usingProjection(ProjectionRegistry.getProjection());
341 repaint();
342 }
343
344 /**
345 * Gets the current view state. This includes the scale, the current view area and the position.
346 * @return The current state.
347 */
348 public MapViewState getState() {
349 return state;
350 }
351
352 /**
353 * Returns the text describing the given distance in the current system of measurement.
354 * @param dist The distance in metres.
355 * @return the text describing the given distance in the current system of measurement.
356 * @since 3406
357 */
358 public static String getDistText(double dist) {
359 return SystemOfMeasurement.getSystemOfMeasurement().getDistText(dist);
360 }
361
362 /**
363 * Returns the text describing the given distance in the current system of measurement.
364 * @param dist The distance in metres
365 * @param format A {@link NumberFormat} to format the area value
366 * @param threshold Values lower than this {@code threshold} are displayed as {@code "< [threshold]"}
367 * @return the text describing the given distance in the current system of measurement.
368 * @since 7135
369 */
370 public static String getDistText(final double dist, final NumberFormat format, final double threshold) {
371 return SystemOfMeasurement.getSystemOfMeasurement().getDistText(dist, format, threshold);
372 }
373
374 /**
375 * Returns the text describing the distance in meter that correspond to 100 px on screen.
376 * @return the text describing the distance in meter that correspond to 100 px on screen
377 */
378 public String getDist100PixelText() {
379 return getDistText(getDist100Pixel());
380 }
381
382 /**
383 * Get the distance in meter that correspond to 100 px on screen.
384 *
385 * @return the distance in meter that correspond to 100 px on screen
386 */
387 public double getDist100Pixel() {
388 return getDist100Pixel(true);
389 }
390
391 /**
392 * Get the distance in meter that correspond to 100 px on screen.
393 *
394 * @param alwaysPositive if true, makes sure the return value is always
395 * &gt; 0. (Two points 100 px apart can appear to be identical if the user
396 * has zoomed out a lot and the projection code does something funny.)
397 * @return the distance in meter that correspond to 100 px on screen
398 */
399 public double getDist100Pixel(boolean alwaysPositive) {
400 int w = getWidth()/2;
401 int h = getHeight()/2;
402 LatLon ll1 = getLatLon(w-50, h);
403 LatLon ll2 = getLatLon(w+50, h);
404 double gcd = ll1.greatCircleDistance(ll2);
405 if (alwaysPositive && gcd <= 0)
406 return 0.1;
407 return gcd;
408 }
409
410 /**
411 * Returns the current center of the viewport.
412 *
413 * (Use {@link #zoomTo(EastNorth)} to the change the center.)
414 *
415 * @return the current center of the viewport
416 */
417 public EastNorth getCenter() {
418 return state.getCenter().getEastNorth();
419 }
420
421 /**
422 * Returns the current scale.
423 *
424 * In east/north units per pixel.
425 *
426 * @return the current scale
427 */
428 public double getScale() {
429 return state.getScale();
430 }
431
432 /**
433 * Returns geographic coordinates from a specific pixel coordination on the screen.
434 * @param x X-Pixelposition to get coordinate from
435 * @param y Y-Pixelposition to get coordinate from
436 *
437 * @return Geographic coordinates from a specific pixel coordination on the screen.
438 */
439 public EastNorth getEastNorth(int x, int y) {
440 return state.getForView(x, y).getEastNorth();
441 }
442
443 /**
444 * Determines the projection bounds of view area.
445 * @return the projection bounds of view area
446 */
447 public ProjectionBounds getProjectionBounds() {
448 return getState().getViewArea().getProjectionBounds();
449 }
450
451 /* FIXME: replace with better method - used by MapSlider */
452 public ProjectionBounds getMaxProjectionBounds() {
453 Bounds b = getProjection().getWorldBoundsLatLon();
454 return new ProjectionBounds(getProjection().latlon2eastNorth(b.getMin()),
455 getProjection().latlon2eastNorth(b.getMax()));
456 }
457
458 /* FIXME: replace with better method - used by Main to reset Bounds when projection changes, don't use otherwise */
459 public Bounds getRealBounds() {
460 return getState().getViewArea().getCornerBounds();
461 }
462
463 /**
464 * Returns unprojected geographic coordinates for a specific pixel position on the screen.
465 * @param x X-Pixelposition to get coordinate from
466 * @param y Y-Pixelposition to get coordinate from
467 *
468 * @return Geographic unprojected coordinates from a specific pixel position on the screen.
469 */
470 public LatLon getLatLon(int x, int y) {
471 return getProjection().eastNorth2latlon(getEastNorth(x, y));
472 }
473
474 /**
475 * Returns unprojected geographic coordinates for a specific pixel position on the screen.
476 * @param x X-Pixelposition to get coordinate from
477 * @param y Y-Pixelposition to get coordinate from
478 *
479 * @return Geographic unprojected coordinates from a specific pixel position on the screen.
480 */
481 public LatLon getLatLon(double x, double y) {
482 return getLatLon((int) x, (int) y);
483 }
484
485 /**
486 * Determines the projection bounds of given rectangle.
487 * @param r rectangle
488 * @return the projection bounds of {@code r}
489 */
490 public ProjectionBounds getProjectionBounds(Rectangle r) {
491 return getState().getViewArea(r).getProjectionBounds();
492 }
493
494 /**
495 * Returns minimum bounds that will cover a given rectangle.
496 * @param r rectangle
497 * @return Minimum bounds that will cover rectangle
498 */
499 public Bounds getLatLonBounds(Rectangle r) {
500 return ProjectionRegistry.getProjection().getLatLonBoundsBox(getProjectionBounds(r));
501 }
502
503 /**
504 * Creates an affine transform that is used to convert the east/north coordinates to view coordinates.
505 * @return The affine transform.
506 */
507 public AffineTransform getAffineTransform() {
508 return getState().getAffineTransform();
509 }
510
511 /**
512 * Return the point on the screen where this Coordinate would be.
513 * @param p The point, where this geopoint would be drawn.
514 * @return The point on screen where "point" would be drawn, relative to the own top/left.
515 */
516 public Point2D getPoint2D(EastNorth p) {
517 if (null == p)
518 return new Point();
519 return getState().getPointFor(p).getInView();
520 }
521
522 /**
523 * Return the point on the screen where this Coordinate would be.
524 *
525 * Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)}
526 * @param latlon The point, where this geopoint would be drawn.
527 * @return The point on screen where "point" would be drawn, relative to the own top/left.
528 */
529 public Point2D getPoint2D(ILatLon latlon) {
530 if (latlon == null) {
531 return new Point();
532 } else {
533 return getPoint2D(latlon.getEastNorth(ProjectionRegistry.getProjection()));
534 }
535 }
536
537 /**
538 * Return the point on the screen where this Coordinate would be.
539 *
540 * Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)}
541 * @param latlon The point, where this geopoint would be drawn.
542 * @return The point on screen where "point" would be drawn, relative to the own top/left.
543 */
544 public Point2D getPoint2D(LatLon latlon) {
545 return getPoint2D((ILatLon) latlon);
546 }
547
548 /**
549 * Return the point on the screen where this Node would be.
550 *
551 * Alternative: {@link #getState()}, then {@link MapViewState#getPointFor(ILatLon)}
552 * @param n The node, where this geopoint would be drawn.
553 * @return The point on screen where "node" would be drawn, relative to the own top/left.
554 */
555 public Point2D getPoint2D(Node n) {
556 return getPoint2D(n.getEastNorth());
557 }
558
559 /**
560 * looses precision, may overflow (depends on p and current scale)
561 * @param p east/north
562 * @return point
563 * @see #getPoint2D(EastNorth)
564 */
565 public Point getPoint(EastNorth p) {
566 Point2D d = getPoint2D(p);
567 return new Point((int) d.getX(), (int) d.getY());
568 }
569
570 /**
571 * looses precision, may overflow (depends on p and current scale)
572 * @param latlon lat/lon
573 * @return point
574 * @see #getPoint2D(LatLon)
575 * @since 12725
576 */
577 public Point getPoint(ILatLon latlon) {
578 Point2D d = getPoint2D(latlon);
579 return new Point((int) d.getX(), (int) d.getY());
580 }
581
582 /**
583 * looses precision, may overflow (depends on p and current scale)
584 * @param latlon lat/lon
585 * @return point
586 * @see #getPoint2D(LatLon)
587 */
588 public Point getPoint(LatLon latlon) {
589 return getPoint((ILatLon) latlon);
590 }
591
592 /**
593 * looses precision, may overflow (depends on p and current scale)
594 * @param n node
595 * @return point
596 * @see #getPoint2D(Node)
597 */
598 public Point getPoint(Node n) {
599 Point2D d = getPoint2D(n);
600 return new Point((int) d.getX(), (int) d.getY());
601 }
602
603 /**
604 * Zoom to the given coordinate and scale.
605 *
606 * @param newCenter The center x-value (easting) to zoom to.
607 * @param newScale The scale to use.
608 */
609 public void zoomTo(EastNorth newCenter, double newScale) {
610 zoomTo(newCenter, newScale, false);
611 }
612
613 /**
614 * Zoom to the given coordinate and scale.
615 *
616 * @param center The center x-value (easting) to zoom to.
617 * @param scale The scale to use.
618 * @param initial true if this call initializes the viewport.
619 */
620 public void zoomTo(EastNorth center, double scale, boolean initial) {
621 Bounds b = getProjection().getWorldBoundsLatLon();
622 ProjectionBounds pb = getProjection().getWorldBoundsBoxEastNorth();
623 double newScale = scale;
624 int width = getWidth();
625 int height = getHeight();
626
627 // make sure, the center of the screen is within projection bounds
628 double east = center.east();
629 double north = center.north();
630 east = Math.max(east, pb.minEast);
631 east = Math.min(east, pb.maxEast);
632 north = Math.max(north, pb.minNorth);
633 north = Math.min(north, pb.maxNorth);
634 EastNorth newCenter = new EastNorth(east, north);
635
636 // don't zoom out too much, the world bounds should be at least
637 // half the size of the screen
638 double pbHeight = pb.maxNorth - pb.minNorth;
639 if (height > 0 && 2 * pbHeight < height * newScale) {
640 double newScaleH = 2 * pbHeight / height;
641 double pbWidth = pb.maxEast - pb.minEast;
642 if (width > 0 && 2 * pbWidth < width * newScale) {
643 double newScaleW = 2 * pbWidth / width;
644 newScale = Math.max(newScaleH, newScaleW);
645 }
646 }
647
648 // don't zoom in too much, minimum: 100 px = 1 cm
649 LatLon ll1 = getLatLon(width / 2 - 50, height / 2);
650 LatLon ll2 = getLatLon(width / 2 + 50, height / 2);
651 if (ll1.isValid() && ll2.isValid() && b.contains(ll1) && b.contains(ll2)) {
652 double dm = ll1.greatCircleDistance(ll2);
653 double den = 100 * getScale();
654 double scaleMin = 0.01 * den / dm / 100;
655 if (newScale < scaleMin && !Double.isInfinite(scaleMin)) {
656 newScale = scaleMin;
657 }
658 }
659
660 // snap scale to imagery if needed
661 newScale = scaleRound(newScale);
662
663 // Align to the pixel grid:
664 // This is a sub-pixel correction to ensure consistent drawing at a certain scale.
665 // For example take 2 nodes, that have a distance of exactly 2.6 pixels.
666 // Depending on the offset, the distance in rounded or truncated integer
667 // pixels will be 2 or 3. It is preferable to have a consistent distance
668 // and not switch back and forth as the viewport moves. This can be achieved by
669 // locking an arbitrary point to integer pixel coordinates. (Here the EastNorth
670 // origin is used as reference point.)
671 // Note that the normal right mouse button drag moves the map by integer pixel
672 // values, so it is not an issue in this case. It only shows when zooming
673 // in & back out, etc.
674 MapViewState mvs = getState().usingScale(newScale);
675 mvs = mvs.movedTo(mvs.getCenter(), newCenter);
676 Point2D enOrigin = mvs.getPointFor(new EastNorth(0, 0)).getInView();
677 // as a result of the alignment, it is common to round "half integer" values
678 // like 1.49999, which is numerically unstable; add small epsilon to resolve this
679 Point2D enOriginAligned = new Point2D.Double(
680 Math.round(enOrigin.getX()) + ALIGNMENT_EPSILON,
681 Math.round(enOrigin.getY()) + ALIGNMENT_EPSILON);
682 EastNorth enShift = mvs.getForView(enOriginAligned.getX(), enOriginAligned.getY()).getEastNorth();
683 newCenter = newCenter.subtract(enShift);
684
685 EastNorth oldCenter = getCenter();
686 if (!newCenter.equals(oldCenter) || !Utils.equalsEpsilon(getScale(), newScale)) {
687 if (!initial) {
688 pushZoomUndo(oldCenter, getScale());
689 }
690 zoomNoUndoTo(newCenter, newScale, initial);
691 }
692 }
693
694 /**
695 * Zoom to the given coordinate without adding to the zoom undo buffer.
696 *
697 * @param newCenter The center x-value (easting) to zoom to.
698 * @param newScale The scale to use.
699 * @param initial true if this call initializes the viewport.
700 */
701 private void zoomNoUndoTo(EastNorth newCenter, double newScale, boolean initial) {
702 if (!Utils.equalsEpsilon(getScale(), newScale)) {
703 state = state.usingScale(newScale);
704 }
705 if (!newCenter.equals(getCenter())) {
706 state = state.movedTo(state.getCenter(), newCenter);
707 }
708 if (!initial) {
709 repaint();
710 fireZoomChanged();
711 }
712 }
713
714 /**
715 * Zoom to given east/north.
716 * @param newCenter new center coordinates
717 */
718 public void zoomTo(EastNorth newCenter) {
719 zoomTo(newCenter, getScale());
720 }
721
722 /**
723 * Zoom to given lat/lon.
724 * @param newCenter new center coordinates
725 * @since 12725
726 */
727 public void zoomTo(ILatLon newCenter) {
728 zoomTo(getProjection().latlon2eastNorth(newCenter));
729 }
730
731 /**
732 * Zoom to given lat/lon.
733 * @param newCenter new center coordinates
734 */
735 public void zoomTo(LatLon newCenter) {
736 zoomTo((ILatLon) newCenter);
737 }
738
739 /**
740 * Thread class for smooth scrolling. Made a separate class, so we can safely terminate it.
741 */
742 private class SmoothScrollThread extends Thread {
743 private boolean doStop;
744 private final EastNorth oldCenter = getCenter();
745 private final EastNorth finalNewCenter;
746 private final long frames;
747 private final long sleepTime;
748
749 SmoothScrollThread(EastNorth newCenter, long frameNum, int fps) {
750 super("smooth-scroller");
751 finalNewCenter = newCenter;
752 frames = frameNum;
753 sleepTime = 1000L / fps;
754 }
755
756 @Override
757 public void run() {
758 try {
759 for (int i = 0; i < frames && !doStop; i++) {
760 final EastNorth z = oldCenter.interpolate(finalNewCenter, (1.0+i) / frames);
761 GuiHelper.runInEDTAndWait(() -> {
762 zoomTo(z);
763 });
764 Thread.sleep(sleepTime);
765 }
766 } catch (InterruptedException ex) {
767 Logging.warn("Interruption during smooth scrolling");
768 }
769 }
770
771 public void stopIt() {
772 doStop = true;
773 }
774 }
775
776 /**
777 * Create a thread that moves the viewport to the given center in an animated fashion.
778 * @param newCenter new east/north center
779 */
780 public void smoothScrollTo(EastNorth newCenter) {
781 final EastNorth oldCenter = getCenter();
782 if (!newCenter.equals(oldCenter)) {
783 final int fps = Config.getPref().getInt("smooth.scroll.fps", 20); // animation frames per second
784 final int speed = Config.getPref().getInt("smooth.scroll.speed", 1500); // milliseconds for full-screen-width pan
785 final int maxtime = Config.getPref().getInt("smooth.scroll.maxtime", 5000); // milliseconds maximum scroll time
786 final double distance = newCenter.distance(oldCenter) / getScale();
787 double milliseconds = distance / getWidth() * speed;
788 if (milliseconds > maxtime) { // prevent overlong scroll time, speed up if necessary
789 milliseconds = maxtime;
790 }
791
792 ThreadGroup group = Thread.currentThread().getThreadGroup();
793 Thread[] threads = new Thread[group.activeCount()];
794 group.enumerate(threads, true);
795 boolean stopped = false;
796 for (Thread t : threads) {
797 if (t instanceof SmoothScrollThread) {
798 ((SmoothScrollThread) t).stopIt();
799 /* handle this case outside in case there is more than one smooth thread */
800 stopped = true;
801 }
802 }
803 if (stopped && milliseconds > maxtime/2.0) { /* we aren't fast enough, skip smooth */
804 Logging.warn("Skip smooth scrolling");
805 zoomTo(newCenter);
806 } else {
807 long frames = Math.round(milliseconds * fps / 1000);
808 if (frames <= 1)
809 zoomTo(newCenter);
810 else
811 new SmoothScrollThread(newCenter, frames, fps).start();
812 }
813 }
814 }
815
816 public void zoomManyTimes(double x, double y, int times) {
817 double oldScale = getScale();
818 double newScale = scaleZoomManyTimes(times);
819 zoomToFactor(x, y, newScale / oldScale);
820 }
821
822 public void zoomToFactor(double x, double y, double factor) {
823 double newScale = getScale()*factor;
824 EastNorth oldUnderMouse = getState().getForView(x, y).getEastNorth();
825 MapViewState newState = getState().usingScale(newScale);
826 newState = newState.movedTo(newState.getForView(x, y), oldUnderMouse);
827 zoomTo(newState.getCenter().getEastNorth(), newScale);
828 }
829
830 public void zoomToFactor(EastNorth newCenter, double factor) {
831 zoomTo(newCenter, getScale()*factor);
832 }
833
834 public void zoomToFactor(double factor) {
835 zoomTo(getCenter(), getScale()*factor);
836 }
837
838 /**
839 * Zoom to given projection bounds.
840 * @param box new projection bounds
841 */
842 public void zoomTo(ProjectionBounds box) {
843 double newScale = box.getScale(getWidth(), getHeight());
844 newScale = scaleFloor(newScale);
845 zoomTo(box.getCenter(), newScale);
846 }
847
848 /**
849 * Zoom to given bounds.
850 * @param box new bounds
851 */
852 public void zoomTo(Bounds box) {
853 zoomTo(new ProjectionBounds(getProjection().latlon2eastNorth(box.getMin()),
854 getProjection().latlon2eastNorth(box.getMax())));
855 }
856
857 /**
858 * Zoom to given viewport data.
859 * @param viewport new viewport data
860 */
861 public void zoomTo(ViewportData viewport) {
862 if (viewport == null) return;
863 if (viewport.getBounds() != null) {
864 if (!viewport.getBounds().hasExtend()) {
865 // see #18623
866 BoundingXYVisitor v = new BoundingXYVisitor();
867 v.visit(viewport.getBounds());
868 zoomTo(v);
869 } else {
870 zoomTo(viewport.getBounds());
871 }
872
873 } else {
874 zoomTo(viewport.getCenter(), viewport.getScale(), true);
875 }
876 }
877
878 /**
879 * Set the new dimension to the view.
880 * @param v box to zoom to
881 */
882 public void zoomTo(BoundingXYVisitor v) {
883 if (v == null) {
884 v = new BoundingXYVisitor();
885 }
886 if (v.getBounds() == null) {
887 v.visit(getProjection().getWorldBoundsLatLon());
888 }
889
890 // increase bbox. This is required
891 // especially if the bbox contains one single node, but helpful
892 // in most other cases as well.
893 // Do not zoom if the current scale covers the selection, #16706
894 final MapView mapView = MainApplication.getMap().mapView;
895 final double mapScale = mapView.getScale();
896 final double minScale = v.getBounds().getScale(mapView.getWidth(), mapView.getHeight());
897 v.enlargeBoundingBoxLogarithmically();
898 final double maxScale = v.getBounds().getScale(mapView.getWidth(), mapView.getHeight());
899 if (minScale <= mapScale && mapScale < maxScale) {
900 mapView.zoomTo(v.getBounds().getCenter());
901 } else {
902 zoomTo(v.getBounds());
903 }
904 }
905
906 private static class ZoomData {
907 private final EastNorth center;
908 private final double scale;
909
910 ZoomData(EastNorth center, double scale) {
911 this.center = center;
912 this.scale = scale;
913 }
914
915 public EastNorth getCenterEastNorth() {
916 return center;
917 }
918
919 public double getScale() {
920 return scale;
921 }
922 }
923
924 private final transient Stack<ZoomData> zoomUndoBuffer = new Stack<>();
925 private final transient Stack<ZoomData> zoomRedoBuffer = new Stack<>();
926 private Date zoomTimestamp = new Date();
927
928 private void pushZoomUndo(EastNorth center, double scale) {
929 Date now = new Date();
930 if ((now.getTime() - zoomTimestamp.getTime()) > (Config.getPref().getDouble("zoom.undo.delay", 1.0) * 1000)) {
931 zoomUndoBuffer.push(new ZoomData(center, scale));
932 if (zoomUndoBuffer.size() > Config.getPref().getInt("zoom.undo.max", 50)) {
933 zoomUndoBuffer.remove(0);
934 }
935 zoomRedoBuffer.clear();
936 }
937 zoomTimestamp = now;
938 }
939
940 /**
941 * Zoom to previous location.
942 */
943 public void zoomPrevious() {
944 if (!zoomUndoBuffer.isEmpty()) {
945 ZoomData zoom = zoomUndoBuffer.pop();
946 zoomRedoBuffer.push(new ZoomData(getCenter(), getScale()));
947 zoomNoUndoTo(zoom.getCenterEastNorth(), zoom.getScale(), false);
948 }
949 }
950
951 /**
952 * Zoom to next location.
953 */
954 public void zoomNext() {
955 if (!zoomRedoBuffer.isEmpty()) {
956 ZoomData zoom = zoomRedoBuffer.pop();
957 zoomUndoBuffer.push(new ZoomData(getCenter(), getScale()));
958 zoomNoUndoTo(zoom.getCenterEastNorth(), zoom.getScale(), false);
959 }
960 }
961
962 /**
963 * Determines if zoom history contains "undo" entries.
964 * @return {@code true} if zoom history contains "undo" entries
965 */
966 public boolean hasZoomUndoEntries() {
967 return !zoomUndoBuffer.isEmpty();
968 }
969
970 /**
971 * Determines if zoom history contains "redo" entries.
972 * @return {@code true} if zoom history contains "redo" entries
973 */
974 public boolean hasZoomRedoEntries() {
975 return !zoomRedoBuffer.isEmpty();
976 }
977
978 private BBox getBBox(Point p, int snapDistance) {
979 return new BBox(getLatLon(p.x - snapDistance, p.y - snapDistance),
980 getLatLon(p.x + snapDistance, p.y + snapDistance));
981 }
982
983 /**
984 * The *result* does not depend on the current map selection state, neither does the result *order*.
985 * It solely depends on the distance to point p.
986 * @param p point
987 * @param predicate predicate to match
988 *
989 * @return a sorted map with the keys representing the distance of their associated nodes to point p.
990 */
991 private Map<Double, List<Node>> getNearestNodesImpl(Point p, Predicate<OsmPrimitive> predicate) {
992 Map<Double, List<Node>> nearestMap = new TreeMap<>();
993 DataSet ds = MainApplication.getLayerManager().getActiveDataSet();
994
995 if (ds != null) {
996 double dist, snapDistanceSq = PROP_SNAP_DISTANCE.get();
997 snapDistanceSq *= snapDistanceSq;
998
999 for (Node n : ds.searchNodes(getBBox(p, PROP_SNAP_DISTANCE.get()))) {
1000 if (predicate.test(n)
1001 && (dist = getPoint2D(n).distanceSq(p)) < snapDistanceSq) {
1002 nearestMap.computeIfAbsent(dist, k -> new LinkedList<>()).add(n);
1003 }
1004 }
1005 }
1006
1007 return nearestMap;
1008 }
1009
1010 /**
1011 * The *result* does not depend on the current map selection state,
1012 * neither does the result *order*.
1013 * It solely depends on the distance to point p.
1014 *
1015 * @param p the point for which to search the nearest segment.
1016 * @param ignore a collection of nodes which are not to be returned.
1017 * @param predicate the returned objects have to fulfill certain properties.
1018 *
1019 * @return All nodes nearest to point p that are in a belt from
1020 * dist(nearest) to dist(nearest)+4px around p and
1021 * that are not in ignore.
1022 */
1023 public final List<Node> getNearestNodes(Point p,
1024 Collection<Node> ignore, Predicate<OsmPrimitive> predicate) {
1025 List<Node> nearestList = Collections.emptyList();
1026
1027 if (ignore == null) {
1028 ignore = Collections.emptySet();
1029 }
1030
1031 Map<Double, List<Node>> nlists = getNearestNodesImpl(p, predicate);
1032 if (!nlists.isEmpty()) {
1033 Double minDistSq = null;
1034 for (Entry<Double, List<Node>> entry : nlists.entrySet()) {
1035 Double distSq = entry.getKey();
1036 List<Node> nlist = entry.getValue();
1037
1038 // filter nodes to be ignored before determining minDistSq..
1039 nlist.removeAll(ignore);
1040 if (minDistSq == null) {
1041 if (!nlist.isEmpty()) {
1042 minDistSq = distSq;
1043 nearestList = new ArrayList<>();
1044 nearestList.addAll(nlist);
1045 }
1046 } else {
1047 if (distSq-minDistSq < 16) {
1048 nearestList.addAll(nlist);
1049 }
1050 }
1051 }
1052 }
1053
1054 return nearestList;
1055 }
1056
1057 /**
1058 * The *result* does not depend on the current map selection state,
1059 * neither does the result *order*.
1060 * It solely depends on the distance to point p.
1061 *
1062 * @param p the point for which to search the nearest segment.
1063 * @param predicate the returned objects have to fulfill certain properties.
1064 *
1065 * @return All nodes nearest to point p that are in a belt from
1066 * dist(nearest) to dist(nearest)+4px around p.
1067 * @see #getNearestNodes(Point, Collection, Predicate)
1068 */
1069 public final List<Node> getNearestNodes(Point p, Predicate<OsmPrimitive> predicate) {
1070 return getNearestNodes(p, null, predicate);
1071 }
1072
1073 /**
1074 * The *result* depends on the current map selection state IF use_selected is true.
1075 *
1076 * If more than one node within node.snap-distance pixels is found,
1077 * the nearest node selected is returned IF use_selected is true.
1078 *
1079 * Else the nearest new/id=0 node within about the same distance
1080 * as the true nearest node is returned.
1081 *
1082 * If no such node is found either, the true nearest node to p is returned.
1083 *
1084 * Finally, if a node is not found at all, null is returned.
1085 *
1086 * @param p the screen point
1087 * @param predicate this parameter imposes a condition on the returned object, e.g.
1088 * give the nearest node that is tagged.
1089 * @param useSelected make search depend on selection
1090 *
1091 * @return A node within snap-distance to point p, that is chosen by the algorithm described.
1092 */
1093 public final Node getNearestNode(Point p, Predicate<OsmPrimitive> predicate, boolean useSelected) {
1094 return getNearestNode(p, predicate, useSelected, null);
1095 }
1096
1097 /**
1098 * The *result* depends on the current map selection state IF use_selected is true
1099 *
1100 * If more than one node within node.snap-distance pixels is found,
1101 * the nearest node selected is returned IF use_selected is true.
1102 *
1103 * If there are no selected nodes near that point, the node that is related to some of the preferredRefs
1104 *
1105 * Else the nearest new/id=0 node within about the same distance
1106 * as the true nearest node is returned.
1107 *
1108 * If no such node is found either, the true nearest node to p is returned.
1109 *
1110 * Finally, if a node is not found at all, null is returned.
1111 *
1112 * @param p the screen point
1113 * @param predicate this parameter imposes a condition on the returned object, e.g.
1114 * give the nearest node that is tagged.
1115 * @param useSelected make search depend on selection
1116 * @param preferredRefs primitives, whose nodes we prefer
1117 *
1118 * @return A node within snap-distance to point p, that is chosen by the algorithm described.
1119 * @since 6065
1120 */
1121 public final Node getNearestNode(Point p, Predicate<OsmPrimitive> predicate,
1122 boolean useSelected, Collection<OsmPrimitive> preferredRefs) {
1123
1124 Map<Double, List<Node>> nlists = getNearestNodesImpl(p, predicate);
1125 if (nlists.isEmpty()) return null;
1126
1127 if (preferredRefs != null && preferredRefs.isEmpty()) preferredRefs = null;
1128 Node ntsel = null, ntnew = null, ntref = null;
1129 boolean useNtsel = useSelected;
1130 double minDistSq = nlists.keySet().iterator().next();
1131
1132 for (Entry<Double, List<Node>> entry : nlists.entrySet()) {
1133 Double distSq = entry.getKey();
1134 for (Node nd : entry.getValue()) {
1135 // find the nearest selected node
1136 if (ntsel == null && nd.isSelected()) {
1137 ntsel = nd;
1138 // if there are multiple nearest nodes, prefer the one
1139 // that is selected. This is required in order to drag
1140 // the selected node if multiple nodes have the same
1141 // coordinates (e.g. after unglue)
1142 useNtsel |= Utils.equalsEpsilon(distSq, minDistSq);
1143 }
1144 if (ntref == null && preferredRefs != null && Utils.equalsEpsilon(distSq, minDistSq)) {
1145 List<OsmPrimitive> ndRefs = nd.getReferrers();
1146 if (preferredRefs.stream().anyMatch(ndRefs::contains)) {
1147 ntref = nd;
1148 }
1149 }
1150 // find the nearest newest node that is within about the same
1151 // distance as the true nearest node
1152 if (ntnew == null && nd.isNew() && (distSq-minDistSq < 1)) {
1153 ntnew = nd;
1154 }
1155 }
1156 }
1157
1158 // take nearest selected, nearest new or true nearest node to p, in that order
1159 if (ntsel != null && useNtsel)
1160 return ntsel;
1161 if (ntref != null)
1162 return ntref;
1163 if (ntnew != null)
1164 return ntnew;
1165 return nlists.values().iterator().next().get(0);
1166 }
1167
1168 /**
1169 * Convenience method to {@link #getNearestNode(Point, Predicate, boolean)}.
1170 * @param p the screen point
1171 * @param predicate this parameter imposes a condition on the returned object, e.g.
1172 * give the nearest node that is tagged.
1173 *
1174 * @return The nearest node to point p.
1175 */
1176 public final Node getNearestNode(Point p, Predicate<OsmPrimitive> predicate) {
1177 return getNearestNode(p, predicate, true);
1178 }
1179
1180 /**
1181 * The *result* does not depend on the current map selection state, neither does the result *order*.
1182 * It solely depends on the distance to point p.
1183 * @param p the screen point
1184 * @param predicate this parameter imposes a condition on the returned object, e.g.
1185 * give the nearest node that is tagged.
1186 *
1187 * @return a sorted map with the keys representing the perpendicular
1188 * distance of their associated way segments to point p.
1189 */
1190 private Map<Double, List<WaySegment>> getNearestWaySegmentsImpl(Point p, Predicate<OsmPrimitive> predicate) {
1191 Map<Double, List<WaySegment>> nearestMap = new TreeMap<>();
1192 DataSet ds = MainApplication.getLayerManager().getActiveDataSet();
1193
1194 if (ds != null) {
1195 double snapDistanceSq = Config.getPref().getInt("mappaint.segment.snap-distance", 10);
1196 snapDistanceSq *= snapDistanceSq;
1197
1198 for (Way w : ds.searchWays(getBBox(p, Config.getPref().getInt("mappaint.segment.snap-distance", 10)))) {
1199 if (!predicate.test(w)) {
1200 continue;
1201 }
1202 Node lastN = null;
1203 int i = -2;
1204 for (Node n : w.getNodes()) {
1205 i++;
1206 if (n.isDeleted() || n.isIncomplete()) { //FIXME: This shouldn't happen, raise exception?
1207 continue;
1208 }
1209 if (lastN == null) {
1210 lastN = n;
1211 continue;
1212 }
1213
1214 Point2D pA = getPoint2D(lastN);
1215 Point2D pB = getPoint2D(n);
1216 double c = pA.distanceSq(pB);
1217 double a = p.distanceSq(pB);
1218 double b = p.distanceSq(pA);
1219
1220 /* perpendicular distance squared
1221 * loose some precision to account for possible deviations in the calculation above
1222 * e.g. if identical (A and B) come about reversed in another way, values may differ
1223 * -- zero out least significant 32 dual digits of mantissa..
1224 */
1225 double perDistSq = Double.longBitsToDouble(
1226 Double.doubleToLongBits(a - (a - b + c) * (a - b + c) / 4 / c)
1227 >> 32 << 32); // resolution in numbers with large exponent not needed here..
1228
1229 if (perDistSq < snapDistanceSq && a < c + snapDistanceSq && b < c + snapDistanceSq) {
1230 nearestMap.computeIfAbsent(perDistSq, k -> new LinkedList<>()).add(new WaySegment(w, i));
1231 }
1232
1233 lastN = n;
1234 }
1235 }
1236 }
1237
1238 return nearestMap;
1239 }
1240
1241 /**
1242 * The result *order* depends on the current map selection state.
1243 * Segments within 10px of p are searched and sorted by their distance to {@code p},
1244 * then, within groups of equally distant segments, prefer those that are selected.
1245 *
1246 * @param p the point for which to search the nearest segments.
1247 * @param ignore a collection of segments which are not to be returned.
1248 * @param predicate the returned objects have to fulfill certain properties.
1249 *
1250 * @return all segments within 10px of p that are not in ignore,
1251 * sorted by their perpendicular distance.
1252 */
1253 public final List<WaySegment> getNearestWaySegments(Point p,
1254 Collection<WaySegment> ignore, Predicate<OsmPrimitive> predicate) {
1255 List<WaySegment> nearestList = new ArrayList<>();
1256 List<WaySegment> unselected = new LinkedList<>();
1257
1258 for (List<WaySegment> wss : getNearestWaySegmentsImpl(p, predicate).values()) {
1259 // put selected waysegs within each distance group first
1260 // makes the order of nearestList dependent on current selection state
1261 for (WaySegment ws : wss) {
1262 (ws.way.isSelected() ? nearestList : unselected).add(ws);
1263 }
1264 nearestList.addAll(unselected);
1265 unselected.clear();
1266 }
1267 if (ignore != null) {
1268 nearestList.removeAll(ignore);
1269 }
1270
1271 return nearestList;
1272 }
1273
1274 /**
1275 * The result *order* depends on the current map selection state.
1276 *
1277 * @param p the point for which to search the nearest segments.
1278 * @param predicate the returned objects have to fulfill certain properties.
1279 *
1280 * @return all segments within 10px of p, sorted by their perpendicular distance.
1281 * @see #getNearestWaySegments(Point, Collection, Predicate)
1282 */
1283 public final List<WaySegment> getNearestWaySegments(Point p, Predicate<OsmPrimitive> predicate) {
1284 return getNearestWaySegments(p, null, predicate);
1285 }
1286
1287 /**
1288 * The *result* depends on the current map selection state IF use_selected is true.
1289 *
1290 * @param p the point for which to search the nearest segment.
1291 * @param predicate the returned object has to fulfill certain properties.
1292 * @param useSelected whether selected way segments should be preferred.
1293 *
1294 * @return The nearest way segment to point p,
1295 * and, depending on use_selected, prefers a selected way segment, if found.
1296 * @see #getNearestWaySegments(Point, Collection, Predicate)
1297 */
1298 public final WaySegment getNearestWaySegment(Point p, Predicate<OsmPrimitive> predicate, boolean useSelected) {
1299 WaySegment wayseg = null;
1300 WaySegment ntsel = null;
1301
1302 for (List<WaySegment> wslist : getNearestWaySegmentsImpl(p, predicate).values()) {
1303 if (wayseg != null && ntsel != null) {
1304 break;
1305 }
1306 for (WaySegment ws : wslist) {
1307 if (wayseg == null) {
1308 wayseg = ws;
1309 }
1310 if (ntsel == null && ws.way.isSelected()) {
1311 ntsel = ws;
1312 }
1313 }
1314 }
1315
1316 return (ntsel != null && useSelected) ? ntsel : wayseg;
1317 }
1318
1319 /**
1320 * The *result* depends on the current map selection state IF use_selected is true.
1321 *
1322 * @param p the point for which to search the nearest segment.
1323 * @param predicate the returned object has to fulfill certain properties.
1324 * @param useSelected whether selected way segments should be preferred.
1325 * @param preferredRefs - prefer segments related to these primitives, may be null
1326 *
1327 * @return The nearest way segment to point p,
1328 * and, depending on use_selected, prefers a selected way segment, if found.
1329 * Also prefers segments of ways that are related to one of preferredRefs primitives
1330 *
1331 * @see #getNearestWaySegments(Point, Collection, Predicate)
1332 * @since 6065
1333 */
1334 public final WaySegment getNearestWaySegment(Point p, Predicate<OsmPrimitive> predicate,
1335 boolean useSelected, Collection<OsmPrimitive> preferredRefs) {
1336 WaySegment wayseg = null;
1337 if (preferredRefs != null && preferredRefs.isEmpty())
1338 preferredRefs = null;
1339
1340 for (List<WaySegment> wslist : getNearestWaySegmentsImpl(p, predicate).values()) {
1341 for (WaySegment ws : wslist) {
1342 if (wayseg == null) {
1343 wayseg = ws;
1344 }
1345 if (useSelected && ws.way.isSelected()) {
1346 return ws;
1347 }
1348 if (preferredRefs != null && !preferredRefs.isEmpty()) {
1349 // prefer ways containing given nodes
1350 if (preferredRefs.contains(ws.getFirstNode()) || preferredRefs.contains(ws.getSecondNode())) {
1351 return ws;
1352 }
1353 Collection<OsmPrimitive> wayRefs = ws.way.getReferrers();
1354 // prefer member of the given relations
1355 for (OsmPrimitive ref: preferredRefs) {
1356 if (ref instanceof Relation && wayRefs.contains(ref)) {
1357 return ws;
1358 }
1359 }
1360 }
1361 }
1362 }
1363 return wayseg;
1364 }
1365
1366 /**
1367 * Convenience method to {@link #getNearestWaySegment(Point, Predicate, boolean)}.
1368 * @param p the point for which to search the nearest segment.
1369 * @param predicate the returned object has to fulfill certain properties.
1370 *
1371 * @return The nearest way segment to point p.
1372 */
1373 public final WaySegment getNearestWaySegment(Point p, Predicate<OsmPrimitive> predicate) {
1374 return getNearestWaySegment(p, predicate, true);
1375 }
1376
1377 /**
1378 * The *result* does not depend on the current map selection state,
1379 * neither does the result *order*.
1380 * It solely depends on the perpendicular distance to point p.
1381 *
1382 * @param p the point for which to search the nearest ways.
1383 * @param ignore a collection of ways which are not to be returned.
1384 * @param predicate the returned object has to fulfill certain properties.
1385 *
1386 * @return all nearest ways to the screen point given that are not in ignore.
1387 * @see #getNearestWaySegments(Point, Collection, Predicate)
1388 */
1389 public final List<Way> getNearestWays(Point p,
1390 Collection<Way> ignore, Predicate<OsmPrimitive> predicate) {
1391 Set<Way> wset = new HashSet<>();
1392
1393 List<Way> nearestList = getNearestWaySegmentsImpl(p, predicate).values().stream()
1394 .flatMap(Collection::stream)
1395 .filter(ws -> wset.add(ws.way))
1396 .map(ws -> ws.way)
1397 .collect(Collectors.toList());
1398 if (ignore != null) {
1399 nearestList.removeAll(ignore);
1400 }
1401
1402 return nearestList;
1403 }
1404
1405 /**
1406 * The *result* does not depend on the current map selection state,
1407 * neither does the result *order*.
1408 * It solely depends on the perpendicular distance to point p.
1409 *
1410 * @param p the point for which to search the nearest ways.
1411 * @param predicate the returned object has to fulfill certain properties.
1412 *
1413 * @return all nearest ways to the screen point given.
1414 * @see #getNearestWays(Point, Collection, Predicate)
1415 */
1416 public final List<Way> getNearestWays(Point p, Predicate<OsmPrimitive> predicate) {
1417 return getNearestWays(p, null, predicate);
1418 }
1419
1420 /**
1421 * The *result* depends on the current map selection state.
1422 *
1423 * @param p the point for which to search the nearest segment.
1424 * @param predicate the returned object has to fulfill certain properties.
1425 *
1426 * @return The nearest way to point p, prefer a selected way if there are multiple nearest.
1427 * @see #getNearestWaySegment(Point, Predicate)
1428 */
1429 public final Way getNearestWay(Point p, Predicate<OsmPrimitive> predicate) {
1430 WaySegment nearestWaySeg = getNearestWaySegment(p, predicate);
1431 return (nearestWaySeg == null) ? null : nearestWaySeg.way;
1432 }
1433
1434 /**
1435 * The *result* does not depend on the current map selection state,
1436 * neither does the result *order*.
1437 * It solely depends on the distance to point p.
1438 *
1439 * First, nodes will be searched. If there are nodes within BBox found,
1440 * return a collection of those nodes only.
1441 *
1442 * If no nodes are found, search for nearest ways. If there are ways
1443 * within BBox found, return a collection of those ways only.
1444 *
1445 * If nothing is found, return an empty collection.
1446 *
1447 * @param p The point on screen.
1448 * @param ignore a collection of ways which are not to be returned.
1449 * @param predicate the returned object has to fulfill certain properties.
1450 *
1451 * @return Primitives nearest to the given screen point that are not in ignore.
1452 * @see #getNearestNodes(Point, Collection, Predicate)
1453 * @see #getNearestWays(Point, Collection, Predicate)
1454 */
1455 public final List<OsmPrimitive> getNearestNodesOrWays(Point p,
1456 Collection<OsmPrimitive> ignore, Predicate<OsmPrimitive> predicate) {
1457 List<OsmPrimitive> nearestList = Collections.emptyList();
1458 OsmPrimitive osm = getNearestNodeOrWay(p, predicate, false);
1459
1460 if (osm != null) {
1461 if (osm instanceof Node) {
1462 nearestList = new ArrayList<>(getNearestNodes(p, predicate));
1463 } else if (osm instanceof Way) {
1464 nearestList = new ArrayList<>(getNearestWays(p, predicate));
1465 }
1466 if (ignore != null) {
1467 nearestList.removeAll(ignore);
1468 }
1469 }
1470
1471 return nearestList;
1472 }
1473
1474 /**
1475 * The *result* does not depend on the current map selection state,
1476 * neither does the result *order*.
1477 * It solely depends on the distance to point p.
1478 *
1479 * @param p The point on screen.
1480 * @param predicate the returned object has to fulfill certain properties.
1481 * @return Primitives nearest to the given screen point.
1482 * @see #getNearestNodesOrWays(Point, Collection, Predicate)
1483 */
1484 public final List<OsmPrimitive> getNearestNodesOrWays(Point p, Predicate<OsmPrimitive> predicate) {
1485 return getNearestNodesOrWays(p, null, predicate);
1486 }
1487
1488 /**
1489 * This is used as a helper routine to {@link #getNearestNodeOrWay(Point, Predicate, boolean)}
1490 * It decides, whether to yield the node to be tested or look for further (way) candidates.
1491 *
1492 * @param osm node to check
1493 * @param p point clicked
1494 * @param useSelected whether to prefer selected nodes
1495 * @return true, if the node fulfills the properties of the function body
1496 */
1497 private boolean isPrecedenceNode(Node osm, Point p, boolean useSelected) {
1498 if (osm != null) {
1499 if (p.distanceSq(getPoint2D(osm)) <= (4*4)) return true;
1500 if (osm.isTagged()) return true;
1501 if (useSelected && osm.isSelected()) return true;
1502 }
1503 return false;
1504 }
1505
1506 /**
1507 * The *result* depends on the current map selection state IF use_selected is true.
1508 *
1509 * IF use_selected is true, use {@link #getNearestNode(Point, Predicate)} to find
1510 * the nearest, selected node. If not found, try {@link #getNearestWaySegment(Point, Predicate)}
1511 * to find the nearest selected way.
1512 *
1513 * IF use_selected is false, or if no selected primitive was found, do the following.
1514 *
1515 * If the nearest node found is within 4px of p, simply take it.
1516 * Else, find the nearest way segment. Then, if p is closer to its
1517 * middle than to the node, take the way segment, else take the node.
1518 *
1519 * Finally, if no nearest primitive is found at all, return null.
1520 *
1521 * @param p The point on screen.
1522 * @param predicate the returned object has to fulfill certain properties.
1523 * @param useSelected whether to prefer primitives that are currently selected or referred by selected primitives
1524 *
1525 * @return A primitive within snap-distance to point p,
1526 * that is chosen by the algorithm described.
1527 * @see #getNearestNode(Point, Predicate)
1528 * @see #getNearestWay(Point, Predicate)
1529 */
1530 public final OsmPrimitive getNearestNodeOrWay(Point p, Predicate<OsmPrimitive> predicate, boolean useSelected) {
1531 Collection<OsmPrimitive> sel;
1532 DataSet ds = MainApplication.getLayerManager().getActiveDataSet();
1533 if (useSelected && ds != null) {
1534 sel = ds.getSelected();
1535 } else {
1536 sel = null;
1537 }
1538 OsmPrimitive osm = getNearestNode(p, predicate, useSelected, sel);
1539
1540 if (isPrecedenceNode((Node) osm, p, useSelected)) return osm;
1541 WaySegment ws;
1542 if (useSelected) {
1543 ws = getNearestWaySegment(p, predicate, useSelected, sel);
1544 } else {
1545 ws = getNearestWaySegment(p, predicate, useSelected);
1546 }
1547 if (ws == null) return osm;
1548
1549 if ((ws.way.isSelected() && useSelected) || osm == null) {
1550 // either (no _selected_ nearest node found, if desired) or no nearest node was found
1551 osm = ws.way;
1552 } else {
1553 int maxWaySegLenSq = 3*PROP_SNAP_DISTANCE.get();
1554 maxWaySegLenSq *= maxWaySegLenSq;
1555
1556 Point2D wp1 = getPoint2D(ws.getFirstNode());
1557 Point2D wp2 = getPoint2D(ws.getSecondNode());
1558
1559 // is wayseg shorter than maxWaySegLenSq and
1560 // is p closer to the middle of wayseg than to the nearest node?
1561 if (wp1.distanceSq(wp2) < maxWaySegLenSq &&
1562 p.distanceSq(project(0.5, wp1, wp2)) < p.distanceSq(getPoint2D((Node) osm))) {
1563 osm = ws.way;
1564 }
1565 }
1566 return osm;
1567 }
1568
1569 /**
1570 * if r = 0 returns a, if r=1 returns b,
1571 * if r = 0.5 returns center between a and b, etc..
1572 *
1573 * @param r scale value
1574 * @param a root of vector
1575 * @param b vector
1576 * @return new point at a + r*(ab)
1577 */
1578 public static Point2D project(double r, Point2D a, Point2D b) {
1579 Point2D ret = null;
1580
1581 if (a != null && b != null) {
1582 ret = new Point2D.Double(a.getX() + r*(b.getX()-a.getX()),
1583 a.getY() + r*(b.getY()-a.getY()));
1584 }
1585 return ret;
1586 }
1587
1588 /**
1589 * The *result* does not depend on the current map selection state, neither does the result *order*.
1590 * It solely depends on the distance to point p.
1591 *
1592 * @param p The point on screen.
1593 * @param ignore a collection of ways which are not to be returned.
1594 * @param predicate the returned object has to fulfill certain properties.
1595 *
1596 * @return a list of all objects that are nearest to point p and
1597 * not in ignore or an empty list if nothing was found.
1598 */
1599 public final List<OsmPrimitive> getAllNearest(Point p,
1600 Collection<OsmPrimitive> ignore, Predicate<OsmPrimitive> predicate) {
1601 Set<Way> wset = new HashSet<>();
1602
1603 // add nearby ways
1604 List<OsmPrimitive> nearestList = getNearestWaySegmentsImpl(p, predicate).values().stream()
1605 .flatMap(Collection::stream)
1606 .filter(ws -> wset.add(ws.way))
1607 .map(ws -> ws.way)
1608 .collect(Collectors.toList());
1609
1610 // add nearby nodes
1611 getNearestNodesImpl(p, predicate).values()
1612 .forEach(nearestList::addAll);
1613
1614 // add parent relations of nearby nodes and ways
1615 Set<OsmPrimitive> parentRelations = nearestList.stream()
1616 .flatMap(o -> o.referrers(Relation.class))
1617 .filter(predicate)
1618 .collect(Collectors.toSet());
1619 nearestList.addAll(parentRelations);
1620
1621 if (ignore != null) {
1622 nearestList.removeAll(ignore);
1623 }
1624
1625 return nearestList;
1626 }
1627
1628 /**
1629 * The *result* does not depend on the current map selection state, neither does the result *order*.
1630 * It solely depends on the distance to point p.
1631 *
1632 * @param p The point on screen.
1633 * @param predicate the returned object has to fulfill certain properties.
1634 *
1635 * @return a list of all objects that are nearest to point p
1636 * or an empty list if nothing was found.
1637 * @see #getAllNearest(Point, Collection, Predicate)
1638 */
1639 public final List<OsmPrimitive> getAllNearest(Point p, Predicate<OsmPrimitive> predicate) {
1640 return getAllNearest(p, null, predicate);
1641 }
1642
1643 /**
1644 * Returns the projection to be used in calculating stuff.
1645 * @return The projection to be used in calculating stuff.
1646 */
1647 public Projection getProjection() {
1648 return state.getProjection();
1649 }
1650
1651 @Override
1652 public String helpTopic() {
1653 String n = getClass().getName();
1654 return n.substring(n.lastIndexOf('.')+1);
1655 }
1656
1657 /**
1658 * Return a ID which is unique as long as viewport dimensions are the same
1659 * @return A unique ID, as long as viewport dimensions are the same
1660 */
1661 public int getViewID() {
1662 EastNorth center = getCenter();
1663 String x = new StringBuilder().append(center.east())
1664 .append('_').append(center.north())
1665 .append('_').append(getScale())
1666 .append('_').append(getWidth())
1667 .append('_').append(getHeight())
1668 .append('_').append(getProjection()).toString();
1669 CRC32 id = new CRC32();
1670 id.update(x.getBytes(StandardCharsets.UTF_8));
1671 return (int) id.getValue();
1672 }
1673
1674 /**
1675 * Set new cursor.
1676 * @param cursor The new cursor to use.
1677 * @param reference A reference object that can be passed to the next set/reset calls to identify the caller.
1678 */
1679 public void setNewCursor(Cursor cursor, Object reference) {
1680 cursorManager.setNewCursor(cursor, reference);
1681 }
1682
1683 /**
1684 * Set new cursor.
1685 * @param cursor the type of predefined cursor
1686 * @param reference A reference object that can be passed to the next set/reset calls to identify the caller.
1687 */
1688 public void setNewCursor(int cursor, Object reference) {
1689 setNewCursor(Cursor.getPredefinedCursor(cursor), reference);
1690 }
1691
1692 /**
1693 * Remove the new cursor and reset to previous
1694 * @param reference Cursor reference
1695 */
1696 public void resetCursor(Object reference) {
1697 cursorManager.resetCursor(reference);
1698 }
1699
1700 /**
1701 * Gets the cursor manager that is used for this NavigatableComponent.
1702 * @return The cursor manager.
1703 */
1704 public CursorManager getCursorManager() {
1705 return cursorManager;
1706 }
1707
1708 /**
1709 * Get a max scale for projection that describes world in 1/512 of the projection unit
1710 * @return max scale
1711 */
1712 public double getMaxScale() {
1713 ProjectionBounds world = getMaxProjectionBounds();
1714 return Math.max(
1715 world.maxNorth-world.minNorth,
1716 world.maxEast-world.minEast
1717 )/512;
1718 }
1719}
Note: See TracBrowser for help on using the repository browser.