001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.bbox; 003 004import java.awt.Color; 005import java.awt.Dimension; 006import java.awt.Graphics; 007import java.awt.Graphics2D; 008import java.awt.Point; 009import java.awt.Rectangle; 010import java.awt.geom.Area; 011import java.awt.geom.Path2D; 012import java.util.ArrayList; 013import java.util.LinkedHashMap; 014import java.util.List; 015import java.util.Map; 016import java.util.concurrent.CopyOnWriteArrayList; 017import java.util.stream.Collectors; 018 019import javax.swing.ButtonModel; 020import javax.swing.JToggleButton; 021import javax.swing.SpringLayout; 022import javax.swing.event.ChangeEvent; 023import javax.swing.event.ChangeListener; 024 025import org.openstreetmap.gui.jmapviewer.Coordinate; 026import org.openstreetmap.gui.jmapviewer.MapMarkerDot; 027import org.openstreetmap.gui.jmapviewer.MemoryTileCache; 028import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate; 029import org.openstreetmap.gui.jmapviewer.interfaces.MapMarker; 030import org.openstreetmap.gui.jmapviewer.interfaces.TileSource; 031import org.openstreetmap.josm.data.Bounds; 032import org.openstreetmap.josm.data.coor.ILatLon; 033import org.openstreetmap.josm.data.coor.LatLon; 034import org.openstreetmap.josm.data.osm.BBox; 035import org.openstreetmap.josm.data.osm.DataSet; 036import org.openstreetmap.josm.data.preferences.BooleanProperty; 037import org.openstreetmap.josm.data.preferences.StringProperty; 038import org.openstreetmap.josm.gui.MainApplication; 039import org.openstreetmap.josm.gui.MapScaler; 040import org.openstreetmap.josm.gui.NavigatableComponent; 041import org.openstreetmap.josm.gui.layer.ImageryLayer; 042import org.openstreetmap.josm.gui.layer.LayerManager.LayerAddEvent; 043import org.openstreetmap.josm.gui.layer.LayerManager.LayerChangeListener; 044import org.openstreetmap.josm.gui.layer.LayerManager.LayerOrderChangeEvent; 045import org.openstreetmap.josm.gui.layer.LayerManager.LayerRemoveEvent; 046import org.openstreetmap.josm.gui.layer.MainLayerManager; 047import org.openstreetmap.josm.gui.layer.MainLayerManager.ActiveLayerChangeListener; 048import org.openstreetmap.josm.spi.preferences.Config; 049import org.openstreetmap.josm.tools.Logging; 050 051/** 052 * This panel displays a map and lets the user chose a {@link BBox}. 053 */ 054public class SlippyMapBBoxChooser extends JosmMapViewer implements BBoxChooser, ChangeListener, ActiveLayerChangeListener, LayerChangeListener { 055 056 /** 057 * Plugins that wish to add custom tile sources to slippy map choose should call this method 058 * @param tileSourceProvider new tile source provider 059 */ 060 public static void addTileSourceProvider(TileSourceProvider tileSourceProvider) { 061 providers.addIfAbsent(tileSourceProvider); 062 } 063 064 private static final CopyOnWriteArrayList<TileSourceProvider> providers = new CopyOnWriteArrayList<>(); 065 static { 066 addTileSourceProvider(new DefaultOsmTileSourceProvider()); 067 addTileSourceProvider(new TMSTileSourceProvider()); 068 addTileSourceProvider(new CurrentLayersTileSourceProvider()); 069 } 070 071 private static final StringProperty PROP_MAPSTYLE = new StringProperty("slippy_map_chooser.mapstyle", "Mapnik"); 072 private static final BooleanProperty PROP_SHOWDLAREA = new BooleanProperty("slippy_map_chooser.show_downloaded_area", true); 073 074 /** 075 * The property name used for the resize button. 076 * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) 077 */ 078 public static final String RESIZE_PROP = SlippyMapBBoxChooser.class.getName() + ".resize"; 079 080 /** 081 * The property name used for the {@link org.openstreetmap.josm.data.coor.ILatLon} of the mouse cursor on the map. 082 * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) 083 */ 084 public static final String CURSOR_COORDINATE_PROP = SlippyMapBBoxChooser.class.getName() + ".coordinate"; 085 086 private final SizeButton iSizeButton; 087 private final ButtonModel showDownloadAreaButtonModel; 088 private final SourceButton iSourceButton; 089 private transient Bounds bbox; 090 091 // upper left and lower right corners of the selection rectangle (x/y on ZOOM_MAX) 092 private transient ICoordinate iSelectionRectStart; 093 private transient ICoordinate iSelectionRectEnd; 094 095 static { 096 debug = Logging.isDebugEnabled(); 097 } 098 099 /** 100 * Constructs a new {@code SlippyMapBBoxChooser}. 101 */ 102 public SlippyMapBBoxChooser() { 103 SpringLayout springLayout = new SpringLayout(); 104 setLayout(springLayout); 105 106 setZoomControlsVisible(Config.getPref().getBoolean("slippy_map_chooser.zoomcontrols", false)); 107 setMapMarkerVisible(false); 108 setMinimumSize(new Dimension(350, 350 / 2)); 109 // We need to set an initial size - this prevents a wrong zoom selection 110 // for the area before the component has been displayed the first time 111 setBounds(new Rectangle(getMinimumSize())); 112 if (cachedLoader == null) { 113 setFileCacheEnabled(false); 114 } else { 115 setFileCacheEnabled(Config.getPref().getBoolean("slippy_map_chooser.file_cache", true)); 116 } 117 setMaxTilesInMemory(Config.getPref().getInt("slippy_map_chooser.max_tiles", 1000)); 118 119 List<TileSource> tileSources = new ArrayList<>(getAllTileSources().values()); 120 121 this.showDownloadAreaButtonModel = new JToggleButton.ToggleButtonModel(); 122 this.showDownloadAreaButtonModel.setSelected(PROP_SHOWDLAREA.get()); 123 this.showDownloadAreaButtonModel.addChangeListener(this); 124 iSourceButton = new SourceButton(this, tileSources, this.showDownloadAreaButtonModel); 125 add(iSourceButton); 126 springLayout.putConstraint(SpringLayout.EAST, iSourceButton, -2, SpringLayout.EAST, this); 127 springLayout.putConstraint(SpringLayout.NORTH, iSourceButton, 2, SpringLayout.NORTH, this); 128 129 iSizeButton = new SizeButton(this); 130 add(iSizeButton); 131 132 MapScaler scaler = new MapScaler(this::getDist100Pixel, () -> Color.BLACK); 133 add(scaler); 134 springLayout.putConstraint(SpringLayout.NORTH, scaler, 2, SpringLayout.NORTH, this); 135 springLayout.putConstraint(SpringLayout.WEST, scaler, 2, SpringLayout.EAST, iSizeButton); 136 137 String mapStyle = PROP_MAPSTYLE.get(); 138 final TileSource tileSource = tileSources.stream() 139 .filter(source -> source.getName().equals(mapStyle)) 140 .findFirst() 141 .orElse(tileSources.get(0)); 142 setTileSource(tileSource); 143 iSourceButton.setCurrentMap(tileSource); 144 145 MainApplication.getLayerManager().addActiveLayerChangeListener(this); 146 147 new SlippyMapController(this, this); 148 } 149 150 private static Map<String, TileSource> getAllTileSources() { 151 // using a LinkedHashMap of <id, TileSource> to retain ordering but provide deduplication 152 return providers.stream().flatMap( 153 provider -> provider.getTileSources().stream() 154 ).collect(Collectors.toMap( 155 ts -> getTileSourceId(ts), 156 ts -> ts, 157 (oldTs, newTs) -> oldTs, 158 LinkedHashMap::new 159 )); 160 } 161 162 /** 163 * In case the tile source has no ID, use the name 164 */ 165 private static String getTileSourceId(TileSource ts) { 166 String id = ts.getId(); 167 if (id == null) 168 id = ts.getName(); 169 return id; 170 } 171 172 /** 173 * Get the distance in meter that correspond to 100 px on screen. 174 * @return the distance in meter that correspond to 100 px on screen 175 * @see NavigatableComponent#getDist100Pixel 176 */ 177 private double getDist100Pixel() { 178 int w = getWidth() / 2; 179 int h = getHeight() / 2; 180 ICoordinate c1 = getPosition(w - 50, h); 181 ICoordinate c2 = getPosition(w + 50, h); 182 final ILatLon ll1 = new LatLon(c1.getLat(), c1.getLon()); 183 final ILatLon ll2 = new LatLon(c2.getLat(), c2.getLon()); 184 double gcd = ll1.greatCircleDistance(ll2); 185 return gcd <= 0 ? 0.1 : gcd; 186 } 187 188 /** 189 * Handles a click/move on the attribution 190 * @param p The point in the view 191 * @param click true if it was a click, false for hover 192 * @return if the attribution handled the event 193 */ 194 public boolean handleAttribution(Point p, boolean click) { 195 return attribution.handleAttribution(p, click); 196 } 197 198 /** 199 * Draw the map. 200 */ 201 @Override 202 public void paintComponent(Graphics g) { 203 super.paintComponent(g); 204 Graphics2D g2d = (Graphics2D) g; 205 206 // draw shaded area for non-downloaded region of current data set, but only if there *is* a current data set, 207 // and it has defined bounds. Routine is analogous to that in OsmDataLayer's paint routine (but just different 208 // enough to make sharing code impractical) 209 final DataSet ds = MainApplication.getLayerManager().getActiveDataSet(); 210 if (ds != null && this.showDownloadAreaButtonModel.isSelected() && !ds.getDataSources().isEmpty()) { 211 // initialize area with current viewport 212 Rectangle b = this.getBounds(); 213 // ensure we comfortably cover full area 214 b.grow(100, 100); 215 Path2D p = new Path2D.Float(); 216 217 // combine successively downloaded areas after converting to screen-space 218 for (Bounds bounds : ds.getDataSourceBounds()) { 219 if (bounds.isCollapsed()) { 220 continue; 221 } 222 Rectangle r = new Rectangle(this.getMapPosition(bounds.getMinLat(), bounds.getMinLon(), false)); 223 r.add(this.getMapPosition(bounds.getMaxLat(), bounds.getMaxLon(), false)); 224 p.append(r, false); 225 } 226 // subtract combined areas 227 Area a = new Area(b); 228 a.subtract(new Area(p)); 229 230 // paint remainder 231 g2d.setPaint(new Color(0, 0, 0, 32)); 232 g2d.fill(a); 233 } 234 235 // draw selection rectangle 236 if (iSelectionRectStart != null && iSelectionRectEnd != null) { 237 Rectangle box = new Rectangle(getMapPosition(iSelectionRectStart, false)); 238 box.add(getMapPosition(iSelectionRectEnd, false)); 239 240 g.setColor(new Color(0.9f, 0.7f, 0.7f, 0.6f)); 241 g.fillRect(box.x, box.y, box.width, box.height); 242 243 g.setColor(Color.BLACK); 244 g.drawRect(box.x, box.y, box.width, box.height); 245 } 246 } 247 248 @Override 249 public void activeOrEditLayerChanged(MainLayerManager.ActiveLayerChangeEvent e) { 250 this.repaint(); 251 } 252 253 @Override 254 public void stateChanged(ChangeEvent e) { 255 // fired for the stateChanged event of this.showDownloadAreaButtonModel 256 PROP_SHOWDLAREA.put(this.showDownloadAreaButtonModel.isSelected()); 257 this.repaint(); 258 } 259 260 /** 261 * Handles a {@link SlippyMapController#mouseMoved} event 262 * @param point The point in the view 263 */ 264 public void handleMouseMoved(Point point) { 265 final ICoordinate coordinate = getPosition(point); 266 final LatLon latLon = new LatLon(coordinate.getLat(), coordinate.getLon()); 267 firePropertyChange(CURSOR_COORDINATE_PROP, null, latLon); 268 } 269 270 /** 271 * Callback for the OsmMapControl. (Re-)Sets the start and end point of the selection rectangle. 272 * 273 * @param aStart selection start 274 * @param aEnd selection end 275 */ 276 public void setSelection(Point aStart, Point aEnd) { 277 if (aStart == null || aEnd == null || aStart.x == aEnd.x || aStart.y == aEnd.y) 278 return; 279 280 Point pMax = new Point(Math.max(aEnd.x, aStart.x), Math.max(aEnd.y, aStart.y)); 281 Point pMin = new Point(Math.min(aEnd.x, aStart.x), Math.min(aEnd.y, aStart.y)); 282 283 iSelectionRectStart = getPosition(pMin); 284 iSelectionRectEnd = getPosition(pMax); 285 286 Bounds b = new Bounds( 287 new LatLon( 288 Math.min(iSelectionRectStart.getLat(), iSelectionRectEnd.getLat()), 289 LatLon.toIntervalLon(Math.min(iSelectionRectStart.getLon(), iSelectionRectEnd.getLon())) 290 ), 291 new LatLon( 292 Math.max(iSelectionRectStart.getLat(), iSelectionRectEnd.getLat()), 293 LatLon.toIntervalLon(Math.max(iSelectionRectStart.getLon(), iSelectionRectEnd.getLon()))) 294 ); 295 Bounds oldValue = this.bbox; 296 this.bbox = b; 297 repaint(); 298 firePropertyChange(BBOX_PROP, oldValue, this.bbox); 299 } 300 301 /** 302 * Performs resizing of the DownloadDialog in order to enlarge or shrink the 303 * map. 304 */ 305 public void resizeSlippyMap() { 306 boolean large = iSizeButton.isEnlarged(); 307 firePropertyChange(RESIZE_PROP, !large, large); 308 } 309 310 /** 311 * Sets the active tile source 312 * @param tileSource The active tile source 313 */ 314 public void toggleMapSource(TileSource tileSource) { 315 this.tileController.setTileCache(new MemoryTileCache()); 316 this.setTileSource(tileSource); 317 PROP_MAPSTYLE.put(tileSource.getName()); // TODO Is name really unique? 318 319 // we need to refresh the tile sources in case the deselected source should no longer be present 320 // (and only remained there because its removal was deferred while the source was still the 321 // selected one). this should also have the effect of propagating the new selection to the 322 // iSourceButton & menu: it attempts to re-select the current source when rebuilding its menu. 323 this.refreshTileSources(); 324 } 325 326 @Override 327 public Bounds getBoundingBox() { 328 return bbox; 329 } 330 331 /** 332 * Sets the current bounding box in this bbox chooser without 333 * emitting a property change event. 334 * 335 * @param bbox the bounding box. null to reset the bounding box 336 */ 337 @Override 338 public void setBoundingBox(Bounds bbox) { 339 if (bbox == null || (bbox.getMinLat() == 0 && bbox.getMinLon() == 0 340 && bbox.getMaxLat() == 0 && bbox.getMaxLon() == 0)) { 341 this.bbox = null; 342 iSelectionRectStart = null; 343 iSelectionRectEnd = null; 344 repaint(); 345 return; 346 } 347 348 this.bbox = bbox; 349 iSelectionRectStart = new Coordinate(bbox.getMinLat(), bbox.getMinLon()); 350 iSelectionRectEnd = new Coordinate(bbox.getMaxLat(), bbox.getMaxLon()); 351 352 // calc the screen coordinates for the new selection rectangle 353 MapMarkerDot min = new MapMarkerDot(bbox.getMinLat(), bbox.getMinLon()); 354 MapMarkerDot max = new MapMarkerDot(bbox.getMaxLat(), bbox.getMaxLon()); 355 356 List<MapMarker> marker = new ArrayList<>(2); 357 marker.add(min); 358 marker.add(max); 359 setMapMarkerList(marker); 360 setDisplayToFitMapMarkers(); 361 zoomOut(); 362 repaint(); 363 } 364 365 /** 366 * Enables or disables painting of the shrink/enlarge button 367 * 368 * @param visible {@code true} to enable painting of the shrink/enlarge button 369 */ 370 public void setSizeButtonVisible(boolean visible) { 371 iSizeButton.setVisible(visible); 372 } 373 374 /** 375 * Refreshes the tile sources 376 * @since 6364 377 */ 378 public final void refreshTileSources() { 379 final Map<String, TileSource> newTileSources = getAllTileSources(); 380 final TileSource currentTileSource = this.getTileController().getTileSource(); 381 382 // re-add the currently active TileSource to prevent inconsistent display of menu 383 newTileSources.putIfAbsent(currentTileSource.getId(), currentTileSource); 384 385 this.iSourceButton.setSources(new ArrayList<>(newTileSources.values())); 386 } 387 388 @Override 389 public void layerAdded(LayerAddEvent e) { 390 if (e.getAddedLayer() instanceof ImageryLayer) { 391 this.refreshTileSources(); 392 } 393 } 394 395 @Override 396 public void layerRemoving(LayerRemoveEvent e) { 397 if (e.getRemovedLayer() instanceof ImageryLayer) { 398 this.refreshTileSources(); 399 } 400 } 401 402 @Override 403 public void layerOrderChanged(LayerOrderChangeEvent e) { 404 // Do nothing 405 } 406 407 /** 408 * Returns the currently visible map area 409 * @return the currently visible map area 410 */ 411 public Bounds getVisibleMapArea() { 412 final ICoordinate topLeft = getPosition(0, 0); 413 final ICoordinate bottomRight = getPosition(getWidth(), getHeight()); 414 final Bounds bounds = new Bounds(topLeft.getLat(), topLeft.getLon(), false); 415 bounds.extend(bottomRight.getLat(), bottomRight.getLon()); 416 return bounds; 417 } 418}