source: josm/trunk/src/org/openstreetmap/josm/gui/MapView.java@ 12522

Last change on this file since 12522 was 12400, checked in by Don-vip, 7 years ago

see #14929 - Automatic filters on numeric tag values (level, layer, maxspeed, voltage)

  • Property svn:eol-style set to native
File size: 33.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import java.awt.AlphaComposite;
5import java.awt.Color;
6import java.awt.Dimension;
7import java.awt.Graphics;
8import java.awt.Graphics2D;
9import java.awt.Point;
10import java.awt.Rectangle;
11import java.awt.event.ComponentAdapter;
12import java.awt.event.ComponentEvent;
13import java.awt.event.KeyEvent;
14import java.awt.event.MouseAdapter;
15import java.awt.event.MouseEvent;
16import java.awt.event.MouseMotionListener;
17import java.awt.geom.Area;
18import java.awt.image.BufferedImage;
19import java.beans.PropertyChangeEvent;
20import java.beans.PropertyChangeListener;
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Collections;
24import java.util.HashMap;
25import java.util.IdentityHashMap;
26import java.util.LinkedHashSet;
27import java.util.List;
28import java.util.Set;
29import java.util.TreeSet;
30import java.util.concurrent.CopyOnWriteArrayList;
31import java.util.concurrent.atomic.AtomicBoolean;
32
33import javax.swing.AbstractButton;
34import javax.swing.JComponent;
35import javax.swing.JPanel;
36
37import org.openstreetmap.josm.Main;
38import org.openstreetmap.josm.actions.mapmode.MapMode;
39import org.openstreetmap.josm.data.Bounds;
40import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
41import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
42import org.openstreetmap.josm.data.ProjectionBounds;
43import org.openstreetmap.josm.data.ViewportData;
44import org.openstreetmap.josm.data.coor.EastNorth;
45import org.openstreetmap.josm.data.imagery.ImageryInfo;
46import org.openstreetmap.josm.data.osm.DataSelectionListener;
47import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
48import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
49import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
50import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
51import org.openstreetmap.josm.gui.MapViewState.MapViewRectangle;
52import org.openstreetmap.josm.gui.autofilter.AutoFilterManager;
53import org.openstreetmap.josm.gui.datatransfer.OsmTransferHandler;
54import org.openstreetmap.josm.gui.layer.GpxLayer;
55import org.openstreetmap.josm.gui.layer.ImageryLayer;
56import org.openstreetmap.josm.gui.layer.Layer;
57import org.openstreetmap.josm.gui.layer.LayerManager;
58import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
59import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
60import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
61import org.openstreetmap.josm.gui.layer.MainLayerManager;
62import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
63import org.openstreetmap.josm.gui.layer.MapViewGraphics;
64import org.openstreetmap.josm.gui.layer.MapViewPaintable;
65import org.openstreetmap.josm.gui.layer.MapViewPaintable.LayerPainter;
66import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent;
67import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent;
68import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener;
69import org.openstreetmap.josm.gui.layer.OsmDataLayer;
70import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer;
71import org.openstreetmap.josm.gui.layer.markerlayer.PlayHeadMarker;
72import org.openstreetmap.josm.io.audio.AudioPlayer;
73import org.openstreetmap.josm.tools.JosmRuntimeException;
74import org.openstreetmap.josm.tools.Logging;
75import org.openstreetmap.josm.tools.Shortcut;
76import org.openstreetmap.josm.tools.Utils;
77import org.openstreetmap.josm.tools.bugreport.BugReport;
78
79/**
80 * This is a component used in the {@link MapFrame} for browsing the map. It use is to
81 * provide the MapMode's enough capabilities to operate.<br><br>
82 *
83 * {@code MapView} holds meta-data about the data set currently displayed, as scale level,
84 * center point viewed, what scrolling mode or editing mode is selected or with
85 * what projection the map is viewed etc..<br><br>
86 *
87 * {@code MapView} is able to administrate several layers.
88 *
89 * @author imi
90 */
91public class MapView extends NavigatableComponent
92implements PropertyChangeListener, PreferenceChangedListener,
93LayerManager.LayerChangeListener, MainLayerManager.ActiveLayerChangeListener {
94
95 /**
96 * An invalidation listener that simply calls repaint() for now.
97 * @author Michael Zangl
98 * @since 10271
99 */
100 private class LayerInvalidatedListener implements PaintableInvalidationListener {
101 private boolean ignoreRepaint;
102
103 private final Set<MapViewPaintable> invalidatedLayers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>());
104
105 @Override
106 public void paintableInvalidated(PaintableInvalidationEvent event) {
107 invalidate(event.getLayer());
108 }
109
110 /**
111 * Invalidate contents and repaint map view
112 * @param mapViewPaintable invalidated layer
113 */
114 public synchronized void invalidate(MapViewPaintable mapViewPaintable) {
115 ignoreRepaint = true;
116 invalidatedLayers.add(mapViewPaintable);
117 repaint();
118 }
119
120 /**
121 * Temporary until all {@link MapViewPaintable}s support this.
122 * @param p The paintable.
123 */
124 public synchronized void addTo(MapViewPaintable p) {
125 p.addInvalidationListener(this);
126 }
127
128 /**
129 * Temporary until all {@link MapViewPaintable}s support this.
130 * @param p The paintable.
131 */
132 public synchronized void removeFrom(MapViewPaintable p) {
133 p.removeInvalidationListener(this);
134 invalidatedLayers.remove(p);
135 }
136
137 /**
138 * Attempts to trace repaints that did not originate from this listener. Good to find missed {@link MapView#repaint()}s in code.
139 */
140 protected synchronized void traceRandomRepaint() {
141 if (!ignoreRepaint) {
142 System.err.println("Repaint:");
143 Thread.dumpStack();
144 }
145 ignoreRepaint = false;
146 }
147
148 /**
149 * Retrieves a set of all layers that have been marked as invalid since the last call to this method.
150 * @return The layers
151 */
152 protected synchronized Set<MapViewPaintable> collectInvalidatedLayers() {
153 Set<MapViewPaintable> layers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>());
154 layers.addAll(invalidatedLayers);
155 invalidatedLayers.clear();
156 return layers;
157 }
158 }
159
160 /**
161 * A layer painter that issues a warning when being called.
162 * @author Michael Zangl
163 * @since 10474
164 */
165 private static class WarningLayerPainter implements LayerPainter {
166 boolean warningPrinted;
167 private final Layer layer;
168
169 WarningLayerPainter(Layer layer) {
170 this.layer = layer;
171 }
172
173 @Override
174 public void paint(MapViewGraphics graphics) {
175 if (!warningPrinted) {
176 Main.debug("A layer triggered a repaint while being added: " + layer);
177 warningPrinted = true;
178 }
179 }
180
181 @Override
182 public void detachFromMapView(MapViewEvent event) {
183 // ignored
184 }
185 }
186
187 /**
188 * A list of all layers currently loaded. If we support multiple map views, this list may be different for each of them.
189 */
190 private final MainLayerManager layerManager;
191
192 /**
193 * The play head marker: there is only one of these so it isn't in any specific layer
194 */
195 public transient PlayHeadMarker playHeadMarker;
196
197 /**
198 * The last event performed by mouse.
199 */
200 public MouseEvent lastMEvent = new MouseEvent(this, 0, 0, 0, 0, 0, 0, false); // In case somebody reads it before first mouse move
201
202 /**
203 * Temporary layers (selection rectangle, etc.) that are never cached and
204 * drawn on top of regular layers.
205 * Access must be synchronized.
206 */
207 private final transient Set<MapViewPaintable> temporaryLayers = new LinkedHashSet<>();
208
209 private transient BufferedImage nonChangedLayersBuffer;
210 private transient BufferedImage offscreenBuffer;
211 // Layers that wasn't changed since last paint
212 private final transient List<Layer> nonChangedLayers = new ArrayList<>();
213 private int lastViewID;
214 private final AtomicBoolean paintPreferencesChanged = new AtomicBoolean(true);
215 private Rectangle lastClipBounds = new Rectangle();
216 private transient MapMover mapMover;
217
218 /**
219 * The listener that listens to invalidations of all layers.
220 */
221 private final LayerInvalidatedListener invalidatedListener = new LayerInvalidatedListener();
222
223 /**
224 * This is a map of all Layers that have been added to this view.
225 */
226 private final HashMap<Layer, LayerPainter> registeredLayers = new HashMap<>();
227
228 /**
229 * Constructs a new {@code MapView}.
230 * @param layerManager The layers to display.
231 * @param contentPane Ignored. Main content pane is used.
232 * @param viewportData the initial viewport of the map. Can be null, then
233 * the viewport is derived from the layer data.
234 * @since 10279
235 * @deprecated use {@link #MapView(MainLayerManager, ViewportData)} instead
236 */
237 @Deprecated
238 public MapView(MainLayerManager layerManager, final JPanel contentPane, final ViewportData viewportData) {
239 this(layerManager, viewportData);
240 }
241
242 /**
243 * Constructs a new {@code MapView}.
244 * @param layerManager The layers to display.
245 * @param viewportData the initial viewport of the map. Can be null, then
246 * the viewport is derived from the layer data.
247 * @since 11713
248 */
249 public MapView(MainLayerManager layerManager, final ViewportData viewportData) {
250 this.layerManager = layerManager;
251 initialViewport = viewportData;
252 layerManager.addAndFireLayerChangeListener(this);
253 layerManager.addActiveLayerChangeListener(this);
254 Main.pref.addPreferenceChangeListener(this);
255
256 addComponentListener(new ComponentAdapter() {
257 @Override
258 public void componentResized(ComponentEvent e) {
259 removeComponentListener(this);
260 mapMover = new MapMover(MapView.this);
261 }
262 });
263
264 // listens to selection changes to redraw the map
265 SelectionEventManager.getInstance().addSelectionListenerForEdt(repaintSelectionChangedListener);
266
267 //store the last mouse action
268 this.addMouseMotionListener(new MouseMotionListener() {
269 @Override
270 public void mouseDragged(MouseEvent e) {
271 mouseMoved(e);
272 }
273
274 @Override
275 public void mouseMoved(MouseEvent e) {
276 lastMEvent = e;
277 }
278 });
279 this.addMouseListener(new MouseAdapter() {
280 @Override
281 public void mousePressed(MouseEvent me) {
282 // focus the MapView component when mouse is pressed inside it
283 requestFocus();
284 }
285 });
286
287 setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
288
289 for (JComponent c : getMapNavigationComponents(this)) {
290 add(c);
291 }
292 if (AutoFilterManager.PROP_AUTO_FILTER_ENABLED.get()) {
293 AutoFilterManager.getInstance().enableAutoFilterRule(AutoFilterManager.PROP_AUTO_FILTER_RULE.get());
294 }
295 setTransferHandler(new OsmTransferHandler());
296 }
297
298 /**
299 * Adds the map navigation components to a
300 * @param forMapView The map view to get the components for.
301 * @return A list containing the correctly positioned map navigation components.
302 */
303 public static List<? extends JComponent> getMapNavigationComponents(MapView forMapView) {
304 MapSlider zoomSlider = new MapSlider(forMapView);
305 Dimension size = zoomSlider.getPreferredSize();
306 zoomSlider.setSize(size);
307 zoomSlider.setLocation(3, 0);
308 zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
309
310 MapScaler scaler = new MapScaler(forMapView);
311 scaler.setPreferredLineLength(size.width - 10);
312 scaler.setSize(scaler.getPreferredSize());
313 scaler.setLocation(3, size.height);
314
315 return Arrays.asList(zoomSlider, scaler);
316 }
317
318 // remebered geometry of the component
319 private Dimension oldSize;
320 private Point oldLoc;
321
322 /**
323 * Call this method to keep map position on screen during next repaint
324 */
325 public void rememberLastPositionOnScreen() {
326 oldSize = getSize();
327 oldLoc = getLocationOnScreen();
328 }
329
330 @Override
331 public void layerAdded(LayerAddEvent e) {
332 try {
333 Layer layer = e.getAddedLayer();
334 registeredLayers.put(layer, new WarningLayerPainter(layer));
335 // Layers may trigger a redraw during this call if they open dialogs.
336 LayerPainter painter = layer.attachToMapView(new MapViewEvent(this, false));
337 if (!registeredLayers.containsKey(layer)) {
338 // The layer may have removed itself during attachToMapView()
339 Main.warn("Layer was removed during attachToMapView()");
340 } else {
341 registeredLayers.put(layer, painter);
342
343 if (e.isZoomRequired()) {
344 ProjectionBounds viewProjectionBounds = layer.getViewProjectionBounds();
345 if (viewProjectionBounds != null) {
346 scheduleZoomTo(new ViewportData(viewProjectionBounds));
347 }
348 }
349
350 layer.addPropertyChangeListener(this);
351 Main.addProjectionChangeListener(layer);
352 invalidatedListener.addTo(layer);
353 AudioPlayer.reset();
354
355 repaint();
356 }
357 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
358 throw BugReport.intercept(t).put("layer", e.getAddedLayer());
359 }
360 }
361
362 /**
363 * Replies true if the active data layer (edit layer) is drawable.
364 *
365 * @return true if the active data layer (edit layer) is drawable, false otherwise
366 */
367 public boolean isActiveLayerDrawable() {
368 return layerManager.getEditLayer() != null;
369 }
370
371 /**
372 * Replies true if the active data layer (edit layer) is visible.
373 *
374 * @return true if the active data layer (edit layer) is visible, false otherwise
375 */
376 public boolean isActiveLayerVisible() {
377 OsmDataLayer e = layerManager.getEditLayer();
378 return e != null && e.isVisible();
379 }
380
381 @Override
382 public void layerRemoving(LayerRemoveEvent e) {
383 Layer layer = e.getRemovedLayer();
384
385 LayerPainter painter = registeredLayers.remove(layer);
386 if (painter == null) {
387 Main.error("The painter for layer " + layer + " was not registered.");
388 return;
389 }
390 painter.detachFromMapView(new MapViewEvent(this, false));
391 Main.removeProjectionChangeListener(layer);
392 layer.removePropertyChangeListener(this);
393 invalidatedListener.removeFrom(layer);
394 layer.destroy();
395 AudioPlayer.reset();
396
397 repaint();
398 }
399
400 private boolean virtualNodesEnabled;
401
402 /**
403 * Enables or disables drawing of the virtual nodes.
404 * @param enabled if virtual nodes are enabled
405 */
406 public void setVirtualNodesEnabled(boolean enabled) {
407 if (virtualNodesEnabled != enabled) {
408 virtualNodesEnabled = enabled;
409 repaint();
410 }
411 }
412
413 /**
414 * Checks if virtual nodes should be drawn. Default is <code>false</code>
415 * @return The virtual nodes property.
416 * @see Rendering#render(DataSet, boolean, Bounds)
417 */
418 public boolean isVirtualNodesEnabled() {
419 return virtualNodesEnabled;
420 }
421
422 /**
423 * Moves the layer to the given new position. No event is fired, but repaints
424 * according to the new Z-Order of the layers.
425 *
426 * @param layer The layer to move
427 * @param pos The new position of the layer
428 */
429 public void moveLayer(Layer layer, int pos) {
430 layerManager.moveLayer(layer, pos);
431 }
432
433 @Override
434 public void layerOrderChanged(LayerOrderChangeEvent e) {
435 AudioPlayer.reset();
436 repaint();
437 }
438
439 /**
440 * Paints the given layer to the graphics object, using the current state of this map view.
441 * @param layer The layer to draw.
442 * @param g A graphics object. It should have the width and height of this component
443 * @throws IllegalArgumentException If the layer is not part of this map view.
444 * @since 11226
445 */
446 public void paintLayer(Layer layer, Graphics2D g) {
447 try {
448 LayerPainter painter = registeredLayers.get(layer);
449 if (painter == null) {
450 Logging.warn("Cannot paint layer, it is not registered: {0}", layer);
451 return;
452 }
453 MapViewRectangle clipBounds = getState().getViewArea(g.getClipBounds());
454 MapViewGraphics paintGraphics = new MapViewGraphics(this, g, clipBounds);
455
456 if (layer.getOpacity() < 1) {
457 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) layer.getOpacity()));
458 }
459 painter.paint(paintGraphics);
460 g.setPaintMode();
461 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
462 BugReport.intercept(t).put("layer", layer).warn();
463 }
464 }
465
466 /**
467 * Draw the component.
468 */
469 @Override
470 public void paint(Graphics g) {
471 try {
472 if (!prepareToDraw()) {
473 return;
474 }
475 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
476 BugReport.intercept(e).put("center", this::getCenter).warn();
477 return;
478 }
479
480 try {
481 drawMapContent(g);
482 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
483 throw BugReport.intercept(e).put("visibleLayers", layerManager::getVisibleLayersInZOrder)
484 .put("temporaryLayers", temporaryLayers);
485 }
486 super.paint(g);
487 }
488
489 private void drawMapContent(Graphics g) {
490 List<Layer> visibleLayers = layerManager.getVisibleLayersInZOrder();
491
492 int nonChangedLayersCount = 0;
493 Set<MapViewPaintable> invalidated = invalidatedListener.collectInvalidatedLayers();
494 for (Layer l: visibleLayers) {
495 if (invalidated.contains(l)) {
496 break;
497 } else {
498 nonChangedLayersCount++;
499 }
500 }
501
502 boolean canUseBuffer = !paintPreferencesChanged.getAndSet(false)
503 && nonChangedLayers.size() <= nonChangedLayersCount
504 && lastViewID == getViewID()
505 && lastClipBounds.contains(g.getClipBounds())
506 && nonChangedLayers.equals(visibleLayers.subList(0, nonChangedLayers.size()));
507
508 if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth() || offscreenBuffer.getHeight() != getHeight()) {
509 offscreenBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
510 }
511
512 Graphics2D tempG = offscreenBuffer.createGraphics();
513 tempG.setClip(g.getClip());
514
515 if (!canUseBuffer || nonChangedLayersBuffer == null) {
516 if (null == nonChangedLayersBuffer
517 || nonChangedLayersBuffer.getWidth() != getWidth() || nonChangedLayersBuffer.getHeight() != getHeight()) {
518 nonChangedLayersBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
519 }
520 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
521 g2.setClip(g.getClip());
522 g2.setColor(PaintColors.getBackgroundColor());
523 g2.fillRect(0, 0, getWidth(), getHeight());
524
525 for (int i = 0; i < nonChangedLayersCount; i++) {
526 paintLayer(visibleLayers.get(i), g2);
527 }
528 } else {
529 // Maybe there were more unchanged layers then last time - draw them to buffer
530 if (nonChangedLayers.size() != nonChangedLayersCount) {
531 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
532 g2.setClip(g.getClip());
533 for (int i = nonChangedLayers.size(); i < nonChangedLayersCount; i++) {
534 paintLayer(visibleLayers.get(i), g2);
535 }
536 }
537 }
538
539 nonChangedLayers.clear();
540 nonChangedLayers.addAll(visibleLayers.subList(0, nonChangedLayersCount));
541 lastViewID = getViewID();
542 lastClipBounds = g.getClipBounds();
543
544 tempG.drawImage(nonChangedLayersBuffer, 0, 0, null);
545
546 for (int i = nonChangedLayersCount; i < visibleLayers.size(); i++) {
547 paintLayer(visibleLayers.get(i), tempG);
548 }
549
550 try {
551 drawTemporaryLayers(tempG, getLatLonBounds(g.getClipBounds()));
552 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
553 BugReport.intercept(e).put("temporaryLayers", temporaryLayers).warn();
554 }
555
556 // draw world borders
557 try {
558 drawWorldBorders(tempG);
559 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
560 // getProjection() needs to be inside lambda to catch errors.
561 BugReport.intercept(e).put("bounds", () -> getProjection().getWorldBoundsLatLon()).warn();
562 }
563
564 if (AutoFilterManager.getInstance().getCurrentAutoFilter() != null) {
565 AutoFilterManager.getInstance().drawOSDText(tempG);
566 } else if (Main.isDisplayingMapView() && Main.map.filterDialog != null) {
567 Main.map.filterDialog.drawOSDText(tempG);
568 }
569
570 if (playHeadMarker != null) {
571 playHeadMarker.paint(tempG, this);
572 }
573
574 try {
575 g.drawImage(offscreenBuffer, 0, 0, null);
576 } catch (ClassCastException e) {
577 // See #11002 and duplicate tickets. On Linux with Java >= 8 Many users face this error here:
578 //
579 // java.lang.ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
580 // at sun.java2d.xr.XRPMBlitLoops.cacheToTmpSurface(XRPMBlitLoops.java:145)
581 // at sun.java2d.xr.XrSwToPMBlit.Blit(XRPMBlitLoops.java:353)
582 // at sun.java2d.pipe.DrawImage.blitSurfaceData(DrawImage.java:959)
583 // at sun.java2d.pipe.DrawImage.renderImageCopy(DrawImage.java:577)
584 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:67)
585 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:1014)
586 // at sun.java2d.pipe.ValidatePipe.copyImage(ValidatePipe.java:186)
587 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3318)
588 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3296)
589 // at org.openstreetmap.josm.gui.MapView.paint(MapView.java:834)
590 //
591 // It seems to be this JDK bug, but Oracle does not seem to be fixing it:
592 // https://bugs.openjdk.java.net/browse/JDK-7172749
593 //
594 // According to bug reports it can happen for a variety of reasons such as:
595 // - long period of time
596 // - change of screen resolution
597 // - addition/removal of a secondary monitor
598 //
599 // But the application seems to work fine after, so let's just log the error
600 Main.error(e);
601 }
602 }
603
604 private void drawTemporaryLayers(Graphics2D tempG, Bounds box) {
605 synchronized (temporaryLayers) {
606 for (MapViewPaintable mvp : temporaryLayers) {
607 try {
608 mvp.paint(tempG, this, box);
609 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
610 throw BugReport.intercept(e).put("mvp", mvp);
611 }
612 }
613 }
614 }
615
616 private void drawWorldBorders(Graphics2D tempG) {
617 tempG.setColor(Color.WHITE);
618 Bounds b = getProjection().getWorldBoundsLatLon();
619
620 int w = getWidth();
621 int h = getHeight();
622
623 // Work around OpenJDK having problems when drawing out of bounds
624 final Area border = getState().getArea(b);
625 // Make the viewport 1px larger in every direction to prevent an
626 // additional 1px border when zooming in
627 final Area viewport = new Area(new Rectangle(-1, -1, w + 2, h + 2));
628 border.intersect(viewport);
629 tempG.draw(border);
630 }
631
632 /**
633 * Sets up the viewport to prepare for drawing the view.
634 * @return <code>true</code> if the view can be drawn, <code>false</code> otherwise.
635 */
636 public boolean prepareToDraw() {
637 updateLocationState();
638 if (initialViewport != null) {
639 zoomTo(initialViewport);
640 initialViewport = null;
641 }
642
643 if (getCenter() == null)
644 return false; // no data loaded yet.
645
646 // if the position was remembered, we need to adjust center once before repainting
647 if (oldLoc != null && oldSize != null) {
648 Point l1 = getLocationOnScreen();
649 final EastNorth newCenter = new EastNorth(
650 getCenter().getX()+ (l1.x-oldLoc.x - (oldSize.width-getWidth())/2.0)*getScale(),
651 getCenter().getY()+ (oldLoc.y-l1.y + (oldSize.height-getHeight())/2.0)*getScale()
652 );
653 oldLoc = null; oldSize = null;
654 zoomTo(newCenter);
655 }
656
657 return true;
658 }
659
660 @Override
661 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
662 if (Main.map != null) {
663 /* This only makes the buttons look disabled. Disabling the actions as well requires
664 * the user to re-select the tool after i.e. moving a layer. While testing I found
665 * that I switch layers and actions at the same time and it was annoying to mind the
666 * order. This way it works as visual clue for new users */
667 // FIXME: This does not belong here.
668 for (final AbstractButton b: Main.map.allMapModeButtons) {
669 MapMode mode = (MapMode) b.getAction();
670 final boolean activeLayerSupported = mode.layerIsSupported(layerManager.getActiveLayer());
671 if (activeLayerSupported) {
672 Main.registerActionShortcut(mode, mode.getShortcut()); //fix #6876
673 } else {
674 Main.unregisterShortcut(mode.getShortcut());
675 }
676 b.setEnabled(activeLayerSupported);
677 }
678 }
679 // invalidate repaint cache. The layer order may have changed by this, so we invalidate every layer
680 getLayerManager().getLayers().forEach(invalidatedListener::invalidate);
681 AudioPlayer.reset();
682 }
683
684 /**
685 * Adds a new temporary layer.
686 * <p>
687 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added.
688 *
689 * @param mvp The layer to paint.
690 * @return <code>true</code> if the layer was added.
691 */
692 public boolean addTemporaryLayer(MapViewPaintable mvp) {
693 synchronized (temporaryLayers) {
694 boolean added = temporaryLayers.add(mvp);
695 if (added) {
696 invalidatedListener.addTo(mvp);
697 }
698 repaint();
699 return added;
700 }
701 }
702
703 /**
704 * Removes a layer previously added as temporary layer.
705 * @param mvp The layer to remove.
706 * @return <code>true</code> if that layer was removed.
707 */
708 public boolean removeTemporaryLayer(MapViewPaintable mvp) {
709 synchronized (temporaryLayers) {
710 boolean removed = temporaryLayers.remove(mvp);
711 if (removed) {
712 invalidatedListener.removeFrom(mvp);
713 }
714 repaint();
715 return removed;
716 }
717 }
718
719 /**
720 * Gets a list of temporary layers.
721 * @return The layers in the order they are added.
722 */
723 public List<MapViewPaintable> getTemporaryLayers() {
724 synchronized (temporaryLayers) {
725 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers));
726 }
727 }
728
729 @Override
730 public void propertyChange(PropertyChangeEvent evt) {
731 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
732 repaint();
733 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) ||
734 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) {
735 Layer l = (Layer) evt.getSource();
736 if (l.isVisible()) {
737 invalidatedListener.invalidate(l);
738 }
739 }
740 }
741
742 @Override
743 public void preferenceChanged(PreferenceChangeEvent e) {
744 paintPreferencesChanged.set(true);
745 }
746
747 private final transient DataSelectionListener repaintSelectionChangedListener = event -> repaint();
748
749 /**
750 * Destroy this map view panel. Should be called once when it is not needed any more.
751 */
752 public void destroy() {
753 layerManager.removeAndFireLayerChangeListener(this);
754 layerManager.removeActiveLayerChangeListener(this);
755 Main.pref.removePreferenceChangeListener(this);
756 SelectionEventManager.getInstance().removeSelectionListener(repaintSelectionChangedListener);
757 MultipolygonCache.getInstance().clear();
758 if (mapMover != null) {
759 mapMover.destroy();
760 }
761 nonChangedLayers.clear();
762 synchronized (temporaryLayers) {
763 temporaryLayers.clear();
764 }
765 nonChangedLayersBuffer = null;
766 offscreenBuffer = null;
767 }
768
769 /**
770 * Get a string representation of all layers suitable for the {@code source} changeset tag.
771 * @return A String of sources separated by ';'
772 */
773 public String getLayerInformationForSourceTag() {
774 final Set<String> layerInfo = new TreeSet<>();
775 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) {
776 // no i18n for international values
777 layerInfo.add("survey");
778 }
779 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) {
780 if (i.isVisible()) {
781 layerInfo.add(i.getName());
782 }
783 }
784 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) {
785 if (i.isVisible()) {
786 layerInfo.add(ImageryInfo.ImageryType.BING.equals(i.getInfo().getImageryType()) ? "Bing" : i.getName());
787 }
788 }
789 return Utils.join("; ", layerInfo);
790 }
791
792 /**
793 * This is a listener that gets informed whenever repaint is called for this MapView.
794 * <p>
795 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly.
796 * @author Michael Zangl
797 * @since 10600 (functional interface)
798 */
799 @FunctionalInterface
800 public interface RepaintListener {
801 /**
802 * Called when any repaint method is called (using default arguments if required).
803 * @param tm see {@link JComponent#repaint(long, int, int, int, int)}
804 * @param x see {@link JComponent#repaint(long, int, int, int, int)}
805 * @param y see {@link JComponent#repaint(long, int, int, int, int)}
806 * @param width see {@link JComponent#repaint(long, int, int, int, int)}
807 * @param height see {@link JComponent#repaint(long, int, int, int, int)}
808 */
809 void repaint(long tm, int x, int y, int width, int height);
810 }
811
812 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>();
813
814 /**
815 * Adds a listener that gets informed whenever repaint() is called for this class.
816 * @param l The listener.
817 */
818 public void addRepaintListener(RepaintListener l) {
819 repaintListeners.add(l);
820 }
821
822 /**
823 * Removes a registered repaint listener.
824 * @param l The listener.
825 */
826 public void removeRepaintListener(RepaintListener l) {
827 repaintListeners.remove(l);
828 }
829
830 @Override
831 public void repaint(long tm, int x, int y, int width, int height) {
832 // This is the main repaint method, all other methods are convenience methods and simply call this method.
833 // This is just an observation, not a must, but seems to be true for all implementations I found so far.
834 if (repaintListeners != null) {
835 // Might get called early in super constructor
836 for (RepaintListener l : repaintListeners) {
837 l.repaint(tm, x, y, width, height);
838 }
839 }
840 super.repaint(tm, x, y, width, height);
841 }
842
843 @Override
844 public void repaint() {
845 if (Main.isTraceEnabled()) {
846 invalidatedListener.traceRandomRepaint();
847 }
848 super.repaint();
849 }
850
851 /**
852 * Returns the layer manager.
853 * @return the layer manager
854 * @since 10282
855 */
856 public final MainLayerManager getLayerManager() {
857 return layerManager;
858 }
859
860 /**
861 * Schedule a zoom to the given position on the next redraw.
862 * Temporary, may be removed without warning.
863 * @param viewportData the viewport to zoom to
864 * @since 10394
865 */
866 public void scheduleZoomTo(ViewportData viewportData) {
867 initialViewport = viewportData;
868 }
869}
Note: See TracBrowser for help on using the repository browser.