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