001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Color;
007import java.awt.Cursor;
008import java.awt.Dimension;
009import java.awt.Graphics;
010import java.awt.Graphics2D;
011import java.awt.GraphicsEnvironment;
012import java.awt.Image;
013import java.awt.Point;
014import java.awt.RenderingHints;
015import java.awt.Toolkit;
016import java.awt.Transparency;
017import java.awt.image.BufferedImage;
018import java.awt.image.ColorModel;
019import java.awt.image.FilteredImageSource;
020import java.awt.image.ImageFilter;
021import java.awt.image.ImageProducer;
022import java.awt.image.RGBImageFilter;
023import java.awt.image.WritableRaster;
024import java.io.ByteArrayInputStream;
025import java.io.File;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.StringReader;
029import java.net.URI;
030import java.net.URL;
031import java.nio.charset.StandardCharsets;
032import java.util.ArrayList;
033import java.util.Arrays;
034import java.util.Base64;
035import java.util.Collection;
036import java.util.HashMap;
037import java.util.Hashtable;
038import java.util.Iterator;
039import java.util.LinkedList;
040import java.util.List;
041import java.util.Map;
042import java.util.TreeSet;
043import java.util.concurrent.CompletableFuture;
044import java.util.concurrent.ExecutorService;
045import java.util.concurrent.Executors;
046import java.util.regex.Matcher;
047import java.util.regex.Pattern;
048import java.util.zip.ZipEntry;
049import java.util.zip.ZipFile;
050
051import javax.imageio.IIOException;
052import javax.imageio.ImageIO;
053import javax.imageio.ImageReadParam;
054import javax.imageio.ImageReader;
055import javax.imageio.metadata.IIOMetadata;
056import javax.imageio.stream.ImageInputStream;
057import javax.swing.ImageIcon;
058import javax.xml.parsers.ParserConfigurationException;
059
060import org.openstreetmap.josm.Main;
061import org.openstreetmap.josm.data.osm.DataSet;
062import org.openstreetmap.josm.data.osm.OsmPrimitive;
063import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
064import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
065import org.openstreetmap.josm.gui.mappaint.Range;
066import org.openstreetmap.josm.gui.mappaint.StyleElementList;
067import org.openstreetmap.josm.gui.mappaint.styleelement.MapImage;
068import org.openstreetmap.josm.gui.mappaint.styleelement.NodeElement;
069import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
070import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
071import org.openstreetmap.josm.gui.tagging.presets.TaggingPresets;
072import org.openstreetmap.josm.gui.util.GuiSizesHelper;
073import org.openstreetmap.josm.io.CachedFile;
074import org.openstreetmap.josm.plugins.PluginHandler;
075import org.w3c.dom.Element;
076import org.w3c.dom.Node;
077import org.w3c.dom.NodeList;
078import org.xml.sax.Attributes;
079import org.xml.sax.InputSource;
080import org.xml.sax.SAXException;
081import org.xml.sax.XMLReader;
082import org.xml.sax.helpers.DefaultHandler;
083
084import com.kitfox.svg.SVGDiagram;
085import com.kitfox.svg.SVGException;
086import com.kitfox.svg.SVGUniverse;
087
088/**
089 * Helper class to support the application with images.
090 *
091 * How to use:
092 *
093 * <code>ImageIcon icon = new ImageProvider(name).setMaxSize(ImageSizes.MAP).get();</code>
094 * (there are more options, see below)
095 *
096 * short form:
097 * <code>ImageIcon icon = ImageProvider.get(name);</code>
098 *
099 * @author imi
100 */
101public class ImageProvider {
102
103    // CHECKSTYLE.OFF: SingleSpaceSeparator
104    private static final String HTTP_PROTOCOL  = "http://";
105    private static final String HTTPS_PROTOCOL = "https://";
106    private static final String WIKI_PROTOCOL  = "wiki://";
107    // CHECKSTYLE.ON: SingleSpaceSeparator
108
109    /**
110     * Supported image types
111     */
112    public enum ImageType {
113        /** Scalable vector graphics */
114        SVG,
115        /** Everything else, e.g. png, gif (must be supported by Java) */
116        OTHER
117    }
118
119    /**
120     * Supported image sizes
121     * @since 7687
122     */
123    public enum ImageSizes {
124        /** SMALL_ICON value of an Action */
125        SMALLICON(Main.pref.getInteger("iconsize.smallicon", 16)),
126        /** LARGE_ICON_KEY value of an Action */
127        LARGEICON(Main.pref.getInteger("iconsize.largeicon", 24)),
128        /** map icon */
129        MAP(Main.pref.getInteger("iconsize.map", 16)),
130        /** map icon maximum size */
131        MAPMAX(Main.pref.getInteger("iconsize.mapmax", 48)),
132        /** cursor icon size */
133        CURSOR(Main.pref.getInteger("iconsize.cursor", 32)),
134        /** cursor overlay icon size */
135        CURSOROVERLAY(CURSOR),
136        /** menu icon size */
137        MENU(SMALLICON),
138        /** menu icon size in popup menus
139         * @since 8323
140         */
141        POPUPMENU(LARGEICON),
142        /** Layer list icon size
143         * @since 8323
144         */
145        LAYER(Main.pref.getInteger("iconsize.layer", 16)),
146        /** Toolbar button icon size
147         * @since 9253
148         */
149        TOOLBAR(LARGEICON),
150        /** Side button maximum height
151         * @since 9253
152         */
153        SIDEBUTTON(Main.pref.getInteger("iconsize.sidebutton", 20)),
154        /** Settings tab icon size
155         * @since 9253
156         */
157        SETTINGS_TAB(Main.pref.getInteger("iconsize.settingstab", 48)),
158        /**
159         * The default image size
160         * @since 9705
161         */
162        DEFAULT(Main.pref.getInteger("iconsize.default", 24)),
163        /**
164         * Splash dialog logo size
165         * @since 10358
166         */
167        SPLASH_LOGO(128, 129),
168        /**
169         * About dialog logo size
170         * @since 10358
171         */
172        ABOUT_LOGO(256, 258);
173
174        private final int virtualWidth;
175        private final int virtualHeight;
176
177        ImageSizes(int imageSize) {
178            this.virtualWidth = imageSize;
179            this.virtualHeight = imageSize;
180        }
181
182        ImageSizes(int width, int height) {
183            this.virtualWidth = width;
184            this.virtualHeight = height;
185        }
186
187        ImageSizes(ImageSizes that) {
188            this.virtualWidth = that.virtualWidth;
189            this.virtualHeight = that.virtualHeight;
190        }
191
192        /**
193         * Returns the image width in virtual pixels
194         * @return the image width in virtual pixels
195         * @since 9705
196         */
197        public int getVirtualWidth() {
198            return virtualWidth;
199        }
200
201        /**
202         * Returns the image height in virtual pixels
203         * @return the image height in virtual pixels
204         * @since 9705
205         */
206        public int getVirtualHeight() {
207            return virtualHeight;
208        }
209
210        /**
211         * Returns the image width in pixels to use for display
212         * @return the image width in pixels to use for display
213         * @since 10484
214         */
215        public int getAdjustedWidth() {
216            return GuiSizesHelper.getSizeDpiAdjusted(virtualWidth);
217        }
218
219        /**
220         * Returns the image height in pixels to use for display
221         * @return the image height in pixels to use for display
222         * @since 10484
223         */
224        public int getAdjustedHeight() {
225            return GuiSizesHelper.getSizeDpiAdjusted(virtualHeight);
226        }
227
228        /**
229         * Returns the image size as dimension
230         * @return the image size as dimension
231         * @since 9705
232         */
233        public Dimension getImageDimension() {
234            return new Dimension(virtualWidth, virtualHeight);
235        }
236    }
237
238    /**
239     * Property set on {@code BufferedImage} returned by {@link #makeImageTransparent}.
240     * @since 7132
241     */
242    public static final String PROP_TRANSPARENCY_FORCED = "josm.transparency.forced";
243
244    /**
245     * Property set on {@code BufferedImage} returned by {@link #read} if metadata is required.
246     * @since 7132
247     */
248    public static final String PROP_TRANSPARENCY_COLOR = "josm.transparency.color";
249
250    /** directories in which images are searched */
251    protected Collection<String> dirs;
252    /** caching identifier */
253    protected String id;
254    /** sub directory the image can be found in */
255    protected String subdir;
256    /** image file name */
257    protected String name;
258    /** archive file to take image from */
259    protected File archive;
260    /** directory inside the archive */
261    protected String inArchiveDir;
262    /** virtual width of the resulting image, -1 when original image data should be used */
263    protected int virtualWidth = -1;
264    /** virtual height of the resulting image, -1 when original image data should be used */
265    protected int virtualHeight = -1;
266    /** virtual maximum width of the resulting image, -1 for no restriction */
267    protected int virtualMaxWidth = -1;
268    /** virtual maximum height of the resulting image, -1 for no restriction */
269    protected int virtualMaxHeight = -1;
270    /** In case of errors do not throw exception but return <code>null</code> for missing image */
271    protected boolean optional;
272    /** <code>true</code> if warnings should be suppressed */
273    protected boolean suppressWarnings;
274    /** list of class loaders to take images from */
275    protected Collection<ClassLoader> additionalClassLoaders;
276    /** ordered list of overlay images */
277    protected List<ImageOverlay> overlayInfo;
278    /** <code>true</code> if icon must be grayed out */
279    protected boolean isDisabled;
280
281    private static SVGUniverse svgUniverse;
282
283    /**
284     * The icon cache
285     */
286    private static final Map<String, ImageResource> cache = new HashMap<>();
287
288    /**
289     * Caches the image data for rotated versions of the same image.
290     */
291    private static final Map<Image, Map<Long, ImageResource>> ROTATE_CACHE = new HashMap<>();
292
293    private static final ExecutorService IMAGE_FETCHER =
294            Executors.newSingleThreadExecutor(Utils.newThreadFactory("image-fetcher-%d", Thread.NORM_PRIORITY));
295
296    /**
297     * Constructs a new {@code ImageProvider} from a filename in a given directory.
298     * @param subdir subdirectory the image lies in
299     * @param name the name of the image. If it does not end with '.png' or '.svg',
300     * both extensions are tried.
301     */
302    public ImageProvider(String subdir, String name) {
303        this.subdir = subdir;
304        this.name = name;
305    }
306
307    /**
308     * Constructs a new {@code ImageProvider} from a filename.
309     * @param name the name of the image. If it does not end with '.png' or '.svg',
310     * both extensions are tried.
311     */
312    public ImageProvider(String name) {
313        this.name = name;
314    }
315
316    /**
317     * Constructs a new {@code ImageProvider} from an existing one.
318     * @param image the existing image provider to be copied
319     * @since 8095
320     */
321    public ImageProvider(ImageProvider image) {
322        this.dirs = image.dirs;
323        this.id = image.id;
324        this.subdir = image.subdir;
325        this.name = image.name;
326        this.archive = image.archive;
327        this.inArchiveDir = image.inArchiveDir;
328        this.virtualWidth = image.virtualWidth;
329        this.virtualHeight = image.virtualHeight;
330        this.virtualMaxWidth = image.virtualMaxWidth;
331        this.virtualMaxHeight = image.virtualMaxHeight;
332        this.optional = image.optional;
333        this.suppressWarnings = image.suppressWarnings;
334        this.additionalClassLoaders = image.additionalClassLoaders;
335        this.overlayInfo = image.overlayInfo;
336        this.isDisabled = image.isDisabled;
337    }
338
339    /**
340     * Directories to look for the image.
341     * @param dirs The directories to look for.
342     * @return the current object, for convenience
343     */
344    public ImageProvider setDirs(Collection<String> dirs) {
345        this.dirs = dirs;
346        return this;
347    }
348
349    /**
350     * Set an id used for caching.
351     * If name starts with <tt>http://</tt> Id is not used for the cache.
352     * (A URL is unique anyway.)
353     * @param id the id for the cached image
354     * @return the current object, for convenience
355     */
356    public ImageProvider setId(String id) {
357        this.id = id;
358        return this;
359    }
360
361    /**
362     * Specify a zip file where the image is located.
363     *
364     * (optional)
365     * @param archive zip file where the image is located
366     * @return the current object, for convenience
367     */
368    public ImageProvider setArchive(File archive) {
369        this.archive = archive;
370        return this;
371    }
372
373    /**
374     * Specify a base path inside the zip file.
375     *
376     * The subdir and name will be relative to this path.
377     *
378     * (optional)
379     * @param inArchiveDir path inside the archive
380     * @return the current object, for convenience
381     */
382    public ImageProvider setInArchiveDir(String inArchiveDir) {
383        this.inArchiveDir = inArchiveDir;
384        return this;
385    }
386
387    /**
388     * Add an overlay over the image. Multiple overlays are possible.
389     *
390     * @param overlay overlay image and placement specification
391     * @return the current object, for convenience
392     * @since 8095
393     */
394    public ImageProvider addOverlay(ImageOverlay overlay) {
395        if (overlayInfo == null) {
396            overlayInfo = new LinkedList<>();
397        }
398        overlayInfo.add(overlay);
399        return this;
400    }
401
402    /**
403     * Set the dimensions of the image.
404     *
405     * If not specified, the original size of the image is used.
406     * The width part of the dimension can be -1. Then it will only set the height but
407     * keep the aspect ratio. (And the other way around.)
408     * @param size final dimensions of the image
409     * @return the current object, for convenience
410     */
411    public ImageProvider setSize(Dimension size) {
412        this.virtualWidth = size.width;
413        this.virtualHeight = size.height;
414        return this;
415    }
416
417    /**
418     * Set the dimensions of the image.
419     *
420     * If not specified, the original size of the image is used.
421     * @param size final dimensions of the image
422     * @return the current object, for convenience
423     * @since 7687
424     */
425    public ImageProvider setSize(ImageSizes size) {
426        return setSize(size.getImageDimension());
427    }
428
429    /**
430     * Set the dimensions of the image.
431     *
432     * @param width final width of the image
433     * @param height final height of the image
434     * @return the current object, for convenience
435     * @since 10358
436     */
437    public ImageProvider setSize(int width, int height) {
438        this.virtualWidth = width;
439        this.virtualHeight = height;
440        return this;
441    }
442
443    /**
444     * Set image width
445     * @param width final width of the image
446     * @return the current object, for convenience
447     * @see #setSize
448     */
449    public ImageProvider setWidth(int width) {
450        this.virtualWidth = width;
451        return this;
452    }
453
454    /**
455     * Set image height
456     * @param height final height of the image
457     * @return the current object, for convenience
458     * @see #setSize
459     */
460    public ImageProvider setHeight(int height) {
461        this.virtualHeight = height;
462        return this;
463    }
464
465    /**
466     * Limit the maximum size of the image.
467     *
468     * It will shrink the image if necessary, but keep the aspect ratio.
469     * The given width or height can be -1 which means this direction is not bounded.
470     *
471     * 'size' and 'maxSize' are not compatible, you should set only one of them.
472     * @param maxSize maximum image size
473     * @return the current object, for convenience
474     */
475    public ImageProvider setMaxSize(Dimension maxSize) {
476        this.virtualMaxWidth = maxSize.width;
477        this.virtualMaxHeight = maxSize.height;
478        return this;
479    }
480
481    /**
482     * Limit the maximum size of the image.
483     *
484     * It will shrink the image if necessary, but keep the aspect ratio.
485     * The given width or height can be -1 which means this direction is not bounded.
486     *
487     * This function sets value using the most restrictive of the new or existing set of
488     * values.
489     *
490     * @param maxSize maximum image size
491     * @return the current object, for convenience
492     * @see #setMaxSize(Dimension)
493     */
494    public ImageProvider resetMaxSize(Dimension maxSize) {
495        if (this.virtualMaxWidth == -1 || maxSize.width < this.virtualMaxWidth) {
496            this.virtualMaxWidth = maxSize.width;
497        }
498        if (this.virtualMaxHeight == -1 || maxSize.height < this.virtualMaxHeight) {
499            this.virtualMaxHeight = maxSize.height;
500        }
501        return this;
502    }
503
504    /**
505     * Limit the maximum size of the image.
506     *
507     * It will shrink the image if necessary, but keep the aspect ratio.
508     * The given width or height can be -1 which means this direction is not bounded.
509     *
510     * 'size' and 'maxSize' are not compatible, you should set only one of them.
511     * @param size maximum image size
512     * @return the current object, for convenience
513     * @since 7687
514     */
515    public ImageProvider setMaxSize(ImageSizes size) {
516        return setMaxSize(size.getImageDimension());
517    }
518
519    /**
520     * Convenience method, see {@link #setMaxSize(Dimension)}.
521     * @param maxSize maximum image size
522     * @return the current object, for convenience
523     */
524    public ImageProvider setMaxSize(int maxSize) {
525        return this.setMaxSize(new Dimension(maxSize, maxSize));
526    }
527
528    /**
529     * Limit the maximum width of the image.
530     * @param maxWidth maximum image width
531     * @return the current object, for convenience
532     * @see #setMaxSize
533     */
534    public ImageProvider setMaxWidth(int maxWidth) {
535        this.virtualMaxWidth = maxWidth;
536        return this;
537    }
538
539    /**
540     * Limit the maximum height of the image.
541     * @param maxHeight maximum image height
542     * @return the current object, for convenience
543     * @see #setMaxSize
544     */
545    public ImageProvider setMaxHeight(int maxHeight) {
546        this.virtualMaxHeight = maxHeight;
547        return this;
548    }
549
550    /**
551     * Decide, if an exception should be thrown, when the image cannot be located.
552     *
553     * Set to true, when the image URL comes from user data and the image may be missing.
554     *
555     * @param optional true, if JOSM should <b>not</b> throw a RuntimeException
556     * in case the image cannot be located.
557     * @return the current object, for convenience
558     */
559    public ImageProvider setOptional(boolean optional) {
560        this.optional = optional;
561        return this;
562    }
563
564    /**
565     * Suppresses warning on the command line in case the image cannot be found.
566     *
567     * In combination with setOptional(true);
568     * @param suppressWarnings if <code>true</code> warnings are suppressed
569     * @return the current object, for convenience
570     */
571    public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
572        this.suppressWarnings = suppressWarnings;
573        return this;
574    }
575
576    /**
577     * Add a collection of additional class loaders to search image for.
578     * @param additionalClassLoaders class loaders to add to the internal list
579     * @return the current object, for convenience
580     */
581    public ImageProvider setAdditionalClassLoaders(Collection<ClassLoader> additionalClassLoaders) {
582        this.additionalClassLoaders = additionalClassLoaders;
583        return this;
584    }
585
586    /**
587     * Set, if image must be filtered to grayscale so it will look like disabled icon.
588     *
589     * @param disabled true, if image must be grayed out for disabled state
590     * @return the current object, for convenience
591     * @since 10428
592     */
593    public ImageProvider setDisabled(boolean disabled) {
594        this.isDisabled = disabled;
595        return this;
596    }
597
598    /**
599     * Execute the image request and scale result.
600     * @return the requested image or null if the request failed
601     */
602    public ImageIcon get() {
603        ImageResource ir = getResource();
604
605        if (ir == null) {
606            return null;
607        }
608        if (virtualMaxWidth != -1 || virtualMaxHeight != -1)
609            return ir.getImageIconBounded(new Dimension(virtualMaxWidth, virtualMaxHeight));
610        else
611            return ir.getImageIcon(new Dimension(virtualWidth, virtualHeight));
612    }
613
614    /**
615     * Load the image in a background thread.
616     *
617     * This method returns immediately and runs the image request asynchronously.
618     *
619     * @return the future of the requested image
620     * @since 10714
621     */
622    public CompletableFuture<ImageIcon> getAsync() {
623        return name.startsWith(HTTP_PROTOCOL) || name.startsWith(WIKI_PROTOCOL)
624                ? CompletableFuture.supplyAsync(this::get, IMAGE_FETCHER)
625                : CompletableFuture.completedFuture(get());
626    }
627
628    /**
629     * Execute the image request.
630     *
631     * @return the requested image or null if the request failed
632     * @since 7693
633     */
634    public ImageResource getResource() {
635        ImageResource ir = getIfAvailableImpl(additionalClassLoaders);
636        if (ir == null) {
637            if (!optional) {
638                String ext = name.indexOf('.') != -1 ? "" : ".???";
639                throw new RuntimeException(
640                        tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.",
641                                name + ext));
642            } else {
643                if (!suppressWarnings) {
644                    Main.error(tr("Failed to locate image ''{0}''", name));
645                }
646                return null;
647            }
648        }
649        if (overlayInfo != null) {
650            ir = new ImageResource(ir, overlayInfo);
651        }
652        if (isDisabled) {
653            ir.setDisabled(true);
654        }
655        return ir;
656    }
657
658    /**
659     * Load the image in a background thread.
660     *
661     * This method returns immediately and runs the image request asynchronously.
662     *
663     * @return the future of the requested image
664     * @since 10714
665     */
666    public CompletableFuture<ImageResource> getResourceAsync() {
667        return name.startsWith(HTTP_PROTOCOL) || name.startsWith(WIKI_PROTOCOL)
668                ? CompletableFuture.supplyAsync(this::getResource, IMAGE_FETCHER)
669                : CompletableFuture.completedFuture(getResource());
670    }
671
672    /**
673     * Load an image with a given file name.
674     *
675     * @param subdir subdirectory the image lies in
676     * @param name The icon name (base name with or without '.png' or '.svg' extension)
677     * @return The requested Image.
678     * @throws RuntimeException if the image cannot be located
679     */
680    public static ImageIcon get(String subdir, String name) {
681        return new ImageProvider(subdir, name).get();
682    }
683
684    /**
685     * Load an image with a given file name.
686     *
687     * @param name The icon name (base name with or without '.png' or '.svg' extension)
688     * @return the requested image or null if the request failed
689     * @see #get(String, String)
690     */
691    public static ImageIcon get(String name) {
692        return new ImageProvider(name).get();
693    }
694
695    /**
696     * Load an image from directory with a given file name and size.
697     *
698     * @param subdir subdirectory the image lies in
699     * @param name The icon name (base name with or without '.png' or '.svg' extension)
700     * @param size Target icon size
701     * @return The requested Image.
702     * @throws RuntimeException if the image cannot be located
703     * @since 10428
704     */
705    public static ImageIcon get(String subdir, String name, ImageSizes size) {
706        return new ImageProvider(subdir, name).setSize(size).get();
707    }
708
709    /**
710     * Load an empty image with a given size.
711     *
712     * @param size Target icon size
713     * @return The requested Image.
714     * @since 10358
715     */
716    public static ImageIcon getEmpty(ImageSizes size) {
717        Dimension iconRealSize = GuiSizesHelper.getDimensionDpiAdjusted(size.getImageDimension());
718        return new ImageIcon(new BufferedImage(iconRealSize.width, iconRealSize.height,
719            BufferedImage.TYPE_INT_ARGB));
720    }
721
722    /**
723     * Load an image with a given file name, but do not throw an exception
724     * when the image cannot be found.
725     *
726     * @param subdir subdirectory the image lies in
727     * @param name The icon name (base name with or without '.png' or '.svg' extension)
728     * @return the requested image or null if the request failed
729     * @see #get(String, String)
730     */
731    public static ImageIcon getIfAvailable(String subdir, String name) {
732        return new ImageProvider(subdir, name).setOptional(true).get();
733    }
734
735    /**
736     * Load an image with a given file name and size.
737     *
738     * @param name The icon name (base name with or without '.png' or '.svg' extension)
739     * @param size Target icon size
740     * @return the requested image or null if the request failed
741     * @see #get(String, String)
742     * @since 10428
743     */
744    public static ImageIcon get(String name, ImageSizes size) {
745        return new ImageProvider(name).setSize(size).get();
746    }
747
748    /**
749     * Load an image with a given file name, but do not throw an exception
750     * when the image cannot be found.
751     *
752     * @param name The icon name (base name with or without '.png' or '.svg' extension)
753     * @return the requested image or null if the request failed
754     * @see #getIfAvailable(String, String)
755     */
756    public static ImageIcon getIfAvailable(String name) {
757        return new ImageProvider(name).setOptional(true).get();
758    }
759
760    /**
761     * {@code data:[<mediatype>][;base64],<data>}
762     * @see <a href="http://tools.ietf.org/html/rfc2397">RFC2397</a>
763     */
764    private static final Pattern dataUrlPattern = Pattern.compile(
765            "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
766
767    /**
768     * Clears the internal image cache.
769     * @since 11021
770     */
771    public static void clearCache() {
772        synchronized (cache) {
773            cache.clear();
774        }
775    }
776
777    /**
778     * Internal implementation of the image request.
779     *
780     * @param additionalClassLoaders the list of class loaders to use
781     * @return the requested image or null if the request failed
782     */
783    private ImageResource getIfAvailableImpl(Collection<ClassLoader> additionalClassLoaders) {
784        synchronized (cache) {
785            // This method is called from different thread and modifying HashMap concurrently can result
786            // for example in loops in map entries (ie freeze when such entry is retrieved)
787            // Yes, it did happen to me :-)
788            if (name == null)
789                return null;
790
791            String prefix = "";
792            if (isDisabled)
793                prefix = "dis:"+prefix;
794            if (name.startsWith("data:")) {
795                String url = name;
796                ImageResource ir = cache.get(prefix+url);
797                if (ir != null) return ir;
798                ir = getIfAvailableDataUrl(url);
799                if (ir != null) {
800                    cache.put(prefix+url, ir);
801                }
802                return ir;
803            }
804
805            ImageType type = Utils.hasExtension(name, "svg") ? ImageType.SVG : ImageType.OTHER;
806
807            if (name.startsWith(HTTP_PROTOCOL) || name.startsWith(HTTPS_PROTOCOL)) {
808                String url = name;
809                ImageResource ir = cache.get(prefix+url);
810                if (ir != null) return ir;
811                ir = getIfAvailableHttp(url, type);
812                if (ir != null) {
813                    cache.put(prefix+url, ir);
814                }
815                return ir;
816            } else if (name.startsWith(WIKI_PROTOCOL)) {
817                ImageResource ir = cache.get(prefix+name);
818                if (ir != null) return ir;
819                ir = getIfAvailableWiki(name, type);
820                if (ir != null) {
821                    cache.put(prefix+name, ir);
822                }
823                return ir;
824            }
825
826            if (subdir == null) {
827                subdir = "";
828            } else if (!subdir.isEmpty() && !subdir.endsWith("/")) {
829                subdir += '/';
830            }
831            String[] extensions;
832            if (name.indexOf('.') != -1) {
833                extensions = new String[] {""};
834            } else {
835                extensions = new String[] {".png", ".svg"};
836            }
837            final int typeArchive = 0;
838            final int typeLocal = 1;
839            for (int place : new Integer[] {typeArchive, typeLocal}) {
840                for (String ext : extensions) {
841
842                    if (".svg".equals(ext)) {
843                        type = ImageType.SVG;
844                    } else if (".png".equals(ext)) {
845                        type = ImageType.OTHER;
846                    }
847
848                    String fullName = subdir + name + ext;
849                    String cacheName = prefix + fullName;
850                    /* cache separately */
851                    if (dirs != null && !dirs.isEmpty()) {
852                        cacheName = "id:" + id + ':' + fullName;
853                        if (archive != null) {
854                            cacheName += ':' + archive.getName();
855                        }
856                    }
857
858                    switch (place) {
859                    case typeArchive:
860                        if (archive != null) {
861                            cacheName = "zip:"+archive.hashCode()+':'+cacheName;
862                            ImageResource ir = cache.get(cacheName);
863                            if (ir != null) return ir;
864
865                            ir = getIfAvailableZip(fullName, archive, inArchiveDir, type);
866                            if (ir != null) {
867                                cache.put(cacheName, ir);
868                                return ir;
869                            }
870                        }
871                        break;
872                    case typeLocal:
873                        ImageResource ir = cache.get(cacheName);
874                        if (ir != null) return ir;
875
876                        // getImageUrl() does a ton of "stat()" calls and gets expensive
877                        // and redundant when you have a whole ton of objects. So,
878                        // index the cache by the name of the icon we're looking for
879                        // and don't bother to create a URL unless we're actually
880                        // creating the image.
881                        URL path = getImageUrl(fullName, dirs, additionalClassLoaders);
882                        if (path == null) {
883                            continue;
884                        }
885                        ir = getIfAvailableLocalURL(path, type);
886                        if (ir != null) {
887                            cache.put(cacheName, ir);
888                            return ir;
889                        }
890                        break;
891                    }
892                }
893            }
894            return null;
895        }
896    }
897
898    /**
899     * Internal implementation of the image request for URL's.
900     *
901     * @param url URL of the image
902     * @param type data type of the image
903     * @return the requested image or null if the request failed
904     */
905    private static ImageResource getIfAvailableHttp(String url, ImageType type) {
906        CachedFile cf = new CachedFile(url)
907                .setDestDir(new File(Main.pref.getCacheDirectory(), "images").getPath());
908        try (InputStream is = cf.getInputStream()) {
909            switch (type) {
910            case SVG:
911                SVGDiagram svg = null;
912                synchronized (getSvgUniverse()) {
913                    URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(cf.getFile()).toString());
914                    svg = getSvgUniverse().getDiagram(uri);
915                }
916                return svg == null ? null : new ImageResource(svg);
917            case OTHER:
918                BufferedImage img = null;
919                try {
920                    img = read(Utils.fileToURL(cf.getFile()), false, false);
921                } catch (IOException e) {
922                    Main.warn(e, "IOException while reading HTTP image:");
923                }
924                return img == null ? null : new ImageResource(img);
925            default:
926                throw new AssertionError();
927            }
928        } catch (IOException e) {
929            Main.debug(e);
930            return null;
931        } finally {
932            cf.close();
933        }
934    }
935
936    /**
937     * Internal implementation of the image request for inline images (<b>data:</b> urls).
938     *
939     * @param url the data URL for image extraction
940     * @return the requested image or null if the request failed
941     */
942    private static ImageResource getIfAvailableDataUrl(String url) {
943        Matcher m = dataUrlPattern.matcher(url);
944        if (m.matches()) {
945            String base64 = m.group(2);
946            String data = m.group(3);
947            byte[] bytes;
948            if (";base64".equals(base64)) {
949                bytes = Base64.getDecoder().decode(data);
950            } else {
951                try {
952                    bytes = Utils.decodeUrl(data).getBytes(StandardCharsets.UTF_8);
953                } catch (IllegalArgumentException ex) {
954                    Main.warn(ex, "Unable to decode URL data part: "+ex.getMessage() + " (" + data + ')');
955                    return null;
956                }
957            }
958            String mediatype = m.group(1);
959            if ("image/svg+xml".equals(mediatype)) {
960                String s = new String(bytes, StandardCharsets.UTF_8);
961                SVGDiagram svg;
962                synchronized (getSvgUniverse()) {
963                    URI uri = getSvgUniverse().loadSVG(new StringReader(s), Utils.encodeUrl(s));
964                    svg = getSvgUniverse().getDiagram(uri);
965                }
966                if (svg == null) {
967                    Main.warn("Unable to process svg: "+s);
968                    return null;
969                }
970                return new ImageResource(svg);
971            } else {
972                try {
973                    // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
974                    // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
975                    // CHECKSTYLE.OFF: LineLength
976                    // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
977                    // CHECKSTYLE.ON: LineLength
978                    Image img = read(new ByteArrayInputStream(bytes), false, true);
979                    return img == null ? null : new ImageResource(img);
980                } catch (IOException e) {
981                    Main.warn(e, "IOException while reading image:");
982                }
983            }
984        }
985        return null;
986    }
987
988    /**
989     * Internal implementation of the image request for wiki images.
990     *
991     * @param name image file name
992     * @param type data type of the image
993     * @return the requested image or null if the request failed
994     */
995    private static ImageResource getIfAvailableWiki(String name, ImageType type) {
996        final Collection<String> defaultBaseUrls = Arrays.asList(
997                "https://wiki.openstreetmap.org/w/images/",
998                "https://upload.wikimedia.org/wikipedia/commons/",
999                "https://wiki.openstreetmap.org/wiki/File:"
1000                );
1001        final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
1002
1003        final String fn = name.substring(name.lastIndexOf('/') + 1);
1004
1005        ImageResource result = null;
1006        for (String b : baseUrls) {
1007            String url;
1008            if (b.endsWith(":")) {
1009                url = getImgUrlFromWikiInfoPage(b, fn);
1010                if (url == null) {
1011                    continue;
1012                }
1013            } else {
1014                final String fnMD5 = Utils.md5Hex(fn);
1015                url = b + fnMD5.substring(0, 1) + '/' + fnMD5.substring(0, 2) + '/' + fn;
1016            }
1017            result = getIfAvailableHttp(url, type);
1018            if (result != null) {
1019                break;
1020            }
1021        }
1022        return result;
1023    }
1024
1025    /**
1026     * Internal implementation of the image request for images in Zip archives.
1027     *
1028     * @param fullName image file name
1029     * @param archive the archive to get image from
1030     * @param inArchiveDir directory of the image inside the archive or <code>null</code>
1031     * @param type data type of the image
1032     * @return the requested image or null if the request failed
1033     */
1034    private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
1035        try (ZipFile zipFile = new ZipFile(archive, StandardCharsets.UTF_8)) {
1036            if (inArchiveDir == null || ".".equals(inArchiveDir)) {
1037                inArchiveDir = "";
1038            } else if (!inArchiveDir.isEmpty()) {
1039                inArchiveDir += '/';
1040            }
1041            String entryName = inArchiveDir + fullName;
1042            ZipEntry entry = zipFile.getEntry(entryName);
1043            if (entry != null) {
1044                int size = (int) entry.getSize();
1045                int offs = 0;
1046                byte[] buf = new byte[size];
1047                try (InputStream is = zipFile.getInputStream(entry)) {
1048                    switch (type) {
1049                    case SVG:
1050                        SVGDiagram svg = null;
1051                        synchronized (getSvgUniverse()) {
1052                            URI uri = getSvgUniverse().loadSVG(is, entryName);
1053                            svg = getSvgUniverse().getDiagram(uri);
1054                        }
1055                        return svg == null ? null : new ImageResource(svg);
1056                    case OTHER:
1057                        while (size > 0) {
1058                            int l = is.read(buf, offs, size);
1059                            offs += l;
1060                            size -= l;
1061                        }
1062                        BufferedImage img = null;
1063                        try {
1064                            img = read(new ByteArrayInputStream(buf), false, false);
1065                        } catch (IOException e) {
1066                            Main.warn(e);
1067                        }
1068                        return img == null ? null : new ImageResource(img);
1069                    default:
1070                        throw new AssertionError("Unknown ImageType: "+type);
1071                    }
1072                }
1073            }
1074        } catch (IOException e) {
1075            Main.warn(e, tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
1076        }
1077        return null;
1078    }
1079
1080    /**
1081     * Internal implementation of the image request for local images.
1082     *
1083     * @param path image file path
1084     * @param type data type of the image
1085     * @return the requested image or null if the request failed
1086     */
1087    private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
1088        switch (type) {
1089        case SVG:
1090            SVGDiagram svg;
1091            synchronized (getSvgUniverse()) {
1092                URI uri = getSvgUniverse().loadSVG(path);
1093                svg = getSvgUniverse().getDiagram(uri);
1094            }
1095            return svg == null ? null : new ImageResource(svg);
1096        case OTHER:
1097            BufferedImage img = null;
1098            try {
1099                // See #10479: for PNG files, always enforce transparency to be sure tNRS chunk is used even not in paletted mode
1100                // This can be removed if someday Oracle fixes https://bugs.openjdk.java.net/browse/JDK-6788458
1101                // hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/dc4322602480/src/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java#l656
1102                img = read(path, false, true);
1103                if (Main.isDebugEnabled() && isTransparencyForced(img)) {
1104                    Main.debug("Transparency has been forced for image "+path.toExternalForm());
1105                }
1106            } catch (IOException e) {
1107                Main.warn(e);
1108            }
1109            return img == null ? null : new ImageResource(img);
1110        default:
1111            throw new AssertionError();
1112        }
1113    }
1114
1115    private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
1116        if (path != null && path.startsWith("resource://")) {
1117            String p = path.substring("resource://".length());
1118            Collection<ClassLoader> classLoaders = new ArrayList<>(PluginHandler.getResourceClassLoaders());
1119            if (additionalClassLoaders != null) {
1120                classLoaders.addAll(additionalClassLoaders);
1121            }
1122            for (ClassLoader source : classLoaders) {
1123                URL res;
1124                if ((res = source.getResource(p + name)) != null)
1125                    return res;
1126            }
1127        } else {
1128            File f = new File(path, name);
1129            if ((path != null || f.isAbsolute()) && f.exists())
1130                return Utils.fileToURL(f);
1131        }
1132        return null;
1133    }
1134
1135    private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
1136        URL u;
1137
1138        // Try passed directories first
1139        if (dirs != null) {
1140            for (String name : dirs) {
1141                try {
1142                    u = getImageUrl(name, imageName, additionalClassLoaders);
1143                    if (u != null)
1144                        return u;
1145                } catch (SecurityException e) {
1146                    Main.warn(e, tr(
1147                            "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
1148                            name, e.toString()));
1149                }
1150
1151            }
1152        }
1153        // Try user-data directory
1154        if (Main.pref != null) {
1155            String dir = new File(Main.pref.getUserDataDirectory(), "images").getAbsolutePath();
1156            try {
1157                u = getImageUrl(dir, imageName, additionalClassLoaders);
1158                if (u != null)
1159                    return u;
1160            } catch (SecurityException e) {
1161                Main.warn(e, tr(
1162                        "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
1163                        .toString()));
1164            }
1165        }
1166
1167        // Absolute path?
1168        u = getImageUrl(null, imageName, additionalClassLoaders);
1169        if (u != null)
1170            return u;
1171
1172        // Try plugins and josm classloader
1173        u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
1174        if (u != null)
1175            return u;
1176
1177        // Try all other resource directories
1178        if (Main.pref != null) {
1179            for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
1180                u = getImageUrl(location + "images", imageName, additionalClassLoaders);
1181                if (u != null)
1182                    return u;
1183                u = getImageUrl(location, imageName, additionalClassLoaders);
1184                if (u != null)
1185                    return u;
1186            }
1187        }
1188
1189        return null;
1190    }
1191
1192    /** Quit parsing, when a certain condition is met */
1193    private static class SAXReturnException extends SAXException {
1194        private final String result;
1195
1196        SAXReturnException(String result) {
1197            this.result = result;
1198        }
1199
1200        public String getResult() {
1201            return result;
1202        }
1203    }
1204
1205    /**
1206     * Reads the wiki page on a certain file in html format in order to find the real image URL.
1207     *
1208     * @param base base URL for Wiki image
1209     * @param fn filename of the Wiki image
1210     * @return image URL for a Wiki image or null in case of error
1211     */
1212    private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
1213        try {
1214            final XMLReader parser = Utils.newSafeSAXParser().getXMLReader();
1215            parser.setContentHandler(new DefaultHandler() {
1216                @Override
1217                public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
1218                    if ("img".equalsIgnoreCase(localName)) {
1219                        String val = atts.getValue("src");
1220                        if (val.endsWith(fn))
1221                            throw new SAXReturnException(val);  // parsing done, quit early
1222                    }
1223                }
1224            });
1225
1226            parser.setEntityResolver((publicId, systemId) -> new InputSource(new ByteArrayInputStream(new byte[0])));
1227
1228            CachedFile cf = new CachedFile(base + fn).setDestDir(
1229                    new File(Main.pref.getUserDataDirectory(), "images").getPath());
1230            try (InputStream is = cf.getInputStream()) {
1231                parser.parse(new InputSource(is));
1232            }
1233            cf.close();
1234        } catch (SAXReturnException r) {
1235            Main.trace(r);
1236            return r.getResult();
1237        } catch (IOException | SAXException | ParserConfigurationException e) {
1238            Main.warn("Parsing " + base + fn + " failed:\n" + e);
1239            return null;
1240        }
1241        Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
1242        return null;
1243    }
1244
1245    /**
1246     * Load a cursor with a given file name, optionally decorated with an overlay image.
1247     *
1248     * @param name the cursor image filename in "cursor" directory
1249     * @param overlay optional overlay image
1250     * @return cursor with a given file name, optionally decorated with an overlay image
1251     */
1252    public static Cursor getCursor(String name, String overlay) {
1253        ImageIcon img = get("cursor", name);
1254        if (overlay != null) {
1255            img = new ImageProvider("cursor", name).setMaxSize(ImageSizes.CURSOR)
1256                .addOverlay(new ImageOverlay(new ImageProvider("cursor/modifier/" + overlay)
1257                    .setMaxSize(ImageSizes.CURSOROVERLAY))).get();
1258        }
1259        if (GraphicsEnvironment.isHeadless()) {
1260            if (Main.isDebugEnabled()) {
1261                Main.debug("Cursors are not available in headless mode. Returning null for '"+name+'\'');
1262            }
1263            return null;
1264        }
1265        return Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
1266                "crosshair".equals(name) ? new Point(10, 10) : new Point(3, 2), "Cursor");
1267    }
1268
1269    /** 90 degrees in radians units */
1270    private static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
1271
1272    /**
1273     * Creates a rotated version of the input image.
1274     *
1275     * @param img the image to be rotated.
1276     * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
1277     * will mod it with 360 before using it. More over for caching performance, it will be rounded to
1278     * an entire value between 0 and 360.
1279     *
1280     * @return the image after rotating.
1281     * @since 6172
1282     */
1283    public static Image createRotatedImage(Image img, double rotatedAngle) {
1284        return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
1285    }
1286
1287    /**
1288     * Creates a rotated version of the input image, scaled to the given dimension.
1289     *
1290     * @param img the image to be rotated.
1291     * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
1292     * will mod it with 360 before using it. More over for caching performance, it will be rounded to
1293     * an entire value between 0 and 360.
1294     * @param dimension The requested dimensions. Use (-1,-1) for the original size
1295     * and (width, -1) to set the width, but otherwise scale the image proportionally.
1296     * @return the image after rotating and scaling.
1297     * @since 6172
1298     */
1299    public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
1300        CheckParameterUtil.ensureParameterNotNull(img, "img");
1301
1302        // convert rotatedAngle to an integer value from 0 to 360
1303        Long originalAngle = Math.round(rotatedAngle % 360);
1304        if (rotatedAngle != 0 && originalAngle == 0) {
1305            originalAngle = 360L;
1306        }
1307
1308        ImageResource imageResource;
1309
1310        synchronized (ROTATE_CACHE) {
1311            Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
1312            if (cacheByAngle == null) {
1313                cacheByAngle = new HashMap<>();
1314                ROTATE_CACHE.put(img, cacheByAngle);
1315            }
1316
1317            imageResource = cacheByAngle.get(originalAngle);
1318
1319            if (imageResource == null) {
1320                // convert originalAngle to a value from 0 to 90
1321                double angle = originalAngle % 90;
1322                if (originalAngle != 0 && angle == 0) {
1323                    angle = 90.0;
1324                }
1325
1326                double radian = Math.toRadians(angle);
1327
1328                new ImageIcon(img); // load completely
1329                int iw = img.getWidth(null);
1330                int ih = img.getHeight(null);
1331                int w;
1332                int h;
1333
1334                if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
1335                    w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
1336                    h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
1337                } else {
1338                    w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
1339                    h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
1340                }
1341                Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
1342                imageResource = new ImageResource(image);
1343                cacheByAngle.put(originalAngle, imageResource);
1344                Graphics g = image.getGraphics();
1345                Graphics2D g2d = (Graphics2D) g.create();
1346
1347                // calculate the center of the icon.
1348                int cx = iw / 2;
1349                int cy = ih / 2;
1350
1351                // move the graphics center point to the center of the icon.
1352                g2d.translate(w / 2, h / 2);
1353
1354                // rotate the graphics about the center point of the icon
1355                g2d.rotate(Math.toRadians(originalAngle));
1356
1357                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
1358                g2d.drawImage(img, -cx, -cy, null);
1359
1360                g2d.dispose();
1361                new ImageIcon(image); // load completely
1362            }
1363            return imageResource.getImageIcon(dimension).getImage();
1364        }
1365    }
1366
1367    /**
1368     * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
1369     *
1370     * @param img the image to be scaled down.
1371     * @param maxSize the maximum size in pixels (both for width and height)
1372     *
1373     * @return the image after scaling.
1374     * @since 6172
1375     */
1376    public static Image createBoundedImage(Image img, int maxSize) {
1377        return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
1378    }
1379
1380    /**
1381     * Replies the icon for an OSM primitive type
1382     * @param type the type
1383     * @return the icon
1384     */
1385    public static ImageIcon get(OsmPrimitiveType type) {
1386        CheckParameterUtil.ensureParameterNotNull(type, "type");
1387        return get("data", type.getAPIName());
1388    }
1389
1390    /**
1391     * @param primitive Object for which an icon shall be fetched. The icon is chosen based on tags.
1392     * @param iconSize Target size of icon. Icon is padded if required.
1393     * @return Icon for {@code primitive} that fits in cell.
1394     * @since 8903
1395     */
1396    public static ImageIcon getPadded(OsmPrimitive primitive, Dimension iconSize) {
1397        // Check if the current styles have special icon for tagged nodes.
1398        if (primitive instanceof org.openstreetmap.josm.data.osm.Node) {
1399            Pair<StyleElementList, Range> nodeStyles;
1400            DataSet ds = primitive.getDataSet();
1401            if (ds != null) {
1402                ds.getReadLock().lock();
1403            }
1404            try {
1405                nodeStyles = MapPaintStyles.getStyles().generateStyles(primitive, 100, false);
1406            } finally {
1407                if (ds != null) {
1408                    ds.getReadLock().unlock();
1409                }
1410            }
1411            for (StyleElement style : nodeStyles.a) {
1412                if (style instanceof NodeElement) {
1413                    NodeElement nodeStyle = (NodeElement) style;
1414                    MapImage icon = nodeStyle.mapImage;
1415                    if (icon != null) {
1416                        int backgroundRealWidth = GuiSizesHelper.getSizeDpiAdjusted(iconSize.width);
1417                        int backgroundRealHeight = GuiSizesHelper.getSizeDpiAdjusted(iconSize.height);
1418                        int iconRealWidth = icon.getWidth();
1419                        int iconRealHeight = icon.getHeight();
1420                        BufferedImage image = new BufferedImage(backgroundRealWidth, backgroundRealHeight,
1421                                BufferedImage.TYPE_INT_ARGB);
1422                        double scaleFactor = Math.min(backgroundRealWidth / (double) iconRealWidth, backgroundRealHeight
1423                                / (double) iconRealHeight);
1424                        BufferedImage iconImage = icon.getImage(false);
1425                        Image scaledIcon;
1426                        final int scaledWidth;
1427                        final int scaledHeight;
1428                        if (scaleFactor < 1) {
1429                            // Scale icon such that it fits on background.
1430                            scaledWidth = (int) (iconRealWidth * scaleFactor);
1431                            scaledHeight = (int) (iconRealHeight * scaleFactor);
1432                            scaledIcon = iconImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
1433                        } else {
1434                            // Use original size, don't upscale.
1435                            scaledWidth = iconRealWidth;
1436                            scaledHeight = iconRealHeight;
1437                            scaledIcon = iconImage;
1438                        }
1439                        image.getGraphics().drawImage(scaledIcon, (backgroundRealWidth - scaledWidth) / 2,
1440                                (backgroundRealHeight - scaledHeight) / 2, null);
1441
1442                        return new ImageIcon(image);
1443                    }
1444                }
1445            }
1446        }
1447
1448        // Check if the presets have icons for nodes/relations.
1449        if (!OsmPrimitiveType.WAY.equals(primitive.getType())) {
1450            final Collection<TaggingPreset> presets = new TreeSet<>((o1, o2) -> {
1451                final int o1TypesSize = o1.types == null || o1.types.isEmpty() ? Integer.MAX_VALUE : o1.types.size();
1452                final int o2TypesSize = o2.types == null || o2.types.isEmpty() ? Integer.MAX_VALUE : o2.types.size();
1453                return Integer.compare(o1TypesSize, o2TypesSize);
1454            });
1455            presets.addAll(TaggingPresets.getMatchingPresets(primitive));
1456            for (final TaggingPreset preset : presets) {
1457                if (preset.getIcon() != null) {
1458                    return preset.getIcon();
1459                }
1460            }
1461        }
1462
1463        // Use generic default icon.
1464        return ImageProvider.get(primitive.getDisplayType());
1465    }
1466
1467    /**
1468     * Constructs an image from the given SVG data.
1469     * @param svg the SVG data
1470     * @param dim the desired image dimension
1471     * @return an image from the given SVG data at the desired dimension.
1472     */
1473    public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
1474        if (Main.isTraceEnabled()) {
1475            Main.trace(String.format("createImageFromSvg: %s %s", svg.getXMLBase(), dim));
1476        }
1477        float sourceWidth = svg.getWidth();
1478        float sourceHeight = svg.getHeight();
1479        int realWidth = Math.round(GuiSizesHelper.getSizeDpiAdjusted(sourceWidth));
1480        int realHeight = Math.round(GuiSizesHelper.getSizeDpiAdjusted(sourceHeight));
1481        Double scaleX, scaleY;
1482        if (dim.width != -1) {
1483            realWidth = dim.width;
1484            scaleX = (double) realWidth / sourceWidth;
1485            if (dim.height == -1) {
1486                scaleY = scaleX;
1487                realHeight = (int) Math.round(sourceHeight * scaleY);
1488            } else {
1489                realHeight = dim.height;
1490                scaleY = (double) realHeight / sourceHeight;
1491            }
1492        } else if (dim.height != -1) {
1493            realHeight = dim.height;
1494            scaleX = scaleY = (double) realHeight / sourceHeight;
1495            realWidth = (int) Math.round(sourceWidth * scaleX);
1496        } else {
1497            scaleX = scaleY = (double) realHeight / sourceHeight;
1498        }
1499
1500        if (realWidth == 0 || realHeight == 0) {
1501            return null;
1502        }
1503        BufferedImage img = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_INT_ARGB);
1504        Graphics2D g = img.createGraphics();
1505        g.setClip(0, 0, realWidth, realHeight);
1506        g.scale(scaleX, scaleY);
1507        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
1508        try {
1509            synchronized (getSvgUniverse()) {
1510                svg.render(g);
1511            }
1512        } catch (SVGException ex) {
1513            Main.error(ex, "Unable to load svg:");
1514            return null;
1515        }
1516        return img;
1517    }
1518
1519    private static synchronized SVGUniverse getSvgUniverse() {
1520        if (svgUniverse == null) {
1521            svgUniverse = new SVGUniverse();
1522        }
1523        return svgUniverse;
1524    }
1525
1526    /**
1527     * Returns a <code>BufferedImage</code> as the result of decoding
1528     * a supplied <code>File</code> with an <code>ImageReader</code>
1529     * chosen automatically from among those currently registered.
1530     * The <code>File</code> is wrapped in an
1531     * <code>ImageInputStream</code>.  If no registered
1532     * <code>ImageReader</code> claims to be able to read the
1533     * resulting stream, <code>null</code> is returned.
1534     *
1535     * <p> The current cache settings from <code>getUseCache</code>and
1536     * <code>getCacheDirectory</code> will be used to control caching in the
1537     * <code>ImageInputStream</code> that is created.
1538     *
1539     * <p> Note that there is no <code>read</code> method that takes a
1540     * filename as a <code>String</code>; use this method instead after
1541     * creating a <code>File</code> from the filename.
1542     *
1543     * <p> This method does not attempt to locate
1544     * <code>ImageReader</code>s that can read directly from a
1545     * <code>File</code>; that may be accomplished using
1546     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1547     *
1548     * @param input a <code>File</code> to read from.
1549     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color, if any.
1550     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1551     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1552     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1553     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1554     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1555     *
1556     * @return a <code>BufferedImage</code> containing the decoded
1557     * contents of the input, or <code>null</code>.
1558     *
1559     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1560     * @throws IOException if an error occurs during reading.
1561     * @see BufferedImage#getProperty
1562     * @since 7132
1563     */
1564    public static BufferedImage read(File input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1565        CheckParameterUtil.ensureParameterNotNull(input, "input");
1566        if (!input.canRead()) {
1567            throw new IIOException("Can't read input file!");
1568        }
1569
1570        ImageInputStream stream = ImageIO.createImageInputStream(input);
1571        if (stream == null) {
1572            throw new IIOException("Can't create an ImageInputStream!");
1573        }
1574        BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1575        if (bi == null) {
1576            stream.close();
1577        }
1578        return bi;
1579    }
1580
1581    /**
1582     * Returns a <code>BufferedImage</code> as the result of decoding
1583     * a supplied <code>InputStream</code> with an <code>ImageReader</code>
1584     * chosen automatically from among those currently registered.
1585     * The <code>InputStream</code> is wrapped in an
1586     * <code>ImageInputStream</code>.  If no registered
1587     * <code>ImageReader</code> claims to be able to read the
1588     * resulting stream, <code>null</code> is returned.
1589     *
1590     * <p> The current cache settings from <code>getUseCache</code>and
1591     * <code>getCacheDirectory</code> will be used to control caching in the
1592     * <code>ImageInputStream</code> that is created.
1593     *
1594     * <p> This method does not attempt to locate
1595     * <code>ImageReader</code>s that can read directly from an
1596     * <code>InputStream</code>; that may be accomplished using
1597     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1598     *
1599     * <p> This method <em>does not</em> close the provided
1600     * <code>InputStream</code> after the read operation has completed;
1601     * it is the responsibility of the caller to close the stream, if desired.
1602     *
1603     * @param input an <code>InputStream</code> to read from.
1604     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1605     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1606     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1607     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1608     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1609     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1610     *
1611     * @return a <code>BufferedImage</code> containing the decoded
1612     * contents of the input, or <code>null</code>.
1613     *
1614     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1615     * @throws IOException if an error occurs during reading.
1616     * @since 7132
1617     */
1618    public static BufferedImage read(InputStream input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1619        CheckParameterUtil.ensureParameterNotNull(input, "input");
1620
1621        ImageInputStream stream = ImageIO.createImageInputStream(input);
1622        BufferedImage bi = read(stream, readMetadata, enforceTransparency);
1623        if (bi == null) {
1624            stream.close();
1625        }
1626        return bi;
1627    }
1628
1629    /**
1630     * Returns a <code>BufferedImage</code> as the result of decoding
1631     * a supplied <code>URL</code> with an <code>ImageReader</code>
1632     * chosen automatically from among those currently registered.  An
1633     * <code>InputStream</code> is obtained from the <code>URL</code>,
1634     * which is wrapped in an <code>ImageInputStream</code>.  If no
1635     * registered <code>ImageReader</code> claims to be able to read
1636     * the resulting stream, <code>null</code> is returned.
1637     *
1638     * <p> The current cache settings from <code>getUseCache</code>and
1639     * <code>getCacheDirectory</code> will be used to control caching in the
1640     * <code>ImageInputStream</code> that is created.
1641     *
1642     * <p> This method does not attempt to locate
1643     * <code>ImageReader</code>s that can read directly from a
1644     * <code>URL</code>; that may be accomplished using
1645     * <code>IIORegistry</code> and <code>ImageReaderSpi</code>.
1646     *
1647     * @param input a <code>URL</code> to read from.
1648     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1649     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1650     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1651     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1652     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1653     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1654     *
1655     * @return a <code>BufferedImage</code> containing the decoded
1656     * contents of the input, or <code>null</code>.
1657     *
1658     * @throws IllegalArgumentException if <code>input</code> is <code>null</code>.
1659     * @throws IOException if an error occurs during reading.
1660     * @since 7132
1661     */
1662    public static BufferedImage read(URL input, boolean readMetadata, boolean enforceTransparency) throws IOException {
1663        CheckParameterUtil.ensureParameterNotNull(input, "input");
1664
1665        InputStream istream = null;
1666        try {
1667            istream = input.openStream();
1668        } catch (IOException e) {
1669            throw new IIOException("Can't get input stream from URL!", e);
1670        }
1671        ImageInputStream stream = ImageIO.createImageInputStream(istream);
1672        BufferedImage bi;
1673        try {
1674            bi = read(stream, readMetadata, enforceTransparency);
1675            if (bi == null) {
1676                stream.close();
1677            }
1678        } finally {
1679            istream.close();
1680        }
1681        return bi;
1682    }
1683
1684    /**
1685     * Returns a <code>BufferedImage</code> as the result of decoding
1686     * a supplied <code>ImageInputStream</code> with an
1687     * <code>ImageReader</code> chosen automatically from among those
1688     * currently registered.  If no registered
1689     * <code>ImageReader</code> claims to be able to read the stream,
1690     * <code>null</code> is returned.
1691     *
1692     * <p> Unlike most other methods in this class, this method <em>does</em>
1693     * close the provided <code>ImageInputStream</code> after the read
1694     * operation has completed, unless <code>null</code> is returned,
1695     * in which case this method <em>does not</em> close the stream.
1696     *
1697     * @param stream an <code>ImageInputStream</code> to read from.
1698     * @param readMetadata if {@code true}, makes sure to read image metadata to detect transparency color for non translucent images, if any.
1699     * In that case the color can be retrieved later through {@link #PROP_TRANSPARENCY_COLOR}.
1700     * Always considered {@code true} if {@code enforceTransparency} is also {@code true}
1701     * @param enforceTransparency if {@code true}, makes sure to read image metadata and, if the image does not
1702     * provide an alpha channel but defines a {@code TransparentColor} metadata node, that the resulting image
1703     * has a transparency set to {@code TRANSLUCENT} and uses the correct transparent color.
1704     *
1705     * @return a <code>BufferedImage</code> containing the decoded
1706     * contents of the input, or <code>null</code>.
1707     *
1708     * @throws IllegalArgumentException if <code>stream</code> is <code>null</code>.
1709     * @throws IOException if an error occurs during reading.
1710     * @since 7132
1711     */
1712    public static BufferedImage read(ImageInputStream stream, boolean readMetadata, boolean enforceTransparency) throws IOException {
1713        CheckParameterUtil.ensureParameterNotNull(stream, "stream");
1714
1715        Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
1716        if (!iter.hasNext()) {
1717            return null;
1718        }
1719
1720        ImageReader reader = iter.next();
1721        ImageReadParam param = reader.getDefaultReadParam();
1722        reader.setInput(stream, true, !readMetadata && !enforceTransparency);
1723        BufferedImage bi;
1724        try {
1725            bi = reader.read(0, param);
1726            if (bi.getTransparency() != Transparency.TRANSLUCENT && (readMetadata || enforceTransparency)) {
1727                Color color = getTransparentColor(bi.getColorModel(), reader);
1728                if (color != null) {
1729                    Hashtable<String, Object> properties = new Hashtable<>(1);
1730                    properties.put(PROP_TRANSPARENCY_COLOR, color);
1731                    bi = new BufferedImage(bi.getColorModel(), bi.getRaster(), bi.isAlphaPremultiplied(), properties);
1732                    if (enforceTransparency) {
1733                        if (Main.isTraceEnabled()) {
1734                            Main.trace("Enforcing image transparency of "+stream+" for "+color);
1735                        }
1736                        bi = makeImageTransparent(bi, color);
1737                    }
1738                }
1739            }
1740        } finally {
1741            reader.dispose();
1742            stream.close();
1743        }
1744        return bi;
1745    }
1746
1747    // CHECKSTYLE.OFF: LineLength
1748
1749    /**
1750     * Returns the {@code TransparentColor} defined in image reader metadata.
1751     * @param model The image color model
1752     * @param reader The image reader
1753     * @return the {@code TransparentColor} defined in image reader metadata, or {@code null}
1754     * @throws IOException if an error occurs during reading
1755     * @see <a href="http://docs.oracle.com/javase/8/docs/api/javax/imageio/metadata/doc-files/standard_metadata.html">javax_imageio_1.0 metadata</a>
1756     * @since 7499
1757     */
1758    public static Color getTransparentColor(ColorModel model, ImageReader reader) throws IOException {
1759        // CHECKSTYLE.ON: LineLength
1760        try {
1761            IIOMetadata metadata = reader.getImageMetadata(0);
1762            if (metadata != null) {
1763                String[] formats = metadata.getMetadataFormatNames();
1764                if (formats != null) {
1765                    for (String f : formats) {
1766                        if ("javax_imageio_1.0".equals(f)) {
1767                            Node root = metadata.getAsTree(f);
1768                            if (root instanceof Element) {
1769                                NodeList list = ((Element) root).getElementsByTagName("TransparentColor");
1770                                if (list.getLength() > 0) {
1771                                    Node item = list.item(0);
1772                                    if (item instanceof Element) {
1773                                        // Handle different color spaces (tested with RGB and grayscale)
1774                                        String value = ((Element) item).getAttribute("value");
1775                                        if (!value.isEmpty()) {
1776                                            String[] s = value.split(" ");
1777                                            if (s.length == 3) {
1778                                                return parseRGB(s);
1779                                            } else if (s.length == 1) {
1780                                                int pixel = Integer.parseInt(s[0]);
1781                                                int r = model.getRed(pixel);
1782                                                int g = model.getGreen(pixel);
1783                                                int b = model.getBlue(pixel);
1784                                                return new Color(r, g, b);
1785                                            } else {
1786                                                Main.warn("Unable to translate TransparentColor '"+value+"' with color model "+model);
1787                                            }
1788                                        }
1789                                    }
1790                                }
1791                            }
1792                            break;
1793                        }
1794                    }
1795                }
1796            }
1797        } catch (IIOException | NumberFormatException e) {
1798            // JAI doesn't like some JPEG files with error "Inconsistent metadata read from stream" (see #10267)
1799            Main.warn(e);
1800        }
1801        return null;
1802    }
1803
1804    private static Color parseRGB(String ... s) {
1805        int[] rgb = new int[3];
1806        try {
1807            for (int i = 0; i < 3; i++) {
1808                rgb[i] = Integer.parseInt(s[i]);
1809            }
1810            return new Color(rgb[0], rgb[1], rgb[2]);
1811        } catch (IllegalArgumentException e) {
1812            Main.error(e);
1813            return null;
1814        }
1815    }
1816
1817    /**
1818     * Returns a transparent version of the given image, based on the given transparent color.
1819     * @param bi The image to convert
1820     * @param color The transparent color
1821     * @return The same image as {@code bi} where all pixels of the given color are transparent.
1822     * This resulting image has also the special property {@link #PROP_TRANSPARENCY_FORCED} set to {@code color}
1823     * @see BufferedImage#getProperty
1824     * @see #isTransparencyForced
1825     * @since 7132
1826     */
1827    public static BufferedImage makeImageTransparent(BufferedImage bi, Color color) {
1828        // the color we are looking for. Alpha bits are set to opaque
1829        final int markerRGB = color.getRGB() | 0xFF000000;
1830        ImageFilter filter = new RGBImageFilter() {
1831            @Override
1832            public int filterRGB(int x, int y, int rgb) {
1833                if ((rgb | 0xFF000000) == markerRGB) {
1834                   // Mark the alpha bits as zero - transparent
1835                   return 0x00FFFFFF & rgb;
1836                } else {
1837                   return rgb;
1838                }
1839            }
1840        };
1841        ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
1842        Image img = Toolkit.getDefaultToolkit().createImage(ip);
1843        ColorModel colorModel = ColorModel.getRGBdefault();
1844        WritableRaster raster = colorModel.createCompatibleWritableRaster(img.getWidth(null), img.getHeight(null));
1845        String[] names = bi.getPropertyNames();
1846        Hashtable<String, Object> properties = new Hashtable<>(1 + (names != null ? names.length : 0));
1847        if (names != null) {
1848            for (String name : names) {
1849                properties.put(name, bi.getProperty(name));
1850            }
1851        }
1852        properties.put(PROP_TRANSPARENCY_FORCED, Boolean.TRUE);
1853        BufferedImage result = new BufferedImage(colorModel, raster, false, properties);
1854        Graphics2D g2 = result.createGraphics();
1855        g2.drawImage(img, 0, 0, null);
1856        g2.dispose();
1857        return result;
1858    }
1859
1860    /**
1861     * Determines if the transparency of the given {@code BufferedImage} has been enforced by a previous call to {@link #makeImageTransparent}.
1862     * @param bi The {@code BufferedImage} to test
1863     * @return {@code true} if the transparency of {@code bi} has been enforced by a previous call to {@code makeImageTransparent}.
1864     * @see #makeImageTransparent
1865     * @since 7132
1866     */
1867    public static boolean isTransparencyForced(BufferedImage bi) {
1868        return bi != null && !bi.getProperty(PROP_TRANSPARENCY_FORCED).equals(Image.UndefinedProperty);
1869    }
1870
1871    /**
1872     * Determines if the given {@code BufferedImage} has a transparent color determined by a previous call to {@link #read}.
1873     * @param bi The {@code BufferedImage} to test
1874     * @return {@code true} if {@code bi} has a transparent color determined by a previous call to {@code read}.
1875     * @see #read
1876     * @since 7132
1877     */
1878    public static boolean hasTransparentColor(BufferedImage bi) {
1879        return bi != null && !bi.getProperty(PROP_TRANSPARENCY_COLOR).equals(Image.UndefinedProperty);
1880    }
1881
1882    /**
1883     * Shutdown background image fetcher.
1884     * @param now if {@code true}, attempts to stop all actively executing tasks, halts the processing of waiting tasks.
1885     * if {@code false}, initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted
1886     * @since 8412
1887     */
1888    public static void shutdown(boolean now) {
1889        if (now) {
1890            IMAGE_FETCHER.shutdownNow();
1891        } else {
1892            IMAGE_FETCHER.shutdown();
1893        }
1894    }
1895}