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

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

sonar - various fixes

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