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