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

Last change on this file since 19057 was 19057, checked in by stoecker, 5 weeks ago

fix checkstyle

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