001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.layer;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.awt.BasicStroke;
008import java.awt.Color;
009import java.awt.Component;
010import java.awt.Dimension;
011import java.awt.Font;
012import java.awt.Graphics;
013import java.awt.Graphics2D;
014import java.awt.GridBagConstraints;
015import java.awt.GridBagLayout;
016import java.awt.Image;
017import java.awt.Rectangle;
018import java.awt.Shape;
019import java.awt.Stroke;
020import java.awt.Toolkit;
021import java.awt.event.ActionEvent;
022import java.awt.event.MouseAdapter;
023import java.awt.event.MouseEvent;
024import java.awt.geom.AffineTransform;
025import java.awt.geom.Point2D;
026import java.awt.geom.Rectangle2D;
027import java.awt.image.BufferedImage;
028import java.awt.image.ImageObserver;
029import java.io.File;
030import java.io.IOException;
031import java.net.MalformedURLException;
032import java.net.URI;
033import java.net.URISyntaxException;
034import java.time.Instant;
035import java.util.ArrayList;
036import java.util.Arrays;
037import java.util.Collection;
038import java.util.Collections;
039import java.util.Comparator;
040import java.util.LinkedList;
041import java.util.List;
042import java.util.Map;
043import java.util.Map.Entry;
044import java.util.Objects;
045import java.util.Set;
046import java.util.TreeSet;
047import java.util.concurrent.ConcurrentHashMap;
048import java.util.concurrent.ConcurrentSkipListSet;
049import java.util.concurrent.atomic.AtomicInteger;
050import java.util.function.Consumer;
051import java.util.function.Function;
052import java.util.stream.Collectors;
053import java.util.stream.IntStream;
054import java.util.stream.Stream;
055
056import javax.swing.AbstractAction;
057import javax.swing.Action;
058import javax.swing.JLabel;
059import javax.swing.JMenu;
060import javax.swing.JMenuItem;
061import javax.swing.JOptionPane;
062import javax.swing.JPanel;
063import javax.swing.JPopupMenu;
064import javax.swing.JSeparator;
065import javax.swing.Timer;
066
067import org.openstreetmap.gui.jmapviewer.AttributionSupport;
068import org.openstreetmap.gui.jmapviewer.MemoryTileCache;
069import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
070import org.openstreetmap.gui.jmapviewer.Tile;
071import org.openstreetmap.gui.jmapviewer.TileRange;
072import org.openstreetmap.gui.jmapviewer.TileXY;
073import org.openstreetmap.gui.jmapviewer.interfaces.CachedTileLoader;
074import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
075import org.openstreetmap.gui.jmapviewer.interfaces.IProjected;
076import org.openstreetmap.gui.jmapviewer.interfaces.TemplatedTileSource;
077import org.openstreetmap.gui.jmapviewer.interfaces.TileCache;
078import org.openstreetmap.gui.jmapviewer.interfaces.TileLoader;
079import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
080import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
081import org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource;
082import org.openstreetmap.josm.actions.AutoScaleAction;
083import org.openstreetmap.josm.actions.ExpertToggleAction;
084import org.openstreetmap.josm.actions.ImageryAdjustAction;
085import org.openstreetmap.josm.actions.RenameLayerAction;
086import org.openstreetmap.josm.actions.SaveActionBase;
087import org.openstreetmap.josm.data.Bounds;
088import org.openstreetmap.josm.data.ProjectionBounds;
089import org.openstreetmap.josm.data.coor.EastNorth;
090import org.openstreetmap.josm.data.coor.LatLon;
091import org.openstreetmap.josm.data.imagery.CoordinateConversion;
092import org.openstreetmap.josm.data.imagery.ImageryInfo;
093import org.openstreetmap.josm.data.imagery.OffsetBookmark;
094import org.openstreetmap.josm.data.imagery.TMSCachedTileLoader;
095import org.openstreetmap.josm.data.imagery.TileLoaderFactory;
096import org.openstreetmap.josm.data.imagery.vectortile.VectorTile;
097import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
098import org.openstreetmap.josm.data.preferences.BooleanProperty;
099import org.openstreetmap.josm.data.preferences.IntegerProperty;
100import org.openstreetmap.josm.data.preferences.NamedColorProperty;
101import org.openstreetmap.josm.data.projection.Projection;
102import org.openstreetmap.josm.data.projection.ProjectionRegistry;
103import org.openstreetmap.josm.data.projection.Projections;
104import org.openstreetmap.josm.gui.ExtendedDialog;
105import org.openstreetmap.josm.gui.MainApplication;
106import org.openstreetmap.josm.gui.MapView;
107import org.openstreetmap.josm.gui.NavigatableComponent;
108import org.openstreetmap.josm.gui.NavigatableComponent.ZoomChangeListener;
109import org.openstreetmap.josm.gui.Notification;
110import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
111import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
112import org.openstreetmap.josm.gui.io.importexport.WMSLayerImporter;
113import org.openstreetmap.josm.gui.layer.imagery.AutoLoadTilesAction;
114import org.openstreetmap.josm.gui.layer.imagery.AutoZoomAction;
115import org.openstreetmap.josm.gui.layer.imagery.DecreaseZoomAction;
116import org.openstreetmap.josm.gui.layer.imagery.FlushTileCacheAction;
117import org.openstreetmap.josm.gui.layer.imagery.ImageryFilterSettings.FilterChangeListener;
118import org.openstreetmap.josm.gui.layer.imagery.IncreaseZoomAction;
119import org.openstreetmap.josm.gui.layer.imagery.LoadAllTilesAction;
120import org.openstreetmap.josm.gui.layer.imagery.LoadErroneousTilesAction;
121import org.openstreetmap.josm.gui.layer.imagery.MVTLayer;
122import org.openstreetmap.josm.gui.layer.imagery.ReprojectionTile;
123import org.openstreetmap.josm.gui.layer.imagery.ShowErrorsAction;
124import org.openstreetmap.josm.gui.layer.imagery.ShowTileBordersAction;
125import org.openstreetmap.josm.gui.layer.imagery.TileAnchor;
126import org.openstreetmap.josm.gui.layer.imagery.TileCoordinateConverter;
127import org.openstreetmap.josm.gui.layer.imagery.TilePosition;
128import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings;
129import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings.DisplaySettingsChangeEvent;
130import org.openstreetmap.josm.gui.layer.imagery.TileSourceDisplaySettings.DisplaySettingsChangeListener;
131import org.openstreetmap.josm.gui.layer.imagery.ZoomToBestAction;
132import org.openstreetmap.josm.gui.layer.imagery.ZoomToNativeLevelAction;
133import org.openstreetmap.josm.gui.progress.ProgressMonitor;
134import org.openstreetmap.josm.gui.util.GuiHelper;
135import org.openstreetmap.josm.tools.GBC;
136import org.openstreetmap.josm.tools.HttpClient;
137import org.openstreetmap.josm.tools.Logging;
138import org.openstreetmap.josm.tools.MemoryManager;
139import org.openstreetmap.josm.tools.MemoryManager.MemoryHandle;
140import org.openstreetmap.josm.tools.MemoryManager.NotEnoughMemoryException;
141import org.openstreetmap.josm.tools.TextUtils;
142import org.openstreetmap.josm.tools.Utils;
143import org.openstreetmap.josm.tools.bugreport.BugReport;
144
145/**
146 * Base abstract class that supports displaying images provided by TileSource. It might be TMS source, WMS or WMTS
147 * It implements all standard functions of tilesource based layers: autozoom, tile reloads, layer saving, loading,etc.
148 *
149 * @author Upliner
150 * @author Wiktor Niesiobędzki
151 * @param <T> Tile Source class used for this layer
152 * @since 3715
153 * @since 8526 (copied from TMSLayer)
154 */
155public abstract class AbstractTileSourceLayer<T extends AbstractTMSTileSource> extends ImageryLayer
156implements ImageObserver, TileLoaderListener, ZoomChangeListener, FilterChangeListener, DisplaySettingsChangeListener {
157    private static final String PREFERENCE_PREFIX = "imagery.generic";
158    private static final int MAX_TILES_SPANNED = 40;
159    static { // Registers all setting properties
160        new TileSourceDisplaySettings();
161    }
162
163    /** maximum zoom level supported */
164    public static final int MAX_ZOOM = 30;
165    /** minimum zoom level supported */
166    public static final int MIN_ZOOM = 2;
167    private static final Font InfoFont = new Font("sansserif", Font.BOLD, 13);
168
169    /** additional layer menu actions */
170    private static final List<MenuAddition> menuAdditions = new LinkedList<>();
171
172    /** minimum zoom level to show to user */
173    public static final IntegerProperty PROP_MIN_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".min_zoom_lvl", 2);
174    /** maximum zoom level to show to user */
175    public static final IntegerProperty PROP_MAX_ZOOM_LVL = new IntegerProperty(PREFERENCE_PREFIX + ".max_zoom_lvl", 20);
176
177    //public static final BooleanProperty PROP_DRAW_DEBUG = new BooleanProperty(PREFERENCE_PREFIX + ".draw_debug", false);
178    /** Zoomlevel at which tiles is currently downloaded. Initial zoom lvl is set to bestZoom */
179    private int currentZoomLevel;
180    /** Zoom level the tiles were actually displayed at (auto-zoom fallback) for attribution */
181    private int lastDisplayZoomLevel;
182
183    private final AttributionSupport attribution = new AttributionSupport();
184
185    /**
186     * Offset between calculated zoom level and zoom level used to download and show tiles. Negative values will result in
187     * lower resolution of imagery useful in "retina" displays, positive values will result in higher resolution
188     */
189    public static final IntegerProperty ZOOM_OFFSET = new IntegerProperty(PREFERENCE_PREFIX + ".zoom_offset", 0);
190
191    private static final BooleanProperty POPUP_MENU_ENABLED = new BooleanProperty(PREFERENCE_PREFIX + ".popupmenu", true);
192    /** Color of the border drawn around each tile if enabled, see {@link TileSourceDisplaySettings#isShowTileBorders()} */
193    private static final NamedColorProperty TILE_BORDER_COLOR = new NamedColorProperty(marktr("imagery tile border"), new Color(0, 0, 0, 96));
194    private static final Stroke TILE_BORDER_STROKE = new BasicStroke(1f);
195    private static final String ERROR_STRING = marktr("Error");
196
197    /*
198     *  use MemoryTileCache instead of tileLoader JCS cache, as tileLoader caches only content (byte[] of image)
199     *  and MemoryTileCache caches whole Tile. This gives huge performance improvement when a lot of tiles are visible
200     *  in MapView (for example - when limiting min zoom in imagery)
201     *
202     *  Use per-layer tileCache instance, as the more layers there are, the more tiles needs to be cached
203     */
204    protected TileCache tileCache; // initialized together with tileSource
205    protected T tileSource;
206    protected TileLoader tileLoader;
207
208    /** A timer that is used to delay invalidation events if required. */
209    private final Timer invalidateLaterTimer = new Timer(100, e -> this.invalidate());
210
211    // keys of the tiles which failed to load and have not been loaded successfully since
212    private final Set<String> failedTiles = ConcurrentHashMap.newKeySet();
213
214    private final MouseAdapter adapter = new MouseAdapter() {
215        @Override
216        public void mouseClicked(MouseEvent e) {
217            if (!isVisible()) return;
218            if (e.getButton() == MouseEvent.BUTTON3) {
219                Component component = e.getComponent();
220                if (Boolean.TRUE.equals(POPUP_MENU_ENABLED.get()) && component.isShowing()) {
221                    new TileSourceLayerPopup(e.getX(), e.getY()).show(component, e.getX(), e.getY());
222                }
223            } else if (e.getButton() == MouseEvent.BUTTON1) {
224                attribution.handleAttribution(e.getPoint(), true);
225            }
226        }
227    };
228
229    private final TileSourceDisplaySettings displaySettings = createDisplaySettings();
230
231    private final ImageryAdjustAction adjustAction = new ImageryAdjustAction(this);
232    // prepared to be moved to the painter
233    protected TileCoordinateConverter coordinateConverter;
234    private final long minimumTileExpire;
235
236    /**
237     * Creates Tile Source based Imagery Layer based on Imagery Info
238     * @param info imagery info
239     */
240    protected AbstractTileSourceLayer(ImageryInfo info) {
241        super(info);
242        setBackgroundLayer(true);
243        this.setVisible(true);
244        getFilterSettings().addFilterChangeListener(this);
245        getDisplaySettings().addSettingsChangeListener(this);
246        this.minimumTileExpire = info.getMinimumTileExpire();
247    }
248
249    /**
250     * This method creates the {@link TileSourceDisplaySettings} object. Subclasses may implement it to e.g. change the prefix.
251     * @return The object.
252     * @since 10568
253     */
254    protected TileSourceDisplaySettings createDisplaySettings() {
255        return new TileSourceDisplaySettings();
256    }
257
258    /**
259     * Gets the {@link TileSourceDisplaySettings} instance associated with this tile source.
260     * @return The tile source display settings
261     * @since 10568
262     */
263    public TileSourceDisplaySettings getDisplaySettings() {
264        return displaySettings;
265    }
266
267    @Override
268    public void filterChanged() {
269        invalidate();
270    }
271
272    protected abstract TileLoaderFactory getTileLoaderFactory();
273
274    /**
275     * Get projections this imagery layer supports natively.
276     * <p>
277     * For example projection of tiles that are downloaded from a server. Layer may support even more
278     * projections (by reprojecting the tiles), but with a certain loss in image quality and performance.
279     * @return projections this imagery layer supports natively; null if layer is projection agnostic.
280     */
281    public abstract Collection<String> getNativeProjections();
282
283    /**
284     * Creates and returns a new {@link TileSource} instance depending on {@link #info} specified in the constructor.
285     *
286     * @return TileSource for specified ImageryInfo
287     * @throws IllegalArgumentException when Imagery is not supported by layer
288     */
289    protected abstract T getTileSource();
290
291    protected Map<String, String> getHeaders(T tileSource) {
292        if (tileSource instanceof TemplatedTileSource) {
293            return ((TemplatedTileSource) tileSource).getHeaders();
294        }
295        return null;
296    }
297
298    protected void initTileSource(T tileSource) {
299        coordinateConverter = new TileCoordinateConverter(MainApplication.getMap().mapView, tileSource, getDisplaySettings());
300        attribution.initialize(tileSource);
301
302        currentZoomLevel = getBestZoom();
303        lastDisplayZoomLevel = currentZoomLevel;
304
305        Map<String, String> headers = getHeaders(tileSource);
306
307        tileLoader = getTileLoaderFactory().makeTileLoader(this, headers, minimumTileExpire);
308
309        try {
310            if (tileSource.getBaseUrl() != null && "file".equalsIgnoreCase(new URI(tileSource.getBaseUrl()).toURL().getProtocol())) {
311                tileLoader = new OsmTileLoader(this);
312            }
313        } catch (URISyntaxException | MalformedURLException e) {
314            // ignore, assume that this is not a file
315            Logging.log(Logging.LEVEL_DEBUG, e);
316        }
317
318        if (tileLoader == null)
319            tileLoader = new OsmTileLoader(this, headers);
320
321        tileCache = new MemoryTileCache(estimateTileCacheSize());
322    }
323
324    @Override
325    public synchronized void tileLoadingFinished(Tile tile, boolean success) {
326        if (tile.hasError()) {
327            success = false;
328            tile.setImage(null);
329            failedTiles.add(tile.getKey());
330        } else if (success) {
331            failedTiles.remove(tile.getKey());
332        }
333        invalidateLater();
334        Logging.debug("tileLoadingFinished() tile: {0} success: {1}", tile, success);
335    }
336
337    /**
338     * Clears the tile cache.
339     */
340    public void clearTileCache() {
341        if (tileLoader instanceof CachedTileLoader) {
342            ((CachedTileLoader) tileLoader).clearCache(tileSource);
343        }
344        tileCache.clear();
345    }
346
347    @Override
348    public Object getInfoComponent() {
349        JPanel panel = (JPanel) super.getInfoComponent();
350        List<List<String>> content = new ArrayList<>();
351        Collection<String> nativeProjections = getNativeProjections();
352        if (nativeProjections != null) {
353            content.add(Arrays.asList(tr("Native projections"), String.join(", ", getNativeProjections())));
354        }
355        EastNorth offset = getDisplaySettings().getDisplacement();
356        if (offset.distanceSq(0, 0) > 1e-10) {
357            content.add(Arrays.asList(tr("Offset"), offset.east() + ";" + offset.north()));
358        }
359        if (coordinateConverter.requiresReprojection()) {
360            content.add(Arrays.asList(tr("Tile download projection"), tileSource.getServerCRS()));
361            content.add(Arrays.asList(tr("Tile display projection"), ProjectionRegistry.getProjection().toCode()));
362        }
363        content.add(Arrays.asList(tr("Current zoom"), Integer.toString(currentZoomLevel)));
364        for (List<String> entry: content) {
365            panel.add(new JLabel(entry.get(0) + ':'), GBC.std());
366            panel.add(GBC.glue(5, 0), GBC.std());
367            panel.add(createTextField(entry.get(1)), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
368        }
369        return panel;
370    }
371
372    @Override
373    protected Action getAdjustAction() {
374        return adjustAction;
375    }
376
377    /**
378     * Returns average number of screen pixels per tile pixel for current mapview
379     * @param zoom zoom level
380     * @return average number of screen pixels per tile pixel
381     */
382    public double getScaleFactor(int zoom) {
383        if (coordinateConverter != null) {
384            return coordinateConverter.getScaleFactor(zoom);
385        } else {
386            return 1;
387        }
388    }
389
390    /**
391     * Returns best zoom level.
392     * @return best zoom level
393     */
394    public int getBestZoom() {
395        double factor = getScaleFactor(1); // check the ratio between area of tilesize at zoom 1 to current view
396        double result = Math.log(factor)/Math.log(2)/2;
397        /*
398         * Math.log(factor)/Math.log(2) - gives log base 2 of factor
399         * We divide result by 2, as factor contains ratio between areas. We could do Math.sqrt before log, or just divide log by 2
400         *
401         * ZOOM_OFFSET controls, whether we work with overzoomed or underzoomed tiles. Positive ZOOM_OFFSET
402         * is for working with underzoomed tiles (higher quality when working with aerial imagery), negative ZOOM_OFFSET
403         * is for working with overzoomed tiles (big, pixelated), which is good when working with high-dpi screens and/or
404         * maps as a imagery layer
405         */
406        int intResult = (int) Math.round(result + 1 + ZOOM_OFFSET.get() / 1.9);
407        int minZoom = getMinZoomLvl();
408        int maxZoom = getMaxZoomLvl();
409        if (minZoom <= maxZoom) {
410            intResult = Utils.clamp(intResult, minZoom, maxZoom);
411        } else if (intResult > maxZoom) {
412            intResult = maxZoom;
413        }
414        return intResult;
415    }
416
417    /**
418     * Default implementation of {@link org.openstreetmap.josm.gui.layer.Layer.LayerAction#supportLayers(List)}.
419     * @param layers layers
420     * @return {@code true} is layers contains only a {@code TMSLayer}
421     */
422    public static boolean actionSupportLayers(List<Layer> layers) {
423        return layers.size() == 1 && layers.get(0) instanceof TMSLayer;
424    }
425
426    private abstract static class AbstractTileAction extends AbstractAction {
427
428        protected final AbstractTileSourceLayer<?> layer;
429        protected final Tile tile;
430
431        AbstractTileAction(String name, AbstractTileSourceLayer<?> layer, Tile tile) {
432            super(name);
433            this.layer = layer;
434            this.tile = tile;
435        }
436    }
437
438    private static final class ShowTileInfoAction extends AbstractTileAction {
439
440        private ShowTileInfoAction(AbstractTileSourceLayer<?> layer, Tile tile) {
441            super(tr("Show tile info"), layer, tile);
442            setEnabled(tile != null);
443        }
444
445        private static String getSizeString(int size) {
446            return Integer.toString(size) + 'x' + size;
447        }
448
449        @Override
450        public void actionPerformed(ActionEvent ae) {
451            if (tile != null) {
452                ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(), tr("Tile Info"), tr("OK"));
453                JPanel panel = new JPanel(new GridBagLayout());
454                Rectangle2D displaySize = layer.coordinateConverter.getRectangleForTile(tile);
455                String url = "";
456                try {
457                    url = TextUtils.stripUrl(tile.getUrl());
458                } catch (IOException e) {
459                    // silence exceptions
460                    Logging.trace(e);
461                }
462
463                List<List<String>> content = new ArrayList<>();
464                content.add(Arrays.asList(tr("Tile name"), tile.getKey()));
465                content.add(Arrays.asList(tr("Tile URL"), url));
466                if (tile.getTileSource() instanceof TemplatedTileSource) {
467                    Map<String, String> headers = ((TemplatedTileSource) tile.getTileSource()).getHeaders();
468                    for (String key: new TreeSet<>(headers.keySet())) {
469                        // iterate over sorted keys
470                        content.add(Arrays.asList(tr("Custom header: {0}", key), headers.get(key)));
471                    }
472                }
473                content.add(Arrays.asList(tr("Tile size"),
474                        getSizeString(tile.getTileSource().getTileSize())));
475                content.add(Arrays.asList(tr("Tile display size"),
476                        Double.toString(displaySize.getWidth()) +
477                                'x' +
478                                displaySize.getHeight()));
479                if (layer.coordinateConverter.requiresReprojection()) {
480                    content.add(Arrays.asList(tr("Reprojection"),
481                            tile.getTileSource().getServerCRS() +
482                            " -> " + ProjectionRegistry.getProjection().toCode()));
483                    BufferedImage img = tile.getImage();
484                    if (img != null) {
485                        content.add(Arrays.asList(tr("Reprojected tile size"),
486                            img.getWidth() + "x" + img.getHeight()));
487
488                    }
489                }
490                content.add(Arrays.asList(tr("Status"), tr(tile.getStatus())));
491                content.add(Arrays.asList(tr("Loaded"), tr(Boolean.toString(tile.isLoaded()))));
492                content.add(Arrays.asList(tr("Loading"), tr(Boolean.toString(tile.isLoading()))));
493                content.add(Arrays.asList(tr(ERROR_STRING), tr(Boolean.toString(tile.hasError()))));
494                for (List<String> entry: content) {
495                    panel.add(new JLabel(entry.get(0) + ':'), GBC.std());
496                    panel.add(GBC.glue(5, 0), GBC.std());
497                    panel.add(layer.createTextField(entry.get(1)), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
498                }
499
500                for (Entry<String, String> e: tile.getMetadata().entrySet()) {
501                    panel.add(new JLabel(tr("Metadata ") + tr(e.getKey()) + ':'), GBC.std());
502                    panel.add(GBC.glue(5, 0), GBC.std());
503                    String value = e.getValue();
504                    if ("lastModification".equals(e.getKey()) || "expirationTime".equals(e.getKey())) {
505                        value = Instant.ofEpochMilli(Long.parseLong(value)).toString();
506                    }
507                    panel.add(layer.createTextField(value), GBC.eol().fill(GridBagConstraints.HORIZONTAL));
508
509                }
510                ed.setIcon(JOptionPane.INFORMATION_MESSAGE);
511                ed.setContent(panel);
512                ed.showDialog();
513            }
514        }
515    }
516
517    private static final class LoadTileAction extends AbstractTileAction {
518
519        private LoadTileAction(AbstractTileSourceLayer<?> layer, Tile tile) {
520            super(tr("Load tile"), layer, tile);
521            setEnabled(tile != null);
522        }
523
524        @Override
525        public void actionPerformed(ActionEvent ae) {
526            if (tile != null) {
527                layer.loadTile(tile, true);
528                layer.invalidate();
529            }
530        }
531    }
532
533    private static void sendOsmTileRequest(Tile tile, String request) {
534        if (tile != null) {
535            try {
536                new Notification(HttpClient.create(new URI(tile.getUrl() + '/' + request).toURL())
537                        .connect().fetchContent()).setIcon(JOptionPane.INFORMATION_MESSAGE).show();
538            } catch (URISyntaxException | IOException ex) {
539                Logging.error(ex);
540            }
541        }
542    }
543
544    private static final class GetOsmTileStatusAction extends AbstractTileAction {
545        private GetOsmTileStatusAction(AbstractTileSourceLayer<?> layer, Tile tile) {
546            super(tr("Get tile status"), layer, tile);
547            setEnabled(tile != null);
548        }
549
550        @Override
551        public void actionPerformed(ActionEvent e) {
552            sendOsmTileRequest(tile, "status");
553        }
554    }
555
556    private static final class MarkOsmTileDirtyAction extends AbstractTileAction {
557        private MarkOsmTileDirtyAction(AbstractTileSourceLayer<?> layer, Tile tile) {
558            super(tr("Force tile rendering"), layer, tile);
559            setEnabled(tile != null);
560        }
561
562        @Override
563        public void actionPerformed(ActionEvent e) {
564            sendOsmTileRequest(tile, "dirty");
565        }
566    }
567
568    /**
569     * Creates popup menu items and binds to mouse actions
570     */
571    @Override
572    public void hookUpMapView() {
573        // this needs to be here and not in constructor to allow empty TileSource class construction using SessionWriter
574        initializeIfRequired();
575        super.hookUpMapView();
576    }
577
578    @Override
579    public LayerPainter attachToMapView(MapViewEvent event) {
580        initializeIfRequired();
581
582        event.getMapView().addMouseListener(adapter);
583        NavigatableComponent.addZoomChangeListener(this);
584
585        if (this instanceof NativeScaleLayer && Boolean.TRUE.equals(NavigatableComponent.PROP_ZOOM_SCALE_FOLLOW_NATIVE_RES_AT_LOAD.get())) {
586            event.getMapView().setNativeScaleLayer((NativeScaleLayer) this);
587        }
588
589        // FIXME: why do we need this? Without this, if you add a WMS layer and do not move the mouse, sometimes, tiles do not start loading.
590        // FIXME: Check if this is still required.
591        event.getMapView().repaint(500);
592
593        return super.attachToMapView(event);
594    }
595
596    private void initializeIfRequired() {
597        if (tileSource == null) {
598            tileSource = getTileSource();
599            if (tileSource == null) {
600                throw new IllegalArgumentException(tr("Failed to create tile source"));
601            }
602            // check if projection is supported
603            projectionChanged(null, ProjectionRegistry.getProjection());
604            initTileSource(this.tileSource);
605        }
606    }
607
608    @Override
609    protected LayerPainter createMapViewPainter(MapViewEvent event) {
610        return new TileSourcePainter();
611    }
612
613    /**
614     * Tile source layer popup menu.
615     */
616    public class TileSourceLayerPopup extends JPopupMenu {
617        /**
618         * Constructs a new {@code TileSourceLayerPopup}.
619         * @param x horizontal dimension where user clicked
620         * @param y vertical dimension where user clicked
621         */
622        public TileSourceLayerPopup(int x, int y) {
623            List<JMenu> submenus = new ArrayList<>();
624            MainApplication.getLayerManager().getVisibleLayersInZOrder().stream()
625            .filter(AbstractTileSourceLayer.class::isInstance)
626            .map(AbstractTileSourceLayer.class::cast)
627            .forEachOrdered(layer -> {
628                JMenu submenu = new JMenu(layer.getName());
629                for (Action a : layer.getCommonEntries()) {
630                    if (a instanceof LayerAction) {
631                        submenu.add(((LayerAction) a).createMenuComponent());
632                    } else {
633                        submenu.add(new JMenuItem(a));
634                    }
635                }
636                submenu.add(new JSeparator());
637                Tile tile = layer.getTileForPixelpos(x, y);
638                submenu.add(new JMenuItem(new LoadTileAction(layer, tile)));
639                submenu.add(new JMenuItem(new ShowTileInfoAction(layer, tile)));
640                if (ExpertToggleAction.isExpert() && tileSource != null && tileSource.isModTileFeatures()) {
641                    submenu.add(new JMenuItem(new GetOsmTileStatusAction(layer, tile)));
642                    submenu.add(new JMenuItem(new MarkOsmTileDirtyAction(layer, tile)));
643                }
644                submenus.add(submenu);
645            });
646
647            if (submenus.size() == 1) {
648                JMenu menu = submenus.get(0);
649                Arrays.stream(menu.getMenuComponents()).forEachOrdered(this::add);
650            } else if (submenus.size() > 1) {
651                submenus.stream().forEachOrdered(this::add);
652            }
653        }
654    }
655
656    protected int estimateTileCacheSize() {
657        Dimension screenSize = GuiHelper.getMaximumScreenSize();
658        int height = screenSize.height;
659        int width = screenSize.width;
660        int tileSize = 256; // default tile size
661        if (tileSource != null) {
662            tileSize = tileSource.getTileSize();
663        }
664        /*
665         * As we can see part of the tile at the top and at the bottom, use Math.ceil(...) + 1 to accommodate for that
666         */
667        int maxYtiles = (int) Math.ceil((double) height / tileSize + 1);
668        int maxXtiles = (int) Math.ceil((double) width / tileSize + 1);
669        int visibleTiles = maxXtiles * maxYtiles;
670
671        int ret = calculateRealTiles(visibleTiles, maxXtiles, maxYtiles);
672        Logging.info("AbstractTileSourceLayer: estimated visible tiles: {0}, estimated cache size: {1}", visibleTiles, ret);
673        return ret;
674    }
675
676    /**
677     * Take into account ZOOM_OFFSET to calculate real number of tiles and multiply by 7, to cover all tiles, that might be
678     * accessed when looking for tiles outside current zoom level.
679     * <p>
680     * Currently we use otherZooms = {1, 2, -1, -2, -3, -4, -5}
681     * <p>
682     * The value should be sum(2^x for x in (-5 to 2)) - 1
683     * -1 to exclude current zoom level
684     * <p>
685     * Add +2 to maxYtiles / maxXtiles to add space in cache for extra tiles in current zoom level that are
686     * download by overloadTiles(). This is not added in computation of visibleTiles as this unnecessarily grow the cache size
687     * <p>
688     * Check call to tryLoadFromDifferentZoom
689     * @param visibleTiles number of currently visible tiles
690     * @param maxXtiles maximum number of tiles along the horizontal (X) axis
691     * @param maxYtiles maximum number of tiles along the vertical (Y) axis
692     * @return estimated total number of tiles to load across zoom levels and borders
693     * @see #tryLoadFromDifferentZoom(Graphics2D, int, List, int)
694     * @see #drawInViewArea(Graphics2D, MapView, ProjectionBounds)
695     * @see AbstractTileSourceLayer.TileSet#overloadTiles()
696     */
697    private static int calculateRealTiles(int visibleTiles, int maxXtiles, int maxYtiles) {
698        return (int) Math.ceil(
699                Math.pow(2d, ZOOM_OFFSET.get()) * // use offset to decide, how many tiles are visible
700                        visibleTiles * 7 + // 7 to cover tiles from other zooms as described above
701                        ((maxYtiles + 2) * (maxXtiles +2))); // to add as many tiles as they will be accessed on current zoom level
702    }
703
704    @Override
705    public void displaySettingsChanged(DisplaySettingsChangeEvent e) {
706        if (tileSource == null) {
707            return;
708        }
709        switch (e.getChangedSetting()) {
710        case TileSourceDisplaySettings.AUTO_ZOOM:
711            if (getDisplaySettings().isAutoZoom() && getBestZoom() != currentZoomLevel) {
712                setZoomLevel(getBestZoom());
713                invalidate();
714            }
715            break;
716        case TileSourceDisplaySettings.AUTO_LOAD:
717            if (getDisplaySettings().isAutoLoad()) {
718                invalidate();
719            }
720            break;
721        default:
722            // e.g. displacement
723            // trigger a redraw in every case
724            invalidate();
725        }
726    }
727
728    /**
729     * Checks zoom level against settings
730     * @param maxZoomLvl zoom level to check
731     * @param ts tile source to crosscheck with
732     * @return maximum zoom level, not higher than supported by tilesource nor set by the user
733     */
734    public static int checkMaxZoomLvl(int maxZoomLvl, TileSource ts) {
735        if (maxZoomLvl > MAX_ZOOM) {
736            maxZoomLvl = MAX_ZOOM;
737        }
738        if (maxZoomLvl < PROP_MIN_ZOOM_LVL.get()) {
739            maxZoomLvl = PROP_MIN_ZOOM_LVL.get();
740        }
741        if (ts != null && ts.getMaxZoom() != 0 && ts.getMaxZoom() < maxZoomLvl) {
742            maxZoomLvl = ts.getMaxZoom();
743        }
744        return maxZoomLvl;
745    }
746
747    /**
748     * Checks zoom level against settings
749     * @param minZoomLvl zoom level to check
750     * @param ts tile source to crosscheck with
751     * @return minimum zoom level, not higher than supported by tilesource nor set by the user
752     */
753    public static int checkMinZoomLvl(int minZoomLvl, TileSource ts) {
754        if (minZoomLvl < MIN_ZOOM) {
755            minZoomLvl = MIN_ZOOM;
756        }
757        if (minZoomLvl > PROP_MAX_ZOOM_LVL.get()) {
758            minZoomLvl = getMaxZoomLvl(ts);
759        }
760        if (ts != null && ts.getMinZoom() > minZoomLvl) {
761            minZoomLvl = ts.getMinZoom();
762        }
763        return minZoomLvl;
764    }
765
766    /**
767     * Returns maximum max zoom level, that will be shown on layer.
768     * @param ts TileSource for which we want to know maximum zoom level
769     * @return maximum max zoom level, that will be shown on layer
770     */
771    public static int getMaxZoomLvl(TileSource ts) {
772        return checkMaxZoomLvl(PROP_MAX_ZOOM_LVL.get(), ts);
773    }
774
775    /**
776     * Returns minimum zoom level, that will be shown on layer.
777     * @param ts TileSource for which we want to know minimum zoom level
778     * @return minimum zoom level, that will be shown on layer
779     */
780    public static int getMinZoomLvl(TileSource ts) {
781        return checkMinZoomLvl(PROP_MIN_ZOOM_LVL.get(), ts);
782    }
783
784    /**
785     * Sets maximum zoom level, that layer will attempt show
786     * @param maxZoomLvl maximum zoom level
787     */
788    public static void setMaxZoomLvl(int maxZoomLvl) {
789        PROP_MAX_ZOOM_LVL.put(checkMaxZoomLvl(maxZoomLvl, null));
790    }
791
792    /**
793     * Sets minimum zoom level, that layer will attempt show
794     * @param minZoomLvl minimum zoom level
795     */
796    public static void setMinZoomLvl(int minZoomLvl) {
797        PROP_MIN_ZOOM_LVL.put(checkMinZoomLvl(minZoomLvl, null));
798    }
799
800    /**
801     * This fires every time the user changes the zoom, but also (due to ZoomChangeListener) - on all
802     * changes to visible map (panning/zooming)
803     */
804    @Override
805    public void zoomChanged() {
806        zoomChanged(true);
807    }
808
809    private void zoomChanged(boolean invalidate) {
810        Logging.debug("zoomChanged(): {0}", currentZoomLevel);
811        if (tileLoader instanceof TMSCachedTileLoader) {
812            tileLoader.cancelOutstandingTasks();
813        }
814        if (invalidate) {
815            invalidate();
816        }
817    }
818
819    protected int getMaxZoomLvl() {
820        if (info.getMaxZoom() != 0)
821            return checkMaxZoomLvl(info.getMaxZoom(), tileSource);
822        else
823            return getMaxZoomLvl(tileSource);
824    }
825
826    protected int getMinZoomLvl() {
827        if (info.getMinZoom() != 0)
828            return checkMinZoomLvl(info.getMinZoom(), tileSource);
829        else
830            return getMinZoomLvl(tileSource);
831    }
832
833    /**
834     * Determines if it is allowed to zoom in.
835     * @return if it is allowed to zoom in
836     */
837    public boolean zoomIncreaseAllowed() {
838        boolean zia = currentZoomLevel < this.getMaxZoomLvl();
839        Logging.debug("zoomIncreaseAllowed(): {0} {1} vs. {2}", zia, currentZoomLevel, this.getMaxZoomLvl());
840        return zia;
841    }
842
843    /**
844     * Zoom in, go closer to map.
845     *
846     * @return    true, if zoom increasing was successful, false otherwise
847     */
848    public boolean increaseZoomLevel() {
849        if (zoomIncreaseAllowed()) {
850            currentZoomLevel++;
851            Logging.debug("increasing zoom level to: {0}", currentZoomLevel);
852            zoomChanged();
853        } else {
854            Logging.warn("Current zoom level ("+currentZoomLevel+") could not be increased. "+
855                    "Max.zZoom Level "+this.getMaxZoomLvl()+" reached.");
856            return false;
857        }
858        return true;
859    }
860
861    /**
862     * Get the current zoom level of the layer
863     * @return the current zoom level
864     * @since 12603
865     */
866    public int getZoomLevel() {
867        return currentZoomLevel;
868    }
869
870    /**
871     * Sets the zoom level of the layer
872     * @param zoom zoom level
873     * @return true, when zoom has changed to desired value, false if it was outside supported zoom levels
874     */
875    public boolean setZoomLevel(int zoom) {
876        return setZoomLevel(zoom, true);
877    }
878
879    private boolean setZoomLevel(int zoom, boolean invalidate) {
880        if (zoom == currentZoomLevel) return true;
881        if (zoom > this.getMaxZoomLvl()) return false;
882        if (zoom < this.getMinZoomLvl()) return false;
883        currentZoomLevel = zoom;
884        zoomChanged(invalidate);
885        return true;
886    }
887
888    /**
889     * Check if zooming out is allowed
890     *
891     * @return    true, if zooming out is allowed (currentZoomLevel &gt; minZoomLevel)
892     */
893    public boolean zoomDecreaseAllowed() {
894        boolean zda = currentZoomLevel > this.getMinZoomLvl();
895        Logging.debug("zoomDecreaseAllowed(): {0} {1} vs. {2}", zda, currentZoomLevel, this.getMinZoomLvl());
896        return zda;
897    }
898
899    /**
900     * Zoom out from map.
901     *
902     * @return    true, if zoom increasing was successful, false otherwise
903     */
904    public boolean decreaseZoomLevel() {
905        if (zoomDecreaseAllowed()) {
906            Logging.debug("decreasing zoom level to: {0}", currentZoomLevel);
907            currentZoomLevel--;
908            zoomChanged();
909        } else {
910            return false;
911        }
912        return true;
913    }
914
915    private Tile getOrCreateTile(TilePosition tilePosition) {
916        return getOrCreateTile(tilePosition.getX(), tilePosition.getY(), tilePosition.getZoom());
917    }
918
919    private Tile getOrCreateTile(int x, int y, int zoom) {
920        Tile tile = getTile(x, y, zoom);
921        if (tile == null) {
922            if (coordinateConverter.requiresReprojection()) {
923                tile = new ReprojectionTile(createTile(tileSource, x, y, zoom));
924            } else {
925                tile = createTile(tileSource, x, y, zoom);
926            }
927            tileCache.addTile(tile);
928        }
929        return tile;
930    }
931
932    private Tile getTile(TilePosition tilePosition) {
933        return getTile(tilePosition.getX(), tilePosition.getY(), tilePosition.getZoom());
934    }
935
936    /**
937     * Returns tile at given position.
938     * This can and will return null for tiles that are not already in the cache.
939     * @param x tile number on the x axis of the tile to be retrieved
940     * @param y tile number on the y axis of the tile to be retrieved
941     * @param zoom zoom level of the tile to be retrieved
942     * @return tile at given position
943     */
944    private Tile getTile(int x, int y, int zoom) {
945        if (x < tileSource.getTileXMin(zoom) || x > tileSource.getTileXMax(zoom)
946         || y < tileSource.getTileYMin(zoom) || y > tileSource.getTileYMax(zoom))
947            return null;
948        return tileCache.getTile(tileSource, x, y, zoom);
949    }
950
951    private boolean loadTile(Tile tile, boolean force) {
952        if (tile == null)
953            return false;
954        if (!force && tile.isLoaded())
955            return false;
956        if (tile.isLoading())
957            return false;
958        tileLoader.createTileLoaderJob(tile).submit(force);
959        return true;
960    }
961
962    private TileSet getVisibleTileSet() {
963        if (!MainApplication.isDisplayingMapView())
964            return new TileSet();
965        ProjectionBounds bounds = MainApplication.getMap().mapView.getProjectionBounds();
966        return getTileSet(bounds, currentZoomLevel);
967    }
968
969    /**
970     * Load all visible tiles.
971     * @param force {@code true} to force loading if auto-load is disabled
972     * @since 11950
973     */
974    public void loadAllTiles(boolean force) {
975        TileSet ts = getVisibleTileSet();
976        ts.loadAllTiles(force);
977        invalidate();
978    }
979
980    /**
981     * Load all visible tiles in error.
982     * @param force {@code true} to force loading if auto-load is disabled
983     * @since 11950
984     */
985    public void loadAllErrorTiles(boolean force) {
986        TileSet ts = getVisibleTileSet();
987        ts.loadAllErrorTiles(force);
988        invalidate();
989    }
990
991    /**
992     * Remove all cached error tiles
993     * @since 19192
994     */
995    public void clearErrorTiles() {
996        tileCache.clearErrorTiles();
997        invalidate();
998    }
999
1000    @Override
1001    public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
1002        boolean done = (infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0;
1003        Logging.debug("imageUpdate() done: {0} calling repaint", done);
1004
1005        if (done) {
1006            invalidate();
1007        } else {
1008            invalidateLater();
1009        }
1010        return !done;
1011    }
1012
1013    /**
1014     * Invalidate the layer at a time in the future so that the user still sees the interface responsive.
1015     */
1016    private void invalidateLater() {
1017        GuiHelper.runInEDT(() -> {
1018            if (!invalidateLaterTimer.isRunning()) {
1019                invalidateLaterTimer.setRepeats(false);
1020                invalidateLaterTimer.start();
1021            }
1022        });
1023    }
1024
1025    private boolean imageLoaded(Image i) {
1026        if (i == null)
1027            return false;
1028        int status = Toolkit.getDefaultToolkit().checkImage(i, -1, -1, this);
1029        return (status & ALLBITS) != 0;
1030    }
1031
1032    /**
1033     * Returns the image for the given tile image is loaded.
1034     * Otherwise returns  null.
1035     *
1036     * @param tile the Tile for which the image should be returned
1037     * @return  the image of the tile or null.
1038     */
1039    private BufferedImage getLoadedTileImage(Tile tile) {
1040        BufferedImage img = tile.getImage();
1041        if (!imageLoaded(img))
1042            return null;
1043        return img;
1044    }
1045
1046    /**
1047     * Draw a tile image on screen.
1048     * @param g the Graphics2D
1049     * @param toDrawImg tile image
1050     * @param anchorImage tile anchor in image coordinates
1051     * @param anchorScreen tile anchor in screen coordinates
1052     * @param clip clipping region in screen coordinates (can be null)
1053     */
1054    private void drawImageInside(Graphics2D g, BufferedImage toDrawImg, TileAnchor anchorImage, TileAnchor anchorScreen, Shape clip) {
1055        AffineTransform imageToScreen = anchorImage.convert(anchorScreen);
1056        Point2D screen0 = imageToScreen.transform(new Point2D.Double(0, 0), null);
1057        Point2D screen1 = imageToScreen.transform(new Point2D.Double(
1058                toDrawImg.getWidth(), toDrawImg.getHeight()), null);
1059
1060        Shape oldClip = null;
1061        if (clip != null) {
1062            oldClip = g.getClip();
1063            g.clip(clip);
1064        }
1065        g.drawImage(toDrawImg, (int) Math.round(screen0.getX()), (int) Math.round(screen0.getY()),
1066                (int) Math.round(screen1.getX()) - (int) Math.round(screen0.getX()),
1067                (int) Math.round(screen1.getY()) - (int) Math.round(screen0.getY()), this);
1068        if (clip != null) {
1069            g.setClip(oldClip);
1070        }
1071    }
1072
1073    private List<Tile> paintTileImages(Graphics2D g, TileSet ts) {
1074        Object paintMutex = new Object();
1075        List<TilePosition> missed = Collections.synchronizedList(new ArrayList<>());
1076        ts.visitTiles(tile -> {
1077            boolean miss = false;
1078            BufferedImage img = null;
1079            TileAnchor anchorImage = null;
1080            if (!tile.isLoaded() || tile.hasError()) {
1081                miss = true;
1082            } else {
1083                synchronized (tile) {
1084                    img = getLoadedTileImage(tile);
1085                    anchorImage = getAnchor(tile, img);
1086                }
1087                if (img == null || anchorImage == null || (tile instanceof VectorTile && !tile.isLoaded())) {
1088                    miss = true;
1089                }
1090            }
1091            if (miss) {
1092                missed.add(new TilePosition(tile));
1093                return;
1094            }
1095
1096            if (img != null) {
1097                img = applyImageProcessors(img);
1098            }
1099
1100            TileAnchor anchorScreen = coordinateConverter.getScreenAnchorForTile(tile);
1101            synchronized (paintMutex) {
1102                //cannot paint in parallel
1103                drawImageInside(g, img, anchorImage, anchorScreen, null);
1104            }
1105            MapView mapView = MainApplication.getMap().mapView;
1106            if (tile instanceof ReprojectionTile && ((ReprojectionTile) tile).needsUpdate(mapView.getScale())) {
1107                // This means we have a reprojected tile in memory cache, but not at
1108                // current scale. Generally, the positioning of the tile will still
1109                // be correct, but for best image quality, the tile should be
1110                // reprojected to the target scale. The original tile image should
1111                // still be in disk cache, so this is fairly cheap.
1112                ((ReprojectionTile) tile).invalidate();
1113                loadTile(tile, false);
1114            }
1115
1116        }, missed::add);
1117
1118        return missed.stream().map(this::getOrCreateTile).collect(Collectors.toList());
1119    }
1120
1121    // This function is called for several zoom levels, not just the current one.
1122    // It should not trigger any tiles to be downloaded.
1123    // It should also avoid polluting the tile cache with any tiles since these tiles are not mandatory.
1124    //
1125    // The "border" tile tells us the boundaries of where we may drawn.
1126    // It will not be from the zoom level that is being drawn currently.
1127    // If drawing the displayZoomLevel, border is null and we draw the entire tile set.
1128    private List<Tile> paintTileImages(Graphics2D g, TileSet ts, int zoom, Tile border) {
1129        if (zoom <= 0) return Collections.emptyList();
1130        Shape borderClip = coordinateConverter.getTileShapeScreen(border);
1131        List<Tile> missedTiles = new LinkedList<>();
1132        // The callers of this code *require* that we return any tiles that we do not draw in missedTiles.
1133        // ts.allExistingTiles() by default will only return already-existing tiles.
1134        // However, we need to return *all* tiles to the callers, so force creation here.
1135        for (Tile tile : ts.allTilesCreate()) {
1136            boolean miss = false;
1137            BufferedImage img = null;
1138            TileAnchor anchorImage = null;
1139            if (!tile.isLoaded() || tile.hasError()) {
1140                miss = true;
1141            } else {
1142                synchronized (tile) {
1143                    img = getLoadedTileImage(tile);
1144                    anchorImage = getAnchor(tile, img);
1145                }
1146
1147                if (img == null || anchorImage == null) {
1148                    miss = true;
1149                }
1150            }
1151            if (miss) {
1152                missedTiles.add(tile);
1153                continue;
1154            }
1155
1156            // applying all filters to this layer
1157            img = applyImageProcessors(img);
1158
1159            Shape clip;
1160            if (tileSource.isInside(tile, border)) {
1161                clip = null;
1162            } else if (tileSource.isInside(border, tile)) {
1163                clip = borderClip;
1164            } else {
1165                continue;
1166            }
1167            TileAnchor anchorScreen = coordinateConverter.getScreenAnchorForTile(tile);
1168            drawImageInside(g, img, anchorImage, anchorScreen, clip);
1169        }
1170        return Collections.unmodifiableList(missedTiles);
1171    }
1172
1173    private static TileAnchor getAnchor(Tile tile, BufferedImage image) {
1174        if (tile instanceof ReprojectionTile) {
1175            return ((ReprojectionTile) tile).getAnchor();
1176        } else if (image != null) {
1177            return new TileAnchor(new Point2D.Double(0, 0), new Point2D.Double(image.getWidth(), image.getHeight()));
1178        } else {
1179            return null;
1180        }
1181    }
1182
1183    private void myDrawString(Graphics g, String text, int x, int y) {
1184        Color oldColor = g.getColor();
1185        String textToDraw = text;
1186        if (g.getFontMetrics().stringWidth(text) > tileSource.getTileSize()) {
1187            // text longer than tile size, split it
1188            StringBuilder line = new StringBuilder();
1189            StringBuilder ret = new StringBuilder();
1190            for (String s: text.split(" ", -1)) {
1191                if (g.getFontMetrics().stringWidth(line + s) > tileSource.getTileSize()) {
1192                    ret.append(line).append('\n');
1193                    line.setLength(0);
1194                }
1195                line.append(s).append(' ');
1196            }
1197            ret.append(line);
1198            textToDraw = ret.toString();
1199        }
1200        int offset = 0;
1201        for (String s: textToDraw.split("\n", -1)) {
1202            g.setColor(Color.black);
1203            g.drawString(s, x + 1, y + offset + 1);
1204            g.setColor(oldColor);
1205            g.drawString(s, x, y + offset);
1206            offset += g.getFontMetrics().getHeight() + 3;
1207        }
1208    }
1209
1210    /**
1211     * Returns the image which shows the state of a tile that failed to load.
1212     * <p>
1213     * Tiles which never failed get no image, so that the normal loading of tiles shows the imagery of other zoom levels
1214     * or layers, as before. Once a tile has failed, it shows the error image while it has its error, and the hourglass
1215     * while it is loaded again, until it is loaded successfully (see #25133).
1216     * @param tile the tile
1217     * @return {@link Tile#ERROR_IMAGE}, {@link Tile#LOADING_IMAGE}, or {@code null} for no image
1218     */
1219    BufferedImage getTileStatusImage(Tile tile) {
1220        if (tile == null || !getDisplaySettings().isShowErrors() || !failedTiles.contains(tile.getKey())) {
1221            return null;
1222        }
1223        if (tile.hasError()) {
1224            return Tile.ERROR_IMAGE;
1225        }
1226        if (tile.isLoading() || !tile.isLoaded()) {
1227            return Tile.LOADING_IMAGE;
1228        }
1229        return null;
1230    }
1231
1232    private void paintTileStatus(Tile tile, Graphics2D g) {
1233        BufferedImage statusImage = getTileStatusImage(tile);
1234        if (statusImage != null) {
1235            Rectangle bounds = coordinateConverter.getTileShapeScreen(tile).getBounds();
1236            g.drawImage(statusImage, bounds.x, bounds.y, bounds.width, bounds.height, null);
1237        }
1238    }
1239
1240    private void paintTileText(Tile tile, Graphics2D g) {
1241        if (tile == null) {
1242            return;
1243        }
1244        Point2D p = coordinateConverter.getPixelForTile(tile);
1245        int fontHeight = g.getFontMetrics().getHeight();
1246        int x = (int) p.getX();
1247        int y = (int) p.getY();
1248        int texty = y + 2 + fontHeight;
1249
1250        /*if (PROP_DRAW_DEBUG.get()) {
1251            myDrawString(g, "x=" + tile.getXtile() + " y=" + tile.getYtile() + " z=" + tile.getZoom() + "", x + 2, texty);
1252            texty += 1 + fontHeight;
1253            if ((tile.getXtile() % 32 == 0) && (tile.getYtile() % 32 == 0)) {
1254                myDrawString(g, "x=" + tile.getXtile() / 32 + " y=" + tile.getYtile() / 32 + " z=7", x + 2, texty);
1255                texty += 1 + fontHeight;
1256            }
1257        }
1258
1259        String tileStatus = tile.getStatus();
1260        if (!tile.isLoaded() && PROP_DRAW_DEBUG.get()) {
1261            myDrawString(g, tr("image " + tileStatus), x, texty);
1262            texty += 1 + fontHeight;
1263        }*/
1264
1265        if (tile.hasError() && getDisplaySettings().isShowErrors()) {
1266            String errorMessage = tile.getErrorMessage();
1267            if (errorMessage != null) {
1268                try {
1269                    errorMessage = tr(tile.getErrorMessage());
1270                } catch (IllegalArgumentException e) {
1271                    Logging.debug(e);
1272                }
1273                if (!errorMessage.startsWith(ERROR_STRING) && !errorMessage.startsWith(tr(ERROR_STRING))) {
1274                    errorMessage = tr(ERROR_STRING) + ": " + errorMessage;
1275                }
1276                myDrawString(g, errorMessage, x + 2, texty);
1277            }
1278            //texty += 1 + fontHeight;
1279        }
1280
1281        if (getDisplaySettings().isShowTileBorders()) {
1282            // draw a thin border around the tile
1283            Color oldColor = g.getColor();
1284            Stroke oldStroke = g.getStroke();
1285            g.setColor(TILE_BORDER_COLOR.get());
1286            g.setStroke(TILE_BORDER_STROKE);
1287            g.draw(coordinateConverter.getTileShapeScreen(tile));
1288            g.setStroke(oldStroke);
1289            g.setColor(oldColor);
1290        } else if (Logging.isDebugEnabled()) {
1291            // draw tile outline in semi-transparent red
1292            g.setColor(new Color(255, 0, 0, 50));
1293            g.draw(coordinateConverter.getTileShapeScreen(tile));
1294        }
1295    }
1296
1297    private LatLon getShiftedLatLon(EastNorth en) {
1298        return coordinateConverter.getProjecting().eastNorth2latlonClamped(en);
1299    }
1300
1301    private ICoordinate getShiftedCoord(EastNorth en) {
1302        return CoordinateConversion.llToCoor(getShiftedLatLon(en));
1303    }
1304
1305    private final TileSet nullTileSet = new TileSet();
1306
1307    protected class TileSet extends TileRange {
1308
1309        private volatile TileSetInfo info;
1310
1311        protected TileSet(TileXY t1, TileXY t2, int zoom) {
1312            super(t1, t2, zoom);
1313            sanitize();
1314        }
1315
1316        protected TileSet(TileRange range) {
1317            super(range);
1318            sanitize();
1319        }
1320
1321        /**
1322         * null tile set
1323         */
1324        private TileSet() {
1325            // default
1326        }
1327
1328        protected void sanitize() {
1329            minX = Utils.clamp(minX, tileSource.getTileXMin(zoom), tileSource.getTileXMax(zoom));
1330            maxX = Utils.clamp(maxX, tileSource.getTileXMin(zoom), tileSource.getTileXMax(zoom));
1331            minY = Utils.clamp(minY, tileSource.getTileYMin(zoom), tileSource.getTileYMax(zoom));
1332            maxY = Utils.clamp(maxY, tileSource.getTileYMin(zoom), tileSource.getTileYMax(zoom));
1333        }
1334
1335        private boolean tooSmall() {
1336            return this.tilesSpanned() < 2.1;
1337        }
1338
1339        private boolean tooLarge() {
1340            try {
1341                return tileCache == null || size() > tileCache.getCacheSize();
1342            } catch (ArithmeticException arithmeticException) {
1343                Logging.trace(arithmeticException);
1344                return true;
1345            }
1346        }
1347
1348        /**
1349         * Get all tiles represented by this TileSet that are already in the tileCache.
1350         * @return all tiles represented by this TileSet that are already in the tileCache
1351         */
1352        private List<Tile> allExistingTiles() {
1353            return allTiles(AbstractTileSourceLayer.this::getTile);
1354        }
1355
1356        private List<Tile> allTilesCreate() {
1357            return allTiles(AbstractTileSourceLayer.this::getOrCreateTile);
1358        }
1359
1360        private List<Tile> allTiles(Function<TilePosition, Tile> mapper) {
1361            return tilePositions().map(mapper).filter(Objects::nonNull).collect(Collectors.toList());
1362        }
1363
1364        /**
1365         * Gets a stream of all tile positions in this set
1366         * @return A stream of all positions
1367         */
1368        public Stream<TilePosition> tilePositions() {
1369            if (zoom == 0 || this.tooLarge()) {
1370                return Stream.empty(); // Tileset is either empty or too large
1371            } else {
1372                return IntStream.rangeClosed(minX, maxX).mapToObj(
1373                        x -> IntStream.rangeClosed(minY, maxY).mapToObj(y -> new TilePosition(x, y, zoom))
1374                        ).flatMap(Function.identity());
1375            }
1376        }
1377
1378        private List<Tile> allLoadedTiles() {
1379            return allExistingTiles().stream().filter(Tile::isLoaded).collect(Collectors.toList());
1380        }
1381
1382        /**
1383         * @return comparator, that sorts the tiles from the center to the edge of the current screen
1384         */
1385        private Comparator<Tile> getTileDistanceComparator() {
1386            final int centerX = (int) Math.ceil((minX + maxX) / 2d);
1387            final int centerY = (int) Math.ceil((minY + maxY) / 2d);
1388            return Comparator.comparingInt(t -> Math.abs(t.getXtile() - centerX) + Math.abs(t.getYtile() - centerY));
1389        }
1390
1391        private void loadAllTiles(boolean force) {
1392            if (!getDisplaySettings().isAutoLoad() && !force) {
1393                return;
1394            }
1395            if (tooLarge()) {
1396                // Too many tiles... refuse to download
1397                Logging.warn("Not downloading all tiles because there are more than {0} tiles on an axis!", MAX_TILES_SPANNED);
1398                return;
1399            }
1400            List<Tile> allTiles = allTilesCreate();
1401            allTiles.sort(getTileDistanceComparator());
1402            for (Tile t : allTiles) {
1403                loadTile(t, force);
1404            }
1405        }
1406
1407        /**
1408         * Extend tile loading corridor, so that no flickering happens when panning
1409         */
1410        private void overloadTiles() {
1411            /*
1412             * consult calculation in estimateTileCacheSize() before changing values here.
1413             *
1414             *  @see #estimateTileCacheSize()
1415             */
1416            int overload = 1;
1417
1418            int minXo = Utils.clamp(minX-overload, tileSource.getTileXMin(zoom), tileSource.getTileXMax(zoom));
1419            int maxXo = Utils.clamp(maxX+overload, tileSource.getTileXMin(zoom), tileSource.getTileXMax(zoom));
1420            int minYo = Utils.clamp(minY-overload, tileSource.getTileYMin(zoom), tileSource.getTileYMax(zoom));
1421            int maxYo = Utils.clamp(maxY+overload, tileSource.getTileYMin(zoom), tileSource.getTileYMax(zoom));
1422
1423            TileSet ts = new TileSet(new TileXY(minXo, minYo), new TileXY(maxXo, maxYo), zoom);
1424            ts.loadAllTiles(false);
1425        }
1426
1427        private void loadAllErrorTiles(boolean force) {
1428            if (!getDisplaySettings().isAutoLoad() && !force)
1429                return;
1430            for (Tile t : this.allTilesCreate()) {
1431                if (t.hasError()) {
1432                    tileLoader.createTileLoaderJob(t).submit(force);
1433                }
1434            }
1435        }
1436
1437        /**
1438         * Call the given paint method for all tiles in this tile set.<p>
1439         * Uses a parallel stream.
1440         * @param visitor A visitor to call for each tile.
1441         * @param missed a consumer to call for each missed tile.
1442         */
1443        public void visitTiles(Consumer<Tile> visitor, Consumer<TilePosition> missed) {
1444            tilePositions().parallel().forEach(tp -> visitTilePosition(visitor, tp, missed));
1445        }
1446
1447        private void visitTilePosition(Consumer<Tile> visitor, TilePosition tp, Consumer<TilePosition> missed) {
1448            Tile tile = getTile(tp);
1449            if (tile == null) {
1450                missed.accept(tp);
1451            } else {
1452                visitor.accept(tile);
1453            }
1454        }
1455
1456        /**
1457         * Check if there is any tile fully loaded without error.
1458         * @return true if there is any tile fully loaded without error
1459         */
1460        public boolean hasVisibleTiles() {
1461            return getTileSetInfo().hasVisibleTiles;
1462        }
1463
1464        /**
1465         * Check if there there is a tile that is overzoomed.
1466         * <p>
1467         * I.e. the server response for one tile was "there is no tile here".
1468         * This usually happens when zoomed in too much. The limit depends on
1469         * the region, so at the edge of such a region, some tiles may be
1470         * available and some not.
1471         * @return true if there there is a tile that is overzoomed
1472         */
1473        public boolean hasOverzoomedTiles() {
1474            return getTileSetInfo().hasOverzoomedTiles;
1475        }
1476
1477        /**
1478         * Check if there are tiles still loading.
1479         * <p>
1480         * This is the case if there is a tile not yet in the cache, or in the
1481         * cache but marked as loading ({@link Tile#isLoading()}.
1482         * @return true if there are tiles still loading
1483         */
1484        public boolean hasLoadingTiles() {
1485            return getTileSetInfo().hasLoadingTiles;
1486        }
1487
1488        /**
1489         * Check if all tiles in the range are fully loaded.
1490         * <p>
1491         * A tile is considered to be fully loaded even if the result of loading
1492         * the tile was an error.
1493         * @return true if all tiles in the range are fully loaded
1494         */
1495        public boolean hasAllLoadedTiles() {
1496            return getTileSetInfo().hasAllLoadedTiles;
1497        }
1498
1499        private TileSetInfo getTileSetInfo() {
1500            if (info == null) {
1501                synchronized (this) {
1502                    if (info == null) {
1503                        List<Tile> allTiles = this.allExistingTiles();
1504                        TileSetInfo newInfo = new TileSetInfo();
1505                        try {
1506                            newInfo.hasLoadingTiles = allTiles.size() < this.size();
1507                        } catch (ArithmeticException arithmeticException) {
1508                            Logging.trace(arithmeticException);
1509                            newInfo.hasLoadingTiles = false;
1510                        }
1511                        newInfo.hasAllLoadedTiles = true;
1512                        for (Tile t : allTiles) {
1513                            if ("no-tile".equals(t.getValue("tile-info"))) {
1514                                newInfo.hasOverzoomedTiles = true;
1515                            }
1516                            if (t.isLoaded()) {
1517                                if (!t.hasError()) {
1518                                    newInfo.hasVisibleTiles = true;
1519                                }
1520                            } else {
1521                                newInfo.hasAllLoadedTiles = false;
1522                                if (t.isLoading()) {
1523                                    newInfo.hasLoadingTiles = true;
1524                                }
1525                            }
1526                        }
1527                        info = newInfo;
1528                    }
1529                }
1530            }
1531            return info;
1532        }
1533
1534        @Override
1535        public String toString() {
1536            int size;
1537            try {
1538                size = size();
1539            } catch (ArithmeticException arithmeticException) {
1540                Logging.trace(arithmeticException);
1541                size = Integer.MIN_VALUE;
1542            }
1543            return getClass().getName()
1544                    + ": zoom: " + zoom
1545                    + " X(" + minX + ", " + maxX
1546                    + ") Y(" + minY + ", " + maxY
1547                    + ") size: " + (size >= 0 ? size : "Integer Overflow");
1548        }
1549    }
1550
1551    /**
1552     * Data container to hold information about a {@code TileSet} class.
1553     */
1554    private static final class TileSetInfo {
1555        boolean hasVisibleTiles;
1556        boolean hasOverzoomedTiles;
1557        boolean hasLoadingTiles;
1558        boolean hasAllLoadedTiles;
1559    }
1560
1561    /**
1562     * Create a TileSet by EastNorth bbox taking a layer shift in account
1563     * @param bounds the EastNorth bounds
1564     * @param zoom zoom level
1565     * @return the tile set
1566     */
1567    protected TileSet getTileSet(ProjectionBounds bounds, int zoom) {
1568        if (zoom == 0)
1569            return new TileSet();
1570        TileXY t1;
1571        TileXY t2;
1572        IProjected topLeftUnshifted = coordinateConverter.shiftDisplayToServer(bounds.getMin());
1573        IProjected botRightUnshifted = coordinateConverter.shiftDisplayToServer(bounds.getMax());
1574        if (coordinateConverter.requiresReprojection()) {
1575            Projection projServer = Projections.getProjectionByCode(tileSource.getServerCRS());
1576            if (projServer == null) {
1577                throw new IllegalStateException(tileSource.toString());
1578            }
1579            ProjectionBounds projBounds = new ProjectionBounds(
1580                    CoordinateConversion.projToEn(topLeftUnshifted),
1581                    CoordinateConversion.projToEn(botRightUnshifted));
1582            ProjectionBounds bbox = projServer.getEastNorthBoundsBox(projBounds, ProjectionRegistry.getProjection());
1583            t1 = tileSource.projectedToTileXY(CoordinateConversion.enToProj(bbox.getMin()), zoom);
1584            t2 = tileSource.projectedToTileXY(CoordinateConversion.enToProj(bbox.getMax()), zoom);
1585        } else {
1586            t1 = tileSource.projectedToTileXY(topLeftUnshifted, zoom);
1587            t2 = tileSource.projectedToTileXY(botRightUnshifted, zoom);
1588        }
1589        return new TileSet(t1, t2, zoom);
1590    }
1591
1592    private class DeepTileSet {
1593        private final ProjectionBounds bounds;
1594        private final int minZoom;
1595        private final int maxZoom;
1596        private final TileSet[] tileSets;
1597
1598        @SuppressWarnings("unchecked")
1599        DeepTileSet(ProjectionBounds bounds, int minZoom, int maxZoom) {
1600            this.bounds = bounds;
1601            this.minZoom = minZoom;
1602            this.maxZoom = maxZoom;
1603            if (minZoom > maxZoom) {
1604                throw new IllegalArgumentException(minZoom + " > " + maxZoom);
1605            }
1606            this.tileSets = new AbstractTileSourceLayer.TileSet[maxZoom - minZoom + 1];
1607        }
1608
1609        public TileSet getTileSet(int zoom) {
1610            if (zoom < minZoom)
1611                return nullTileSet;
1612            synchronized (tileSets) {
1613                TileSet ts = tileSets[zoom-minZoom];
1614                if (ts == null) {
1615                    ts = AbstractTileSourceLayer.this.getTileSet(bounds, zoom);
1616                    tileSets[zoom-minZoom] = ts;
1617                }
1618                return ts;
1619            }
1620        }
1621    }
1622
1623    @Override
1624    public void paint(Graphics2D g, MapView mv, Bounds bounds) {
1625        // old and unused.
1626    }
1627
1628    /**
1629     * Paints the imagery attribution as a viewport-fixed overlay.
1630     * @param g the graphics context to paint on
1631     * @param mv the map view to paint for
1632     * @since 19701
1633     */
1634    public void paintAttribution(Graphics2D g, MapView mv) {
1635        ProjectionBounds pb = mv.getState().getViewArea(new Rectangle(0, 0, mv.getWidth(), mv.getHeight()))
1636                .getProjectionBounds();
1637        attribution.paintAttribution(g, mv.getWidth(), mv.getHeight(), getShiftedCoord(pb.getMin()),
1638                getShiftedCoord(pb.getMax()), lastDisplayZoomLevel, this);
1639    }
1640
1641    private void drawInViewArea(Graphics2D g, MapView mv, ProjectionBounds pb) {
1642        int zoom = currentZoomLevel;
1643        if (getDisplaySettings().isAutoZoom()) {
1644            zoom = getBestZoom();
1645        }
1646
1647        DeepTileSet dts = new DeepTileSet(pb, getMinZoomLvl(), zoom);
1648
1649        int displayZoomLevel = zoom;
1650
1651        boolean noTilesAtZoom = false;
1652        if (getDisplaySettings().isAutoZoom() && getDisplaySettings().isAutoLoad()) {
1653            // Auto-detection of tilesource maxzoom (currently fully works only for Bing)
1654            TileSet ts0 = dts.getTileSet(zoom);
1655            if (!ts0.hasVisibleTiles() && (!ts0.hasLoadingTiles() || ts0.hasOverzoomedTiles())) {
1656                noTilesAtZoom = true;
1657            }
1658            // Find highest zoom level with at least one visible tile
1659            for (int tmpZoom = zoom; tmpZoom > dts.minZoom; tmpZoom--) {
1660                if (dts.getTileSet(tmpZoom).hasVisibleTiles()) {
1661                    displayZoomLevel = tmpZoom;
1662                    break;
1663                }
1664            }
1665            // Do binary search between currentZoomLevel and displayZoomLevel
1666            while (zoom > displayZoomLevel && !ts0.hasVisibleTiles() && ts0.hasOverzoomedTiles()) {
1667                zoom = (zoom + displayZoomLevel)/2;
1668                ts0 = dts.getTileSet(zoom);
1669            }
1670
1671            setZoomLevel(zoom, false);
1672
1673            // If all tiles at displayZoomLevel is loaded, load all tiles at next zoom level
1674            // to make sure there're really no more zoom levels
1675            // loading is done in the next if section
1676            if (zoom == displayZoomLevel && !ts0.hasLoadingTiles() && zoom < dts.maxZoom) {
1677                zoom++;
1678                ts0 = dts.getTileSet(zoom);
1679            }
1680            // When we have overzoomed tiles and all tiles at current zoomlevel is loaded,
1681            // load tiles at previovus zoomlevels until we have all tiles on screen is loaded.
1682            // loading is done in the next if section
1683            while (zoom > dts.minZoom && ts0.hasOverzoomedTiles() && !ts0.hasLoadingTiles()) {
1684                zoom--;
1685                ts0 = dts.getTileSet(zoom);
1686            }
1687        } else if (getDisplaySettings().isAutoZoom()) {
1688            setZoomLevel(zoom, false);
1689        }
1690        TileSet ts = dts.getTileSet(zoom);
1691        lastDisplayZoomLevel = displayZoomLevel;
1692
1693        // try to load tiles from desired zoom level, no matter what we will show (for example, tiles from previous zoom level
1694        // on zoom in)
1695        ts.loadAllTiles(false);
1696
1697        if (displayZoomLevel != zoom) {
1698            ts = dts.getTileSet(displayZoomLevel);
1699            if (!dts.getTileSet(displayZoomLevel).hasAllLoadedTiles() && displayZoomLevel < zoom) {
1700                // if we are showing tiles from lower zoom level, ensure that all tiles are loaded as they are few,
1701                // and should not trash the tile cache
1702                // This is especially needed when dts.getTileSet(zoom).tooLarge() is true and we are not loading tiles
1703                ts.loadAllTiles(false);
1704            }
1705        }
1706
1707        g.setColor(Color.DARK_GRAY);
1708
1709        List<Tile> missedTiles = this.paintTileImages(g, ts);
1710        if (getDisplaySettings().isAutoLoad()) {
1711            ts.overloadTiles();
1712        }
1713        if (getDisplaySettings().isAutoZoom()) {
1714            /*
1715             * consult calculation in estimateTileCacheSize() before changing values here.
1716             *
1717             *  @see #estimateTileCacheSize()
1718             */
1719            int[] otherZooms = {1, 2, -1, -2, -3, -4, -5};
1720
1721            for (int otherZoom: otherZooms) {
1722                missedTiles = tryLoadFromDifferentZoom(g, displayZoomLevel, missedTiles, otherZoom);
1723                if (missedTiles.isEmpty()) {
1724                    break;
1725                }
1726            }
1727        }
1728
1729        if (Logging.isDebugEnabled() && !missedTiles.isEmpty()) {
1730            Logging.debug("still missed {0} in the end", missedTiles.size());
1731        }
1732        g.setColor(Color.red);
1733        g.setFont(InfoFont);
1734
1735        // The current zoom tileset should have all of its tiles due to the loadAllTiles(), unless it to tooLarge()
1736        for (Tile t : ts.allExistingTiles()) {
1737            this.paintTileStatus(t, g);
1738            this.paintTileText(t, g);
1739        }
1740
1741        g.setColor(Color.lightGray);
1742
1743        if (ts.tooLarge()) {
1744            myDrawString(g, tr("zoom in to load more tiles"), 120, 120);
1745        } else if (!getDisplaySettings().isAutoZoom() && ts.tooSmall()) {
1746            myDrawString(g, tr("increase tiles zoom level (change resolution) to see more detail"), 120, 120);
1747        }
1748        if (noTilesAtZoom) {
1749            myDrawString(g, tr("No tiles at this zoom level"), 120, 120);
1750        }
1751        if (Logging.isDebugEnabled()) {
1752            int xOffset = 50;
1753            myDrawString(g, tr("Current zoom: {0}", currentZoomLevel), xOffset, 165);
1754            myDrawString(g, tr("Display zoom: {0}", displayZoomLevel), xOffset, 180);
1755            myDrawString(g, tr("Pixel scale: {0}", getScaleFactor(currentZoomLevel)), xOffset, 195);
1756            myDrawString(g, tr("Best zoom: {0}", getBestZoom()), xOffset, 210);
1757            myDrawString(g, tr("Estimated cache size: {0}", estimateTileCacheSize()), xOffset, 225);
1758            if (tileLoader instanceof TMSCachedTileLoader) {
1759                int yOffset = 255;
1760                myDrawString(g, tr("=== Cache stats ==="), xOffset, yOffset);
1761                yOffset += 5;
1762                for (String part: ((TMSCachedTileLoader) tileLoader).getStats().split("\n", -1)) {
1763                    String regex = "^-{3,}(.+)";
1764                    if (part.matches(regex)) {
1765                        part = part.replaceAll(regex, "--- $1");
1766                        yOffset += 5;
1767                    }
1768                    yOffset += 15;
1769                    myDrawString(g, tr(part), xOffset, yOffset);
1770                }
1771            }
1772        }
1773    }
1774
1775    private List<Tile> tryLoadFromDifferentZoom(Graphics2D g, int displayZoomLevel, List<Tile> missedTiles,
1776            int zoomOffset) {
1777
1778        int newzoom = displayZoomLevel + zoomOffset;
1779        if (newzoom < getMinZoomLvl() || newzoom > getMaxZoomLvl()) {
1780            return missedTiles;
1781        }
1782
1783        List<Tile> newlyMissedTiles = new LinkedList<>();
1784        for (Tile missed : missedTiles) {
1785            if (zoomOffset > 0 && "no-tile".equals(missed.getValue("tile-info"))) {
1786                // Don't try to paint from higher zoom levels when tile is overzoomed
1787                newlyMissedTiles.add(missed);
1788                continue;
1789            }
1790            TileSet ts2 = new TileSet(tileSource.getCoveringTileRange(missed, newzoom));
1791            // Instantiating large TileSets is expensive. If there are no loaded tiles, don't bother even trying.
1792            if (ts2.allLoadedTiles().isEmpty()) {
1793                if (zoomOffset > 0) {
1794                    newlyMissedTiles.add(missed);
1795                    continue;
1796                } else {
1797                    /*
1798                     *  We have negative zoom offset. Try to load tiles from lower zoom levels, as they may be not present
1799                     *  in tile cache (e.g. when user panned the map or opened layer above zoom level, for which tiles are present.
1800                     *  This will ensure, that tileCache is populated with tiles from lower zoom levels so it will be possible to
1801                     *  use them to paint overzoomed tiles.
1802                     *  See: #14562
1803                     */
1804                    ts2.loadAllTiles(false);
1805                }
1806            }
1807            if (ts2.tooLarge()) {
1808                continue;
1809            }
1810            newlyMissedTiles.addAll(this.paintTileImages(g, ts2, newzoom, missed));
1811        }
1812        return newlyMissedTiles;
1813    }
1814
1815    /**
1816     * Returns tile for a pixel position.<p>
1817     * This isn't very efficient, but it is only used when the user right-clicks on the map.
1818     * @param px pixel X coordinate
1819     * @param py pixel Y coordinate
1820     * @return Tile at pixel position
1821     */
1822    private Tile getTileForPixelpos(int px, int py) {
1823        Logging.debug("getTileForPixelpos({0}, {1})", px, py);
1824        TileXY xy = coordinateConverter.getTileforPixel(px, py, currentZoomLevel);
1825        return getTile(xy.getXIndex(), xy.getYIndex(), currentZoomLevel);
1826    }
1827
1828    /**
1829     * Class to store a menu action and the class it belongs to.
1830     */
1831    private static class MenuAddition {
1832        final Action addition;
1833        @SuppressWarnings("rawtypes")
1834        final Class<? extends AbstractTileSourceLayer> clazz;
1835
1836        @SuppressWarnings("rawtypes")
1837        MenuAddition(Action addition, Class<? extends AbstractTileSourceLayer> clazz) {
1838            this.addition = addition;
1839            this.clazz = clazz;
1840        }
1841    }
1842
1843    /**
1844     * Register an additional layer context menu entry.
1845     *
1846     * @param addition additional menu action
1847     * @since 11197
1848     */
1849    public static void registerMenuAddition(Action addition) {
1850        menuAdditions.add(new MenuAddition(addition, AbstractTileSourceLayer.class));
1851    }
1852
1853    /**
1854     * Register an additional layer context menu entry for a imagery layer
1855     * class.  The menu entry is valid for the specified class and subclasses
1856     * thereof only.
1857     * <p>
1858     * Example:
1859     * <pre>
1860     * TMSLayer.registerMenuAddition(new TMSSpecificAction(), TMSLayer.class);
1861     * </pre>
1862     *
1863     * @param addition additional menu action
1864     * @param clazz class the menu action is registered for
1865     * @since 11197
1866     */
1867    public static void registerMenuAddition(Action addition,
1868                                            Class<? extends AbstractTileSourceLayer<?>> clazz) {
1869        menuAdditions.add(new MenuAddition(addition, clazz));
1870    }
1871
1872    /**
1873     * Prepare list of additional layer context menu entries.  The list is
1874     * empty if there are no additional menu entries.
1875     *
1876     * @return list of additional layer context menu entries
1877     */
1878    private List<Action> getMenuAdditions() {
1879        final LinkedList<Action> menuAdds = menuAdditions.stream()
1880                .filter(menuAdd -> menuAdd.clazz.isInstance(this))
1881                .map(menuAdd -> menuAdd.addition)
1882                .collect(Collectors.toCollection(LinkedList::new));
1883        if (!menuAdds.isEmpty()) {
1884            menuAdds.addFirst(SeparatorLayerAction.INSTANCE);
1885        }
1886        return menuAdds;
1887    }
1888
1889    @Override
1890    public Action[] getMenuEntries() {
1891        ArrayList<Action> actions = new ArrayList<>();
1892        actions.addAll(Arrays.asList(getLayerListEntries()));
1893        actions.addAll(Arrays.asList(getCommonEntries()));
1894        actions.addAll(getMenuAdditions());
1895        actions.add(SeparatorLayerAction.INSTANCE);
1896        actions.add(new LayerListPopup.InfoAction(this));
1897        return actions.toArray(new Action[0]);
1898    }
1899
1900    /**
1901     * Returns the contextual menu entries in layer list dialog.
1902     * @return the contextual menu entries in layer list dialog
1903     */
1904    public Action[] getLayerListEntries() {
1905        return new Action[] {
1906            LayerListDialog.getInstance().createActivateLayerAction(this),
1907            LayerListDialog.getInstance().createShowHideLayerAction(),
1908            MainApplication.getMenu().autoScaleActions.get(AutoScaleAction.AutoScaleMode.LAYER),
1909            LayerListDialog.getInstance().createDeleteLayerAction(),
1910            SeparatorLayerAction.INSTANCE,
1911            // color,
1912            new OffsetAction(),
1913            new RenameLayerAction(this.getAssociatedFile(), this),
1914            SeparatorLayerAction.INSTANCE
1915        };
1916    }
1917
1918    /**
1919     * Returns the common menu entries.
1920     * @return the common menu entries
1921     */
1922    public Action[] getCommonEntries() {
1923        return new Action[] {
1924            new AutoLoadTilesAction(this),
1925            new AutoZoomAction(this),
1926            new ShowErrorsAction(this),
1927            new ShowTileBordersAction(this),
1928            new IncreaseZoomAction(this),
1929            new DecreaseZoomAction(this),
1930            new ZoomToBestAction(this),
1931            new ZoomToNativeLevelAction(this),
1932            new FlushTileCacheAction(this),
1933            new LoadErroneousTilesAction(this),
1934            new LoadAllTilesAction(this)
1935        };
1936    }
1937
1938    @Override
1939    public String getToolTipText() {
1940        if (getDisplaySettings().isAutoLoad()) {
1941            return tr("{0} ({1}), automatically downloading in zoom {2}", this.getClass().getSimpleName(), getName(), currentZoomLevel);
1942        } else {
1943            return tr("{0} ({1}), downloading in zoom {2}", this.getClass().getSimpleName(), getName(), currentZoomLevel);
1944        }
1945    }
1946
1947    @Override
1948    public void visitBoundingBox(BoundingXYVisitor v) {
1949        if (this.getInfo() != null) {
1950            v.visit(this.getInfo().getBounds());
1951        }
1952    }
1953
1954    /**
1955     * Task responsible for precaching imagery along the gpx track
1956     * @since 8526
1957     */
1958    public class PrecacheTask implements TileLoaderListener {
1959        private final ProgressMonitor progressMonitor;
1960        private final int totalCount;
1961        private final AtomicInteger processedCount = new AtomicInteger(0);
1962        private final TileLoader tileLoader;
1963        private final Set<Tile> requestedTiles;
1964
1965        /**
1966         * Constructs a new {@code PrecacheTask}.
1967         * @param progressMonitor that will be notified about progess of the task
1968         * @param bufferY buffer Y in degrees around which to download tiles
1969         * @param bufferX buffer X in degrees around which to download tiles
1970         * @param points list of points along which to download
1971         */
1972        public PrecacheTask(ProgressMonitor progressMonitor, List<LatLon> points, double bufferX, double bufferY) {
1973            this.progressMonitor = progressMonitor;
1974            this.tileLoader = getTileLoaderFactory().makeTileLoader(this, getHeaders(tileSource), minimumTileExpire);
1975            if (this.tileLoader instanceof TMSCachedTileLoader) {
1976                ((TMSCachedTileLoader) this.tileLoader).setDownloadExecutor(
1977                        TMSCachedTileLoader.getNewThreadPoolExecutor("precache-downloader-%d"));
1978            }
1979            requestedTiles = new ConcurrentSkipListSet<>(
1980                    (o1, o2) -> String.CASE_INSENSITIVE_ORDER.compare(o1.getKey(), o2.getKey()));
1981            for (LatLon point: points) {
1982                TileXY minTile = tileSource.latLonToTileXY(point.lat() - bufferY, point.lon() - bufferX, currentZoomLevel);
1983                TileXY curTile = tileSource.latLonToTileXY(CoordinateConversion.llToCoor(point), currentZoomLevel);
1984                TileXY maxTile = tileSource.latLonToTileXY(point.lat() + bufferY, point.lon() + bufferX, currentZoomLevel);
1985
1986                // take at least one tile of buffer
1987                int minY = Math.min(curTile.getYIndex() - 1, minTile.getYIndex());
1988                int maxY = Math.max(curTile.getYIndex() + 1, maxTile.getYIndex());
1989                int minX = Math.min(curTile.getXIndex() - 1, minTile.getXIndex());
1990                int maxX = Math.max(curTile.getXIndex() + 1, maxTile.getXIndex());
1991
1992                for (int x = minX; x <= maxX; x++) {
1993                    for (int y = minY; y <= maxY; y++) {
1994                        requestedTiles.add(createTile(tileSource, x, y, currentZoomLevel));
1995                    }
1996                }
1997            }
1998
1999            this.totalCount = requestedTiles.size();
2000            this.progressMonitor.setTicksCount(requestedTiles.size());
2001        }
2002
2003        /**
2004         * Determines if the task is finished.
2005         * @return true, if all is done
2006         */
2007        public boolean isFinished() {
2008            return processedCount.get() >= totalCount;
2009        }
2010
2011        /**
2012         * Returns total number of tiles to download.
2013         * @return total number of tiles to download
2014         */
2015        public int getTotalCount() {
2016            return totalCount;
2017        }
2018
2019        /**
2020         * cancel the task
2021         */
2022        public void cancel() {
2023            shutdownTmsTileLoader();
2024        }
2025
2026        @Override
2027        public void tileLoadingFinished(Tile tile, boolean success) {
2028            int processed = this.processedCount.incrementAndGet();
2029            if (success) {
2030                synchronized (progressMonitor) {
2031                    if (!this.progressMonitor.isCanceled()) {
2032                        this.progressMonitor.worked(1);
2033                        this.progressMonitor.setCustomText(tr("Downloaded {0}/{1} tiles", processed, totalCount));
2034                    }
2035                }
2036            } else {
2037                Logging.warn("Tile loading failure: " + tile + " - " + tile.getErrorMessage());
2038            }
2039            if (isFinished()) {
2040                shutdownTmsTileLoader();
2041            }
2042        }
2043
2044        private void shutdownTmsTileLoader() {
2045            if (tileLoader instanceof TMSCachedTileLoader) {
2046                ((TMSCachedTileLoader) tileLoader).shutdown();
2047            }
2048        }
2049
2050        /**
2051         * Execute the download
2052         */
2053        public void run() {
2054            for (Tile t: requestedTiles) {
2055                if (!progressMonitor.isCanceled()) {
2056                    tileLoader.createTileLoaderJob(t).submit();
2057                }
2058            }
2059        }
2060    }
2061
2062    /**
2063     * Calculates tiles, that needs to be downloaded to cache, gets a current tile loader and creates a task to download
2064     * all of the tiles. Buffer contains at least one tile.
2065     * <p>
2066     * To prevent accidental clear of the queue, new download executor is created with separate queue
2067     *
2068     * @param progressMonitor progress monitor for download task
2069     * @param points lat/lon coordinates to download
2070     * @param bufferX how many units in current Coordinate Reference System to cover in X axis in both sides
2071     * @param bufferY how many units in current Coordinate Reference System to cover in Y axis in both sides
2072     * @return precache task representing download task
2073     */
2074    public AbstractTileSourceLayer<T>.PrecacheTask getDownloadAreaToCacheTask(final ProgressMonitor progressMonitor, List<LatLon> points,
2075            double bufferX, double bufferY) {
2076        return new PrecacheTask(progressMonitor, points, bufferX, bufferY);
2077    }
2078
2079    @Override
2080    public boolean isSavable() {
2081        return true; // With WMSLayerExporter
2082    }
2083
2084    @Override
2085    public File createAndOpenSaveFileChooser() {
2086        return SaveActionBase.createAndOpenSaveFileChooser(tr("Save WMS file"), WMSLayerImporter.FILE_FILTER);
2087    }
2088
2089    /**
2090     * Create a new tile. Added to allow use of custom {@link Tile} objects.
2091     *
2092     * @param source Tile source
2093     * @param x X coordinate
2094     * @param y Y coordinate
2095     * @param zoom Zoom level
2096     * @return The new {@link Tile}
2097     * @since 17862
2098     */
2099    public Tile createTile(T source, int x, int y, int zoom) {
2100        return new Tile(source, x, y, zoom);
2101    }
2102
2103    @Override
2104    public synchronized void destroy() {
2105        super.destroy();
2106        NavigatableComponent.removeZoomChangeListener(this);
2107        adjustAction.destroy();
2108        if (tileLoader instanceof TMSCachedTileLoader) {
2109            ((TMSCachedTileLoader) tileLoader).shutdown();
2110        }
2111    }
2112
2113    private final class TileSourcePainter extends CompatibilityModeLayerPainter {
2114        /** The memory handle that will hold our tile source. */
2115        private MemoryHandle<?> memory;
2116
2117        @Override
2118        public void paint(MapViewGraphics graphics) {
2119            allocateCacheMemory();
2120            if (memory != null) {
2121                doPaint(graphics);
2122                if (AbstractTileSourceLayer.this instanceof MVTLayer) {
2123                    AbstractTileSourceLayer.this.paint(graphics.getDefaultGraphics(), graphics.getMapView(), graphics.getMapView()
2124                      .getRealBounds());
2125                }
2126            } else {
2127                Graphics g = graphics.getDefaultGraphics();
2128                Color oldColor = g.getColor();
2129                g.setColor(Color.BLACK);
2130                g.drawString("Not enough memory to draw layer: " + getName(), 10, 120);
2131                g.setColor(Color.RED);
2132                g.drawString("Not enough memory to draw layer: " + getName(), 11, 121);
2133                g.setColor(oldColor);
2134            }
2135        }
2136
2137        private void doPaint(MapViewGraphics graphics) {
2138            try {
2139                drawInViewArea(graphics.getDefaultGraphics(), graphics.getMapView(), graphics.getClipBounds().getProjectionBounds());
2140            } catch (IllegalArgumentException | IllegalStateException e) {
2141                throw BugReport.intercept(e)
2142                               .put("graphics", graphics).put("tileSource", tileSource).put("currentZoomLevel", currentZoomLevel);
2143            }
2144        }
2145
2146        private void allocateCacheMemory() {
2147            if (memory == null) {
2148                MemoryManager manager = MemoryManager.getInstance();
2149                if (manager.isAvailable(getEstimatedCacheSize())) {
2150                    try {
2151                        memory = manager.allocateMemory("tile source layer", getEstimatedCacheSize(), Object::new);
2152                    } catch (NotEnoughMemoryException e) {
2153                        Logging.warn("Could not allocate tile source memory", e);
2154                    }
2155                }
2156            }
2157        }
2158
2159        private long getEstimatedCacheSize() {
2160            return 4L * tileSource.getTileSize() * tileSource.getTileSize() * estimateTileCacheSize();
2161        }
2162
2163        @Override
2164        public void detachFromMapView(MapViewEvent event) {
2165            event.getMapView().removeMouseListener(adapter);
2166            NavigatableComponent.removeZoomChangeListener(AbstractTileSourceLayer.this);
2167            super.detachFromMapView(event);
2168            if (memory != null) {
2169                memory.free();
2170            }
2171        }
2172    }
2173
2174    @Override
2175    public void projectionChanged(Projection oldValue, Projection newValue) {
2176        super.projectionChanged(oldValue, newValue);
2177        displaySettings.setOffsetBookmark(displaySettings.getOffsetBookmark());
2178        if (tileCache != null) {
2179            tileCache.clear();
2180        }
2181    }
2182
2183    @Override
2184    protected List<OffsetMenuEntry> getOffsetMenuEntries() {
2185        return OffsetBookmark.getBookmarks()
2186            .stream()
2187            .filter(b -> b.isUsable(this))
2188            .map(OffsetMenuBookmarkEntry::new)
2189            .collect(Collectors.toList());
2190    }
2191
2192    /**
2193     * An entry for a bookmark in the offset menu.
2194     * @author Michael Zangl
2195     */
2196    private class OffsetMenuBookmarkEntry implements OffsetMenuEntry {
2197        private final OffsetBookmark bookmark;
2198
2199        OffsetMenuBookmarkEntry(OffsetBookmark bookmark) {
2200            this.bookmark = bookmark;
2201
2202        }
2203
2204        @Override
2205        public String getLabel() {
2206            return bookmark.getName();
2207        }
2208
2209        @Override
2210        public boolean isActive() {
2211            EastNorth offset = bookmark.getDisplacement(ProjectionRegistry.getProjection());
2212            EastNorth active = getDisplaySettings().getDisplacement();
2213            return Utils.equalsEpsilon(offset.east(), active.east()) && Utils.equalsEpsilon(offset.north(), active.north());
2214        }
2215
2216        @Override
2217        public void actionPerformed() {
2218            getDisplaySettings().setOffsetBookmark(bookmark);
2219        }
2220    }
2221}