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 EastNorth oldCenter = getCenter(); 687 if (oldCenter == null) 688 return false; // no data loaded yet. 689 690 // if the position was remembered, we need to adjust center once before repainting 691 if (oldLoc != null && oldSize != null) { 692 Point l1 = getLocationOnScreen(); 693 final EastNorth newCenter = new EastNorth( 694 oldCenter.getX()+ (l1.x-oldLoc.x - (oldSize.width-getWidth())/2.0)*getScale(), 695 oldCenter.getY()+ (oldLoc.y-l1.y + (oldSize.height-getHeight())/2.0)*getScale() 696 ); 697 oldLoc = null; oldSize = null; 698 zoomTo(newCenter); 699 } 700 701 return true; 702 } 703 704 @Override 705 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) { 706 MapFrame map = MainApplication.getMap(); 707 if (map != null) { 708 /* This only makes the buttons look disabled. Disabling the actions as well requires 709 * the user to re-select the tool after i.e. moving a layer. While testing I found 710 * that I switch layers and actions at the same time and it was annoying to mind the 711 * order. This way it works as visual clue for new users */ 712 // FIXME: This does not belong here. 713 for (final AbstractButton b: map.allMapModeButtons) { 714 MapMode mode = (MapMode) b.getAction(); 715 final boolean activeLayerSupported = mode.layerIsSupported(layerManager.getActiveLayer()); 716 if (activeLayerSupported) { 717 MainApplication.registerActionShortcut(mode, mode.getShortcut()); //fix #6876 718 } else { 719 MainApplication.unregisterShortcut(mode.getShortcut()); 720 } 721 b.setEnabled(activeLayerSupported); 722 } 723 } 724 // invalidate repaint cache. The layer order may have changed by this, so we invalidate every layer 725 getLayerManager().getLayers().forEach(invalidatedListener::invalidate); 726 AudioPlayer.reset(); 727 } 728 729 /** 730 * Adds a new temporary layer. 731 * <p> 732 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added. 733 * 734 * @param mvp The layer to paint. 735 * @return <code>true</code> if the layer was added. 736 */ 737 public boolean addTemporaryLayer(MapViewPaintable mvp) { 738 synchronized (temporaryLayers) { 739 boolean added = temporaryLayers.add(mvp); 740 if (added) { 741 invalidatedListener.addTo(mvp); 742 } 743 repaint(); 744 return added; 745 } 746 } 747 748 /** 749 * Removes a layer previously added as temporary layer. 750 * @param mvp The layer to remove. 751 * @return <code>true</code> if that layer was removed. 752 */ 753 public boolean removeTemporaryLayer(MapViewPaintable mvp) { 754 synchronized (temporaryLayers) { 755 boolean removed = temporaryLayers.remove(mvp); 756 if (removed) { 757 invalidatedListener.removeFrom(mvp); 758 } 759 repaint(); 760 return removed; 761 } 762 } 763 764 /** 765 * Gets a list of temporary layers. 766 * @return The layers in the order they are added. 767 */ 768 public List<MapViewPaintable> getTemporaryLayers() { 769 synchronized (temporaryLayers) { 770 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers)); 771 } 772 } 773 774 @Override 775 public void propertyChange(PropertyChangeEvent evt) { 776 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) { 777 repaint(); 778 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) || 779 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) { 780 Layer l = (Layer) evt.getSource(); 781 if (l.isVisible()) { 782 invalidatedListener.invalidate(l); 783 } 784 } 785 } 786 787 @Override 788 public void preferenceChanged(PreferenceChangeEvent e) { 789 paintPreferencesChanged.set(true); 790 } 791 792 private final transient DataSelectionListener repaintSelectionChangedListener = event -> repaint(); 793 794 /** 795 * Destroy this map view panel. Should be called once when it is not needed any more. 796 */ 797 public void destroy() { 798 layerManager.removeAndFireLayerChangeListener(this); 799 layerManager.removeActiveLayerChangeListener(this); 800 Config.getPref().removePreferenceChangeListener(this); 801 SelectionEventManager.getInstance().removeSelectionListener(repaintSelectionChangedListener); 802 MultipolygonCache.getInstance().clear(); 803 if (mapMover != null) { 804 mapMover.destroy(); 805 } 806 nonChangedLayers.clear(); 807 synchronized (temporaryLayers) { 808 temporaryLayers.clear(); 809 } 810 nonChangedLayersBuffer = null; 811 offscreenBuffer = null; 812 setTransferHandler(null); 813 GuiHelper.destroyComponents(this, false); 814 } 815 816 /** 817 * Get a string representation of all layers suitable for the {@code source} changeset tag. 818 * @return A String of sources separated by ';' 819 */ 820 public String getLayerInformationForSourceTag() { 821 final Set<String> layerInfo = new TreeSet<>(); 822 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) { 823 // no i18n for international values 824 layerInfo.add("survey"); 825 } 826 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) { 827 if (i.isVisible()) { 828 layerInfo.add(i.getName()); 829 } 830 } 831 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) { 832 if (i.isVisible()) { 833 layerInfo.add(i.getInfo().getSourceName()); 834 } 835 } 836 return Utils.join("; ", layerInfo); 837 } 838 839 /** 840 * This is a listener that gets informed whenever repaint is called for this MapView. 841 * <p> 842 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly. 843 * @author Michael Zangl 844 * @since 10600 (functional interface) 845 */ 846 @FunctionalInterface 847 public interface RepaintListener { 848 /** 849 * Called when any repaint method is called (using default arguments if required). 850 * @param tm see {@link JComponent#repaint(long, int, int, int, int)} 851 * @param x see {@link JComponent#repaint(long, int, int, int, int)} 852 * @param y see {@link JComponent#repaint(long, int, int, int, int)} 853 * @param width see {@link JComponent#repaint(long, int, int, int, int)} 854 * @param height see {@link JComponent#repaint(long, int, int, int, int)} 855 */ 856 void repaint(long tm, int x, int y, int width, int height); 857 } 858 859 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>(); 860 861 /** 862 * Adds a listener that gets informed whenever repaint() is called for this class. 863 * @param l The listener. 864 */ 865 public void addRepaintListener(RepaintListener l) { 866 repaintListeners.add(l); 867 } 868 869 /** 870 * Removes a registered repaint listener. 871 * @param l The listener. 872 */ 873 public void removeRepaintListener(RepaintListener l) { 874 repaintListeners.remove(l); 875 } 876 877 @Override 878 public void repaint(long tm, int x, int y, int width, int height) { 879 // This is the main repaint method, all other methods are convenience methods and simply call this method. 880 // This is just an observation, not a must, but seems to be true for all implementations I found so far. 881 if (repaintListeners != null) { 882 // Might get called early in super constructor 883 for (RepaintListener l : repaintListeners) { 884 l.repaint(tm, x, y, width, height); 885 } 886 } 887 super.repaint(tm, x, y, width, height); 888 } 889 890 @Override 891 public void repaint() { 892 if (Logging.isTraceEnabled()) { 893 invalidatedListener.traceRandomRepaint(); 894 } 895 super.repaint(); 896 } 897 898 /** 899 * Returns the layer manager. 900 * @return the layer manager 901 * @since 10282 902 */ 903 public final MainLayerManager getLayerManager() { 904 return layerManager; 905 } 906 907 /** 908 * Schedule a zoom to the given position on the next redraw. 909 * Temporary, may be removed without warning. 910 * @param viewportData the viewport to zoom to 911 * @since 10394 912 */ 913 public void scheduleZoomTo(ViewportData viewportData) { 914 initialViewport = viewportData; 915 } 916 917 /** 918 * Returns the internal {@link MapMover}. 919 * @return the internal {@code MapMover} 920 * @since 13126 921 */ 922 public final MapMover getMapMover() { 923 return mapMover; 924 } 925}