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

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

sonar

  • Property svn:eol-style set to native
File size: 31.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.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 if (l.isChanged() || invalidated.contains(l)) {
463 break;
464 } else {
465 nonChangedLayersCount++;
466 }
467 }
468
469 boolean canUseBuffer = !paintPreferencesChanged.getAndSet(false)
470 && nonChangedLayers.size() <= nonChangedLayersCount
471 && lastViewID == getViewID()
472 && lastClipBounds.contains(g.getClipBounds())
473 && nonChangedLayers.equals(visibleLayers.subList(0, nonChangedLayers.size()));
474
475 if (null == offscreenBuffer || offscreenBuffer.getWidth() != getWidth() || offscreenBuffer.getHeight() != getHeight()) {
476 offscreenBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
477 }
478
479 Graphics2D tempG = offscreenBuffer.createGraphics();
480 tempG.setClip(g.getClip());
481 Bounds box = getLatLonBounds(g.getClipBounds());
482
483 if (!canUseBuffer || nonChangedLayersBuffer == null) {
484 if (null == nonChangedLayersBuffer
485 || nonChangedLayersBuffer.getWidth() != getWidth() || nonChangedLayersBuffer.getHeight() != getHeight()) {
486 nonChangedLayersBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
487 }
488 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
489 g2.setClip(g.getClip());
490 g2.setColor(PaintColors.getBackgroundColor());
491 g2.fillRect(0, 0, getWidth(), getHeight());
492
493 for (int i = 0; i < nonChangedLayersCount; i++) {
494 paintLayer(visibleLayers.get(i), g2, box);
495 }
496 } else {
497 // Maybe there were more unchanged layers then last time - draw them to buffer
498 if (nonChangedLayers.size() != nonChangedLayersCount) {
499 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
500 g2.setClip(g.getClip());
501 for (int i = nonChangedLayers.size(); i < nonChangedLayersCount; i++) {
502 paintLayer(visibleLayers.get(i), g2, box);
503 }
504 }
505 }
506
507 nonChangedLayers.clear();
508 nonChangedLayers.addAll(visibleLayers.subList(0, nonChangedLayersCount));
509 lastViewID = getViewID();
510 lastClipBounds = g.getClipBounds();
511
512 tempG.drawImage(nonChangedLayersBuffer, 0, 0, null);
513
514 for (int i = nonChangedLayersCount; i < visibleLayers.size(); i++) {
515 paintLayer(visibleLayers.get(i), tempG, box);
516 }
517
518 try {
519 drawTemporaryLayers(tempG, box);
520 } catch (RuntimeException e) {
521 BugReport.intercept(e).put("temporaryLayers", temporaryLayers).warn();
522 }
523
524 // draw world borders
525 try {
526 drawWorldBorders(tempG);
527 } catch (RuntimeException e) {
528 // getProjection() needs to be inside lambda to catch errors.
529 BugReport.intercept(e).put("bounds", () -> getProjection().getWorldBoundsLatLon()).warn();
530 }
531
532 if (Main.isDisplayingMapView() && Main.map.filterDialog != null) {
533 Main.map.filterDialog.drawOSDText(tempG);
534 }
535
536 if (playHeadMarker != null) {
537 playHeadMarker.paint(tempG, this);
538 }
539
540 try {
541 g.drawImage(offscreenBuffer, 0, 0, null);
542 } catch (ClassCastException e) {
543 // See #11002 and duplicate tickets. On Linux with Java >= 8 Many users face this error here:
544 //
545 // java.lang.ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
546 // at sun.java2d.xr.XRPMBlitLoops.cacheToTmpSurface(XRPMBlitLoops.java:145)
547 // at sun.java2d.xr.XrSwToPMBlit.Blit(XRPMBlitLoops.java:353)
548 // at sun.java2d.pipe.DrawImage.blitSurfaceData(DrawImage.java:959)
549 // at sun.java2d.pipe.DrawImage.renderImageCopy(DrawImage.java:577)
550 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:67)
551 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:1014)
552 // at sun.java2d.pipe.ValidatePipe.copyImage(ValidatePipe.java:186)
553 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3318)
554 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3296)
555 // at org.openstreetmap.josm.gui.MapView.paint(MapView.java:834)
556 //
557 // It seems to be this JDK bug, but Oracle does not seem to be fixing it:
558 // https://bugs.openjdk.java.net/browse/JDK-7172749
559 //
560 // According to bug reports it can happen for a variety of reasons such as:
561 // - long period of time
562 // - change of screen resolution
563 // - addition/removal of a secondary monitor
564 //
565 // But the application seems to work fine after, so let's just log the error
566 Main.error(e);
567 }
568 super.paint(g);
569 }
570
571 private void drawTemporaryLayers(Graphics2D tempG, Bounds box) {
572 synchronized (temporaryLayers) {
573 for (MapViewPaintable mvp : temporaryLayers) {
574 try {
575 mvp.paint(tempG, this, box);
576 } catch (RuntimeException e) {
577 throw BugReport.intercept(e).put("mvp", mvp);
578 }
579 }
580 }
581 }
582
583 private void drawWorldBorders(Graphics2D tempG) {
584 tempG.setColor(Color.WHITE);
585 Bounds b = getProjection().getWorldBoundsLatLon();
586
587 int w = getWidth();
588 int h = getHeight();
589
590 // Work around OpenJDK having problems when drawing out of bounds
591 final Area border = getState().getArea(b);
592 // Make the viewport 1px larger in every direction to prevent an
593 // additional 1px border when zooming in
594 final Area viewport = new Area(new Rectangle(-1, -1, w + 2, h + 2));
595 border.intersect(viewport);
596 tempG.draw(border);
597 }
598
599 /**
600 * Sets up the viewport to prepare for drawing the view.
601 * @return <code>true</code> if the view can be drawn, <code>false</code> otherwise.
602 */
603 public boolean prepareToDraw() {
604 updateLocationState();
605 if (initialViewport != null) {
606 zoomTo(initialViewport);
607 initialViewport = null;
608 }
609
610 if (getCenter() == null)
611 return false; // no data loaded yet.
612
613 // if the position was remembered, we need to adjust center once before repainting
614 if (oldLoc != null && oldSize != null) {
615 Point l1 = getLocationOnScreen();
616 final EastNorth newCenter = new EastNorth(
617 getCenter().getX()+ (l1.x-oldLoc.x - (oldSize.width-getWidth())/2.0)*getScale(),
618 getCenter().getY()+ (oldLoc.y-l1.y + (oldSize.height-getHeight())/2.0)*getScale()
619 );
620 oldLoc = null; oldSize = null;
621 zoomTo(newCenter);
622 }
623
624 return true;
625 }
626
627 @Override
628 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
629 if (Main.map != null) {
630 /* This only makes the buttons look disabled. Disabling the actions as well requires
631 * the user to re-select the tool after i.e. moving a layer. While testing I found
632 * that I switch layers and actions at the same time and it was annoying to mind the
633 * order. This way it works as visual clue for new users */
634 // FIXME: This does not belong here.
635 for (final AbstractButton b: Main.map.allMapModeButtons) {
636 MapMode mode = (MapMode) b.getAction();
637 final boolean activeLayerSupported = mode.layerIsSupported(layerManager.getActiveLayer());
638 if (activeLayerSupported) {
639 Main.registerActionShortcut(mode, mode.getShortcut()); //fix #6876
640 } else {
641 Main.unregisterShortcut(mode.getShortcut());
642 }
643 b.setEnabled(activeLayerSupported);
644 }
645 }
646 AudioPlayer.reset();
647 repaint();
648 }
649
650 /**
651 * Adds a new temporary layer.
652 * <p>
653 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added.
654 *
655 * @param mvp The layer to paint.
656 * @return <code>true</code> if the layer was added.
657 */
658 public boolean addTemporaryLayer(MapViewPaintable mvp) {
659 synchronized (temporaryLayers) {
660 boolean added = temporaryLayers.add(mvp);
661 if (added) {
662 invalidatedListener.addTo(mvp);
663 }
664 return added;
665 }
666 }
667
668 /**
669 * Removes a layer previously added as temporary layer.
670 * @param mvp The layer to remove.
671 * @return <code>true</code> if that layer was removed.
672 */
673 public boolean removeTemporaryLayer(MapViewPaintable mvp) {
674 synchronized (temporaryLayers) {
675 boolean removed = temporaryLayers.remove(mvp);
676 if (removed) {
677 invalidatedListener.removeFrom(mvp);
678 }
679 return removed;
680 }
681 }
682
683 /**
684 * Gets a list of temporary layers.
685 * @return The layers in the order they are added.
686 */
687 public List<MapViewPaintable> getTemporaryLayers() {
688 synchronized (temporaryLayers) {
689 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers));
690 }
691 }
692
693 @Override
694 public void propertyChange(PropertyChangeEvent evt) {
695 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
696 repaint();
697 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) ||
698 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) {
699 Layer l = (Layer) evt.getSource();
700 if (l.isVisible()) {
701 invalidatedListener.invalidate(l);
702 }
703 }
704 }
705
706 @Override
707 public void preferenceChanged(PreferenceChangeEvent e) {
708 paintPreferencesChanged.set(true);
709 }
710
711 private final transient SelectionChangedListener repaintSelectionChangedListener = newSelection -> repaint();
712
713 /**
714 * Destroy this map view panel. Should be called once when it is not needed any more.
715 */
716 public void destroy() {
717 layerManager.removeLayerChangeListener(this, true);
718 layerManager.removeActiveLayerChangeListener(this);
719 Main.pref.removePreferenceChangeListener(this);
720 DataSet.removeSelectionListener(repaintSelectionChangedListener);
721 MultipolygonCache.getInstance().clear(this);
722 if (mapMover != null) {
723 mapMover.destroy();
724 }
725 nonChangedLayers.clear();
726 synchronized (temporaryLayers) {
727 temporaryLayers.clear();
728 }
729 nonChangedLayersBuffer = null;
730 offscreenBuffer = null;
731 }
732
733 /**
734 * Get a string representation of all layers suitable for the {@code source} changeset tag.
735 * @return A String of sources separated by ';'
736 */
737 public String getLayerInformationForSourceTag() {
738 final Set<String> layerInfo = new TreeSet<>();
739 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) {
740 // no i18n for international values
741 layerInfo.add("survey");
742 }
743 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) {
744 if (i.isVisible()) {
745 layerInfo.add(i.getName());
746 }
747 }
748 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) {
749 if (i.isVisible()) {
750 layerInfo.add(ImageryInfo.ImageryType.BING.equals(i.getInfo().getImageryType()) ? "Bing" : i.getName());
751 }
752 }
753 return Utils.join("; ", layerInfo);
754 }
755
756 /**
757 * This is a listener that gets informed whenever repaint is called for this MapView.
758 * <p>
759 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly.
760 * @author Michael Zangl
761 * @since 10600 (functional interface)
762 */
763 @FunctionalInterface
764 public interface RepaintListener {
765 /**
766 * Called when any repaint method is called (using default arguments if required).
767 * @param tm see {@link JComponent#repaint(long, int, int, int, int)}
768 * @param x see {@link JComponent#repaint(long, int, int, int, int)}
769 * @param y see {@link JComponent#repaint(long, int, int, int, int)}
770 * @param width see {@link JComponent#repaint(long, int, int, int, int)}
771 * @param height see {@link JComponent#repaint(long, int, int, int, int)}
772 */
773 void repaint(long tm, int x, int y, int width, int height);
774 }
775
776 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>();
777
778 /**
779 * Adds a listener that gets informed whenever repaint() is called for this class.
780 * @param l The listener.
781 */
782 public void addRepaintListener(RepaintListener l) {
783 repaintListeners.add(l);
784 }
785
786 /**
787 * Removes a registered repaint listener.
788 * @param l The listener.
789 */
790 public void removeRepaintListener(RepaintListener l) {
791 repaintListeners.remove(l);
792 }
793
794 @Override
795 public void repaint(long tm, int x, int y, int width, int height) {
796 // This is the main repaint method, all other methods are convenience methods and simply call this method.
797 // This is just an observation, not a must, but seems to be true for all implementations I found so far.
798 if (repaintListeners != null) {
799 // Might get called early in super constructor
800 for (RepaintListener l : repaintListeners) {
801 l.repaint(tm, x, y, width, height);
802 }
803 }
804 super.repaint(tm, x, y, width, height);
805 }
806
807 @Override
808 public void repaint() {
809 if (Main.isTraceEnabled()) {
810 invalidatedListener.traceRandomRepaint();
811 }
812 super.repaint();
813 }
814
815 /**
816 * Returns the layer manager.
817 * @return the layer manager
818 * @since 10282
819 */
820 public final MainLayerManager getLayerManager() {
821 return layerManager;
822 }
823
824 /**
825 * Schedule a zoom to the given position on the next redraw.
826 * Temporary, may be removed without warning.
827 * @param viewportData the viewport to zoom to
828 * @since 10394
829 */
830 public void scheduleZoomTo(ViewportData viewportData) {
831 initialViewport = viewportData;
832 }
833}
Note: See TracBrowser for help on using the repository browser.