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

Last change on this file since 12234 was 12182, checked in by michael2402, 7 years ago

Move viewport following option to DrawAction and make it persistent.

  • Property svn:eol-style set to native
File size: 32.8 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.DrawAction;
39import org.openstreetmap.josm.actions.mapmode.MapMode;
40import org.openstreetmap.josm.data.Bounds;
41import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
42import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
43import org.openstreetmap.josm.data.ProjectionBounds;
44import org.openstreetmap.josm.data.ViewportData;
45import org.openstreetmap.josm.data.coor.EastNorth;
46import org.openstreetmap.josm.data.imagery.ImageryInfo;
47import org.openstreetmap.josm.data.osm.DataSelectionListener;
48import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
49import org.openstreetmap.josm.data.osm.visitor.paint.PaintColors;
50import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
51import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
52import org.openstreetmap.josm.gui.MapViewState.MapViewRectangle;
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.tools.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 Main.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 * Replaced by the {@link DrawAction#VIEWPORT_FOLLOWING} property
189 * @deprecated since 12180. Can be remove soon (does any plugin even use this?)
190 */
191 @Deprecated
192 public boolean viewportFollowing;
193
194 /**
195 * A list of all layers currently loaded. If we support multiple map views, this list may be different for each of them.
196 */
197 private final MainLayerManager layerManager;
198
199 /**
200 * The play head marker: there is only one of these so it isn't in any specific layer
201 */
202 public transient PlayHeadMarker playHeadMarker;
203
204 /**
205 * The last event performed by mouse.
206 */
207 public MouseEvent lastMEvent = new MouseEvent(this, 0, 0, 0, 0, 0, 0, false); // In case somebody reads it before first mouse move
208
209 /**
210 * Temporary layers (selection rectangle, etc.) that are never cached and
211 * drawn on top of regular layers.
212 * Access must be synchronized.
213 */
214 private final transient Set<MapViewPaintable> temporaryLayers = new LinkedHashSet<>();
215
216 private transient BufferedImage nonChangedLayersBuffer;
217 private transient BufferedImage offscreenBuffer;
218 // Layers that wasn't changed since last paint
219 private final transient List<Layer> nonChangedLayers = new ArrayList<>();
220 private int lastViewID;
221 private final AtomicBoolean paintPreferencesChanged = new AtomicBoolean(true);
222 private Rectangle lastClipBounds = new Rectangle();
223 private transient MapMover mapMover;
224
225 /**
226 * The listener that listens to invalidations of all layers.
227 */
228 private final LayerInvalidatedListener invalidatedListener = new LayerInvalidatedListener();
229
230 /**
231 * This is a map of all Layers that have been added to this view.
232 */
233 private final HashMap<Layer, LayerPainter> registeredLayers = new HashMap<>();
234
235 /**
236 * Constructs a new {@code MapView}.
237 * @param layerManager The layers to display.
238 * @param contentPane Ignored. Main content pane is used.
239 * @param viewportData the initial viewport of the map. Can be null, then
240 * the viewport is derived from the layer data.
241 * @since 10279
242 * @deprecated use {@link #MapView(MainLayerManager, ViewportData)} instead
243 */
244 @Deprecated
245 public MapView(MainLayerManager layerManager, final JPanel contentPane, final ViewportData viewportData) {
246 this(layerManager, viewportData);
247 }
248
249 /**
250 * Constructs a new {@code MapView}.
251 * @param layerManager The layers to display.
252 * @param viewportData the initial viewport of the map. Can be null, then
253 * the viewport is derived from the layer data.
254 * @since 11713
255 */
256 public MapView(MainLayerManager layerManager, final ViewportData viewportData) {
257 this.layerManager = layerManager;
258 initialViewport = viewportData;
259 layerManager.addAndFireLayerChangeListener(this);
260 layerManager.addActiveLayerChangeListener(this);
261 Main.pref.addPreferenceChangeListener(this);
262
263 addComponentListener(new ComponentAdapter() {
264 @Override
265 public void componentResized(ComponentEvent e) {
266 removeComponentListener(this);
267 mapMover = new MapMover(MapView.this);
268 }
269 });
270
271 // listens to selection changes to redraw the map
272 SelectionEventManager.getInstance().addSelectionListenerForEdt(repaintSelectionChangedListener);
273
274 //store the last mouse action
275 this.addMouseMotionListener(new MouseMotionListener() {
276 @Override
277 public void mouseDragged(MouseEvent e) {
278 mouseMoved(e);
279 }
280
281 @Override
282 public void mouseMoved(MouseEvent e) {
283 lastMEvent = e;
284 }
285 });
286 this.addMouseListener(new MouseAdapter() {
287 @Override
288 public void mousePressed(MouseEvent me) {
289 // focus the MapView component when mouse is pressed inside it
290 requestFocus();
291 }
292 });
293
294 setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
295
296 for (JComponent c : getMapNavigationComponents(this)) {
297 add(c);
298 }
299 setTransferHandler(new OsmTransferHandler());
300 }
301
302 /**
303 * Adds the map navigation components to a
304 * @param forMapView The map view to get the components for.
305 * @return A list containing the correctly positioned map navigation components.
306 */
307 public static List<? extends JComponent> getMapNavigationComponents(MapView forMapView) {
308 MapSlider zoomSlider = new MapSlider(forMapView);
309 Dimension size = zoomSlider.getPreferredSize();
310 zoomSlider.setSize(size);
311 zoomSlider.setLocation(3, 0);
312 zoomSlider.setFocusTraversalKeysEnabled(!Shortcut.findShortcut(KeyEvent.VK_TAB, 0).isPresent());
313
314 MapScaler scaler = new MapScaler(forMapView);
315 scaler.setPreferredLineLength(size.width - 10);
316 scaler.setSize(scaler.getPreferredSize());
317 scaler.setLocation(3, size.height);
318
319 return Arrays.asList(zoomSlider, scaler);
320 }
321
322 // remebered geometry of the component
323 private Dimension oldSize;
324 private Point oldLoc;
325
326 /**
327 * Call this method to keep map position on screen during next repaint
328 */
329 public void rememberLastPositionOnScreen() {
330 oldSize = getSize();
331 oldLoc = getLocationOnScreen();
332 }
333
334 @Override
335 public void layerAdded(LayerAddEvent e) {
336 try {
337 Layer layer = e.getAddedLayer();
338 registeredLayers.put(layer, new WarningLayerPainter(layer));
339 // Layers may trigger a redraw during this call if they open dialogs.
340 LayerPainter painter = layer.attachToMapView(new MapViewEvent(this, false));
341 if (!registeredLayers.containsKey(layer)) {
342 // The layer may have removed itself during attachToMapView()
343 Main.warn("Layer was removed during attachToMapView()");
344 } else {
345 registeredLayers.put(layer, painter);
346
347 if (e.isZoomRequired()) {
348 ProjectionBounds viewProjectionBounds = layer.getViewProjectionBounds();
349 if (viewProjectionBounds != null) {
350 scheduleZoomTo(new ViewportData(viewProjectionBounds));
351 }
352 }
353
354 layer.addPropertyChangeListener(this);
355 Main.addProjectionChangeListener(layer);
356 invalidatedListener.addTo(layer);
357 AudioPlayer.reset();
358
359 repaint();
360 }
361 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException t) {
362 throw BugReport.intercept(t).put("layer", e.getAddedLayer());
363 }
364 }
365
366 /**
367 * Replies true if the active data layer (edit layer) is drawable.
368 *
369 * @return true if the active data layer (edit layer) is drawable, false otherwise
370 */
371 public boolean isActiveLayerDrawable() {
372 return layerManager.getEditLayer() != null;
373 }
374
375 /**
376 * Replies true if the active data layer (edit layer) is visible.
377 *
378 * @return true if the active data layer (edit layer) is visible, false otherwise
379 */
380 public boolean isActiveLayerVisible() {
381 OsmDataLayer e = layerManager.getEditLayer();
382 return e != null && e.isVisible();
383 }
384
385 @Override
386 public void layerRemoving(LayerRemoveEvent e) {
387 Layer layer = e.getRemovedLayer();
388
389 LayerPainter painter = registeredLayers.remove(layer);
390 if (painter == null) {
391 Main.error("The painter for layer " + layer + " was not registered.");
392 return;
393 }
394 painter.detachFromMapView(new MapViewEvent(this, false));
395 Main.removeProjectionChangeListener(layer);
396 layer.removePropertyChangeListener(this);
397 invalidatedListener.removeFrom(layer);
398 layer.destroy();
399 AudioPlayer.reset();
400
401 repaint();
402 }
403
404 private boolean virtualNodesEnabled;
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(DataSet, boolean, Bounds)
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 if (Main.isDisplayingMapView() && Main.map.filterDialog != null) {
565 Main.map.filterDialog.drawOSDText(tempG);
566 }
567
568 if (playHeadMarker != null) {
569 playHeadMarker.paint(tempG, this);
570 }
571
572 try {
573 g.drawImage(offscreenBuffer, 0, 0, null);
574 } catch (ClassCastException e) {
575 // See #11002 and duplicate tickets. On Linux with Java >= 8 Many users face this error here:
576 //
577 // java.lang.ClassCastException: sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData
578 // at sun.java2d.xr.XRPMBlitLoops.cacheToTmpSurface(XRPMBlitLoops.java:145)
579 // at sun.java2d.xr.XrSwToPMBlit.Blit(XRPMBlitLoops.java:353)
580 // at sun.java2d.pipe.DrawImage.blitSurfaceData(DrawImage.java:959)
581 // at sun.java2d.pipe.DrawImage.renderImageCopy(DrawImage.java:577)
582 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:67)
583 // at sun.java2d.pipe.DrawImage.copyImage(DrawImage.java:1014)
584 // at sun.java2d.pipe.ValidatePipe.copyImage(ValidatePipe.java:186)
585 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3318)
586 // at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:3296)
587 // at org.openstreetmap.josm.gui.MapView.paint(MapView.java:834)
588 //
589 // It seems to be this JDK bug, but Oracle does not seem to be fixing it:
590 // https://bugs.openjdk.java.net/browse/JDK-7172749
591 //
592 // According to bug reports it can happen for a variety of reasons such as:
593 // - long period of time
594 // - change of screen resolution
595 // - addition/removal of a secondary monitor
596 //
597 // But the application seems to work fine after, so let's just log the error
598 Main.error(e);
599 }
600 }
601
602 private void drawTemporaryLayers(Graphics2D tempG, Bounds box) {
603 synchronized (temporaryLayers) {
604 for (MapViewPaintable mvp : temporaryLayers) {
605 try {
606 mvp.paint(tempG, this, box);
607 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
608 throw BugReport.intercept(e).put("mvp", mvp);
609 }
610 }
611 }
612 }
613
614 private void drawWorldBorders(Graphics2D tempG) {
615 tempG.setColor(Color.WHITE);
616 Bounds b = getProjection().getWorldBoundsLatLon();
617
618 int w = getWidth();
619 int h = getHeight();
620
621 // Work around OpenJDK having problems when drawing out of bounds
622 final Area border = getState().getArea(b);
623 // Make the viewport 1px larger in every direction to prevent an
624 // additional 1px border when zooming in
625 final Area viewport = new Area(new Rectangle(-1, -1, w + 2, h + 2));
626 border.intersect(viewport);
627 tempG.draw(border);
628 }
629
630 /**
631 * Sets up the viewport to prepare for drawing the view.
632 * @return <code>true</code> if the view can be drawn, <code>false</code> otherwise.
633 */
634 public boolean prepareToDraw() {
635 updateLocationState();
636 if (initialViewport != null) {
637 zoomTo(initialViewport);
638 initialViewport = null;
639 }
640
641 if (getCenter() == null)
642 return false; // no data loaded yet.
643
644 // if the position was remembered, we need to adjust center once before repainting
645 if (oldLoc != null && oldSize != null) {
646 Point l1 = getLocationOnScreen();
647 final EastNorth newCenter = new EastNorth(
648 getCenter().getX()+ (l1.x-oldLoc.x - (oldSize.width-getWidth())/2.0)*getScale(),
649 getCenter().getY()+ (oldLoc.y-l1.y + (oldSize.height-getHeight())/2.0)*getScale()
650 );
651 oldLoc = null; oldSize = null;
652 zoomTo(newCenter);
653 }
654
655 return true;
656 }
657
658 @Override
659 public void activeOrEditLayerChanged(ActiveLayerChangeEvent e) {
660 if (Main.map != null) {
661 /* This only makes the buttons look disabled. Disabling the actions as well requires
662 * the user to re-select the tool after i.e. moving a layer. While testing I found
663 * that I switch layers and actions at the same time and it was annoying to mind the
664 * order. This way it works as visual clue for new users */
665 // FIXME: This does not belong here.
666 for (final AbstractButton b: Main.map.allMapModeButtons) {
667 MapMode mode = (MapMode) b.getAction();
668 final boolean activeLayerSupported = mode.layerIsSupported(layerManager.getActiveLayer());
669 if (activeLayerSupported) {
670 Main.registerActionShortcut(mode, mode.getShortcut()); //fix #6876
671 } else {
672 Main.unregisterShortcut(mode.getShortcut());
673 }
674 b.setEnabled(activeLayerSupported);
675 }
676 }
677 // invalidate repaint cache. The layer order may have changed by this, so we invalidate every layer
678 getLayerManager().getLayers().forEach(invalidatedListener::invalidate);
679 AudioPlayer.reset();
680 }
681
682 /**
683 * Adds a new temporary layer.
684 * <p>
685 * A temporary layer is a layer that is painted above all normal layers. Layers are painted in the order they are added.
686 *
687 * @param mvp The layer to paint.
688 * @return <code>true</code> if the layer was added.
689 */
690 public boolean addTemporaryLayer(MapViewPaintable mvp) {
691 synchronized (temporaryLayers) {
692 boolean added = temporaryLayers.add(mvp);
693 if (added) {
694 invalidatedListener.addTo(mvp);
695 }
696 repaint();
697 return added;
698 }
699 }
700
701 /**
702 * Removes a layer previously added as temporary layer.
703 * @param mvp The layer to remove.
704 * @return <code>true</code> if that layer was removed.
705 */
706 public boolean removeTemporaryLayer(MapViewPaintable mvp) {
707 synchronized (temporaryLayers) {
708 boolean removed = temporaryLayers.remove(mvp);
709 if (removed) {
710 invalidatedListener.removeFrom(mvp);
711 }
712 repaint();
713 return removed;
714 }
715 }
716
717 /**
718 * Gets a list of temporary layers.
719 * @return The layers in the order they are added.
720 */
721 public List<MapViewPaintable> getTemporaryLayers() {
722 synchronized (temporaryLayers) {
723 return Collections.unmodifiableList(new ArrayList<>(temporaryLayers));
724 }
725 }
726
727 @Override
728 public void propertyChange(PropertyChangeEvent evt) {
729 if (evt.getPropertyName().equals(Layer.VISIBLE_PROP)) {
730 repaint();
731 } else if (evt.getPropertyName().equals(Layer.OPACITY_PROP) ||
732 evt.getPropertyName().equals(Layer.FILTER_STATE_PROP)) {
733 Layer l = (Layer) evt.getSource();
734 if (l.isVisible()) {
735 invalidatedListener.invalidate(l);
736 }
737 }
738 }
739
740 @Override
741 public void preferenceChanged(PreferenceChangeEvent e) {
742 paintPreferencesChanged.set(true);
743 }
744
745 private final transient DataSelectionListener repaintSelectionChangedListener = event -> repaint();
746
747 /**
748 * Destroy this map view panel. Should be called once when it is not needed any more.
749 */
750 public void destroy() {
751 layerManager.removeAndFireLayerChangeListener(this);
752 layerManager.removeActiveLayerChangeListener(this);
753 Main.pref.removePreferenceChangeListener(this);
754 SelectionEventManager.getInstance().removeSelectionListener(repaintSelectionChangedListener);
755 MultipolygonCache.getInstance().clear();
756 if (mapMover != null) {
757 mapMover.destroy();
758 }
759 nonChangedLayers.clear();
760 synchronized (temporaryLayers) {
761 temporaryLayers.clear();
762 }
763 nonChangedLayersBuffer = null;
764 offscreenBuffer = null;
765 }
766
767 /**
768 * Get a string representation of all layers suitable for the {@code source} changeset tag.
769 * @return A String of sources separated by ';'
770 */
771 public String getLayerInformationForSourceTag() {
772 final Set<String> layerInfo = new TreeSet<>();
773 if (!layerManager.getLayersOfType(GpxLayer.class).isEmpty()) {
774 // no i18n for international values
775 layerInfo.add("survey");
776 }
777 for (final GeoImageLayer i : layerManager.getLayersOfType(GeoImageLayer.class)) {
778 if (i.isVisible()) {
779 layerInfo.add(i.getName());
780 }
781 }
782 for (final ImageryLayer i : layerManager.getLayersOfType(ImageryLayer.class)) {
783 if (i.isVisible()) {
784 layerInfo.add(ImageryInfo.ImageryType.BING.equals(i.getInfo().getImageryType()) ? "Bing" : i.getName());
785 }
786 }
787 return Utils.join("; ", layerInfo);
788 }
789
790 /**
791 * This is a listener that gets informed whenever repaint is called for this MapView.
792 * <p>
793 * This is the only safe method to find changes to the map view, since many components call MapView.repaint() directly.
794 * @author Michael Zangl
795 * @since 10600 (functional interface)
796 */
797 @FunctionalInterface
798 public interface RepaintListener {
799 /**
800 * Called when any repaint method is called (using default arguments if required).
801 * @param tm see {@link JComponent#repaint(long, int, int, int, int)}
802 * @param x see {@link JComponent#repaint(long, int, int, int, int)}
803 * @param y see {@link JComponent#repaint(long, int, int, int, int)}
804 * @param width see {@link JComponent#repaint(long, int, int, int, int)}
805 * @param height see {@link JComponent#repaint(long, int, int, int, int)}
806 */
807 void repaint(long tm, int x, int y, int width, int height);
808 }
809
810 private final transient CopyOnWriteArrayList<RepaintListener> repaintListeners = new CopyOnWriteArrayList<>();
811
812 /**
813 * Adds a listener that gets informed whenever repaint() is called for this class.
814 * @param l The listener.
815 */
816 public void addRepaintListener(RepaintListener l) {
817 repaintListeners.add(l);
818 }
819
820 /**
821 * Removes a registered repaint listener.
822 * @param l The listener.
823 */
824 public void removeRepaintListener(RepaintListener l) {
825 repaintListeners.remove(l);
826 }
827
828 @Override
829 public void repaint(long tm, int x, int y, int width, int height) {
830 // This is the main repaint method, all other methods are convenience methods and simply call this method.
831 // This is just an observation, not a must, but seems to be true for all implementations I found so far.
832 if (repaintListeners != null) {
833 // Might get called early in super constructor
834 for (RepaintListener l : repaintListeners) {
835 l.repaint(tm, x, y, width, height);
836 }
837 }
838 super.repaint(tm, x, y, width, height);
839 }
840
841 @Override
842 public void repaint() {
843 if (Main.isTraceEnabled()) {
844 invalidatedListener.traceRandomRepaint();
845 }
846 super.repaint();
847 }
848
849 /**
850 * Returns the layer manager.
851 * @return the layer manager
852 * @since 10282
853 */
854 public final MainLayerManager getLayerManager() {
855 return layerManager;
856 }
857
858 /**
859 * Schedule a zoom to the given position on the next redraw.
860 * Temporary, may be removed without warning.
861 * @param viewportData the viewport to zoom to
862 * @since 10394
863 */
864 public void scheduleZoomTo(ViewportData viewportData) {
865 initialViewport = viewportData;
866 }
867}
Note: See TracBrowser for help on using the repository browser.