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

Last change on this file since 10412 was 10410, checked in by stoecker, 8 years ago

do not use full archive name, but only hashCode for cache name

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