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

Last change on this file since 12088 was 12030, checked in by michael2402, 7 years ago

See #13604: Change error to a warning until we figure out what causes a layer not to be registered at that stage.

  • Property svn:eol-style set to native
File size: 32.9 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.SelectionChangedListener;
44import org.openstreetmap.josm.data.ViewportData;
45import org.openstreetmap.josm.data.coor.EastNorth;
46import org.openstreetmap.josm.data.imagery.ImageryInfo;
47import org.openstreetmap.josm.data.osm.DataSet;
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.datatransfer.OsmTransferHandler;
53import org.openstreetmap.josm.gui.layer.AbstractMapViewPaintable;
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.tools.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 if (p instanceof AbstractMapViewPaintable) {
126 ((AbstractMapViewPaintable) p).addInvalidationListener(this);
127 }
128 }
129
130 /**
131 * Temporary until all {@link MapViewPaintable}s support this.
132 * @param p The paintable.
133 */
134 public synchronized void removeFrom(MapViewPaintable p) {
135 if (p instanceof AbstractMapViewPaintable) {
136 ((AbstractMapViewPaintable) p).removeInvalidationListener(this);
137 }
138 invalidatedLayers.remove(p);
139 }
140
141 /**
142 * Attempts to trace repaints that did not originate from this listener. Good to find missed {@link MapView#repaint()}s in code.
143 */
144 protected synchronized void traceRandomRepaint() {
145 if (!ignoreRepaint) {
146 System.err.println("Repaint:");
147 Thread.dumpStack();
148 }
149 ignoreRepaint = false;
150 }
151
152 /**
153 * Retrieves a set of all layers that have been marked as invalid since the last call to this method.
154 * @return The layers
155 */
156 protected synchronized Set<MapViewPaintable> collectInvalidatedLayers() {
157 Set<MapViewPaintable> layers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>());
158 layers.addAll(invalidatedLayers);
159 invalidatedLayers.clear();
160 return layers;
161 }
162 }
163
164 /**
165 * A layer painter that issues a warning when being called.
166 * @author Michael Zangl
167 * @since 10474
168 */
169 private static class WarningLayerPainter implements LayerPainter {
170 boolean warningPrinted;
171 private final Layer layer;
172
173 WarningLayerPainter(Layer layer) {
174 this.layer = layer;
175 }
176
177 @Override
178 public void paint(MapViewGraphics graphics) {
179 if (!warningPrinted) {
180 Main.debug("A layer triggered a repaint while being added: " + layer);
181 warningPrinted = true;
182 }
183 }
184
185 @Override
186 public void detachFromMapView(MapViewEvent event) {
187 // ignored
188 }
189 }
190
191 public boolean viewportFollowing;
192
193 /**
194 * A list of all layers currently loaded. If we support multiple map views, this list may be different for each of them.
195 */
196 private final MainLayerManager layerManager;
197
198 /**
199 * The play head marker: there is only one of these so it isn't in any specific layer
200 */
201 public transient PlayHeadMarker playHeadMarker;
202
203 /**
204 * The last event performed by mouse.
205 */
206 public MouseEvent lastMEvent = new MouseEvent(this, 0, 0, 0, 0, 0, 0, false); // In case somebody reads it before first mouse move
207
208 /**
209 * Temporary layers (selection rectangle, etc.) that are never cached and
210 * drawn on top of regular layers.
211 * Access must be synchronized.
212 */
213 private final transient Set<MapViewPaintable> temporaryLayers = new LinkedHashSet<>();
214
215 private transient BufferedImage nonChangedLayersBuffer;
216 private transient BufferedImage offscreenBuffer;
217 // Layers that wasn't changed since last paint
218 private final transient List<Layer> nonChangedLayers = new ArrayList<>();
219 private int lastViewID;
220 private final AtomicBoolean paintPreferencesChanged = new AtomicBoolean(true);
221 private Rectangle lastClipBounds = new Rectangle();
222 private transient MapMover mapMover;
223
224 /**
225 * The listener that listens to invalidations of all layers.
226 */
227 private final LayerInvalidatedListener invalidatedListener = new LayerInvalidatedListener();
228
229 /**
230 * This is a map of all Layers that have been added to this view.
231 */
232 private final HashMap<Layer, LayerPainter> registeredLayers = new HashMap<>();
233
234 /**
235 * Constructs a new {@code MapView}.
236 * @param layerManager The layers to display.
237 * @param contentPane Ignored. Main content pane is used.
238 * @param viewportData the initial viewport of the map. Can be null, then
239 * the viewport is derived from the layer data.
240 * @since 10279
241 * @deprecated use {@link #MapView(MainLayerManager, ViewportData)} instead
242 */
243 @Deprecated
244 public MapView(MainLayerManager layerManager, final JPanel contentPane, final ViewportData viewportData) {
245 this(layerManager, viewportData);
246 }
247
248 /**
249 * Constructs a new {@code MapView}.
250 * @param layerManager The layers to display.
251 * @param viewportData the initial viewport of the map. Can be null, then
252 * the viewport is derived from the layer data.
253 * @since 11713
254 */
255 public MapView(MainLayerManager layerManager, final ViewportData viewportData) {
256 this.layerManager = layerManager;
257 initialViewport = viewportData;
258 layerManager.addAndFireLayerChangeListener(this);
259 layerManager.addActiveLayerChangeListener(this);
260 Main.pref.addPreferenceChangeListener(this);
261
262 addComponentListener(new ComponentAdapter() {
263 @Override
264 public void componentResized(ComponentEvent e) {
265 removeComponentListener(this);
266 mapMover = new MapMover(MapView.this);
267 }
268 });
269
270 // listens to selection changes to redraw the map
271 DataSet.addSelectionListener(repaintSelectionChangedListener);
272
273 //store the last mouse action
274 this.addMouseMotionListener(new MouseMotionListener() {
275 @Override
276 public void mouseDragged(MouseEvent e) {
277 mouseMoved(e);
278 }
279
280 @Override
281 public void mouseMoved(MouseEvent e) {
282 lastMEvent = e;
283 }
284 });
285 this.addMouseListener(new MouseAdapter() {
286 @Override
287 public void mousePressed(MouseEvent me) {
288 // focus the MapView component when mouse is pressed inside it
289 requestFocus();
290 }
291 });
292
293 setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
294
295 for (JComponent c : getMapNavigationComponents(this)) {
296 add(c);
297 }
298 setTransferHandler(new OsmTransferHandler());
299 }
300
301 /**
302 * Adds the map navigation components to a
303 * @param forMapView The map view to get the components for.
304 * @return A list containing the correctly positioned map navigation components.
305 */
306 public static List<? extends JComponent> getMapNavigationComponents(MapView forMapView) {
307 MapSlider zoomSlider = new MapSlider(forMapView);
308 Dimension size = zoomSlider.getPreferredSize();
309 zoomSlider.setSize(size);
310 zoomSlider.setLocation(3, 0);
311 zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
312
313 MapScaler scaler = new MapScaler(forMapView);
314 scaler.setPreferredLineLength(size.width - 10);
315 scaler.setSize(scaler.getPreferredSize());
316 scaler.setLocation(3, size.height);
317
318 return Arrays.asList(zoomSlider, scaler);
319 }
320
321 // remebered geometry of the component
322 private Dimension oldSize;
323 private Point oldLoc;
324
325 /**
326 * Call this method to keep map position on screen during next repaint
327 */
328 public void rememberLastPositionOnScreen() {
329 oldSize = getSize();
330 oldLoc = getLocationOnScreen();
331 }
332
333 @Override
334 public void layerAdded(LayerAddEvent e) {
335 try {
336 Layer layer = e.getAddedLayer();
337 registeredLayers.put(layer, new WarningLayerPainter(layer));
338 // Layers may trigger a redraw during this call if they open dialogs.
339 LayerPainter painter = layer.attachToMapView(new MapViewEvent(this, false));
340 if (!registeredLayers.containsKey(layer)) {
341 // The layer may have removed itself during attachToMapView()
342 Main.warn("Layer was removed during attachToMapView()");
343 } else {
344 registeredLayers.put(layer, painter);
345
346 if (e.isZoomRequired()) {
347 ProjectionBounds viewProjectionBounds = layer.getViewProjectionBounds();
348 if (viewProjectionBounds != null) {
349 scheduleZoomTo(new ViewportData(viewProjectionBounds));
350 }
351 }
352
353 layer.addPropertyChangeListener(this);
354 Main.addProjectionChangeListener(layer);
355 invalidatedListener.addTo(layer);
356 AudioPlayer.reset();
357
358 repaint();
359 }
360 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
361 throw BugReport.intercept(t).put("layer", e.getAddedLayer());
362 }
363 }
364
365 /**
366 * Replies true if the active data layer (edit layer) is drawable.
367 *
368 * @return true if the active data layer (edit layer) is drawable, false otherwise
369 */
370 public boolean isActiveLayerDrawable() {
371 return layerManager.getEditLayer() != null;
372 }
373
374 /**
375 * Replies true if the active data layer (edit layer) is visible.
376 *
377 * @return true if the active data layer (edit layer) is visible, false otherwise
378 */
379 public boolean isActiveLayerVisible() {
380 OsmDataLayer e = layerManager.getEditLayer();
381 return e != null && e.isVisible();
382 }
383
384 @Override
385 public void layerRemoving(LayerRemoveEvent e) {
386 Layer layer = e.getRemovedLayer();
387
388 LayerPainter painter = registeredLayers.remove(layer);
389 if (painter == null) {
390 Main.error("The painter for layer " + layer + " was not registered.");
391 return;
392 }
393 painter.detachFromMapView(new MapViewEvent(this, false));
394 Main.removeProjectionChangeListener(layer);
395 layer.removePropertyChangeListener(this);
396 invalidatedListener.removeFrom(layer);
397 layer.destroy();
398 AudioPlayer.reset();
399
400 repaint();
401 }
402
403 private boolean virtualNodesEnabled;
404
405 public void setVirtualNodesEnabled(boolean enabled) {
406 if (virtualNodesEnabled != enabled) {
407 virtualNodesEnabled = enabled;
408 repaint();
409 }
410 }
411
412 /**
413 * Checks if virtual nodes should be drawn. Default is <code>false</code>
414 * @return The virtual nodes property.
415 * @see Rendering#render(DataSet, boolean, Bounds)
416 */
417 public boolean isVirtualNodesEnabled() {
418 return virtualNodesEnabled;
419 }
420
421 /**
422 * Moves the layer to the given new position. No event is fired, but repaints
423 * according to the new Z-Order of the layers.
424 *
425 * @param layer The layer to move
426 * @param pos The new position of the layer
427 */
428 public void moveLayer(Layer layer, int pos) {
429 layerManager.moveLayer(layer, pos);
430 }
431
432 @Override
433 public void layerOrderChanged(LayerOrderChangeEvent e) {
434 AudioPlayer.reset();
435 repaint();
436 }
437
438 /**
439 * Paints the given layer to the graphics object, using the current state of this map view.
440 * @param layer The layer to draw.
441 * @param g A graphics object. It should have the width and height of this component
442 * @throws IllegalArgumentException If the layer is not part of this map view.
443 * @since 11226
444 */
445 public void paintLayer(Layer layer, Graphics2D g) {
446 try {
447 LayerPainter painter = registeredLayers.get(layer);
448 if (painter == null) {
449 Logging.warn("Cannot paint layer, it is not registered: {0}", layer);
450 return;
451 }
452 MapViewRectangle clipBounds = getState().getViewArea(g.getClipBounds());
453 MapViewGraphics paintGraphics = new MapViewGraphics(this, g, clipBounds);
454
455 if (layer.getOpacity() < 1) {
456 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) layer.getOpacity()));
457 }
458 painter.paint(paintGraphics);
459 g.setPaintMode();
460 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
461 BugReport.intercept(t).put("layer", layer).warn();
462 }
463 }
464
465 /**
466 * Draw the component.
467 */
468 @Override
469 public void paint(Graphics g) {
470 try {
471 if (!prepareToDraw()) {
472 return;
473 }
474 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
475 BugReport.intercept(e).put("center", this::getCenter).warn();
476 return;
477 }
478
479 try {
480 drawMapContent(g);
481 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
482 throw BugReport.intercept(e).put("visibleLayers", layerManager::getVisibleLayersInZOrder)
483 .put("temporaryLayers", temporaryLayers);
484 }
485 super.paint(g);
486 }
487
488 private void drawMapContent(Graphics g) {
489 List<Layer> visibleLayers = layerManager.getVisibleLayersInZOrder();
490
491 int nonChangedLayersCount = 0;
492 Set<MapViewPaintable> invalidated = invalidatedListener.collectInvalidatedLayers();
493 for (Layer l: visibleLayers) {
494 // `isChanged` for backward compatibility, see https://josm.openstreetmap.de/ticket/13175#comment:7
495 // Layers that still implement it (plugins) will use it to tell the MapView that they have been changed.
496 // This is why the MapView still uses it in addition to the invalidation events.
497 if (l.isChanged() || invalidated.contains(l)) {
498 break;
499 } else {
500 nonChangedLayersCount++;
501 }
502 }
503
504 boolean canUseBuffer = !paintPreferencesChanged.getAndSet(false)
505 && nonChangedLayers.size() <= nonChangedLayersCount
506 && lastViewID == getViewID()
507 && lastClipBounds.contains(g.getClipBounds())
508 && nonChangedLayers.equals(visibleLayers.subList(0, nonChangedLayers.size()));
509
510 if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth() || offscreenBuffer.getHeight() != getHeight()) {
511 offscreenBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
512 }
513
514 Graphics2D tempG = offscreenBuffer.createGraphics();
515 tempG.setClip(g.getClip());
516
517 if (!canUseBuffer || nonChangedLayersBuffer == null) {
518 if (null == nonChangedLayersBuffer
519 || nonChangedLayersBuffer.getWidth() != getWidth() || nonChangedLayersBuffer.getHeight() != getHeight()) {
520 nonChangedLayersBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
521 }
522 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
523 g2.setClip(g.getClip());
524 g2.setColor(PaintColors.getBackgroundColor());
525 g2.fillRect(0, 0, getWidth(), getHeight());
526
527 for (int i = 0; i < nonChangedLayersCount; i++) {
528 paintLayer(visibleLayers.get(i), g2);
529 }
530 } else {
531 // Maybe there were more unchanged layers then last time - draw them to buffer
532 if (nonChangedLayers.size() != nonChangedLayersCount) {
533 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
534 g2.setClip(g.getClip());
535 for (int i = nonChangedLayers.size(); i < nonChangedLayersCount; i++) {
536 paintLayer(visibleLayers.get(i), g2);
537 }
538 }
539 }
540
541 nonChangedLayers.clear();
542 nonChangedLayers.addAll(visibleLayers.subList(0, nonChangedLayersCount));
543 lastViewID = getViewID();
544 lastClipBounds = g.getClipBounds();
545
546 tempG.drawImage(nonChangedLayersBuffer, 0, 0, null);
547
548 for (int i = nonChangedLayersCount; i < visibleLayers.size(); i++) {
549 paintLayer(visibleLayers.get(i), tempG);
550 }
551
552 try {
553 drawTemporaryLayers(tempG, getLatLonBounds(g.getClipBounds()));
554 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
555 BugReport.intercept(e).put("temporaryLayers", temporaryLayers).warn();
556 }
557
558 // draw world borders
559 try {
560 drawWorldBorders(tempG);
561 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
562 // getProjection() needs to be inside lambda to catch errors.
563 BugReport.intercept(e).put("bounds", () -> getProjection().getWorldBoundsLatLon()).warn();
564 }
565
566 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 AudioPlayer.reset();
680 repaint();
681 }
682
683 /**
684 * Adds a new temporary layer.
685 * <p>
686 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added.
687 *
688 * @param mvp The layer to paint.
689 * @return <code>true</code> if the layer was added.
690 */
691 public boolean addTemporaryLayer(MapViewPaintable mvp) {
692 synchronized (temporaryLayers) {
693 boolean added = temporaryLayers.add(mvp);
694 if (added) {
695 invalidatedListener.addTo(mvp);
696 }
697 return added;
698 }
699 }
700
701 /**
702 * Removes a layer previously added as temporary layer.
703 * @param mvp The layer to remove.
704 * @return <code>true</code> if that layer was removed.
705 */
706 public boolean removeTemporaryLayer(MapViewPaintable mvp) {
707 synchronized (temporaryLayers) {
708 boolean removed = temporaryLayers.remove(mvp);
709 if (removed) {
710 invalidatedListener.removeFrom(mvp);
711 }
712 return removed;
713 }
714 }
715
716 /**
717 * Gets a list of temporary layers.
718 * @return The layers in the order they are added.
719 */
720 public List<MapViewPaintable> getTemporaryLayers() {
721 synchronized (temporaryLayers) {
722 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers));
723 }
724 }
725
726 @Override
727 public void propertyChange(PropertyChangeEvent evt) {
728 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
729 repaint();
730 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) ||
731 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) {
732 Layer l = (Layer) evt.getSource();
733 if (l.isVisible()) {
734 invalidatedListener.invalidate(l);
735 }
736 }
737 }
738
739 @Override
740 public void preferenceChanged(PreferenceChangeEvent e) {
741 paintPreferencesChanged.set(true);
742 }
743
744 private final transient SelectionChangedListener repaintSelectionChangedListener = newSelection -> repaint();
745
746 /**
747 * Destroy this map view panel. Should be called once when it is not needed any more.
748 */
749 public void destroy() {
750 layerManager.removeAndFireLayerChangeListener(this);
751 layerManager.removeActiveLayerChangeListener(this);
752 Main.pref.removePreferenceChangeListener(this);
753 DataSet.removeSelectionListener(repaintSelectionChangedListener);
754 MultipolygonCache.getInstance().clear();
755 if (mapMover != null) {
756 mapMover.destroy();
757 }
758 nonChangedLayers.clear();
759 synchronized (temporaryLayers) {
760 temporaryLayers.clear();
761 }
762 nonChangedLayersBuffer = null;
763 offscreenBuffer = null;
764 }
765
766 /**
767 * Get a string representation of all layers suitable for the {@code source} changeset tag.
768 * @return A String of sources separated by ';'
769 */
770 public String getLayerInformationForSourceTag() {
771 final Set<String> layerInfo = new TreeSet<>();
772 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) {
773 // no i18n for international values
774 layerInfo.add("survey");
775 }
776 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) {
777 if (i.isVisible()) {
778 layerInfo.add(i.getName());
779 }
780 }
781 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) {
782 if (i.isVisible()) {
783 layerInfo.add(ImageryInfo.ImageryType.BING.equals(i.getInfo().getImageryType()) ? "Bing" : i.getName());
784 }
785 }
786 return Utils.join("; ", layerInfo);
787 }
788
789 /**
790 * This is a listener that gets informed whenever repaint is called for this MapView.
791 * <p>
792 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly.
793 * @author Michael Zangl
794 * @since 10600 (functional interface)
795 */
796 @FunctionalInterface
797 public interface RepaintListener {
798 /**
799 * Called when any repaint method is called (using default arguments if required).
800 * @param tm see {@link JComponent#repaint(long, int, int, int, int)}
801 * @param x see {@link JComponent#repaint(long, int, int, int, int)}
802 * @param y see {@link JComponent#repaint(long, int, int, int, int)}
803 * @param width see {@link JComponent#repaint(long, int, int, int, int)}
804 * @param height see {@link JComponent#repaint(long, int, int, int, int)}
805 */
806 void repaint(long tm, int x, int y, int width, int height);
807 }
808
809 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>();
810
811 /**
812 * Adds a listener that gets informed whenever repaint() is called for this class.
813 * @param l The listener.
814 */
815 public void addRepaintListener(RepaintListener l) {
816 repaintListeners.add(l);
817 }
818
819 /**
820 * Removes a registered repaint listener.
821 * @param l The listener.
822 */
823 public void removeRepaintListener(RepaintListener l) {
824 repaintListeners.remove(l);
825 }
826
827 @Override
828 public void repaint(long tm, int x, int y, int width, int height) {
829 // This is the main repaint method, all other methods are convenience methods and simply call this method.
830 // This is just an observation, not a must, but seems to be true for all implementations I found so far.
831 if (repaintListeners != null) {
832 // Might get called early in super constructor
833 for (RepaintListener l : repaintListeners) {
834 l.repaint(tm, x, y, width, height);
835 }
836 }
837 super.repaint(tm, x, y, width, height);
838 }
839
840 @Override
841 public void repaint() {
842 if (Main.isTraceEnabled()) {
843 invalidatedListener.traceRandomRepaint();
844 }
845 super.repaint();
846 }
847
848 /**
849 * Returns the layer manager.
850 * @return the layer manager
851 * @since 10282
852 */
853 public final MainLayerManager getLayerManager() {
854 return layerManager;
855 }
856
857 /**
858 * Schedule a zoom to the given position on the next redraw.
859 * Temporary, may be removed without warning.
860 * @param viewportData the viewport to zoom to
861 * @since 10394
862 */
863 public void scheduleZoomTo(ViewportData viewportData) {
864 initialViewport = viewportData;
865 }
866}
Note: See TracBrowser for help on using the repository browser.