001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.imagery;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.StringReader;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collection;
010import java.util.Collections;
011import java.util.EnumMap;
012import java.util.List;
013import java.util.Locale;
014import java.util.Map;
015import java.util.Objects;
016import java.util.Optional;
017import java.util.concurrent.TimeUnit;
018import java.util.regex.Matcher;
019import java.util.regex.Pattern;
020import java.util.stream.Collectors;
021
022import javax.swing.ImageIcon;
023
024import org.openstreetmap.josm.data.StructUtils.StructEntry;
025import org.openstreetmap.josm.data.sources.ISourceCategory;
026import org.openstreetmap.josm.data.sources.ISourceType;
027import org.openstreetmap.josm.data.sources.SourceBounds;
028import org.openstreetmap.josm.data.sources.SourceInfo;
029import org.openstreetmap.josm.data.sources.SourcePreferenceEntry;
030import org.openstreetmap.josm.tools.CheckParameterUtil;
031import org.openstreetmap.josm.tools.ImageProvider;
032import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
033import org.openstreetmap.josm.tools.Logging;
034import org.openstreetmap.josm.tools.MultiMap;
035import org.openstreetmap.josm.tools.PlatformManager;
036import org.openstreetmap.josm.tools.StreamUtils;
037import org.openstreetmap.josm.tools.Utils;
038
039import jakarta.json.Json;
040import jakarta.json.JsonObject;
041import jakarta.json.JsonReader;
042
043/**
044 * Class that stores info about an image background layer.
045 *
046 * @author Frederik Ramm
047 */
048public class ImageryInfo extends
049        SourceInfo<ImageryInfo.ImageryCategory, ImageryInfo.ImageryType, ImageryInfo.ImageryBounds, ImageryInfo.ImageryPreferenceEntry> {
050
051    /**
052     * Type of imagery entry.
053     */
054    public enum ImageryType implements ISourceType<ImageryType> {
055        /** A WMS (Web Map Service) entry. **/
056        WMS("wms"),
057        /** A TMS (Tile Map Service) entry. **/
058        TMS("tms"),
059        /** TMS entry for Microsoft Bing. */
060        BING("bing"),
061        /** TMS entry for Russian company <a href="https://wiki.openstreetmap.org/wiki/WikiProject_Russia/kosmosnimki">ScanEx</a>. **/
062        SCANEX("scanex"),
063        /** A WMS endpoint entry only stores the WMS server info, without layer, which are chosen later by the user. **/
064        WMS_ENDPOINT("wms_endpoint"),
065        /** WMTS stores GetCapabilities URL. Does not store any information about the layer **/
066        WMTS("wmts"),
067        /** Mapbox Vector Tiles entry*/
068        MVT("mvt");
069
070        private final String typeString;
071
072        ImageryType(String typeString) {
073            this.typeString = typeString;
074        }
075
076        /**
077         * Returns the unique string identifying this type.
078         * @return the unique string identifying this type
079         * @since 6690
080         */
081        @Override
082        public String getTypeString() {
083            return typeString;
084        }
085
086        /**
087         * Returns the imagery type from the given type string.
088         * @param s The type string
089         * @return the imagery type matching the given type string
090         */
091        public static ImageryType fromString(String s) {
092            return Arrays.stream(ImageryType.values())
093                    .filter(type -> type.getTypeString().equals(s))
094                    .findFirst().orElse(null);
095        }
096
097        @Override
098        public ImageryType getFromString(String s) {
099            return fromString(s);
100        }
101
102        @Override
103        public ImageryType getDefault() {
104            return WMS;
105        }
106    }
107
108    /**
109     * Category of imagery entry.
110     * @since 13792
111     */
112    public enum ImageryCategory implements ISourceCategory<ImageryCategory> {
113        /** A aerial or satellite photo. **/
114        PHOTO(/* ICON(data/imagery/) */ "photo", tr("Aerial or satellite photo")),
115        /** A map of digital terrain model, digital surface model or contour lines. **/
116        ELEVATION(/* ICON(data/imagery/) */ "elevation", tr("Elevation map")),
117        /** A map. **/
118        MAP(/* ICON(data/imagery/) */ "map", tr("Map")),
119        /** A historic or otherwise outdated map. */
120        HISTORICMAP(/* ICON(data/imagery/) */ "historicmap", tr("Historic or otherwise outdated map")),
121        /** A map based on OSM data. **/
122        OSMBASEDMAP(/* ICON(data/imagery/) */ "osmbasedmap", tr("Map based on OSM data")),
123        /** A historic or otherwise outdated aerial or satellite photo. **/
124        HISTORICPHOTO(/* ICON(data/imagery/) */ "historicphoto", tr("Historic or otherwise outdated aerial or satellite photo")),
125        /** A map for quality assurance **/
126        QUALITY_ASSURANCE(/* ICON(data/imagery/) */ "qa", tr("Map for quality assurance")),
127        /** Any other type of imagery **/
128        OTHER(/* ICON(data/imagery/) */ "other", tr("Imagery not matching any other category"));
129
130        private final String category;
131        private final String description;
132        private static final Map<ImageSizes, Map<ImageryCategory, ImageIcon>> iconCache =
133                Collections.synchronizedMap(new EnumMap<>(ImageSizes.class));
134
135        ImageryCategory(String category, String description) {
136            this.category = category;
137            this.description = description;
138        }
139
140        /**
141         * Returns the unique string identifying this category.
142         * @return the unique string identifying this category
143         */
144        @Override
145        public String getCategoryString() {
146            return category;
147        }
148
149        /**
150         * Returns the description of this category.
151         * @return the description of this category
152         */
153        @Override
154        public String getDescription() {
155            return description;
156        }
157
158        /**
159         * Returns the category icon at the given size.
160         * @param size icon wanted size
161         * @return the category icon at the given size
162         * @since 15049
163         */
164        @Override
165        public ImageIcon getIcon(ImageSizes size) {
166            return iconCache
167                    .computeIfAbsent(size, x -> Collections.synchronizedMap(new EnumMap<>(ImageryCategory.class)))
168                    .computeIfAbsent(this, x -> ImageProvider.get("data/imagery", x.category, size));
169        }
170
171        /**
172         * Returns the imagery category from the given category string.
173         * @param s The category string
174         * @return the imagery category matching the given category string
175         */
176        public static ImageryCategory fromString(String s) {
177            return Arrays.stream(ImageryCategory.values())
178                    .filter(category -> category.getCategoryString().equals(s))
179                    .findFirst().orElse(null);
180        }
181
182        @Override
183        public ImageryCategory getDefault() {
184            return OTHER;
185        }
186
187        @Override
188        public ImageryCategory getFromString(String s) {
189            return fromString(s);
190        }
191    }
192
193    /**
194     * Multi-polygon bounds for imagery backgrounds.
195     * Used to display imagery coverage in preferences and to determine relevant imagery entries based on edit location.
196     */
197    public static class ImageryBounds extends SourceBounds {
198
199        /**
200         * Constructs a new {@code ImageryBounds} from string.
201         * @param asString The string containing the list of shapes defining this bounds
202         * @param separator The shape separator in the given string, usually a comma
203         */
204        public ImageryBounds(String asString, String separator) {
205            super(asString, separator);
206        }
207    }
208
209    private static final String[] EMPTY_STRING = new String[0];
210
211    private double pixelPerDegree;
212    /** maximum zoom level for TMS imagery */
213    private int defaultMaxZoom;
214    /** minimum zoom level for TMS imagery */
215    private int defaultMinZoom;
216    /** projections supported by WMS servers */
217    private List<String> serverProjections = Collections.emptyList();
218    /**
219      * marked as best in other editors
220      * @since 11575
221      */
222    private boolean bestMarked;
223    /**
224      * marked as overlay
225      * @since 13536
226      */
227    private boolean overlay;
228
229    /** mirrors of different type for this entry */
230    protected List<ImageryInfo> mirrors;
231    /**
232     * Auxiliary class to save an {@link ImageryInfo} object in the preferences.
233     */
234    /** is the geo reference correct - don't offer offset handling */
235    private boolean isGeoreferenceValid;
236    /** Should this map be transparent **/
237    private boolean transparent = true;
238    private int minimumTileExpire = (int) TimeUnit.MILLISECONDS.toSeconds(TMSCachedTileLoaderJob.MINIMUM_EXPIRES.get());
239
240    /**
241     * The ImageryPreferenceEntry class for storing data in JOSM preferences.
242     *
243     * @author Frederik Ramm, modified by Taylor Smock
244     */
245    public static class ImageryPreferenceEntry extends SourcePreferenceEntry<ImageryInfo> {
246        @StructEntry String d;
247        @StructEntry double pixel_per_eastnorth;
248        @StructEntry int max_zoom;
249        @StructEntry int min_zoom;
250        @StructEntry String projections;
251        @StructEntry MultiMap<String, String> noTileHeaders;
252        @StructEntry MultiMap<String, String> noTileChecksums;
253        @StructEntry int tileSize = -1;
254        @StructEntry Map<String, String> metadataHeaders;
255        @StructEntry boolean valid_georeference;
256        @StructEntry boolean bestMarked;
257        @StructEntry boolean modTileFeatures;
258        @StructEntry boolean overlay;
259        @StructEntry boolean transparent;
260        @StructEntry int minimumTileExpire;
261
262        /**
263         * Constructs a new empty WMS {@code ImageryPreferenceEntry}.
264         */
265        public ImageryPreferenceEntry() {
266            super();
267        }
268
269        /**
270         * Constructs a new {@code ImageryPreferenceEntry} from a given {@code ImageryInfo}.
271         * @param i The corresponding imagery info
272         */
273        public ImageryPreferenceEntry(ImageryInfo i) {
274            super(i);
275            pixel_per_eastnorth = i.pixelPerDegree;
276            bestMarked = i.bestMarked;
277            overlay = i.overlay;
278            max_zoom = i.defaultMaxZoom;
279            min_zoom = i.defaultMinZoom;
280            if (!i.serverProjections.isEmpty()) {
281                projections = String.join(",", i.serverProjections);
282            }
283            if (!Utils.isEmpty(i.noTileHeaders)) {
284                noTileHeaders = new MultiMap<>(i.noTileHeaders);
285            }
286
287            if (!Utils.isEmpty(i.noTileChecksums)) {
288                noTileChecksums = new MultiMap<>(i.noTileChecksums);
289            }
290
291            if (!Utils.isEmpty(i.metadataHeaders)) {
292                metadataHeaders = i.metadataHeaders;
293            }
294
295            tileSize = i.getTileSize();
296
297            valid_georeference = i.isGeoreferenceValid();
298            modTileFeatures = i.isModTileFeatures();
299            transparent = i.isTransparent();
300            minimumTileExpire = i.minimumTileExpire;
301        }
302
303        @Override
304        public String toString() {
305            StringBuilder s = new StringBuilder("ImageryPreferenceEntry [name=").append(name);
306            if (id != null) {
307                s.append(" id=").append(id);
308            }
309            s.append(']');
310            return s.toString();
311        }
312    }
313
314    /**
315     * Constructs a new WMS {@code ImageryInfo}.
316     */
317    public ImageryInfo() {
318        super();
319    }
320
321    /**
322     * Constructs a new WMS {@code ImageryInfo} with a given name.
323     * @param name The entry name
324     */
325    public ImageryInfo(String name) {
326        super(name);
327    }
328
329    /**
330     * Constructs a new WMS {@code ImageryInfo} with given name and extended URL.
331     * @param name The entry name
332     * @param url The entry extended URL
333     */
334    public ImageryInfo(String name, String url) {
335        this(name);
336        setExtendedUrl(url);
337    }
338
339    /**
340     * Constructs a new WMS {@code ImageryInfo} with given name, extended and EULA URLs.
341     * @param name The entry name
342     * @param url The entry URL
343     * @param eulaAcceptanceRequired The EULA URL
344     */
345    public ImageryInfo(String name, String url, String eulaAcceptanceRequired) {
346        this(name);
347        setExtendedUrl(url);
348        this.eulaAcceptanceRequired = eulaAcceptanceRequired;
349    }
350
351    /**
352     * Constructs a new {@code ImageryInfo} with given name, url, extended and EULA URLs.
353     * @param name The entry name
354     * @param url The entry URL
355     * @param type The entry imagery type. If null, WMS will be used as default
356     * @param eulaAcceptanceRequired The EULA URL
357     * @param cookies The data part of HTTP cookies header in case the service requires cookies to work
358     * @throws IllegalArgumentException if type refers to an unknown imagery type
359     */
360    public ImageryInfo(String name, String url, String type, String eulaAcceptanceRequired, String cookies) {
361        this(name);
362        setExtendedUrl(url);
363        ImageryType t = ImageryType.fromString(type);
364        this.cookies = cookies;
365        this.eulaAcceptanceRequired = eulaAcceptanceRequired;
366        if (t != null) {
367            this.sourceType = t;
368        } else if (!Utils.isEmpty(type)) {
369            throw new IllegalArgumentException("unknown type: "+type);
370        }
371    }
372
373    /**
374     * Constructs a new {@code ImageryInfo} with given name, url, id, extended and EULA URLs.
375     * @param name The entry name
376     * @param url The entry URL
377     * @param type The entry imagery type. If null, WMS will be used as default
378     * @param eulaAcceptanceRequired The EULA URL
379     * @param cookies The data part of HTTP cookies header in case the service requires cookies to work
380     * @param id tile id
381     * @throws IllegalArgumentException if type refers to an unknown imagery type
382     */
383    public ImageryInfo(String name, String url, String type, String eulaAcceptanceRequired, String cookies, String id) {
384        this(name, url, type, eulaAcceptanceRequired, cookies);
385        setId(id);
386    }
387
388    /**
389     * Constructs a new {@code ImageryInfo} from an imagery preference entry.
390     * @param e The imagery preference entry
391     */
392    public ImageryInfo(ImageryPreferenceEntry e) {
393        super(e.name, e.url, e.id);
394        CheckParameterUtil.ensureParameterNotNull(e.name, "name");
395        CheckParameterUtil.ensureParameterNotNull(e.url, "url");
396        description = e.description;
397        cookies = e.cookies;
398        eulaAcceptanceRequired = e.eula;
399        sourceType = ImageryType.fromString(e.type);
400        if (sourceType == null) throw new IllegalArgumentException("unknown type");
401        pixelPerDegree = e.pixel_per_eastnorth;
402        defaultMaxZoom = e.max_zoom;
403        defaultMinZoom = e.min_zoom;
404        if (e.bounds != null) {
405            bounds = new ImageryBounds(e.bounds, ",");
406            if (e.shapes != null) {
407                try {
408                    for (String s : e.shapes.split(";", -1)) {
409                        bounds.addShape(new Shape(s, ","));
410                    }
411                } catch (IllegalArgumentException ex) {
412                    Logging.warn(ex);
413                }
414            }
415        }
416        if (!Utils.isEmpty(e.projections)) {
417            // split generates null element on empty string which gives one element Array[null]
418            setServerProjections(Arrays.asList(e.projections.split(",", -1)));
419        }
420        attributionText = Utils.intern(e.attribution_text);
421        attributionLinkURL = e.attribution_url;
422        permissionReferenceURL = e.permission_reference_url;
423        attributionImage = e.logo_image;
424        attributionImageURL = e.logo_url;
425        date = e.date;
426        bestMarked = e.bestMarked;
427        overlay = e.overlay;
428        termsOfUseText = e.terms_of_use_text;
429        termsOfUseURL = e.terms_of_use_url;
430        countryCode = Utils.intern(e.country_code);
431        icon = Utils.intern(e.icon);
432        if (e.noTileHeaders != null) {
433            noTileHeaders = e.noTileHeaders.toMap();
434        }
435        if (e.noTileChecksums != null) {
436            noTileChecksums = e.noTileChecksums.toMap();
437        }
438        setTileSize(e.tileSize);
439        metadataHeaders = e.metadataHeaders;
440        isGeoreferenceValid = e.valid_georeference;
441        modTileFeatures = e.modTileFeatures;
442        if (e.default_layers != null) {
443            try (JsonReader jsonReader = Json.createReader(new StringReader(e.default_layers))) {
444                defaultLayers = jsonReader.
445                        readArray().
446                        stream().
447                        map(x -> DefaultLayer.fromJson((JsonObject) x, sourceType)).
448                        collect(Collectors.toList());
449            }
450        }
451        setCustomHttpHeaders(e.customHttpHeaders);
452        transparent = e.transparent;
453        minimumTileExpire = e.minimumTileExpire;
454        category = ImageryCategory.fromString(e.category);
455    }
456
457    /**
458     * Constructs a new {@code ImageryInfo} from an existing one.
459     * @param i The other imagery info
460     */
461    public ImageryInfo(ImageryInfo i) {
462        super(i.name, i.url, i.id);
463        this.noTileHeaders = i.noTileHeaders;
464        this.noTileChecksums = i.noTileChecksums;
465        this.minZoom = i.minZoom;
466        this.maxZoom = i.maxZoom;
467        this.cookies = i.cookies;
468        this.tileSize = i.tileSize;
469        this.metadataHeaders = i.metadataHeaders;
470        this.modTileFeatures = i.modTileFeatures;
471
472        this.origName = i.origName;
473        this.langName = i.langName;
474        this.defaultEntry = i.defaultEntry;
475        this.eulaAcceptanceRequired = null;
476        this.sourceType = i.sourceType;
477        this.pixelPerDegree = i.pixelPerDegree;
478        this.defaultMaxZoom = i.defaultMaxZoom;
479        this.defaultMinZoom = i.defaultMinZoom;
480        this.bounds = i.bounds;
481        this.serverProjections = i.serverProjections;
482        this.description = i.description;
483        this.langDescription = i.langDescription;
484        this.attributionText = i.attributionText;
485        this.privacyPolicyURL = i.privacyPolicyURL;
486        this.permissionReferenceURL = i.permissionReferenceURL;
487        this.attributionLinkURL = i.attributionLinkURL;
488        this.attributionImage = i.attributionImage;
489        this.attributionImageURL = i.attributionImageURL;
490        this.termsOfUseText = i.termsOfUseText;
491        this.termsOfUseURL = i.termsOfUseURL;
492        this.countryCode = i.countryCode;
493        this.date = i.date;
494        this.bestMarked = i.bestMarked;
495        this.overlay = i.overlay;
496        // do not copy field {@code mirrors}
497        this.icon = Utils.intern(i.icon);
498        this.isGeoreferenceValid = i.isGeoreferenceValid;
499        setDefaultLayers(i.defaultLayers);
500        setCustomHttpHeaders(i.customHttpHeaders);
501        this.transparent = i.transparent;
502        this.minimumTileExpire = i.minimumTileExpire;
503        this.categoryOriginalString = Utils.intern(i.categoryOriginalString);
504        this.category = i.category;
505    }
506
507    /**
508     * Adds a mirror entry. Mirror entries are completed with the data from the master entry
509     * and only describe another method to access identical data.
510     *
511     * @param entry the mirror to be added
512     * @since 9658
513     */
514    public void addMirror(ImageryInfo entry) {
515        if (mirrors == null) {
516            mirrors = new ArrayList<>();
517        }
518        mirrors.add(entry);
519    }
520
521    /**
522     * Returns the mirror entries. Entries are completed with master entry data.
523     *
524     * @return the list of mirrors
525     * @since 9658
526     */
527    public List<ImageryInfo> getMirrors() {
528        List<ImageryInfo> l = new ArrayList<>();
529        if (mirrors != null) {
530            int num = 1;
531            for (ImageryInfo i : mirrors) {
532                ImageryInfo n = new ImageryInfo(this);
533                if (i.defaultMaxZoom != 0) {
534                    n.defaultMaxZoom = i.defaultMaxZoom;
535                }
536                if (i.defaultMinZoom != 0) {
537                    n.defaultMinZoom = i.defaultMinZoom;
538                }
539                n.setServerProjections(i.getServerProjections());
540                n.url = i.url;
541                n.sourceType = i.sourceType;
542                if (i.getTileSize() != 0) {
543                    n.setTileSize(i.getTileSize());
544                }
545                if (i.getPrivacyPolicyURL() != null) {
546                    n.setPrivacyPolicyURL(i.getPrivacyPolicyURL());
547                }
548                if (n.id != null) {
549                    n.id = n.id + "_mirror" + num;
550                }
551                if (num > 1) {
552                    n.name = tr("{0} mirror server {1}", n.name, num);
553                    if (n.origName != null) {
554                        n.origName += " mirror server " + num;
555                    }
556                } else {
557                    n.name = tr("{0} mirror server", n.name);
558                    if (n.origName != null) {
559                        n.origName += " mirror server";
560                    }
561                }
562                l.add(n);
563                ++num;
564            }
565        }
566        return l;
567    }
568
569    /**
570     * Check if this object equals another ImageryInfo with respect to the properties
571     * that get written to the preference file.
572     * <p>
573     * The field {@link #pixelPerDegree} is ignored.
574     *
575     * @param other the ImageryInfo object to compare to
576     * @return true if they are equal
577     */
578    @Override
579    public boolean equalsPref(SourceInfo<ImageryInfo.ImageryCategory, ImageryInfo.ImageryType,
580            ImageryInfo.ImageryBounds, ImageryInfo.ImageryPreferenceEntry> other) {
581        if (!(other instanceof ImageryInfo)) {
582            return false;
583        }
584        ImageryInfo realOther = (ImageryInfo) other;
585
586        // CHECKSTYLE.OFF: BooleanExpressionComplexity
587        return super.equalsPref(realOther) &&
588                this.bestMarked == realOther.bestMarked &&
589                this.overlay == realOther.overlay &&
590                this.isGeoreferenceValid == realOther.isGeoreferenceValid &&
591                this.defaultMaxZoom == realOther.defaultMaxZoom &&
592                this.defaultMinZoom == realOther.defaultMinZoom &&
593                Objects.equals(this.serverProjections, realOther.serverProjections) &&
594                this.transparent == realOther.transparent &&
595                this.minimumTileExpire == realOther.minimumTileExpire;
596        // CHECKSTYLE.ON: BooleanExpressionComplexity
597    }
598
599    @Override
600    public int compareTo(SourceInfo<ImageryInfo.ImageryCategory, ImageryInfo.ImageryType,
601            ImageryInfo.ImageryBounds, ImageryInfo.ImageryPreferenceEntry> other) {
602        int i = super.compareTo(other);
603        if (other instanceof ImageryInfo) {
604            ImageryInfo in = (ImageryInfo) other;
605            if (i == 0) {
606                i = Double.compare(pixelPerDegree, in.pixelPerDegree);
607            }
608        }
609        return i;
610    }
611
612    /**
613     * Sets the pixel per degree value.
614     * @param ppd The ppd value
615     * @see #getPixelPerDegree()
616     */
617    public void setPixelPerDegree(double ppd) {
618        this.pixelPerDegree = ppd;
619    }
620
621    /**
622     * Sets the maximum zoom level.
623     * @param defaultMaxZoom The maximum zoom level
624     */
625    public void setDefaultMaxZoom(int defaultMaxZoom) {
626        this.defaultMaxZoom = defaultMaxZoom;
627    }
628
629    /**
630     * Sets the minimum zoom level.
631     * @param defaultMinZoom The minimum zoom level
632     */
633    public void setDefaultMinZoom(int defaultMinZoom) {
634        this.defaultMinZoom = defaultMinZoom;
635    }
636
637    @Override
638    public void setBounds(ImageryBounds b) {
639        // for binary compatibility
640        this.bounds = b;
641    }
642
643    @Override
644    public ImageryBounds getBounds() {
645        // for binary compatibility
646        return super.getBounds();
647    }
648
649    /**
650     * Sets the extended URL of this entry.
651     * @param url Entry extended URL containing in addition of service URL, its type and min/max zoom info
652     */
653    public void setExtendedUrl(String url) {
654        CheckParameterUtil.ensureParameterNotNull(url);
655
656        // Default imagery type is WMS
657        this.url = url;
658        this.sourceType = ImageryType.WMS;
659
660        defaultMaxZoom = 0;
661        defaultMinZoom = 0;
662        for (ImageryType type : ImageryType.values()) {
663            Matcher m = Pattern.compile(type.getTypeString()+"(?:\\[(?:(\\d+)[,-])?(\\d+)])?:(.*)").matcher(url);
664            if (m.matches()) {
665                this.url = m.group(3);
666                this.sourceType = type;
667                if (m.group(2) != null) {
668                    defaultMaxZoom = Integer.parseInt(m.group(2));
669                }
670                if (m.group(1) != null) {
671                    defaultMinZoom = Integer.parseInt(m.group(1));
672                }
673                break;
674            }
675        }
676
677        if (serverProjections.isEmpty()) {
678            Matcher m = Pattern.compile(".*\\{PROJ\\(([^)}]+)\\)}.*").matcher(url.toUpperCase(Locale.ENGLISH));
679            if (m.matches()) {
680                setServerProjections(Arrays.asList(m.group(1).split(",", -1)));
681            }
682        }
683    }
684
685    /**
686     * Gets the pixel per degree value
687     * @return The ppd value.
688     */
689    public double getPixelPerDegree() {
690        return this.pixelPerDegree;
691    }
692
693    /**
694     * Returns the maximum zoom level.
695     * @return The maximum zoom level
696     */
697    @Override
698    public int getMaxZoom() {
699        return this.defaultMaxZoom;
700    }
701
702    /**
703     * Returns the minimum zoom level.
704     * @return The minimum zoom level
705     */
706    @Override
707    public int getMinZoom() {
708        return this.defaultMinZoom;
709    }
710
711    /**
712     * Returns a tool tip text for display.
713     * @return The text
714     * @since 8065
715     */
716    @Override
717    public String getToolTipText() {
718        boolean htmlSupported = PlatformManager.getPlatform().isHtmlSupportedInMenuTooltips();
719        StringBuilder res = new StringBuilder(getName());
720        boolean html = false;
721        String dateStr = getDate();
722        if (!Utils.isEmpty(dateStr)) {
723            html = addNewLineInTooltip(res, tr("Date of imagery: {0}", dateStr), htmlSupported);
724        }
725        if (category != null && category.getDescription() != null) {
726            html = addNewLineInTooltip(res, tr("Imagery category: {0}", category.getDescription()), htmlSupported);
727        }
728        if (bestMarked) {
729            html = addNewLineInTooltip(res, tr("This imagery is marked as best in this region in other editors."), htmlSupported);
730        }
731        if (overlay) {
732            html = addNewLineInTooltip(res, tr("This imagery is an overlay."), htmlSupported);
733        }
734        String desc = getDescription();
735        if (!Utils.isEmpty(desc)) {
736            html = addNewLineInTooltip(res, desc, htmlSupported);
737        }
738        if (html) {
739            res.insert(0, "<html>").append("</html>");
740        }
741        return res.toString();
742    }
743
744    private static boolean addNewLineInTooltip(StringBuilder res, String line, boolean htmlSupported) {
745        if (htmlSupported) {
746            res.append("<br>").append(Utils.escapeReservedCharactersHTML(line));
747        } else {
748            res.append('\n').append(line);
749        }
750        return htmlSupported;
751    }
752
753    /**
754     * Get the projections supported by the server. Only relevant for
755     * WMS-type ImageryInfo at the moment.
756     * @return null, if no projections have been specified; the list
757     * of supported projections otherwise.
758     */
759    public List<String> getServerProjections() {
760        return Collections.unmodifiableList(serverProjections);
761    }
762
763    /**
764     * Sets the list of collections the server supports
765     * @param serverProjections The list of supported projections
766     */
767    public void setServerProjections(Collection<String> serverProjections) {
768        CheckParameterUtil.ensureParameterNotNull(serverProjections, "serverProjections");
769        this.serverProjections = serverProjections.stream()
770                .map(String::intern)
771                .collect(StreamUtils.toUnmodifiableList());
772    }
773
774    /**
775     * Returns the extended URL, containing in addition of service URL, its type and min/max zoom info.
776     * @return The extended URL
777     */
778    public String getExtendedUrl() {
779        return sourceType.getTypeString() + (defaultMaxZoom != 0
780            ? ('['+(defaultMinZoom != 0 ? (Integer.toString(defaultMinZoom) + ',') : "")+defaultMaxZoom+']') : "") + ':' + url;
781    }
782
783    /**
784     * Gets a unique toolbar key to store this layer as toolbar item
785     * @return The key.
786     */
787    public String getToolbarName() {
788        String res = name;
789        if (pixelPerDegree != 0) {
790            res += "#PPD="+pixelPerDegree;
791        }
792        return res;
793    }
794
795    /**
796     * Gets the name that should be displayed in the menu to add this imagery layer.
797     * @return The text.
798     */
799    public String getMenuName() {
800        String res = name;
801        if (pixelPerDegree != 0) {
802            res += " ("+pixelPerDegree+')';
803        }
804        return res;
805    }
806
807    /**
808     * Returns the imagery type.
809     * @return The imagery type
810     * @see SourceInfo#getSourceType
811     */
812    public ImageryType getImageryType() {
813        return super.getSourceType() != null ? super.getSourceType() : ImageryType.WMS.getDefault();
814    }
815
816    /**
817     * Sets the imagery type.
818     * @param imageryType The imagery type
819     * @see SourceInfo#setSourceType
820     */
821    public void setImageryType(ImageryType imageryType) {
822        super.setSourceType(imageryType);
823    }
824
825    /**
826     * Returns the imagery category.
827     * @return The imagery category
828     * @see SourceInfo#getSourceCategory
829     * @since 13792
830     */
831    public ImageryCategory getImageryCategory() {
832        return super.getSourceCategory();
833    }
834
835    /**
836     * Sets the imagery category.
837     * @param category The imagery category
838     * @see SourceInfo#setSourceCategory
839     * @since 13792
840     */
841    public void setImageryCategory(ImageryCategory category) {
842        super.setSourceCategory(category);
843    }
844
845    /**
846     * Returns the imagery category original string (don't use except for error checks).
847     * @return The imagery category original string
848     * @see SourceInfo#getSourceCategoryOriginalString
849     * @since 13792
850     */
851    public String getImageryCategoryOriginalString() {
852        return super.getSourceCategoryOriginalString();
853    }
854
855    /**
856     * Sets the imagery category original string (don't use except for error checks).
857     * @param categoryOriginalString The imagery category original string
858     * @see SourceInfo#setSourceCategoryOriginalString
859     * @since 13792
860     */
861    public void setImageryCategoryOriginalString(String categoryOriginalString) {
862        super.setSourceCategoryOriginalString(categoryOriginalString);
863    }
864
865    /**
866     * Gets the flag if the georeference is valid.
867     * @return <code>true</code> if it is valid.
868     */
869    public boolean isGeoreferenceValid() {
870        return isGeoreferenceValid;
871    }
872
873    /**
874     * Sets an indicator that the georeference is valid
875     * @param isGeoreferenceValid <code>true</code> if it is marked as valid.
876     */
877    public void setGeoreferenceValid(boolean isGeoreferenceValid) {
878        this.isGeoreferenceValid = isGeoreferenceValid;
879    }
880
881    /**
882     * Returns the status of "best" marked status in other editors.
883     * @return <code>true</code> if it is marked as best.
884     * @since 11575
885     */
886    public boolean isBestMarked() {
887        return bestMarked;
888    }
889
890    /**
891     * Returns the overlay indication.
892     * @return <code>true</code> if it is an overlay.
893     * @since 13536
894     */
895    public boolean isOverlay() {
896        return overlay;
897    }
898
899    /**
900     * Sets an indicator that in other editors it is marked as best imagery
901     * @param bestMarked <code>true</code> if it is marked as best in other editors.
902     * @since 11575
903     */
904    public void setBestMarked(boolean bestMarked) {
905        this.bestMarked = bestMarked;
906    }
907
908    /**
909     * Sets overlay indication
910     * @param overlay <code>true</code> if it is an overlay.
911     * @since 13536
912     */
913    public void setOverlay(boolean overlay) {
914        this.overlay = overlay;
915    }
916
917    /**
918     * Determines if this imagery should be transparent.
919     * @return should this imagery be transparent
920     */
921    public boolean isTransparent() {
922        return transparent;
923    }
924
925    /**
926     * Sets whether imagery should be transparent.
927     * @param transparent set to true if imagery should be transparent
928     */
929    public void setTransparent(boolean transparent) {
930        this.transparent = transparent;
931    }
932
933    /**
934     * Returns minimum tile expiration in seconds.
935     * @return minimum tile expiration in seconds
936     */
937    public int getMinimumTileExpire() {
938        return minimumTileExpire;
939    }
940
941    /**
942     * Sets minimum tile expiration in seconds.
943     * @param minimumTileExpire minimum tile expiration in seconds
944     */
945    public void setMinimumTileExpire(int minimumTileExpire) {
946        this.minimumTileExpire = minimumTileExpire;
947    }
948
949    /**
950     * Get a string representation of this imagery info suitable for the {@code source} changeset tag.
951     * @return English name, if known
952     * @since 13890
953     */
954    public String getSourceName() {
955        if (ImageryType.BING == getImageryType()) {
956            return "Bing";
957        } else {
958            if (id != null) {
959                // Retrieve english name, unfortunately not saved in preferences
960                Optional<ImageryInfo> infoEn = ImageryLayerInfo.allDefaultLayers.stream().filter(x -> id.equals(x.getId())).findAny();
961                if (infoEn.isPresent()) {
962                    return infoEn.get().getOriginalName();
963                }
964            }
965            return getOriginalName();
966        }
967    }
968
969    /**
970     * Check to see if this info is valid (the XSD is overly permissive due to limitations of the XSD syntax).
971     * @return {@code true} if this info is valid
972     * @see ImageryInfo#getMissingFields()
973     * @since 18989
974     */
975    public boolean isValid() {
976        return this.getName() != null &&
977                this.getId() != null &&
978                this.getSourceType() != null &&
979                this.getUrl() != null &&
980                this.getImageryCategory() != null;
981    }
982
983    /**
984     * Get the missing fields for this info
985     * @return The missing fields, or an empty array
986     * @see ImageryInfo#isValid()
987     * @since 18989
988     */
989    public String[] getMissingFields() {
990        if (this.isValid()) {
991            return EMPTY_STRING;
992        }
993        List<String> missingFields = new ArrayList<>();
994        if (this.getName() == null) {
995            missingFields.add("name");
996        }
997        if (this.getId() == null) {
998            missingFields.add("id");
999        }
1000        if (this.getSourceType() == null) {
1001            missingFields.add("type");
1002        }
1003        if (this.getUrl() == null) {
1004            missingFields.add("url");
1005        }
1006        if (this.getImageryCategory() == null) {
1007            missingFields.add("category");
1008        }
1009        return missingFields.toArray(new String[0]);
1010    }
1011
1012    /**
1013     * Return the sorted list of activated source IDs.
1014     * @return sorted list of activated source IDs
1015     * @since 13536
1016     */
1017    public static Collection<String> getActiveIds() {
1018        return getActiveIds(ImageryInfo.class);
1019    }
1020}