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

Last change on this file since 14017 was 13890, checked in by Don-vip, 6 years ago

fix #16357 - use English imagery names in changeset source tag

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