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

Last change on this file since 12639 was 12639, checked in by Don-vip, 7 years ago

see #15182 - deprecate shortcut handling and mapframe listener methods in Main. Replacement: same methods in gui.MainApplication

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