source: josm/trunk/src/org/openstreetmap/josm/gui/bbox/SlippyMapBBoxChooser.java@ 6084

Last change on this file since 6084 was 6084, checked in by bastiK, 11 years ago

see #8902 - add missing @Override annotations (patch by shinigami)

  • Property svn:eol-style set to native
File size: 14.8 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.gui.bbox;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Color;
7import java.awt.Dimension;
8import java.awt.Graphics;
9import java.awt.Graphics2D;
10import java.awt.Image;
11import java.awt.Point;
12import java.awt.Rectangle;
13import java.io.IOException;
14import java.util.ArrayList;
15import java.util.Arrays;
16import java.util.Collections;
17import java.util.HashSet;
18import java.util.List;
19import java.util.Vector;
20import java.util.concurrent.CopyOnWriteArrayList;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.gui.jmapviewer.Coordinate;
25import org.openstreetmap.gui.jmapviewer.JMapViewer;
26import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
27import org.openstreetmap.gui.jmapviewer.MemoryTileCache;
28import org.openstreetmap.gui.jmapviewer.OsmMercator;
29import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
30import org.openstreetmap.gui.jmapviewer.interfaces.MapMarker;
31import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
32import org.openstreetmap.gui.jmapviewer.tilesources.MapQuestOpenAerialTileSource;
33import org.openstreetmap.gui.jmapviewer.tilesources.MapQuestOsmTileSource;
34import org.openstreetmap.gui.jmapviewer.tilesources.OsmTileSource;
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.data.Bounds;
37import org.openstreetmap.josm.data.Version;
38import org.openstreetmap.josm.data.coor.LatLon;
39import org.openstreetmap.josm.data.imagery.ImageryInfo;
40import org.openstreetmap.josm.data.imagery.ImageryLayerInfo;
41import org.openstreetmap.josm.data.preferences.StringProperty;
42import org.openstreetmap.josm.gui.layer.TMSLayer;
43
44public class SlippyMapBBoxChooser extends JMapViewer implements BBoxChooser{
45
46 public interface TileSourceProvider {
47 List<TileSource> getTileSources();
48 }
49
50 public static class RenamedSourceDecorator implements TileSource {
51
52 private final TileSource source;
53 private final String name;
54
55 public RenamedSourceDecorator(TileSource source, String name) {
56 this.source = source;
57 this.name = name;
58 }
59
60 @Override public String getName() {
61 return name;
62 }
63
64 @Override public int getMaxZoom() { return source.getMaxZoom(); }
65
66 @Override public int getMinZoom() { return source.getMinZoom(); }
67
68 @Override public int getTileSize() { return source.getTileSize(); }
69
70 @Override public String getTileType() { return source.getTileType(); }
71
72 @Override public TileUpdate getTileUpdate() { return source.getTileUpdate(); }
73
74 @Override public String getTileUrl(int zoom, int tilex, int tiley) throws IOException { return source.getTileUrl(zoom, tilex, tiley); }
75
76 @Override public boolean requiresAttribution() { return source.requiresAttribution(); }
77
78 @Override public String getAttributionText(int zoom, Coordinate topLeft, Coordinate botRight) { return source.getAttributionText(zoom, topLeft, botRight); }
79
80 @Override public String getAttributionLinkURL() { return source.getAttributionLinkURL(); }
81
82 @Override public Image getAttributionImage() { return source.getAttributionImage(); }
83
84 @Override public String getAttributionImageURL() { return source.getAttributionImageURL(); }
85
86 @Override public String getTermsOfUseText() { return source.getTermsOfUseText(); }
87
88 @Override public String getTermsOfUseURL() { return source.getTermsOfUseURL(); }
89
90 @Override public double latToTileY(double lat, int zoom) { return source.latToTileY(lat,zoom); }
91
92 @Override public double lonToTileX(double lon, int zoom) { return source.lonToTileX(lon,zoom); }
93
94 @Override public double tileYToLat(int y, int zoom) { return source.tileYToLat(y, zoom); }
95
96 @Override public double tileXToLon(int x, int zoom) { return source.tileXToLon(x, zoom); }
97 }
98
99 /**
100 * TMS TileSource provider for the slippymap chooser
101 */
102 public static class TMSTileSourceProvider implements TileSourceProvider {
103 static final HashSet<String> existingSlippyMapUrls = new HashSet<String>();
104 static {
105 // Urls that already exist in the slippymap chooser and shouldn't be copied from TMS layer list
106 existingSlippyMapUrls.add("http://tile.openstreetmap.org/{zoom}/{x}/{y}.png"); // Mapnik
107 existingSlippyMapUrls.add("http://tile.opencyclemap.org/cycle/{zoom}/{x}/{y}.png"); // Cyclemap
108 existingSlippyMapUrls.add("http://otile{switch:1,2,3,4}.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png"); // MapQuest-OSM
109 existingSlippyMapUrls.add("http://oatile{switch:1,2,3,4}.mqcdn.com/tiles/1.0.0/sat/{zoom}/{x}/{y}.png"); // MapQuest Open Aerial
110 }
111
112 @Override
113 public List<TileSource> getTileSources() {
114 if (!TMSLayer.PROP_ADD_TO_SLIPPYMAP_CHOOSER.get()) return Collections.<TileSource>emptyList();
115 List<TileSource> sources = new ArrayList<TileSource>();
116 for (ImageryInfo info : ImageryLayerInfo.instance.getLayers()) {
117 if (existingSlippyMapUrls.contains(info.getUrl())) {
118 continue;
119 }
120 try {
121 TileSource source = TMSLayer.getTileSource(info);
122 if (source != null) {
123 sources.add(source);
124 }
125 } catch (IllegalArgumentException ex) {
126 if (ex.getMessage() != null && !ex.getMessage().isEmpty()) {
127 JOptionPane.showMessageDialog(Main.parent,
128 ex.getMessage(), tr("Warning"),
129 JOptionPane.WARNING_MESSAGE);
130 }
131 }
132 }
133 return sources;
134 }
135
136 public static void addExistingSlippyMapUrl(String url) {
137 existingSlippyMapUrls.add(url);
138 }
139 }
140
141
142 /**
143 * Plugins that wish to add custom tile sources to slippy map choose should call this method
144 * @param tileSourceProvider
145 */
146 public static void addTileSourceProvider(TileSourceProvider tileSourceProvider) {
147 providers.addIfAbsent(tileSourceProvider);
148 }
149
150 private static CopyOnWriteArrayList<TileSourceProvider> providers = new CopyOnWriteArrayList<TileSourceProvider>();
151
152 static {
153 addTileSourceProvider(new TileSourceProvider() {
154 @Override
155 public List<TileSource> getTileSources() {
156 return Arrays.<TileSource>asList(
157 new RenamedSourceDecorator(new OsmTileSource.Mapnik(), "Mapnik"),
158 new RenamedSourceDecorator(new OsmTileSource.CycleMap(), "Cyclemap"),
159 new RenamedSourceDecorator(new MapQuestOsmTileSource(), "MapQuest-OSM"),
160 new RenamedSourceDecorator(new MapQuestOpenAerialTileSource(), "MapQuest Open Aerial")
161 );
162 }
163 });
164 addTileSourceProvider(new TMSTileSourceProvider());
165 }
166
167 private static final StringProperty PROP_MAPSTYLE = new StringProperty("slippy_map_chooser.mapstyle", "Mapnik");
168 public static final String RESIZE_PROP = SlippyMapBBoxChooser.class.getName() + ".resize";
169
170 private OsmTileLoader cachedLoader;
171 private OsmTileLoader uncachedLoader;
172
173 private final SizeButton iSizeButton = new SizeButton();
174 private final SourceButton iSourceButton;
175 private Bounds bbox;
176
177 // upper left and lower right corners of the selection rectangle (x/y on
178 // ZOOM_MAX)
179 Point iSelectionRectStart;
180 Point iSelectionRectEnd;
181
182 public SlippyMapBBoxChooser() {
183 super();
184 TMSLayer.setMaxWorkers();
185 cachedLoader = TMSLayer.loaderFactory.makeTileLoader(this);
186
187 uncachedLoader = new OsmTileLoader(this);
188 uncachedLoader.headers.put("User-Agent", Version.getInstance().getFullAgentString());
189 setZoomContolsVisible(Main.pref.getBoolean("slippy_map_chooser.zoomcontrols",false));
190 setMapMarkerVisible(false);
191 setMinimumSize(new Dimension(350, 350 / 2));
192 // We need to set an initial size - this prevents a wrong zoom selection
193 // for
194 // the area before the component has been displayed the first time
195 setBounds(new Rectangle(getMinimumSize()));
196 if (cachedLoader == null) {
197 setFileCacheEnabled(false);
198 } else {
199 setFileCacheEnabled(Main.pref.getBoolean("slippy_map_chooser.file_cache", true));
200 }
201 setMaxTilesInMemory(Main.pref.getInteger("slippy_map_chooser.max_tiles", 1000));
202
203 List<TileSource> tileSources = new ArrayList<TileSource>();
204 for (TileSourceProvider provider: providers) {
205 tileSources.addAll(provider.getTileSources());
206 }
207
208 iSourceButton = new SourceButton(tileSources);
209
210 String mapStyle = PROP_MAPSTYLE.get();
211 boolean foundSource = false;
212 for (TileSource source: tileSources) {
213 if (source.getName().equals(mapStyle)) {
214 this.setTileSource(source);
215 iSourceButton.setCurrentMap(source);
216 foundSource = true;
217 break;
218 }
219 }
220 if (!foundSource) {
221 setTileSource(tileSources.get(0));
222 iSourceButton.setCurrentMap(tileSources.get(0));
223 }
224
225 new SlippyMapControler(this, this, iSizeButton, iSourceButton);
226 }
227
228 public boolean handleAttribution(Point p, boolean click) {
229 return attribution.handleAttribution(p, click);
230 }
231
232 protected Point getTopLeftCoordinates() {
233 return new Point(center.x - (getWidth() / 2), center.y - (getHeight() / 2));
234 }
235
236 /**
237 * Draw the map.
238 */
239 @Override
240 public void paint(Graphics g) {
241 try {
242 super.paint(g);
243
244 // draw selection rectangle
245 if (iSelectionRectStart != null && iSelectionRectEnd != null) {
246
247 int zoomDiff = MAX_ZOOM - zoom;
248 Point tlc = getTopLeftCoordinates();
249 int x_min = (iSelectionRectStart.x >> zoomDiff) - tlc.x;
250 int y_min = (iSelectionRectStart.y >> zoomDiff) - tlc.y;
251 int x_max = (iSelectionRectEnd.x >> zoomDiff) - tlc.x;
252 int y_max = (iSelectionRectEnd.y >> zoomDiff) - tlc.y;
253
254 int w = x_max - x_min;
255 int h = y_max - y_min;
256 g.setColor(new Color(0.9f, 0.7f, 0.7f, 0.6f));
257 g.fillRect(x_min, y_min, w, h);
258
259 g.setColor(Color.BLACK);
260 g.drawRect(x_min, y_min, w, h);
261 }
262
263 iSizeButton.paint(g);
264 iSourceButton.paint((Graphics2D)g);
265 } catch (Exception e) {
266 e.printStackTrace();
267 }
268 }
269
270 public void setFileCacheEnabled(boolean enabled) {
271 if (enabled) {
272 setTileLoader(cachedLoader);
273 } else {
274 setTileLoader(uncachedLoader);
275 }
276 }
277
278 public void setMaxTilesInMemory(int tiles) {
279 ((MemoryTileCache) getTileCache()).setCacheSize(tiles);
280 }
281
282
283 /**
284 * Callback for the OsmMapControl. (Re-)Sets the start and end point of the
285 * selection rectangle.
286 *
287 * @param aStart
288 * @param aEnd
289 */
290 public void setSelection(Point aStart, Point aEnd) {
291 if (aStart == null || aEnd == null || aStart.x == aEnd.x || aStart.y == aEnd.y)
292 return;
293
294 Point p_max = new Point(Math.max(aEnd.x, aStart.x), Math.max(aEnd.y, aStart.y));
295 Point p_min = new Point(Math.min(aEnd.x, aStart.x), Math.min(aEnd.y, aStart.y));
296
297 Point tlc = getTopLeftCoordinates();
298 int zoomDiff = MAX_ZOOM - zoom;
299 Point pEnd = new Point(p_max.x + tlc.x, p_max.y + tlc.y);
300 Point pStart = new Point(p_min.x + tlc.x, p_min.y + tlc.y);
301
302 pEnd.x <<= zoomDiff;
303 pEnd.y <<= zoomDiff;
304 pStart.x <<= zoomDiff;
305 pStart.y <<= zoomDiff;
306
307 iSelectionRectStart = pStart;
308 iSelectionRectEnd = pEnd;
309
310 Coordinate l1 = getPosition(p_max); // lon may be outside [-180,180]
311 Coordinate l2 = getPosition(p_min); // lon may be outside [-180,180]
312 Bounds b = new Bounds(
313 new LatLon(
314 Math.min(l2.getLat(), l1.getLat()),
315 LatLon.toIntervalLon(Math.min(l1.getLon(), l2.getLon()))
316 ),
317 new LatLon(
318 Math.max(l2.getLat(), l1.getLat()),
319 LatLon.toIntervalLon(Math.max(l1.getLon(), l2.getLon())))
320 );
321 Bounds oldValue = this.bbox;
322 this.bbox = b;
323 repaint();
324 firePropertyChange(BBOX_PROP, oldValue, this.bbox);
325 }
326
327 /**
328 * Performs resizing of the DownloadDialog in order to enlarge or shrink the
329 * map.
330 */
331 public void resizeSlippyMap() {
332 boolean large = iSizeButton.isEnlarged();
333 firePropertyChange(RESIZE_PROP, !large, large);
334 }
335
336 public void toggleMapSource(TileSource tileSource) {
337 this.tileController.setTileCache(new MemoryTileCache());
338 this.setTileSource(tileSource);
339 PROP_MAPSTYLE.put(tileSource.getName()); // TODO Is name really unique?
340 }
341
342 @Override
343 public Bounds getBoundingBox() {
344 return bbox;
345 }
346
347 /**
348 * Sets the current bounding box in this bbox chooser without
349 * emiting a property change event.
350 *
351 * @param bbox the bounding box. null to reset the bounding box
352 */
353 @Override
354 public void setBoundingBox(Bounds bbox) {
355 if (bbox == null || (bbox.getMin().lat() == 0.0 && bbox.getMin().lon() == 0.0
356 && bbox.getMax().lat() == 0.0 && bbox.getMax().lon() == 0.0)) {
357 this.bbox = null;
358 iSelectionRectStart = null;
359 iSelectionRectEnd = null;
360 repaint();
361 return;
362 }
363
364 this.bbox = bbox;
365 double minLon = bbox.getMin().lon();
366 double maxLon = bbox.getMax().lon();
367
368 if (bbox.crosses180thMeridian()) {
369 minLon -= 360.0;
370 }
371
372 int y1 = OsmMercator.LatToY(bbox.getMin().lat(), MAX_ZOOM);
373 int y2 = OsmMercator.LatToY(bbox.getMax().lat(), MAX_ZOOM);
374 int x1 = OsmMercator.LonToX(minLon, MAX_ZOOM);
375 int x2 = OsmMercator.LonToX(maxLon, MAX_ZOOM);
376
377 iSelectionRectStart = new Point(Math.min(x1, x2), Math.min(y1, y2));
378 iSelectionRectEnd = new Point(Math.max(x1, x2), Math.max(y1, y2));
379
380 // calc the screen coordinates for the new selection rectangle
381 MapMarkerDot xmin_ymin = new MapMarkerDot(bbox.getMin().lat(), bbox.getMin().lon());
382 MapMarkerDot xmax_ymax = new MapMarkerDot(bbox.getMax().lat(), bbox.getMax().lon());
383
384 Vector<MapMarker> marker = new Vector<MapMarker>(2);
385 marker.add(xmin_ymin);
386 marker.add(xmax_ymax);
387 setMapMarkerList(marker);
388 setDisplayToFitMapMarkers();
389 zoomOut();
390 repaint();
391 }
392}
Note: See TracBrowser for help on using the repository browser.