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.concurrent.CopyOnWriteArrayList; 032import java.util.concurrent.atomic.AtomicBoolean; 033import java.util.stream.Collectors; 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.Layer; 054import org.openstreetmap.josm.gui.layer.LayerManager; 055import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent; 056import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent; 057import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent; 058import org.openstreetmap.josm.gui.layer.MainLayerManager; 059import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent; 060import org.openstreetmap.josm.gui.layer.MapViewGraphics; 061import org.openstreetmap.josm.gui.layer.MapViewPaintable; 062import org.openstreetmap.josm.gui.layer.MapViewPaintable.LayerPainter; 063import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent; 064import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent; 065import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener; 066import org.openstreetmap.josm.gui.layer.OsmDataLayer; 067import org.openstreetmap.josm.gui.layer.markerlayer.PlayHeadMarker; 068import org.openstreetmap.josm.gui.mappaint.MapPaintStyles; 069import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.MapPaintStylesUpdateListener; 070import org.openstreetmap.josm.gui.util.GuiHelper; 071import org.openstreetmap.josm.io.audio.AudioPlayer; 072import org.openstreetmap.josm.spi.preferences.Config; 073import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent; 074import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener; 075import org.openstreetmap.josm.tools.JosmRuntimeException; 076import org.openstreetmap.josm.tools.Logging; 077import org.openstreetmap.josm.tools.Shortcut; 078import org.openstreetmap.josm.tools.Utils; 079import org.openstreetmap.josm.tools.bugreport.BugReport; 080 081/** 082 * This is a component used in the {@link MapFrame} for browsing the map. It use is to 083 * provide the MapMode's enough capabilities to operate.<br><br> 084 * 085 * {@code MapView} holds meta-data about the data set currently displayed, as scale level, 086 * center point viewed, what scrolling mode or editing mode is selected or with 087 * what projection the map is viewed etc..<br><br> 088 * 089 * {@code MapView} is able to administrate several layers. 090 * 091 * @author imi 092 */ 093public class MapView extends NavigatableComponent 094implements PropertyChangeListener, PreferenceChangedListener, 095LayerManager.LayerChangeListener, MainLayerManager.ActiveLayerChangeListener { 096 097 static { 098 MapPaintStyles.addMapPaintStylesUpdateListener(new MapPaintStylesUpdateListener() { 099 @Override 100 public void mapPaintStylesUpdated() { 101 SwingUtilities.invokeLater(() -> 102 // Trigger a repaint of all data layers 103 MainApplication.getLayerManager().getLayers() 104 .stream() 105 .filter(layer -> layer instanceof OsmDataLayer) 106 .forEach(Layer::invalidate) 107 ); 108 } 109 110 @Override 111 public void mapPaintStyleEntryUpdated(int index) { 112 mapPaintStylesUpdated(); 113 } 114 }); 115 } 116 117 /** 118 * An invalidation listener that simply calls repaint() for now. 119 * @author Michael Zangl 120 * @since 10271 121 */ 122 private class LayerInvalidatedListener implements PaintableInvalidationListener { 123 private boolean ignoreRepaint; 124 125 private final Set<MapViewPaintable> invalidatedLayers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>()); 126 127 @Override 128 public void paintableInvalidated(PaintableInvalidationEvent event) { 129 invalidate(event.getLayer()); 130 } 131 132 /** 133 * Invalidate contents and repaint map view 134 * @param mapViewPaintable invalidated layer 135 */ 136 public synchronized void invalidate(MapViewPaintable mapViewPaintable) { 137 ignoreRepaint = true; 138 invalidatedLayers.add(mapViewPaintable); 139 repaint(); 140 } 141 142 /** 143 * Temporary until all {@link MapViewPaintable}s support this. 144 * @param p The paintable. 145 */ 146 public synchronized void addTo(MapViewPaintable p) { 147 p.addInvalidationListener(this); 148 } 149 150 /** 151 * Temporary until all {@link MapViewPaintable}s support this. 152 * @param p The paintable. 153 */ 154 public synchronized void removeFrom(MapViewPaintable p) { 155 p.removeInvalidationListener(this); 156 invalidatedLayers.remove(p); 157 } 158 159 /** 160 * Attempts to trace repaints that did not originate from this listener. Good to find missed {@link MapView#repaint()}s in code. 161 */ 162 protected synchronized void traceRandomRepaint() { 163 if (!ignoreRepaint) { 164 Logging.trace("Repaint: {0} from {1}", Thread.currentThread().getStackTrace()[3], Thread.currentThread()); 165 } 166 ignoreRepaint = false; 167 } 168 169 /** 170 * Retrieves a set of all layers that have been marked as invalid since the last call to this method. 171 * @return The layers 172 */ 173 protected synchronized Set<MapViewPaintable> collectInvalidatedLayers() { 174 Set<MapViewPaintable> layers = Collections.newSetFromMap(new IdentityHashMap<MapViewPaintable, Boolean>()); 175 layers.addAll(invalidatedLayers); 176 invalidatedLayers.clear(); 177 return layers; 178 } 179 } 180 181 /** 182 * A layer painter that issues a warning when being called. 183 * @author Michael Zangl 184 * @since 10474 185 */ 186 private static class WarningLayerPainter implements LayerPainter { 187 boolean warningPrinted; 188 private final Layer layer; 189 190 WarningLayerPainter(Layer layer) { 191 this.layer = layer; 192 } 193 194 @Override 195 public void paint(MapViewGraphics graphics) { 196 if (!warningPrinted) { 197 Logging.debug("A layer triggered a repaint while being added: " + layer); 198 warningPrinted = true; 199 } 200 } 201 202 @Override 203 public void detachFromMapView(MapViewEvent event) { 204 // ignored 205 } 206 } 207 208 /** 209 * A list of all layers currently loaded. If we support multiple map views, this list may be different for each of them. 210 */ 211 private final MainLayerManager layerManager; 212 213 /** 214 * The play head marker: there is only one of these so it isn't in any specific layer 215 */ 216 public transient PlayHeadMarker playHeadMarker; 217 218 /** 219 * The last event performed by mouse. 220 */ 221 public MouseEvent lastMEvent = new MouseEvent(this, 0, 0, 0, 0, 0, 0, false); // In case somebody reads it before first mouse move 222 223 /** 224 * Temporary layers (selection rectangle, etc.) that are never cached and 225 * drawn on top of regular layers. 226 * Access must be synchronized. 227 */ 228 private final transient Set<MapViewPaintable> temporaryLayers = new LinkedHashSet<>(); 229 230 private transient BufferedImage nonChangedLayersBuffer; 231 private transient BufferedImage offscreenBuffer; 232 // Layers that wasn't changed since last paint 233 private final transient List<Layer> nonChangedLayers = new ArrayList<>(); 234 private int lastViewID; 235 private final AtomicBoolean paintPreferencesChanged = new AtomicBoolean(true); 236 private Rectangle lastClipBounds = new Rectangle(); 237 private transient MapMover mapMover; 238 239 /** 240 * The listener that listens to invalidations of all layers. 241 */ 242 private final LayerInvalidatedListener invalidatedListener = new LayerInvalidatedListener(); 243 244 /** 245 * This is a map of all Layers that have been added to this view. 246 */ 247 private final HashMap<Layer, LayerPainter> registeredLayers = new HashMap<>(); 248 249 /** 250 * Constructs a new {@code MapView}. 251 * @param layerManager The layers to display. 252 * @param viewportData the initial viewport of the map. Can be null, then 253 * the viewport is derived from the layer data. 254 * @since 11713 255 */ 256 public MapView(MainLayerManager layerManager, final ViewportData viewportData) { 257 this.layerManager = layerManager; 258 initialViewport = viewportData; 259 layerManager.addAndFireLayerChangeListener(this); 260 layerManager.addActiveLayerChangeListener(this); 261 Config.getPref().addPreferenceChangeListener(this); 262 263 addComponentListener(new ComponentAdapter() { 264 @Override 265 public void componentResized(ComponentEvent e) { 266 removeComponentListener(this); 267 mapMover = new MapMover(MapView.this); 268 } 269 }); 270 271 // listens to selection changes to redraw the map 272 SelectionEventManager.getInstance().addSelectionListenerForEdt(repaintSelectionChangedListener); 273 274 //store the last mouse action 275 this.addMouseMotionListener(new MouseMotionListener() { 276 @Override 277 public void mouseDragged(MouseEvent e) { 278 mouseMoved(e); 279 } 280 281 @Override 282 public void mouseMoved(MouseEvent e) { 283 lastMEvent = e; 284 } 285 }); 286 this.addMouseListener(new MouseAdapter() { 287 @Override 288 public void mousePressed(MouseEvent me) { 289 // focus the MapView component when mouse is pressed inside it 290 requestFocus(); 291 } 292 }); 293 294 setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent()); 295 296 for (JComponent c : getMapNavigationComponents(this)) { 297 add(c); 298 } 299 if (AutoFilterManager.PROP_AUTO_FILTER_ENABLED.get()) { 300 AutoFilterManager.getInstance().enableAutoFilterRule(AutoFilterManager.PROP_AUTO_FILTER_RULE.get()); 301 } 302 setTransferHandler(new OsmTransferHandler()); 303 } 304 305 /** 306 * Adds the map navigation components to a 307 * @param forMapView The map view to get the components for. 308 * @return A list containing the correctly positioned map navigation components. 309 */ 310 public static List<? extends JComponent> getMapNavigationComponents(MapView forMapView) { 311 MapSlider zoomSlider = new MapSlider(forMapView); 312 Dimension size = zoomSlider.getPreferredSize(); 313 zoomSlider.setSize(size); 314 zoomSlider.setLocation(3, 0); 315 zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent()); 316 317 MapScaler scaler = new MapScaler(forMapView); 318 scaler.setPreferredLineLength(size.width - 10); 319 scaler.setSize(scaler.getPreferredSize()); 320 scaler.setLocation(3, size.height); 321 322 return Arrays.asList(zoomSlider, scaler); 323 } 324 325 // remebered geometry of the component 326 private Dimension oldSize; 327 private Point oldLoc; 328 329 /** 330 * Call this method to keep map position on screen during next repaint 331 */ 332 public void rememberLastPositionOnScreen() { 333 oldSize = getSize(); 334 oldLoc = getLocationOnScreen(); 335 } 336 337 @Override 338 public void layerAdded(LayerAddEvent e) { 339 try { 340 Layer layer = e.getAddedLayer(); 341 registeredLayers.put(layer, new WarningLayerPainter(layer)); 342 // Layers may trigger a redraw during this call if they open dialogs. 343 LayerPainter painter = layer.attachToMapView(new MapViewEvent(this, false)); 344 if (!registeredLayers.containsKey(layer)) { 345 // The layer may have removed itself during attachToMapView() 346 Logging.warn("Layer was removed during attachToMapView()"); 347 } else { 348 registeredLayers.put(layer, painter); 349 350 if (e.isZoomRequired()) { 351 ProjectionBounds viewProjectionBounds = layer.getViewProjectionBounds(); 352 if (viewProjectionBounds != null) { 353 scheduleZoomTo(new ViewportData(viewProjectionBounds)); 354 } 355 } 356 357 layer.addPropertyChangeListener(this); 358 ProjectionRegistry.addProjectionChangeListener(layer); 359 invalidatedListener.addTo(layer); 360 AudioPlayer.reset(); 361 362 repaint(); 363 } 364 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) { 365 throw BugReport.intercept(t).put("layer", e.getAddedLayer()); 366 } 367 } 368 369 /** 370 * Replies true if the active data layer (edit layer) is drawable. 371 * 372 * @return true if the active data layer (edit layer) is drawable, false otherwise 373 */ 374 public boolean isActiveLayerDrawable() { 375 return layerManager.getEditLayer() != null; 376 } 377 378 /** 379 * Replies true if the active data layer is visible. 380 * 381 * @return true if the active data layer is visible, false otherwise 382 */ 383 public boolean isActiveLayerVisible() { 384 OsmDataLayer e = layerManager.getActiveDataLayer(); 385 return e != null && e.isVisible(); 386 } 387 388 @Override 389 public void layerRemoving(LayerRemoveEvent e) { 390 Layer layer = e.getRemovedLayer(); 391 392 LayerPainter painter = registeredLayers.remove(layer); 393 if (painter == null) { 394 Logging.error("The painter for layer " + layer + " was not registered."); 395 return; 396 } 397 painter.detachFromMapView(new MapViewEvent(this, false)); 398 ProjectionRegistry.removeProjectionChangeListener(layer); 399 layer.removePropertyChangeListener(this); 400 invalidatedListener.removeFrom(layer); 401 if (layer == getNativeScaleLayer()) 402 setNativeScaleLayer(null); 403 layer.destroy(); 404 AudioPlayer.reset(); 405 406 repaint(); 407 } 408 409 private boolean virtualNodesEnabled; 410 411 /** 412 * Enables or disables drawing of the virtual nodes. 413 * @param enabled if virtual nodes are enabled 414 */ 415 public void setVirtualNodesEnabled(boolean enabled) { 416 if (virtualNodesEnabled != enabled) { 417 virtualNodesEnabled = enabled; 418 repaint(); 419 } 420 } 421 422 /** 423 * Checks if virtual nodes should be drawn. Default is <code>false</code> 424 * @return The virtual nodes property. 425 * @see Rendering#render 426 */ 427 public boolean isVirtualNodesEnabled() { 428 return virtualNodesEnabled; 429 } 430 431 /** 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. 434 * 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) { 439 layerManager.moveLayer(layer, pos); 440 } 441 442 @Override 443 public void layerOrderChanged(LayerOrderChangeEvent e) { 444 AudioPlayer.reset(); 445 repaint(); 446 } 447 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) { 456 try { 457 LayerPainter painter = registeredLayers.get(layer); 458 if (painter == null) { 459 Logging.warn("Cannot paint layer, it is not registered: {0}", layer); 460 return; 461 } 462 MapViewRectangle clipBounds = getState().getViewArea(g.getClipBounds()); 463 MapViewGraphics paintGraphics = new MapViewGraphics(this, g, clipBounds); 464 float opacity = (float) layer.getOpacity(); 465 466 if (opacity < 1.0f) { 467 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); 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 return layerManager.getVisibleLayersInZOrder().stream() 822 .filter(layer -> !Utils.isBlank(layer.getChangesetSourceTag())) 823 .map(layer -> layer.getChangesetSourceTag().trim()) 824 .distinct() 825 .collect(Collectors.joining("; ")); 826 } 827 828 /** 829 * This is a listener that gets informed whenever repaint is called for this MapView. 830 * <p> 831 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly. 832 * @author Michael Zangl 833 * @since 10600 (functional interface) 834 */ 835 @FunctionalInterface 836 public interface RepaintListener { 837 /** 838 * Called when any repaint method is called (using default arguments if required). 839 * @param tm see {@link JComponent#repaint(long, int, int, int, int)} 840 * @param x see {@link JComponent#repaint(long, int, int, int, int)} 841 * @param y see {@link JComponent#repaint(long, int, int, int, int)} 842 * @param width see {@link JComponent#repaint(long, int, int, int, int)} 843 * @param height see {@link JComponent#repaint(long, int, int, int, int)} 844 */ 845 void repaint(long tm, int x, int y, int width, int height); 846 } 847 848 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>(); 849 850 /** 851 * Adds a listener that gets informed whenever repaint() is called for this class. 852 * @param l The listener. 853 */ 854 public void addRepaintListener(RepaintListener l) { 855 repaintListeners.add(l); 856 } 857 858 /** 859 * Removes a registered repaint listener. 860 * @param l The listener. 861 */ 862 public void removeRepaintListener(RepaintListener l) { 863 repaintListeners.remove(l); 864 } 865 866 @Override 867 public void repaint(long tm, int x, int y, int width, int height) { 868 // This is the main repaint method, all other methods are convenience methods and simply call this method. 869 // This is just an observation, not a must, but seems to be true for all implementations I found so far. 870 if (repaintListeners != null) { 871 // Might get called early in super constructor 872 for (RepaintListener l : repaintListeners) { 873 l.repaint(tm, x, y, width, height); 874 } 875 } 876 super.repaint(tm, x, y, width, height); 877 } 878 879 @Override 880 public void repaint() { 881 if (Logging.isTraceEnabled()) { 882 invalidatedListener.traceRandomRepaint(); 883 } 884 super.repaint(); 885 } 886 887 /** 888 * Returns the layer manager. 889 * @return the layer manager 890 * @since 10282 891 */ 892 public final MainLayerManager getLayerManager() { 893 return layerManager; 894 } 895 896 /** 897 * Schedule a zoom to the given position on the next redraw. 898 * Temporary, may be removed without warning. 899 * @param viewportData the viewport to zoom to 900 * @since 10394 901 */ 902 public void scheduleZoomTo(ViewportData viewportData) { 903 initialViewport = viewportData; 904 } 905 906 /** 907 * Returns the internal {@link MapMover}. 908 * @return the internal {@code MapMover} 909 * @since 13126 910 */ 911 public final MapMover getMapMover() { 912 return mapMover; 913 } 914}