source: josm/trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java@ 6889

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

fix some Sonar issues (JLS order)

  • Property svn:eol-style set to native
File size: 53.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Color;
7import java.awt.Font;
8import java.awt.Graphics;
9import java.awt.Graphics2D;
10import java.awt.Image;
11import java.awt.Point;
12import java.awt.Rectangle;
13import java.awt.Toolkit;
14import java.awt.event.ActionEvent;
15import java.awt.event.MouseAdapter;
16import java.awt.event.MouseEvent;
17import java.awt.image.ImageObserver;
18import java.io.File;
19import java.io.IOException;
20import java.io.StringReader;
21import java.net.URL;
22import java.util.ArrayList;
23import java.util.Collections;
24import java.util.HashSet;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.Map;
28import java.util.Map.Entry;
29import java.util.Scanner;
30import java.util.Set;
31import java.util.concurrent.Callable;
32import java.util.regex.Matcher;
33import java.util.regex.Pattern;
34
35import javax.swing.AbstractAction;
36import javax.swing.Action;
37import javax.swing.JCheckBoxMenuItem;
38import javax.swing.JMenuItem;
39import javax.swing.JOptionPane;
40import javax.swing.JPopupMenu;
41
42import org.openstreetmap.gui.jmapviewer.AttributionSupport;
43import org.openstreetmap.gui.jmapviewer.Coordinate;
44import org.openstreetmap.gui.jmapviewer.JobDispatcher;
45import org.openstreetmap.gui.jmapviewer.MemoryTileCache;
46import org.openstreetmap.gui.jmapviewer.OsmFileCacheTileLoader;
47import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
48import org.openstreetmap.gui.jmapviewer.Tile;
49import org.openstreetmap.gui.jmapviewer.interfaces.CachedTileLoader;
50import org.openstreetmap.gui.jmapviewer.interfaces.TileCache;
51import org.openstreetmap.gui.jmapviewer.interfaces.TileClearController;
52import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
53import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
54import org.openstreetmap.gui.jmapviewer.tilesources.BingAerialTileSource;
55import org.openstreetmap.gui.jmapviewer.tilesources.ScanexTileSource;
56import org.openstreetmap.gui.jmapviewer.tilesources.TMSTileSource;
57import org.openstreetmap.gui.jmapviewer.tilesources.TemplatedTMSTileSource;
58import org.openstreetmap.josm.Main;
59import org.openstreetmap.josm.actions.RenameLayerAction;
60import org.openstreetmap.josm.data.Bounds;
61import org.openstreetmap.josm.data.Version;
62import org.openstreetmap.josm.data.coor.EastNorth;
63import org.openstreetmap.josm.data.coor.LatLon;
64import org.openstreetmap.josm.data.imagery.ImageryInfo;
65import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
66import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
67import org.openstreetmap.josm.data.preferences.BooleanProperty;
68import org.openstreetmap.josm.data.preferences.IntegerProperty;
69import org.openstreetmap.josm.data.preferences.StringProperty;
70import org.openstreetmap.josm.data.projection.Projection;
71import org.openstreetmap.josm.gui.MapFrame;
72import org.openstreetmap.josm.gui.MapView;
73import org.openstreetmap.josm.gui.MapView.LayerChangeListener;
74import org.openstreetmap.josm.gui.PleaseWaitRunnable;
75import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
76import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
77import org.openstreetmap.josm.gui.progress.ProgressMonitor;
78import org.openstreetmap.josm.gui.progress.ProgressMonitor.CancelListener;
79import org.openstreetmap.josm.io.CacheCustomContent;
80import org.openstreetmap.josm.io.OsmTransferException;
81import org.openstreetmap.josm.io.UTFInputStreamReader;
82import org.openstreetmap.josm.tools.Utils;
83import org.xml.sax.InputSource;
84import org.xml.sax.SAXException;
85
86/**
87 * Class that displays a slippy map layer.
88 *
89 * @author Frederik Ramm
90 * @author LuVar <lubomir.varga@freemap.sk>
91 * @author Dave Hansen <dave@sr71.net>
92 * @author Upliner <upliner@gmail.com>
93 *
94 */
95public class TMSLayer extends ImageryLayer implements ImageObserver, TileLoaderListener {
96 public static final String PREFERENCE_PREFIX = "imagery.tms";
97
98 public static final int MAX_ZOOM = 30;
99 public static final int MIN_ZOOM = 2;
100 public static final int DEFAULT_MAX_ZOOM = 20;
101 public static final int DEFAULT_MIN_ZOOM = 2;
102
103 public static final BooleanProperty PROP_DEFAULT_AUTOZOOM = new BooleanProperty(PREFERENCE_PREFIX + ".default_autozoom", true);
104 public static final BooleanProperty PROP_DEFAULT_AUTOLOAD = new BooleanProperty(PREFERENCE_PREFIX + ".default_autoload", true);
105 public static final BooleanProperty PROP_DEFAULT_SHOWERRORS = new BooleanProperty(PREFERENCE_PREFIX + ".default_showerrors", true);
106 public static final IntegerProperty PROP_MIN_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".min_zoom_lvl", DEFAULT_MIN_ZOOM);
107 public static final IntegerProperty PROP_MAX_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".max_zoom_lvl", DEFAULT_MAX_ZOOM);
108 //public static final BooleanProperty PROP_DRAW_DEBUG = new BooleanProperty(PREFERENCE_PREFIX + ".draw_debug", false);
109 public static final BooleanProperty PROP_ADD_TO_SLIPPYMAP_CHOOSER = new BooleanProperty(PREFERENCE_PREFIX + ".add_to_slippymap_chooser", true);
110 public static final IntegerProperty PROP_TMS_JOBS = new IntegerProperty("tmsloader.maxjobs", 25);
111 public static final StringProperty PROP_TILECACHE_DIR;
112
113 static {
114 String defPath = null;
115 try {
116 defPath = OsmFileCacheTileLoader.getDefaultCacheDir().getAbsolutePath();
117 } catch (SecurityException e) {
118 Main.warn(e);
119 }
120 PROP_TILECACHE_DIR = new StringProperty(PREFERENCE_PREFIX + ".tilecache_path", defPath);
121 }
122
123 /*boolean debug = true;*/
124
125 public interface TileLoaderFactory {
126 OsmTileLoader makeTileLoader(TileLoaderListener listener);
127 }
128
129 protected MemoryTileCache tileCache;
130 protected TileSource tileSource;
131 protected OsmTileLoader tileLoader;
132
133 public static TileLoaderFactory loaderFactory = new TileLoaderFactory() {
134 @Override
135 public OsmTileLoader makeTileLoader(TileLoaderListener listener) {
136 String cachePath = TMSLayer.PROP_TILECACHE_DIR.get();
137 if (cachePath != null && !cachePath.isEmpty()) {
138 try {
139 OsmFileCacheTileLoader loader = new OsmFileCacheTileLoader(listener, new File(cachePath));
140 loader.headers.put("User-Agent", Version.getInstance().getFullAgentString());
141 return loader;
142 } catch (IOException e) {
143 Main.warn(e);
144 }
145 }
146 return null;
147 }
148 };
149
150 /**
151 * Plugins that wish to set custom tile loader should call this method
152 */
153 public static void setCustomTileLoaderFactory(TileLoaderFactory loaderFactory) {
154 TMSLayer.loaderFactory = loaderFactory;
155 }
156
157 private Set<Tile> tileRequestsOutstanding = new HashSet<Tile>();
158
159 @Override
160 public synchronized void tileLoadingFinished(Tile tile, boolean success) {
161 if (tile.hasError()) {
162 success = false;
163 tile.setImage(null);
164 }
165 if (sharpenLevel != 0 && success) {
166 tile.setImage(sharpenImage(tile.getImage()));
167 }
168 tile.setLoaded(true);
169 needRedraw = true;
170 Main.map.repaint(100);
171 tileRequestsOutstanding.remove(tile);
172 /*if (debug) {
173 Main.debug("tileLoadingFinished() tile: " + tile + " success: " + success);
174 }*/
175 }
176
177 @Override
178 public TileCache getTileCache() {
179 return tileCache;
180 }
181
182 private static class TmsTileClearController implements TileClearController, CancelListener {
183
184 private final ProgressMonitor monitor;
185 private boolean cancel = false;
186
187 public TmsTileClearController(ProgressMonitor monitor) {
188 this.monitor = monitor;
189 this.monitor.addCancelListener(this);
190 }
191
192 @Override
193 public void initClearDir(File dir) {
194 }
195
196 @Override
197 public void initClearFiles(File[] files) {
198 monitor.setTicksCount(files.length);
199 monitor.setTicks(0);
200 }
201
202 @Override
203 public boolean cancel() {
204 return cancel;
205 }
206
207 @Override
208 public void fileDeleted(File file) {
209 monitor.setTicks(monitor.getTicks()+1);
210 }
211
212 @Override
213 public void clearFinished() {
214 monitor.finishTask();
215 }
216
217 @Override
218 public void operationCanceled() {
219 cancel = true;
220 }
221 }
222
223 /**
224 * Clears the tile cache.
225 *
226 * If the current tileLoader is an instance of OsmTileLoader, a new
227 * TmsTileClearController is created and passed to the according clearCache
228 * method.
229 *
230 * @param monitor
231 * @see MemoryTileCache#clear()
232 * @see OsmFileCacheTileLoader#clearCache(org.openstreetmap.gui.jmapviewer.interfaces.TileSource, org.openstreetmap.gui.jmapviewer.OsmFileCacheTileLoader.TileClearController)
233 */
234 void clearTileCache(ProgressMonitor monitor) {
235 tileCache.clear();
236 if (tileLoader instanceof CachedTileLoader) {
237 ((CachedTileLoader)tileLoader).clearCache(tileSource, new TmsTileClearController(monitor));
238 }
239 }
240
241 /**
242 * Zoomlevel at which tiles is currently downloaded.
243 * Initial zoom lvl is set to bestZoom
244 */
245 public int currentZoomLevel;
246
247 private Tile clickedTile;
248 private boolean needRedraw;
249 private JPopupMenu tileOptionMenu;
250 JCheckBoxMenuItem autoZoomPopup;
251 JCheckBoxMenuItem autoLoadPopup;
252 JCheckBoxMenuItem showErrorsPopup;
253 Tile showMetadataTile;
254 private AttributionSupport attribution = new AttributionSupport();
255 private static final Font InfoFont = new Font("sansserif", Font.BOLD, 13);
256
257 protected boolean autoZoom;
258 protected boolean autoLoad;
259 protected boolean showErrors;
260
261 /**
262 * Initiates a repaint of Main.map
263 *
264 * @see Main#map
265 * @see MapFrame#repaint()
266 */
267 void redraw() {
268 needRedraw = true;
269 Main.map.repaint();
270 }
271
272 static int checkMaxZoomLvl(int maxZoomLvl, TileSource ts) {
273 if(maxZoomLvl > MAX_ZOOM) {
274 maxZoomLvl = MAX_ZOOM;
275 }
276 if(maxZoomLvl < PROP_MIN_ZOOM_LVL.get()) {
277 maxZoomLvl = PROP_MIN_ZOOM_LVL.get();
278 }
279 if (ts != null && ts.getMaxZoom() != 0 && ts.getMaxZoom() < maxZoomLvl) {
280 maxZoomLvl = ts.getMaxZoom();
281 }
282 return maxZoomLvl;
283 }
284
285 public static int getMaxZoomLvl(TileSource ts) {
286 return checkMaxZoomLvl(PROP_MAX_ZOOM_LVL.get(), ts);
287 }
288
289 public static void setMaxZoomLvl(int maxZoomLvl) {
290 maxZoomLvl = checkMaxZoomLvl(maxZoomLvl, null);
291 PROP_MAX_ZOOM_LVL.put(maxZoomLvl);
292 }
293
294 static int checkMinZoomLvl(int minZoomLvl, TileSource ts) {
295 if(minZoomLvl < MIN_ZOOM) {
296 /*Main.debug("Min. zoom level should not be less than "+MIN_ZOOM+"! Setting to that.");*/
297 minZoomLvl = MIN_ZOOM;
298 }
299 if(minZoomLvl > PROP_MAX_ZOOM_LVL.get()) {
300 /*Main.debug("Min. zoom level should not be more than Max. zoom level! Setting to Max.");*/
301 minZoomLvl = getMaxZoomLvl(ts);
302 }
303 if (ts != null && ts.getMinZoom() > minZoomLvl) {
304 /*Main.debug("Increasing min. zoom level to match tile source");*/
305 minZoomLvl = ts.getMinZoom();
306 }
307 return minZoomLvl;
308 }
309
310 public static int getMinZoomLvl(TileSource ts) {
311 return checkMinZoomLvl(PROP_MIN_ZOOM_LVL.get(), ts);
312 }
313
314 public static void setMinZoomLvl(int minZoomLvl) {
315 minZoomLvl = checkMinZoomLvl(minZoomLvl, null);
316 PROP_MIN_ZOOM_LVL.put(minZoomLvl);
317 }
318
319 private static class CachedAttributionBingAerialTileSource extends BingAerialTileSource {
320
321 class BingAttributionData extends CacheCustomContent<IOException> {
322
323 public BingAttributionData() {
324 super("bing.attribution.xml", CacheCustomContent.INTERVAL_HOURLY);
325 }
326
327 @Override
328 protected byte[] updateData() throws IOException {
329 URL u = getAttributionUrl();
330 UTFInputStreamReader in = UTFInputStreamReader.create(Utils.openURL(u));
331 String r = new Scanner(in).useDelimiter("\\A").next();
332 Utils.close(in);
333 Main.info("Successfully loaded Bing attribution data.");
334 return r.getBytes("utf-8");
335 }
336 }
337
338 @Override
339 protected Callable<List<Attribution>> getAttributionLoaderCallable() {
340 return new Callable<List<Attribution>>() {
341
342 @Override
343 public List<Attribution> call() throws Exception {
344 BingAttributionData attributionLoader = new BingAttributionData();
345 int waitTimeSec = 1;
346 while (true) {
347 try {
348 String xml = attributionLoader.updateIfRequiredString();
349 return parseAttributionText(new InputSource(new StringReader((xml))));
350 } catch (IOException ex) {
351 Main.warn("Could not connect to Bing API. Will retry in " + waitTimeSec + " seconds.");
352 Thread.sleep(waitTimeSec * 1000L);
353 waitTimeSec *= 2;
354 }
355 }
356 }
357 };
358 }
359 }
360
361 /**
362 * Creates and returns a new TileSource instance depending on the {@link ImageryType}
363 * of the passed ImageryInfo object.
364 *
365 * If no appropriate TileSource is found, null is returned.
366 * Currently supported ImageryType are {@link ImageryType#TMS},
367 * {@link ImageryType#BING}, {@link ImageryType#SCANEX}.
368 *
369 * @param info
370 * @return a new TileSource instance or null if no TileSource for the ImageryInfo/ImageryType could be found.
371 * @throws IllegalArgumentException
372 */
373 public static TileSource getTileSource(ImageryInfo info) throws IllegalArgumentException {
374 if (info.getImageryType() == ImageryType.TMS) {
375 checkUrl(info.getUrl());
376 TMSTileSource t = new TemplatedTMSTileSource(info.getName(), info.getUrl(), info.getMinZoom(), info.getMaxZoom());
377 info.setAttribution(t);
378 return t;
379 } else if (info.getImageryType() == ImageryType.BING)
380 return new CachedAttributionBingAerialTileSource();
381 else if (info.getImageryType() == ImageryType.SCANEX) {
382 return new ScanexTileSource(info.getName(), info.getUrl(), info.getMaxZoom());
383 }
384 return null;
385 }
386
387 public static void checkUrl(String url) throws IllegalArgumentException {
388 if (url == null) {
389 throw new IllegalArgumentException();
390 } else {
391 Matcher m = Pattern.compile("\\{[^}]*\\}").matcher(url);
392 while (m.find()) {
393 boolean isSupportedPattern = false;
394 for (String pattern : TemplatedTMSTileSource.ALL_PATTERNS) {
395 if (m.group().matches(pattern)) {
396 isSupportedPattern = true;
397 break;
398 }
399 }
400 if (!isSupportedPattern) {
401 throw new IllegalArgumentException(tr("{0} is not a valid TMS argument. Please check this server URL:\n{1}", m.group(), url));
402 }
403 }
404 }
405 }
406
407 private void initTileSource(TileSource tileSource) {
408 this.tileSource = tileSource;
409 attribution.initialize(tileSource);
410
411 currentZoomLevel = getBestZoom();
412
413 tileCache = new MemoryTileCache();
414
415 tileLoader = loaderFactory.makeTileLoader(this);
416 if (tileLoader == null) {
417 tileLoader = new OsmTileLoader(this);
418 }
419 tileLoader.timeoutConnect = Main.pref.getInteger("socket.timeout.connect",15) * 1000;
420 tileLoader.timeoutRead = Main.pref.getInteger("socket.timeout.read", 30) * 1000;
421 if (tileSource instanceof TemplatedTMSTileSource) {
422 for(Entry<String, String> e : ((TemplatedTMSTileSource)tileSource).getHeaders().entrySet()) {
423 tileLoader.headers.put(e.getKey(), e.getValue());
424 }
425 }
426 tileLoader.headers.put("User-Agent", Version.getInstance().getFullAgentString());
427 }
428
429 @Override
430 public void setOffset(double dx, double dy) {
431 super.setOffset(dx, dy);
432 needRedraw = true;
433 }
434
435 /**
436 * Returns average number of screen pixels per tile pixel for current mapview
437 */
438 private double getScaleFactor(int zoom) {
439 if (!Main.isDisplayingMapView()) return 1;
440 MapView mv = Main.map.mapView;
441 LatLon topLeft = mv.getLatLon(0, 0);
442 LatLon botRight = mv.getLatLon(mv.getWidth(), mv.getHeight());
443 double x1 = tileSource.lonToTileX(topLeft.lon(), zoom);
444 double y1 = tileSource.latToTileY(topLeft.lat(), zoom);
445 double x2 = tileSource.lonToTileX(botRight.lon(), zoom);
446 double y2 = tileSource.latToTileY(botRight.lat(), zoom);
447
448 int screenPixels = mv.getWidth()*mv.getHeight();
449 double tilePixels = Math.abs((y2-y1)*(x2-x1)*tileSource.getTileSize()*tileSource.getTileSize());
450 if (screenPixels == 0 || tilePixels == 0) return 1;
451 return screenPixels/tilePixels;
452 }
453
454 private int getBestZoom() {
455 double factor = getScaleFactor(1);
456 double result = Math.log(factor)/Math.log(2)/2+1;
457 // In general, smaller zoom levels are more readable. We prefer big,
458 // block, pixelated (but readable) map text to small, smeared,
459 // unreadable underzoomed text. So, use .floor() instead of rounding
460 // to skew things a bit toward the lower zooms.
461 int intResult = (int)Math.floor(result);
462 if (intResult > getMaxZoomLvl())
463 return getMaxZoomLvl();
464 if (intResult < getMinZoomLvl())
465 return getMinZoomLvl();
466 return intResult;
467 }
468
469 /**
470 * Function to set the maximum number of workers for tile loading to the value defined
471 * in preferences.
472 */
473 public static void setMaxWorkers() {
474 JobDispatcher.setMaxWorkers(PROP_TMS_JOBS.get());
475 JobDispatcher.getInstance().setLIFO(true);
476 }
477
478 @SuppressWarnings("serial")
479 public TMSLayer(ImageryInfo info) {
480 super(info);
481
482 setMaxWorkers();
483 if(!isProjectionSupported(Main.getProjection())) {
484 JOptionPane.showMessageDialog(Main.parent,
485 tr("TMS layers do not support the projection {0}.\n{1}\n"
486 + "Change the projection or remove the layer.",
487 Main.getProjection().toCode(), nameSupportedProjections()),
488 tr("Warning"),
489 JOptionPane.WARNING_MESSAGE);
490 }
491
492 setBackgroundLayer(true);
493 this.setVisible(true);
494
495 TileSource source = getTileSource(info);
496 if (source == null)
497 throw new IllegalStateException("Cannot create TMSLayer with non-TMS ImageryInfo");
498 initTileSource(source);
499 }
500
501 /**
502 * Adds a context menu to the mapView.
503 */
504 @Override
505 public void hookUpMapView() {
506 tileOptionMenu = new JPopupMenu();
507
508 autoZoom = PROP_DEFAULT_AUTOZOOM.get();
509 autoZoomPopup = new JCheckBoxMenuItem();
510 autoZoomPopup.setAction(new AbstractAction(tr("Auto Zoom")) {
511 @Override
512 public void actionPerformed(ActionEvent ae) {
513 autoZoom = !autoZoom;
514 }
515 });
516 autoZoomPopup.setSelected(autoZoom);
517 tileOptionMenu.add(autoZoomPopup);
518
519 autoLoad = PROP_DEFAULT_AUTOLOAD.get();
520 autoLoadPopup = new JCheckBoxMenuItem();
521 autoLoadPopup.setAction(new AbstractAction(tr("Auto load tiles")) {
522 @Override
523 public void actionPerformed(ActionEvent ae) {
524 autoLoad= !autoLoad;
525 }
526 });
527 autoLoadPopup.setSelected(autoLoad);
528 tileOptionMenu.add(autoLoadPopup);
529
530 showErrors = PROP_DEFAULT_SHOWERRORS.get();
531 showErrorsPopup = new JCheckBoxMenuItem();
532 showErrorsPopup.setAction(new AbstractAction(tr("Show Errors")) {
533 @Override
534 public void actionPerformed(ActionEvent ae) {
535 showErrors = !showErrors;
536 }
537 });
538 showErrorsPopup.setSelected(showErrors);
539 tileOptionMenu.add(showErrorsPopup);
540
541 tileOptionMenu.add(new JMenuItem(new AbstractAction(tr("Load Tile")) {
542 @Override
543 public void actionPerformed(ActionEvent ae) {
544 if (clickedTile != null) {
545 loadTile(clickedTile, true);
546 redraw();
547 }
548 }
549 }));
550
551 tileOptionMenu.add(new JMenuItem(new AbstractAction(
552 tr("Show Tile Info")) {
553 @Override
554 public void actionPerformed(ActionEvent ae) {
555 if (clickedTile != null) {
556 showMetadataTile = clickedTile;
557 redraw();
558 }
559 }
560 }));
561
562 /* FIXME
563 tileOptionMenu.add(new JMenuItem(new AbstractAction(
564 tr("Request Update")) {
565 public void actionPerformed(ActionEvent ae) {
566 if (clickedTile != null) {
567 clickedTile.requestUpdate();
568 redraw();
569 }
570 }
571 }));*/
572
573 tileOptionMenu.add(new JMenuItem(new AbstractAction(
574 tr("Load All Tiles")) {
575 @Override
576 public void actionPerformed(ActionEvent ae) {
577 loadAllTiles(true);
578 redraw();
579 }
580 }));
581
582 tileOptionMenu.add(new JMenuItem(new AbstractAction(
583 tr("Load All Error Tiles")) {
584 @Override
585 public void actionPerformed(ActionEvent ae) {
586 loadAllErrorTiles(true);
587 redraw();
588 }
589 }));
590
591 // increase and decrease commands
592 tileOptionMenu.add(new JMenuItem(new AbstractAction(
593 tr("Increase zoom")) {
594 @Override
595 public void actionPerformed(ActionEvent ae) {
596 increaseZoomLevel();
597 redraw();
598 }
599 }));
600
601 tileOptionMenu.add(new JMenuItem(new AbstractAction(
602 tr("Decrease zoom")) {
603 @Override
604 public void actionPerformed(ActionEvent ae) {
605 decreaseZoomLevel();
606 redraw();
607 }
608 }));
609
610 tileOptionMenu.add(new JMenuItem(new AbstractAction(
611 tr("Snap to tile size")) {
612 @Override
613 public void actionPerformed(ActionEvent ae) {
614 double new_factor = Math.sqrt(getScaleFactor(currentZoomLevel));
615 Main.map.mapView.zoomToFactor(new_factor);
616 redraw();
617 }
618 }));
619
620 tileOptionMenu.add(new JMenuItem(new AbstractAction(
621 tr("Flush Tile Cache")) {
622 @Override
623 public void actionPerformed(ActionEvent ae) {
624 new PleaseWaitRunnable(tr("Flush Tile Cache")) {
625 @Override
626 protected void realRun() throws SAXException, IOException,
627 OsmTransferException {
628 clearTileCache(getProgressMonitor());
629 }
630
631 @Override
632 protected void finish() {
633 }
634
635 @Override
636 protected void cancel() {
637 }
638 }.run();
639 }
640 }));
641 // end of adding menu commands
642
643 final MouseAdapter adapter = new MouseAdapter() {
644 @Override
645 public void mouseClicked(MouseEvent e) {
646 if (!isVisible()) return;
647 if (e.getButton() == MouseEvent.BUTTON3) {
648 clickedTile = getTileForPixelpos(e.getX(), e.getY());
649 tileOptionMenu.show(e.getComponent(), e.getX(), e.getY());
650 } else if (e.getButton() == MouseEvent.BUTTON1) {
651 attribution.handleAttribution(e.getPoint(), true);
652 }
653 }
654 };
655 Main.map.mapView.addMouseListener(adapter);
656
657 MapView.addLayerChangeListener(new LayerChangeListener() {
658 @Override
659 public void activeLayerChange(Layer oldLayer, Layer newLayer) {
660 //
661 }
662
663 @Override
664 public void layerAdded(Layer newLayer) {
665 //
666 }
667
668 @Override
669 public void layerRemoved(Layer oldLayer) {
670 if (oldLayer == TMSLayer.this) {
671 Main.map.mapView.removeMouseListener(adapter);
672 MapView.removeLayerChangeListener(this);
673 }
674 }
675 });
676 }
677
678 void zoomChanged() {
679 /*if (debug) {
680 Main.debug("zoomChanged(): " + currentZoomLevel);
681 }*/
682 needRedraw = true;
683 JobDispatcher.getInstance().cancelOutstandingJobs();
684 tileRequestsOutstanding.clear();
685 }
686
687 int getMaxZoomLvl() {
688 if (info.getMaxZoom() != 0)
689 return checkMaxZoomLvl(info.getMaxZoom(), tileSource);
690 else
691 return getMaxZoomLvl(tileSource);
692 }
693
694 int getMinZoomLvl() {
695 return getMinZoomLvl(tileSource);
696 }
697
698 /**
699 * Zoom in, go closer to map.
700 *
701 * @return true, if zoom increasing was successfull, false othervise
702 */
703 public boolean zoomIncreaseAllowed() {
704 boolean zia = currentZoomLevel < this.getMaxZoomLvl();
705 /*if (debug) {
706 Main.debug("zoomIncreaseAllowed(): " + zia + " " + currentZoomLevel + " vs. " + this.getMaxZoomLvl() );
707 }*/
708 return zia;
709 }
710
711 public boolean increaseZoomLevel() {
712 if (zoomIncreaseAllowed()) {
713 currentZoomLevel++;
714 /*if (debug) {
715 Main.debug("increasing zoom level to: " + currentZoomLevel);
716 }*/
717 zoomChanged();
718 } else {
719 Main.warn("Current zoom level ("+currentZoomLevel+") could not be increased. "+
720 "Max.zZoom Level "+this.getMaxZoomLvl()+" reached.");
721 return false;
722 }
723 return true;
724 }
725
726 public boolean setZoomLevel(int zoom) {
727 if (zoom == currentZoomLevel) return true;
728 if (zoom > this.getMaxZoomLvl()) return false;
729 if (zoom < this.getMinZoomLvl()) return false;
730 currentZoomLevel = zoom;
731 zoomChanged();
732 return true;
733 }
734
735 /**
736 * Check if zooming out is allowed
737 *
738 * @return true, if zooming out is allowed (currentZoomLevel &gt; minZoomLevel)
739 */
740 public boolean zoomDecreaseAllowed() {
741 return currentZoomLevel > this.getMinZoomLvl();
742 }
743
744 /**
745 * Zoom out from map.
746 *
747 * @return true, if zoom increasing was successfull, false othervise
748 */
749 public boolean decreaseZoomLevel() {
750 //int minZoom = this.getMinZoomLvl();
751 if (zoomDecreaseAllowed()) {
752 /*if (debug) {
753 Main.debug("decreasing zoom level to: " + currentZoomLevel);
754 }*/
755 currentZoomLevel--;
756 zoomChanged();
757 } else {
758 /*Main.debug("Current zoom level could not be decreased. Min. zoom level "+minZoom+" reached.");*/
759 return false;
760 }
761 return true;
762 }
763
764 /*
765 * We use these for quick, hackish calculations. They
766 * are temporary only and intentionally not inserted
767 * into the tileCache.
768 */
769 synchronized Tile tempCornerTile(Tile t) {
770 int x = t.getXtile() + 1;
771 int y = t.getYtile() + 1;
772 int zoom = t.getZoom();
773 Tile tile = getTile(x, y, zoom);
774 if (tile != null)
775 return tile;
776 return new Tile(tileSource, x, y, zoom);
777 }
778
779 synchronized Tile getOrCreateTile(int x, int y, int zoom) {
780 Tile tile = getTile(x, y, zoom);
781 if (tile == null) {
782 tile = new Tile(tileSource, x, y, zoom);
783 tileCache.addTile(tile);
784 tile.loadPlaceholderFromCache(tileCache);
785 }
786 return tile;
787 }
788
789 /*
790 * This can and will return null for tiles that are not
791 * already in the cache.
792 */
793 synchronized Tile getTile(int x, int y, int zoom) {
794 int max = (1 << zoom);
795 if (x < 0 || x >= max || y < 0 || y >= max)
796 return null;
797 return tileCache.getTile(tileSource, x, y, zoom);
798 }
799
800 synchronized boolean loadTile(Tile tile, boolean force) {
801 if (tile == null)
802 return false;
803 if (!force && (tile.hasError() || tile.isLoaded()))
804 return false;
805 if (tile.isLoading())
806 return false;
807 if (tileRequestsOutstanding.contains(tile))
808 return false;
809 tileRequestsOutstanding.add(tile);
810 JobDispatcher.getInstance().addJob(tileLoader.createTileLoaderJob(tile));
811 return true;
812 }
813
814 void loadAllTiles(boolean force) {
815 MapView mv = Main.map.mapView;
816 EastNorth topLeft = mv.getEastNorth(0, 0);
817 EastNorth botRight = mv.getEastNorth(mv.getWidth(), mv.getHeight());
818
819 TileSet ts = new TileSet(topLeft, botRight, currentZoomLevel);
820
821 // if there is more than 18 tiles on screen in any direction, do not
822 // load all tiles!
823 if (ts.tooLarge()) {
824 Main.warn("Not downloading all tiles because there is more than 18 tiles on an axis!");
825 return;
826 }
827 ts.loadAllTiles(force);
828 }
829
830 void loadAllErrorTiles(boolean force) {
831 MapView mv = Main.map.mapView;
832 EastNorth topLeft = mv.getEastNorth(0, 0);
833 EastNorth botRight = mv.getEastNorth(mv.getWidth(), mv.getHeight());
834
835 TileSet ts = new TileSet(topLeft, botRight, currentZoomLevel);
836
837 ts.loadAllErrorTiles(force);
838 }
839
840 /*
841 * Attempt to approximate how much the image is being scaled. For instance,
842 * a 100x100 image being scaled to 50x50 would return 0.25.
843 */
844 Image lastScaledImage = null;
845 @Override
846 public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
847 boolean done = ((infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0);
848 needRedraw = true;
849 /*if (debug) {
850 Main.debug("imageUpdate() done: " + done + " calling repaint");
851 }*/
852 Main.map.repaint(done ? 0 : 100);
853 return !done;
854 }
855
856 boolean imageLoaded(Image i) {
857 if (i == null)
858 return false;
859 int status = Toolkit.getDefaultToolkit().checkImage(i, -1, -1, this);
860 if ((status & ALLBITS) != 0)
861 return true;
862 return false;
863 }
864
865 /**
866 * Returns the image for the given tile if both tile and image are loaded.
867 * Otherwise returns null.
868 *
869 * @param tile the Tile for which the image should be returned
870 * @return the image of the tile or null.
871 */
872 Image getLoadedTileImage(Tile tile) {
873 if (!tile.isLoaded())
874 return null;
875 Image img = tile.getImage();
876 if (!imageLoaded(img))
877 return null;
878 return img;
879 }
880
881 LatLon tileLatLon(Tile t) {
882 int zoom = t.getZoom();
883 return new LatLon(tileSource.tileYToLat(t.getYtile(), zoom),
884 tileSource.tileXToLon(t.getXtile(), zoom));
885 }
886
887 Rectangle tileToRect(Tile t1) {
888 /*
889 * We need to get a box in which to draw, so advance by one tile in
890 * each direction to find the other corner of the box.
891 * Note: this somewhat pollutes the tile cache
892 */
893 Tile t2 = tempCornerTile(t1);
894 Rectangle rect = new Rectangle(pixelPos(t1));
895 rect.add(pixelPos(t2));
896 return rect;
897 }
898
899 // 'source' is the pixel coordinates for the area that
900 // the img is capable of filling in. However, we probably
901 // only want a portion of it.
902 //
903 // 'border' is the screen cordinates that need to be drawn.
904 // We must not draw outside of it.
905 void drawImageInside(Graphics g, Image sourceImg, Rectangle source, Rectangle border) {
906 Rectangle target = source;
907
908 // If a border is specified, only draw the intersection
909 // if what we have combined with what we are supposed
910 // to draw.
911 if (border != null) {
912 target = source.intersection(border);
913 /*if (debug) {
914 Main.debug("source: " + source + "\nborder: " + border + "\nintersection: " + target);
915 }*/
916 }
917
918 // All of the rectangles are in screen coordinates. We need
919 // to how these correlate to the sourceImg pixels. We could
920 // avoid doing this by scaling the image up to the 'source' size,
921 // but this should be cheaper.
922 //
923 // In some projections, x any y are scaled differently enough to
924 // cause a pixel or two of fudge. Calculate them separately.
925 double imageYScaling = sourceImg.getHeight(this) / source.getHeight();
926 double imageXScaling = sourceImg.getWidth(this) / source.getWidth();
927
928 // How many pixels into the 'source' rectangle are we drawing?
929 int screen_x_offset = target.x - source.x;
930 int screen_y_offset = target.y - source.y;
931 // And how many pixels into the image itself does that
932 // correlate to?
933 int img_x_offset = (int)(screen_x_offset * imageXScaling);
934 int img_y_offset = (int)(screen_y_offset * imageYScaling);
935 // Now calculate the other corner of the image that we need
936 // by scaling the 'target' rectangle's dimensions.
937 int img_x_end = img_x_offset + (int)(target.getWidth() * imageXScaling);
938 int img_y_end = img_y_offset + (int)(target.getHeight() * imageYScaling);
939
940 /*if (debug) {
941 Main.debug("drawing image into target rect: " + target);
942 }*/
943 g.drawImage(sourceImg,
944 target.x, target.y,
945 target.x + target.width, target.y + target.height,
946 img_x_offset, img_y_offset,
947 img_x_end, img_y_end,
948 this);
949 if (PROP_FADE_AMOUNT.get() != 0) {
950 // dimm by painting opaque rect...
951 g.setColor(getFadeColorWithAlpha());
952 g.fillRect(target.x, target.y,
953 target.width, target.height);
954 }
955 }
956
957 // This function is called for several zoom levels, not just
958 // the current one. It should not trigger any tiles to be
959 // downloaded. It should also avoid polluting the tile cache
960 // with any tiles since these tiles are not mandatory.
961 //
962 // The "border" tile tells us the boundaries of where we may
963 // draw. It will not be from the zoom level that is being
964 // drawn currently. If drawing the displayZoomLevel,
965 // border is null and we draw the entire tile set.
966 List<Tile> paintTileImages(Graphics g, TileSet ts, int zoom, Tile border) {
967 if (zoom <= 0) return Collections.emptyList();
968 Rectangle borderRect = null;
969 if (border != null) {
970 borderRect = tileToRect(border);
971 }
972 List<Tile> missedTiles = new LinkedList<Tile>();
973 // The callers of this code *require* that we return any tiles
974 // that we do not draw in missedTiles. ts.allExistingTiles() by
975 // default will only return already-existing tiles. However, we
976 // need to return *all* tiles to the callers, so force creation
977 // here.
978 //boolean forceTileCreation = true;
979 for (Tile tile : ts.allTilesCreate()) {
980 Image img = getLoadedTileImage(tile);
981 if (img == null || tile.hasError()) {
982 /*if (debug) {
983 Main.debug("missed tile: " + tile);
984 }*/
985 missedTiles.add(tile);
986 continue;
987 }
988 Rectangle sourceRect = tileToRect(tile);
989 if (borderRect != null && !sourceRect.intersects(borderRect)) {
990 continue;
991 }
992 drawImageInside(g, img, sourceRect, borderRect);
993 }// end of for
994 return missedTiles;
995 }
996
997 void myDrawString(Graphics g, String text, int x, int y) {
998 Color oldColor = g.getColor();
999 g.setColor(Color.black);
1000 g.drawString(text,x+1,y+1);
1001 g.setColor(oldColor);
1002 g.drawString(text,x,y);
1003 }
1004
1005 void paintTileText(TileSet ts, Tile tile, Graphics g, MapView mv, int zoom, Tile t) {
1006 int fontHeight = g.getFontMetrics().getHeight();
1007 if (tile == null)
1008 return;
1009 Point p = pixelPos(t);
1010 int texty = p.y + 2 + fontHeight;
1011
1012 /*if (PROP_DRAW_DEBUG.get()) {
1013 myDrawString(g, "x=" + t.getXtile() + " y=" + t.getYtile() + " z=" + zoom + "", p.x + 2, texty);
1014 texty += 1 + fontHeight;
1015 if ((t.getXtile() % 32 == 0) && (t.getYtile() % 32 == 0)) {
1016 myDrawString(g, "x=" + t.getXtile() / 32 + " y=" + t.getYtile() / 32 + " z=7", p.x + 2, texty);
1017 texty += 1 + fontHeight;
1018 }
1019 }*/// end of if draw debug
1020
1021 if (tile == showMetadataTile) {
1022 String md = tile.toString();
1023 if (md != null) {
1024 myDrawString(g, md, p.x + 2, texty);
1025 texty += 1 + fontHeight;
1026 }
1027 Map<String, String> meta = tile.getMetadata();
1028 if (meta != null) {
1029 for (Map.Entry<String, String> entry : meta.entrySet()) {
1030 myDrawString(g, entry.getKey() + ": " + entry.getValue(), p.x + 2, texty);
1031 texty += 1 + fontHeight;
1032 }
1033 }
1034 }
1035
1036 /*String tileStatus = tile.getStatus();
1037 if (!tile.isLoaded() && PROP_DRAW_DEBUG.get()) {
1038 myDrawString(g, tr("image " + tileStatus), p.x + 2, texty);
1039 texty += 1 + fontHeight;
1040 }*/
1041
1042 if (tile.hasError() && showErrors) {
1043 myDrawString(g, tr("Error") + ": " + tr(tile.getErrorMessage()), p.x + 2, texty);
1044 texty += 1 + fontHeight;
1045 }
1046
1047 /*int xCursor = -1;
1048 int yCursor = -1;
1049 if (PROP_DRAW_DEBUG.get()) {
1050 if (yCursor < t.getYtile()) {
1051 if (t.getYtile() % 32 == 31) {
1052 g.fillRect(0, p.y - 1, mv.getWidth(), 3);
1053 } else {
1054 g.drawLine(0, p.y, mv.getWidth(), p.y);
1055 }
1056 yCursor = t.getYtile();
1057 }
1058 // This draws the vertical lines for the entire
1059 // column. Only draw them for the top tile in
1060 // the column.
1061 if (xCursor < t.getXtile()) {
1062 if (t.getXtile() % 32 == 0) {
1063 // level 7 tile boundary
1064 g.fillRect(p.x - 1, 0, 3, mv.getHeight());
1065 } else {
1066 g.drawLine(p.x, 0, p.x, mv.getHeight());
1067 }
1068 xCursor = t.getXtile();
1069 }
1070 }*/
1071 }
1072
1073 private Point pixelPos(LatLon ll) {
1074 return Main.map.mapView.getPoint(Main.getProjection().latlon2eastNorth(ll).add(getDx(), getDy()));
1075 }
1076
1077 private Point pixelPos(Tile t) {
1078 double lon = tileSource.tileXToLon(t.getXtile(), t.getZoom());
1079 LatLon tmpLL = new LatLon(tileSource.tileYToLat(t.getYtile(), t.getZoom()), lon);
1080 return pixelPos(tmpLL);
1081 }
1082
1083 private LatLon getShiftedLatLon(EastNorth en) {
1084 return Main.getProjection().eastNorth2latlon(en.add(-getDx(), -getDy()));
1085 }
1086
1087 private Coordinate getShiftedCoord(EastNorth en) {
1088 LatLon ll = getShiftedLatLon(en);
1089 return new Coordinate(ll.lat(),ll.lon());
1090 }
1091
1092 private final TileSet nullTileSet = new TileSet((LatLon)null, (LatLon)null, 0);
1093 private class TileSet {
1094 int x0, x1, y0, y1;
1095 int zoom;
1096 int tileMax = -1;
1097
1098 /**
1099 * Create a TileSet by EastNorth bbox taking a layer shift in account
1100 */
1101 TileSet(EastNorth topLeft, EastNorth botRight, int zoom) {
1102 this(getShiftedLatLon(topLeft), getShiftedLatLon(botRight),zoom);
1103 }
1104
1105 /**
1106 * Create a TileSet by known LatLon bbox without layer shift correction
1107 */
1108 TileSet(LatLon topLeft, LatLon botRight, int zoom) {
1109 this.zoom = zoom;
1110 if (zoom == 0)
1111 return;
1112
1113 x0 = (int)tileSource.lonToTileX(topLeft.lon(), zoom);
1114 y0 = (int)tileSource.latToTileY(topLeft.lat(), zoom);
1115 x1 = (int)tileSource.lonToTileX(botRight.lon(), zoom);
1116 y1 = (int)tileSource.latToTileY(botRight.lat(), zoom);
1117 if (x0 > x1) {
1118 int tmp = x0;
1119 x0 = x1;
1120 x1 = tmp;
1121 }
1122 if (y0 > y1) {
1123 int tmp = y0;
1124 y0 = y1;
1125 y1 = tmp;
1126 }
1127 tileMax = (int)Math.pow(2.0, zoom);
1128 if (x0 < 0) {
1129 x0 = 0;
1130 }
1131 if (y0 < 0) {
1132 y0 = 0;
1133 }
1134 if (x1 > tileMax) {
1135 x1 = tileMax;
1136 }
1137 if (y1 > tileMax) {
1138 y1 = tileMax;
1139 }
1140 }
1141
1142 boolean tooSmall() {
1143 return this.tilesSpanned() < 2.1;
1144 }
1145
1146 boolean tooLarge() {
1147 return this.tilesSpanned() > 10;
1148 }
1149
1150 boolean insane() {
1151 return this.tilesSpanned() > 100;
1152 }
1153
1154 double tilesSpanned() {
1155 return Math.sqrt(1.0 * this.size());
1156 }
1157
1158 int size() {
1159 int x_span = x1 - x0 + 1;
1160 int y_span = y1 - y0 + 1;
1161 return x_span * y_span;
1162 }
1163
1164 /*
1165 * Get all tiles represented by this TileSet that are
1166 * already in the tileCache.
1167 */
1168 List<Tile> allExistingTiles() {
1169 return this.__allTiles(false);
1170 }
1171
1172 List<Tile> allTilesCreate() {
1173 return this.__allTiles(true);
1174 }
1175
1176 private List<Tile> __allTiles(boolean create) {
1177 // Tileset is either empty or too large
1178 if (zoom == 0 || this.insane())
1179 return Collections.emptyList();
1180 List<Tile> ret = new ArrayList<Tile>();
1181 for (int x = x0; x <= x1; x++) {
1182 for (int y = y0; y <= y1; y++) {
1183 Tile t;
1184 if (create) {
1185 t = getOrCreateTile(x % tileMax, y % tileMax, zoom);
1186 } else {
1187 t = getTile(x % tileMax, y % tileMax, zoom);
1188 }
1189 if (t != null) {
1190 ret.add(t);
1191 }
1192 }
1193 }
1194 return ret;
1195 }
1196
1197 private List<Tile> allLoadedTiles() {
1198 List<Tile> ret = new ArrayList<Tile>();
1199 for (Tile t : this.allExistingTiles()) {
1200 if (t.isLoaded())
1201 ret.add(t);
1202 }
1203 return ret;
1204 }
1205
1206 void loadAllTiles(boolean force) {
1207 if (!autoLoad && !force)
1208 return;
1209 for (Tile t : this.allTilesCreate()) {
1210 loadTile(t, false);
1211 }
1212 }
1213
1214 void loadAllErrorTiles(boolean force) {
1215 if (!autoLoad && !force)
1216 return;
1217 for (Tile t : this.allTilesCreate()) {
1218 if (t.hasError()) {
1219 loadTile(t, true);
1220 }
1221 }
1222 }
1223 }
1224
1225
1226 private static class TileSetInfo {
1227 public boolean hasVisibleTiles = false;
1228 public boolean hasOverzoomedTiles = false;
1229 public boolean hasLoadingTiles = false;
1230 }
1231
1232 private static TileSetInfo getTileSetInfo(TileSet ts) {
1233 List<Tile> allTiles = ts.allExistingTiles();
1234 TileSetInfo result = new TileSetInfo();
1235 result.hasLoadingTiles = allTiles.size() < ts.size();
1236 for (Tile t : allTiles) {
1237 if (t.isLoaded()) {
1238 if (!t.hasError()) {
1239 result.hasVisibleTiles = true;
1240 }
1241 if ("no-tile".equals(t.getValue("tile-info"))) {
1242 result.hasOverzoomedTiles = true;
1243 }
1244 } else {
1245 result.hasLoadingTiles = true;
1246 }
1247 }
1248 return result;
1249 }
1250
1251 private class DeepTileSet {
1252 final EastNorth topLeft, botRight;
1253 final int minZoom, maxZoom;
1254 private final TileSet[] tileSets;
1255 private final TileSetInfo[] tileSetInfos;
1256 public DeepTileSet(EastNorth topLeft, EastNorth botRight, int minZoom, int maxZoom) {
1257 this.topLeft = topLeft;
1258 this.botRight = botRight;
1259 this.minZoom = minZoom;
1260 this.maxZoom = maxZoom;
1261 this.tileSets = new TileSet[maxZoom - minZoom + 1];
1262 this.tileSetInfos = new TileSetInfo[maxZoom - minZoom + 1];
1263 }
1264 public TileSet getTileSet(int zoom) {
1265 if (zoom < minZoom)
1266 return nullTileSet;
1267 TileSet ts = tileSets[zoom-minZoom];
1268 if (ts == null) {
1269 ts = new TileSet(topLeft, botRight, zoom);
1270 tileSets[zoom-minZoom] = ts;
1271 }
1272 return ts;
1273 }
1274 public TileSetInfo getTileSetInfo(int zoom) {
1275 if (zoom < minZoom)
1276 return new TileSetInfo();
1277 TileSetInfo tsi = tileSetInfos[zoom-minZoom];
1278 if (tsi == null) {
1279 tsi = TMSLayer.getTileSetInfo(getTileSet(zoom));
1280 tileSetInfos[zoom-minZoom] = tsi;
1281 }
1282 return tsi;
1283 }
1284 }
1285
1286 @Override
1287 public void paint(Graphics2D g, MapView mv, Bounds bounds) {
1288 //long start = System.currentTimeMillis();
1289 EastNorth topLeft = mv.getEastNorth(0, 0);
1290 EastNorth botRight = mv.getEastNorth(mv.getWidth(), mv.getHeight());
1291
1292 if (botRight.east() == 0.0 || botRight.north() == 0) {
1293 /*Main.debug("still initializing??");*/
1294 // probably still initializing
1295 return;
1296 }
1297
1298 needRedraw = false;
1299
1300 int zoom = currentZoomLevel;
1301 if (autoZoom) {
1302 double pixelScaling = getScaleFactor(zoom);
1303 if (pixelScaling > 3 || pixelScaling < 0.7) {
1304 zoom = getBestZoom();
1305 }
1306 }
1307
1308 DeepTileSet dts = new DeepTileSet(topLeft, botRight, getMinZoomLvl(), zoom);
1309 TileSet ts = dts.getTileSet(zoom);
1310
1311 int displayZoomLevel = zoom;
1312
1313 boolean noTilesAtZoom = false;
1314 if (autoZoom && autoLoad) {
1315 // Auto-detection of tilesource maxzoom (currently fully works only for Bing)
1316 TileSetInfo tsi = dts.getTileSetInfo(zoom);
1317 if (!tsi.hasVisibleTiles && (!tsi.hasLoadingTiles || tsi.hasOverzoomedTiles)) {
1318 noTilesAtZoom = true;
1319 }
1320 // Find highest zoom level with at least one visible tile
1321 for (int tmpZoom = zoom; tmpZoom > dts.minZoom; tmpZoom--) {
1322 if (dts.getTileSetInfo(tmpZoom).hasVisibleTiles) {
1323 displayZoomLevel = tmpZoom;
1324 break;
1325 }
1326 }
1327 // Do binary search between currentZoomLevel and displayZoomLevel
1328 while (zoom > displayZoomLevel && !tsi.hasVisibleTiles && tsi.hasOverzoomedTiles){
1329 zoom = (zoom + displayZoomLevel)/2;
1330 tsi = dts.getTileSetInfo(zoom);
1331 }
1332
1333 setZoomLevel(zoom);
1334
1335 // If all tiles at displayZoomLevel is loaded, load all tiles at next zoom level
1336 // to make sure there're really no more zoom levels
1337 if (zoom == displayZoomLevel && !tsi.hasLoadingTiles && zoom < dts.maxZoom) {
1338 zoom++;
1339 tsi = dts.getTileSetInfo(zoom);
1340 }
1341 // When we have overzoomed tiles and all tiles at current zoomlevel is loaded,
1342 // load tiles at previovus zoomlevels until we have all tiles on screen is loaded.
1343 while (zoom > dts.minZoom && tsi.hasOverzoomedTiles && !tsi.hasLoadingTiles) {
1344 zoom--;
1345 tsi = dts.getTileSetInfo(zoom);
1346 }
1347 ts = dts.getTileSet(zoom);
1348 } else if (autoZoom) {
1349 setZoomLevel(zoom);
1350 }
1351
1352 // Too many tiles... refuse to download
1353 if (!ts.tooLarge()) {
1354 //Main.debug("size: " + ts.size() + " spanned: " + ts.tilesSpanned());
1355 ts.loadAllTiles(false);
1356 }
1357
1358 if (displayZoomLevel != zoom) {
1359 ts = dts.getTileSet(displayZoomLevel);
1360 }
1361
1362 g.setColor(Color.DARK_GRAY);
1363
1364 List<Tile> missedTiles = this.paintTileImages(g, ts, displayZoomLevel, null);
1365 int[] otherZooms = { -1, 1, -2, 2, -3, -4, -5};
1366 for (int zoomOffset : otherZooms) {
1367 if (!autoZoom) {
1368 break;
1369 }
1370 int newzoom = displayZoomLevel + zoomOffset;
1371 if (newzoom < MIN_ZOOM) {
1372 continue;
1373 }
1374 if (missedTiles.size() <= 0) {
1375 break;
1376 }
1377 List<Tile> newlyMissedTiles = new LinkedList<Tile>();
1378 for (Tile missed : missedTiles) {
1379 if ("no-tile".equals(missed.getValue("tile-info")) && zoomOffset > 0) {
1380 // Don't try to paint from higher zoom levels when tile is overzoomed
1381 newlyMissedTiles.add(missed);
1382 continue;
1383 }
1384 Tile t2 = tempCornerTile(missed);
1385 LatLon topLeft2 = tileLatLon(missed);
1386 LatLon botRight2 = tileLatLon(t2);
1387 TileSet ts2 = new TileSet(topLeft2, botRight2, newzoom);
1388 // Instantiating large TileSets is expensive. If there
1389 // are no loaded tiles, don't bother even trying.
1390 if (ts2.allLoadedTiles().isEmpty()) {
1391 newlyMissedTiles.add(missed);
1392 continue;
1393 }
1394 if (ts2.tooLarge()) {
1395 continue;
1396 }
1397 newlyMissedTiles.addAll(this.paintTileImages(g, ts2, newzoom, missed));
1398 }
1399 missedTiles = newlyMissedTiles;
1400 }
1401 /*if (debug && missedTiles.size() > 0) {
1402 Main.debug("still missed "+missedTiles.size()+" in the end");
1403 }*/
1404 g.setColor(Color.red);
1405 g.setFont(InfoFont);
1406
1407 // The current zoom tileset should have all of its tiles
1408 // due to the loadAllTiles(), unless it to tooLarge()
1409 for (Tile t : ts.allExistingTiles()) {
1410 this.paintTileText(ts, t, g, mv, displayZoomLevel, t);
1411 }
1412
1413 attribution.paintAttribution(g, mv.getWidth(), mv.getHeight(), getShiftedCoord(topLeft), getShiftedCoord(botRight), displayZoomLevel, this);
1414
1415 //g.drawString("currentZoomLevel=" + currentZoomLevel, 120, 120);
1416 g.setColor(Color.lightGray);
1417 if (!autoZoom) {
1418 if (ts.insane()) {
1419 myDrawString(g, tr("zoom in to load any tiles"), 120, 120);
1420 } else if (ts.tooLarge()) {
1421 myDrawString(g, tr("zoom in to load more tiles"), 120, 120);
1422 } else if (ts.tooSmall()) {
1423 myDrawString(g, tr("increase zoom level to see more detail"), 120, 120);
1424 }
1425 }
1426 if (noTilesAtZoom) {
1427 myDrawString(g, tr("No tiles at this zoom level"), 120, 120);
1428 }
1429 /*if (debug) {
1430 myDrawString(g, tr("Current zoom: {0}", currentZoomLevel), 50, 140);
1431 myDrawString(g, tr("Display zoom: {0}", displayZoomLevel), 50, 155);
1432 myDrawString(g, tr("Pixel scale: {0}", getScaleFactor(currentZoomLevel)), 50, 170);
1433 myDrawString(g, tr("Best zoom: {0}", Math.log(getScaleFactor(1))/Math.log(2)/2+1), 50, 185);
1434 }*/
1435 }
1436
1437 /**
1438 * This isn't very efficient, but it is only used when the
1439 * user right-clicks on the map.
1440 */
1441 Tile getTileForPixelpos(int px, int py) {
1442 /*if (debug) {
1443 Main.debug("getTileForPixelpos("+px+", "+py+")");
1444 }*/
1445 MapView mv = Main.map.mapView;
1446 Point clicked = new Point(px, py);
1447 EastNorth topLeft = mv.getEastNorth(0, 0);
1448 EastNorth botRight = mv.getEastNorth(mv.getWidth(), mv.getHeight());
1449 int z = currentZoomLevel;
1450 TileSet ts = new TileSet(topLeft, botRight, z);
1451
1452 if (!ts.tooLarge()) {
1453 ts.loadAllTiles(false); // make sure there are tile objects for all tiles
1454 }
1455 Tile clickedTile = null;
1456 for (Tile t1 : ts.allExistingTiles()) {
1457 Tile t2 = tempCornerTile(t1);
1458 Rectangle r = new Rectangle(pixelPos(t1));
1459 r.add(pixelPos(t2));
1460 /*if (debug) {
1461 Main.debug("r: " + r + " clicked: " + clicked);
1462 }*/
1463 if (!r.contains(clicked)) {
1464 continue;
1465 }
1466 clickedTile = t1;
1467 break;
1468 }
1469 if (clickedTile == null)
1470 return null;
1471 /*Main.debug("Clicked on tile: " + clickedTile.getXtile() + " " + clickedTile.getYtile() +
1472 " currentZoomLevel: " + currentZoomLevel);*/
1473 return clickedTile;
1474 }
1475
1476 @Override
1477 public Action[] getMenuEntries() {
1478 return new Action[] {
1479 LayerListDialog.getInstance().createShowHideLayerAction(),
1480 LayerListDialog.getInstance().createDeleteLayerAction(),
1481 SeparatorLayerAction.INSTANCE,
1482 // color,
1483 new OffsetAction(),
1484 new RenameLayerAction(this.getAssociatedFile(), this),
1485 SeparatorLayerAction.INSTANCE,
1486 new LayerListPopup.InfoAction(this) };
1487 }
1488
1489 @Override
1490 public String getToolTipText() {
1491 return tr("TMS layer ({0}), downloading in zoom {1}", getName(), currentZoomLevel);
1492 }
1493
1494 @Override
1495 public void visitBoundingBox(BoundingXYVisitor v) {
1496 }
1497
1498 @Override
1499 public boolean isChanged() {
1500 return needRedraw;
1501 }
1502
1503 @Override
1504 public boolean isProjectionSupported(Projection proj) {
1505 return "EPSG:3857".equals(proj.toCode()) || "EPSG:4326".equals(proj.toCode());
1506 }
1507
1508 @Override
1509 public String nameSupportedProjections() {
1510 return tr("EPSG:4326 and Mercator projection are supported");
1511 }
1512}
Note: See TracBrowser for help on using the repository browser.