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

Last change on this file since 12172 was 12170, checked in by michael2402, 7 years ago

"See #13175, see #14120: Remove isChanged() method call in map view - all layers should invalidate correctly now."

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