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

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

see #15744 - add/rework traces

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