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