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

Last change on this file was 19403, checked in by stoecker, 7 weeks ago

fix #24299 - do zero check

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