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

Last change on this file since 12697 was 12682, checked in by Don-vip, 7 years ago

see #15182 - move GuiSizesHelper from gui.util to tools (only called from there)

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