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