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

Last change on this file since 10694 was 10657, checked in by Don-vip, 8 years ago

see #11390, see #12890 - use Java 8 Predicates

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