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

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

see #15310 - remove most of deprecated APIs

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