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