source: josm/trunk/src/org/openstreetmap/josm/tools/ImageProvider.java@ 12855

Last change on this file since 12855 was 12855, checked in by bastiK, 7 years ago

see #15229 - add separate interface IBaseDirectories to look up pref, user data and cache dir

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