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