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