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

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

see #9995 - overlooked part of the code

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