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

Last change on this file since 12745 was 12722, checked in by bastiK, 7 years ago

see #9995 - fix blurry GUI-icons and map view for Java 9 HiDPI mode

  • 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.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.JPanel;
38import javax.swing.SwingUtilities;
39
40import org.openstreetmap.josm.Main;
41import org.openstreetmap.josm.actions.mapmode.MapMode;
42import org.openstreetmap.josm.data.Bounds;
43import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
44import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
45import org.openstreetmap.josm.data.ProjectionBounds;
46import org.openstreetmap.josm.data.ViewportData;
47import org.openstreetmap.josm.data.coor.EastNorth;
48import org.openstreetmap.josm.data.imagery.ImageryInfo;
49import org.openstreetmap.josm.data.osm.DataSelectionListener;
50import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
51import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
52import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
53import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
54import org.openstreetmap.josm.gui.MapViewState.MapViewRectangle;
55import org.openstreetmap.josm.gui.autofilter.AutoFilterManager;
56import org.openstreetmap.josm.gui.datatransfer.OsmTransferHandler;
57import org.openstreetmap.josm.gui.layer.GpxLayer;
58import org.openstreetmap.josm.gui.layer.ImageryLayer;
59import org.openstreetmap.josm.gui.layer.Layer;
60import org.openstreetmap.josm.gui.layer.LayerManager;
61import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent;
62import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent;
63import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent;
64import org.openstreetmap.josm.gui.layer.MainLayerManager;
65import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeEvent;
66import org.openstreetmap.josm.gui.layer.MapViewGraphics;
67import org.openstreetmap.josm.gui.layer.MapViewPaintable;
68import org.openstreetmap.josm.gui.layer.MapViewPaintable.LayerPainter;
69import org.openstreetmap.josm.gui.layer.MapViewPaintable.MapViewEvent;
70import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationEvent;
71import org.openstreetmap.josm.gui.layer.MapViewPaintable.PaintableInvalidationListener;
72import org.openstreetmap.josm.gui.layer.OsmDataLayer;
73import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer;
74import org.openstreetmap.josm.gui.layer.markerlayer.PlayHeadMarker;
75import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
76import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.MapPaintSylesUpdateListener;
77import org.openstreetmap.josm.io.audio.AudioPlayer;
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 contentPane Ignored. Main content pane is used.
257 * @param viewportData the initial viewport of the map. Can be null, then
258 * the viewport is derived from the layer data.
259 * @since 10279
260 * @deprecated use {@link #MapView(MainLayerManager, ViewportData)} instead
261 */
262 @Deprecated
263 public MapView(MainLayerManager layerManager, final JPanel contentPane, final ViewportData viewportData) {
264 this(layerManager, viewportData);
265 }
266
267 /**
268 * Constructs a new {@code MapView}.
269 * @param layerManager The layers to display.
270 * @param viewportData the initial viewport of the map. Can be null, then
271 * the viewport is derived from the layer data.
272 * @since 11713
273 */
274 public MapView(MainLayerManager layerManager, final ViewportData viewportData) {
275 this.layerManager = layerManager;
276 initialViewport = viewportData;
277 layerManager.addAndFireLayerChangeListener(this);
278 layerManager.addActiveLayerChangeListener(this);
279 Main.pref.addPreferenceChangeListener(this);
280
281 addComponentListener(new ComponentAdapter() {
282 @Override
283 public void componentResized(ComponentEvent e) {
284 removeComponentListener(this);
285 mapMover = new MapMover(MapView.this);
286 }
287 });
288
289 // listens to selection changes to redraw the map
290 SelectionEventManager.getInstance().addSelectionListenerForEdt(repaintSelectionChangedListener);
291
292 //store the last mouse action
293 this.addMouseMotionListener(new MouseMotionListener() {
294 @Override
295 public void mouseDragged(MouseEvent e) {
296 mouseMoved(e);
297 }
298
299 @Override
300 public void mouseMoved(MouseEvent e) {
301 lastMEvent = e;
302 }
303 });
304 this.addMouseListener(new MouseAdapter() {
305 @Override
306 public void mousePressed(MouseEvent me) {
307 // focus the MapView component when mouse is pressed inside it
308 requestFocus();
309 }
310 });
311
312 setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
313
314 for (JComponent c : getMapNavigationComponents(this)) {
315 add(c);
316 }
317 if (AutoFilterManager.PROP_AUTO_FILTER_ENABLED.get()) {
318 AutoFilterManager.getInstance().enableAutoFilterRule(AutoFilterManager.PROP_AUTO_FILTER_RULE.get());
319 }
320 setTransferHandler(new OsmTransferHandler());
321 }
322
323 /**
324 * Adds the map navigation components to a
325 * @param forMapView The map view to get the components for.
326 * @return A list containing the correctly positioned map navigation components.
327 */
328 public static List<? extends JComponent> getMapNavigationComponents(MapView forMapView) {
329 MapSlider zoomSlider = new MapSlider(forMapView);
330 Dimension size = zoomSlider.getPreferredSize();
331 zoomSlider.setSize(size);
332 zoomSlider.setLocation(3, 0);
333 zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
334
335 MapScaler scaler = new MapScaler(forMapView);
336 scaler.setPreferredLineLength(size.width - 10);
337 scaler.setSize(scaler.getPreferredSize());
338 scaler.setLocation(3, size.height);
339
340 return Arrays.asList(zoomSlider, scaler);
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 Main.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 (edit layer) is visible.
398 *
399 * @return true if the active data layer (edit layer) is visible, false otherwise
400 */
401 public boolean isActiveLayerVisible() {
402 OsmDataLayer e = layerManager.getEditLayer();
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 Main.removeProjectionChangeListener(layer);
417 layer.removePropertyChangeListener(this);
418 invalidatedListener.removeFrom(layer);
419 layer.destroy();
420 AudioPlayer.reset();
421
422 repaint();
423 }
424
425 private boolean virtualNodesEnabled;
426
427 /**
428 * Enables or disables drawing of the virtual nodes.
429 * @param enabled if virtual nodes are enabled
430 */
431 public void setVirtualNodesEnabled(boolean enabled) {
432 if (virtualNodesEnabled != enabled) {
433 virtualNodesEnabled = enabled;
434 repaint();
435 }
436 }
437
438 /**
439 * Checks if virtual nodes should be drawn. Default is <code>false</code>
440 * @return The virtual nodes property.
441 * @see Rendering#render
442 */
443 public boolean isVirtualNodesEnabled() {
444 return virtualNodesEnabled;
445 }
446
447 /**
448 * Moves the layer to the given new position. No event is fired, but repaints
449 * according to the new Z-Order of the layers.
450 *
451 * @param layer The layer to move
452 * @param pos The new position of the layer
453 */
454 public void moveLayer(Layer layer, int pos) {
455 layerManager.moveLayer(layer, pos);
456 }
457
458 @Override
459 public void layerOrderChanged(LayerOrderChangeEvent e) {
460 AudioPlayer.reset();
461 repaint();
462 }
463
464 /**
465 * Paints the given layer to the graphics object, using the current state of this map view.
466 * @param layer The layer to draw.
467 * @param g A graphics object. It should have the width and height of this component
468 * @throws IllegalArgumentException If the layer is not part of this map view.
469 * @since 11226
470 */
471 public void paintLayer(Layer layer, Graphics2D g) {
472 try {
473 LayerPainter painter = registeredLayers.get(layer);
474 if (painter == null) {
475 Logging.warn("Cannot paint layer, it is not registered: {0}", layer);
476 return;
477 }
478 MapViewRectangle clipBounds = getState().getViewArea(g.getClipBounds());
479 MapViewGraphics paintGraphics = new MapViewGraphics(this, g, clipBounds);
480
481 if (layer.getOpacity() < 1) {
482 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) layer.getOpacity()));
483 }
484 painter.paint(paintGraphics);
485 g.setPaintMode();
486 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
487 BugReport.intercept(t).put("layer", layer).warn();
488 }
489 }
490
491 /**
492 * Draw the component.
493 */
494 @Override
495 public void paint(Graphics g) {
496 try {
497 if (!prepareToDraw()) {
498 return;
499 }
500 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
501 BugReport.intercept(e).put("center", this::getCenter).warn();
502 return;
503 }
504
505 try {
506 drawMapContent(g);
507 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
508 throw BugReport.intercept(e).put("visibleLayers", layerManager::getVisibleLayersInZOrder)
509 .put("temporaryLayers", temporaryLayers);
510 }
511 super.paint(g);
512 }
513
514 private void drawMapContent(Graphics g) {
515 // In HiDPI-mode, the Graphics g will have a transform that scales
516 // everything by a factor of 2.0 or so. At the same time, the value returned
517 // by getWidth()/getHeight will be reduced by that factor.
518 //
519 // This would work as intended, if we were to draw directly on g. But
520 // with a temporary buffer image, we need to move the scale transform to
521 // the Graphics of the buffer image and (in the end) transfer the content
522 // of the temporary buffer pixel by pixel onto g, without scaling.
523 // (Otherwise, we would upscale a small buffer image and the result would be
524 // blurry, with 2x2 pixel blocks.)
525 Graphics2D gg = (Graphics2D) g;
526 AffineTransform trOrig = gg.getTransform();
527 double uiScaleX = gg.getTransform().getScaleX();
528 double uiScaleY = gg.getTransform().getScaleY();
529 // width/height in full-resolution screen pixels
530 int width = (int) Math.round(getWidth() * uiScaleX);
531 int height = (int) Math.round(getHeight() * uiScaleY);
532 // This transformation corresponds to the original transformation of g,
533 // except for the translation part. It will be applied to the temporary
534 // buffer images.
535 AffineTransform trDef = AffineTransform.getScaleInstance(uiScaleX, uiScaleY);
536 // The goal is to create the temporary image at full pixel resolution,
537 // so scale up the clip shape
538 Shape scaledClip = trDef.createTransformedShape(g.getClip());
539
540 List<Layer> visibleLayers = layerManager.getVisibleLayersInZOrder();
541
542 int nonChangedLayersCount = 0;
543 Set<MapViewPaintable> invalidated = invalidatedListener.collectInvalidatedLayers();
544 for (Layer l: visibleLayers) {
545 if (invalidated.contains(l)) {
546 break;
547 } else {
548 nonChangedLayersCount++;
549 }
550 }
551
552 boolean canUseBuffer = !paintPreferencesChanged.getAndSet(false)
553 && nonChangedLayers.size() <= nonChangedLayersCount
554 && lastViewID == getViewID()
555 && lastClipBounds.contains(g.getClipBounds())
556 && nonChangedLayers.equals(visibleLayers.subList(0, nonChangedLayers.size()));
557
558 if (null == offscreenBuffer || offscreenBuffer.getWidth() != width || offscreenBuffer.getHeight() != height) {
559 offscreenBuffer = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
560 }
561
562 if (!canUseBuffer || nonChangedLayersBuffer == null) {
563 if (null == nonChangedLayersBuffer
564 || nonChangedLayersBuffer.getWidth() != width || nonChangedLayersBuffer.getHeight() != height) {
565 nonChangedLayersBuffer = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
566 }
567 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
568 g2.setClip(scaledClip);
569 g2.setTransform(trDef);
570 g2.setColor(PaintColors.getBackgroundColor());
571 g2.fillRect(0, 0, width, height);
572
573 for (int i = 0; i < nonChangedLayersCount; i++) {
574 paintLayer(visibleLayers.get(i), g2);
575 }
576 } else {
577 // Maybe there were more unchanged layers then last time - draw them to buffer
578 if (nonChangedLayers.size() != nonChangedLayersCount) {
579 Graphics2D g2 = nonChangedLayersBuffer.createGraphics();
580 g2.setClip(scaledClip);
581 g2.setTransform(trDef);
582 for (int i = nonChangedLayers.size(); i < nonChangedLayersCount; i++) {
583 paintLayer(visibleLayers.get(i), g2);
584 }
585 }
586 }
587
588 nonChangedLayers.clear();
589 nonChangedLayers.addAll(visibleLayers.subList(0, nonChangedLayersCount));
590 lastViewID = getViewID();
591 lastClipBounds = g.getClipBounds();
592
593 Graphics2D tempG = offscreenBuffer.createGraphics();
594 tempG.setClip(scaledClip);
595 tempG.setTransform(new AffineTransform());
596 tempG.drawImage(nonChangedLayersBuffer, 0, 0, null);
597 tempG.setTransform(trDef);
598
599 for (int i = nonChangedLayersCount; i < visibleLayers.size(); i++) {
600 paintLayer(visibleLayers.get(i), tempG);
601 }
602
603 try {
604 drawTemporaryLayers(tempG, getLatLonBounds(new Rectangle(
605 (int) Math.round(g.getClipBounds().x * uiScaleX),
606 (int) Math.round(g.getClipBounds().y * uiScaleY))));
607 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
608 BugReport.intercept(e).put("temporaryLayers", temporaryLayers).warn();
609 }
610
611 // draw world borders
612 try {
613 drawWorldBorders(tempG);
614 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
615 // getProjection() needs to be inside lambda to catch errors.
616 BugReport.intercept(e).put("bounds", () -> getProjection().getWorldBoundsLatLon()).warn();
617 }
618
619 MapFrame map = MainApplication.getMap();
620 if (AutoFilterManager.getInstance().getCurrentAutoFilter() != null) {
621 AutoFilterManager.getInstance().drawOSDText(tempG);
622 } else if (MainApplication.isDisplayingMapView() && map.filterDialog != null) {
623 map.filterDialog.drawOSDText(tempG);
624 }
625
626 if (playHeadMarker != null) {
627 playHeadMarker.paint(tempG, this);
628 }
629
630 try {
631 gg.setTransform(new AffineTransform(1, 0, 0, 1, trOrig.getTranslateX(), trOrig.getTranslateY()));
632 gg.drawImage(offscreenBuffer, 0, 0, null);
633 } catch (ClassCastException e) {
634 // See #11002 and duplicate tickets. On Linux with Java >= 8 Many users face this error here:
635 //
636 // java.lang.ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
637 // at sun.java2d.xr.XRPMBlitLoops.cacheToTmpSurface(XRPMBlitLoops.java:145)
638 // at sun.java2d.xr.XrSwToPMBlit.Blit(XRPMBlitLoops.java:353)
639 // at sun.java2d.pipe.DrawImage.blitSurfaceData(DrawImage.java:959)
640 // at sun.java2d.pipe.DrawImage.renderImageCopy(DrawImage.java:577)
641 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:67)
642 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:1014)
643 // at sun.java2d.pipe.ValidatePipe.copyImage(ValidatePipe.java:186)
644 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3318)
645 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3296)
646 // at org.openstreetmap.josm.gui.MapView.paint(MapView.java:834)
647 //
648 // It seems to be this JDK bug, but Oracle does not seem to be fixing it:
649 // https://bugs.openjdk.java.net/browse/JDK-7172749
650 //
651 // According to bug reports it can happen for a variety of reasons such as:
652 // - long period of time
653 // - change of screen resolution
654 // - addition/removal of a secondary monitor
655 //
656 // But the application seems to work fine after, so let's just log the error
657 Logging.error(e);
658 } finally {
659 gg.setTransform(trOrig);
660 }
661 }
662
663 private void drawTemporaryLayers(Graphics2D tempG, Bounds box) {
664 synchronized (temporaryLayers) {
665 for (MapViewPaintable mvp : temporaryLayers) {
666 try {
667 mvp.paint(tempG, this, box);
668 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
669 throw BugReport.intercept(e).put("mvp", mvp);
670 }
671 }
672 }
673 }
674
675 private void drawWorldBorders(Graphics2D tempG) {
676 tempG.setColor(Color.WHITE);
677 Bounds b = getProjection().getWorldBoundsLatLon();
678
679 int w = getWidth();
680 int h = getHeight();
681
682 // Work around OpenJDK having problems when drawing out of bounds
683 final Area border = getState().getArea(b);
684 // Make the viewport 1px larger in every direction to prevent an
685 // additional 1px border when zooming in
686 final Area viewport = new Area(new Rectangle(-1, -1, w + 2, h + 2));
687 border.intersect(viewport);
688 tempG.draw(border);
689 }
690
691 /**
692 * Sets up the viewport to prepare for drawing the view.
693 * @return <code>true</code> if the view can be drawn, <code>false</code> otherwise.
694 */
695 public boolean prepareToDraw() {
696 updateLocationState();
697 if (initialViewport != null) {
698 zoomTo(initialViewport);
699 initialViewport = null;
700 }
701
702 if (getCenter() == null)
703 return false; // no data loaded yet.
704
705 // if the position was remembered, we need to adjust center once before repainting
706 if (oldLoc != null && oldSize != null) {
707 Point l1 = getLocationOnScreen();
708 final EastNorth newCenter = new EastNorth(
709 getCenter().getX()+ (l1.x-oldLoc.x - (oldSize.width-getWidth())/2.0)*getScale(),
710 getCenter().getY()+ (oldLoc.y-l1.y + (oldSize.height-getHeight())/2.0)*getScale()
711 );
712 oldLoc = null; oldSize = null;
713 zoomTo(newCenter);
714 }
715
716 return true;
717 }
718
719 @Override
720 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
721 MapFrame map = MainApplication.getMap();
722 if (map != null) {
723 /* This only makes the buttons look disabled. Disabling the actions as well requires
724 * the user to re-select the tool after i.e. moving a layer. While testing I found
725 * that I switch layers and actions at the same time and it was annoying to mind the
726 * order. This way it works as visual clue for new users */
727 // FIXME: This does not belong here.
728 for (final AbstractButton b: map.allMapModeButtons) {
729 MapMode mode = (MapMode) b.getAction();
730 final boolean activeLayerSupported = mode.layerIsSupported(layerManager.getActiveLayer());
731 if (activeLayerSupported) {
732 MainApplication.registerActionShortcut(mode, mode.getShortcut()); //fix #6876
733 } else {
734 MainApplication.unregisterShortcut(mode.getShortcut());
735 }
736 b.setEnabled(activeLayerSupported);
737 }
738 }
739 // invalidate repaint cache. The layer order may have changed by this, so we invalidate every layer
740 getLayerManager().getLayers().forEach(invalidatedListener::invalidate);
741 AudioPlayer.reset();
742 }
743
744 /**
745 * Adds a new temporary layer.
746 * <p>
747 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added.
748 *
749 * @param mvp The layer to paint.
750 * @return <code>true</code> if the layer was added.
751 */
752 public boolean addTemporaryLayer(MapViewPaintable mvp) {
753 synchronized (temporaryLayers) {
754 boolean added = temporaryLayers.add(mvp);
755 if (added) {
756 invalidatedListener.addTo(mvp);
757 }
758 repaint();
759 return added;
760 }
761 }
762
763 /**
764 * Removes a layer previously added as temporary layer.
765 * @param mvp The layer to remove.
766 * @return <code>true</code> if that layer was removed.
767 */
768 public boolean removeTemporaryLayer(MapViewPaintable mvp) {
769 synchronized (temporaryLayers) {
770 boolean removed = temporaryLayers.remove(mvp);
771 if (removed) {
772 invalidatedListener.removeFrom(mvp);
773 }
774 repaint();
775 return removed;
776 }
777 }
778
779 /**
780 * Gets a list of temporary layers.
781 * @return The layers in the order they are added.
782 */
783 public List<MapViewPaintable> getTemporaryLayers() {
784 synchronized (temporaryLayers) {
785 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers));
786 }
787 }
788
789 @Override
790 public void propertyChange(PropertyChangeEvent evt) {
791 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
792 repaint();
793 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) ||
794 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) {
795 Layer l = (Layer) evt.getSource();
796 if (l.isVisible()) {
797 invalidatedListener.invalidate(l);
798 }
799 }
800 }
801
802 @Override
803 public void preferenceChanged(PreferenceChangeEvent e) {
804 paintPreferencesChanged.set(true);
805 }
806
807 private final transient DataSelectionListener repaintSelectionChangedListener = event -> repaint();
808
809 /**
810 * Destroy this map view panel. Should be called once when it is not needed any more.
811 */
812 public void destroy() {
813 layerManager.removeAndFireLayerChangeListener(this);
814 layerManager.removeActiveLayerChangeListener(this);
815 Main.pref.removePreferenceChangeListener(this);
816 SelectionEventManager.getInstance().removeSelectionListener(repaintSelectionChangedListener);
817 MultipolygonCache.getInstance().clear();
818 if (mapMover != null) {
819 mapMover.destroy();
820 }
821 nonChangedLayers.clear();
822 synchronized (temporaryLayers) {
823 temporaryLayers.clear();
824 }
825 nonChangedLayersBuffer = null;
826 offscreenBuffer = null;
827 }
828
829 /**
830 * Get a string representation of all layers suitable for the {@code source} changeset tag.
831 * @return A String of sources separated by ';'
832 */
833 public String getLayerInformationForSourceTag() {
834 final Set<String> layerInfo = new TreeSet<>();
835 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) {
836 // no i18n for international values
837 layerInfo.add("survey");
838 }
839 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) {
840 if (i.isVisible()) {
841 layerInfo.add(i.getName());
842 }
843 }
844 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) {
845 if (i.isVisible()) {
846 layerInfo.add(ImageryInfo.ImageryType.BING.equals(i.getInfo().getImageryType()) ? "Bing" : i.getName());
847 }
848 }
849 return Utils.join("; ", layerInfo);
850 }
851
852 /**
853 * This is a listener that gets informed whenever repaint is called for this MapView.
854 * <p>
855 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly.
856 * @author Michael Zangl
857 * @since 10600 (functional interface)
858 */
859 @FunctionalInterface
860 public interface RepaintListener {
861 /**
862 * Called when any repaint method is called (using default arguments if required).
863 * @param tm see {@link JComponent#repaint(long, int, int, int, int)}
864 * @param x see {@link JComponent#repaint(long, int, int, int, int)}
865 * @param y see {@link JComponent#repaint(long, int, int, int, int)}
866 * @param width see {@link JComponent#repaint(long, int, int, int, int)}
867 * @param height see {@link JComponent#repaint(long, int, int, int, int)}
868 */
869 void repaint(long tm, int x, int y, int width, int height);
870 }
871
872 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>();
873
874 /**
875 * Adds a listener that gets informed whenever repaint() is called for this class.
876 * @param l The listener.
877 */
878 public void addRepaintListener(RepaintListener l) {
879 repaintListeners.add(l);
880 }
881
882 /**
883 * Removes a registered repaint listener.
884 * @param l The listener.
885 */
886 public void removeRepaintListener(RepaintListener l) {
887 repaintListeners.remove(l);
888 }
889
890 @Override
891 public void repaint(long tm, int x, int y, int width, int height) {
892 // This is the main repaint method, all other methods are convenience methods and simply call this method.
893 // This is just an observation, not a must, but seems to be true for all implementations I found so far.
894 if (repaintListeners != null) {
895 // Might get called early in super constructor
896 for (RepaintListener l : repaintListeners) {
897 l.repaint(tm, x, y, width, height);
898 }
899 }
900 super.repaint(tm, x, y, width, height);
901 }
902
903 @Override
904 public void repaint() {
905 if (Logging.isTraceEnabled()) {
906 invalidatedListener.traceRandomRepaint();
907 }
908 super.repaint();
909 }
910
911 /**
912 * Returns the layer manager.
913 * @return the layer manager
914 * @since 10282
915 */
916 public final MainLayerManager getLayerManager() {
917 return layerManager;
918 }
919
920 /**
921 * Schedule a zoom to the given position on the next redraw.
922 * Temporary, may be removed without warning.
923 * @param viewportData the viewport to zoom to
924 * @since 10394
925 */
926 public void scheduleZoomTo(ViewportData viewportData) {
927 initialViewport = viewportData;
928 }
929}
Note: See TracBrowser for help on using the repository browser.