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

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

see #15182 - code refactoring to avoid dependence on GUI packages from MapPaintStyles

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