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

Last change on this file since 10718 was 10714, checked in by simon04, 8 years ago

see #11390 - Use CompletableFuture for async image loading

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