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