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

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

see #14734 - fix checkstyle warnings

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