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

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

see #9995 - patch mainly by strump - improve HIDPI behaviour

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