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

Last change on this file since 12172 was 12170, checked in by michael2402, 7 years ago

"See #13175, see #14120: Remove isChanged() method call in map view - all layers should invalidate correctly now."

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