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

Last change on this file since 11114 was 11071, checked in by simon04, 8 years ago

see #13175 - Document deprecated method usage

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