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

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

see #8465 - global use of try-with-resources, according to

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