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

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

remove deprecated MapView.viewportFollowing public field

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