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

Last change on this file since 10657 was 10627, checked in by Don-vip, 8 years ago

sonar - squid:S1166 - Exception handlers should preserve the original exceptions

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