1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.Cursor;
|
---|
7 | import java.awt.Dimension;
|
---|
8 | import java.awt.Graphics;
|
---|
9 | import java.awt.Graphics2D;
|
---|
10 | import java.awt.GraphicsConfiguration;
|
---|
11 | import java.awt.GraphicsEnvironment;
|
---|
12 | import java.awt.Image;
|
---|
13 | import java.awt.Point;
|
---|
14 | import java.awt.RenderingHints;
|
---|
15 | import java.awt.Toolkit;
|
---|
16 | import java.awt.Transparency;
|
---|
17 | import java.awt.image.BufferedImage;
|
---|
18 | import java.io.ByteArrayInputStream;
|
---|
19 | import java.io.File;
|
---|
20 | import java.io.IOException;
|
---|
21 | import java.io.InputStream;
|
---|
22 | import java.io.StringReader;
|
---|
23 | import java.io.UnsupportedEncodingException;
|
---|
24 | import java.net.URI;
|
---|
25 | import java.net.URL;
|
---|
26 | import java.net.URLDecoder;
|
---|
27 | import java.net.URLEncoder;
|
---|
28 | import java.util.ArrayList;
|
---|
29 | import java.util.Arrays;
|
---|
30 | import java.util.Collection;
|
---|
31 | import java.util.HashMap;
|
---|
32 | import java.util.Map;
|
---|
33 | import java.util.concurrent.ExecutorService;
|
---|
34 | import java.util.concurrent.Executors;
|
---|
35 | import java.util.regex.Matcher;
|
---|
36 | import java.util.regex.Pattern;
|
---|
37 | import java.util.zip.ZipEntry;
|
---|
38 | import java.util.zip.ZipFile;
|
---|
39 |
|
---|
40 | import javax.imageio.ImageIO;
|
---|
41 | import javax.swing.Icon;
|
---|
42 | import javax.swing.ImageIcon;
|
---|
43 |
|
---|
44 | import org.apache.commons.codec.binary.Base64;
|
---|
45 | import org.openstreetmap.josm.Main;
|
---|
46 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
47 | import org.openstreetmap.josm.io.MirroredInputStream;
|
---|
48 | import org.openstreetmap.josm.plugins.PluginHandler;
|
---|
49 | import org.xml.sax.Attributes;
|
---|
50 | import org.xml.sax.EntityResolver;
|
---|
51 | import org.xml.sax.InputSource;
|
---|
52 | import org.xml.sax.SAXException;
|
---|
53 | import org.xml.sax.XMLReader;
|
---|
54 | import org.xml.sax.helpers.DefaultHandler;
|
---|
55 | import org.xml.sax.helpers.XMLReaderFactory;
|
---|
56 |
|
---|
57 | import com.kitfox.svg.SVGDiagram;
|
---|
58 | import com.kitfox.svg.SVGException;
|
---|
59 | import com.kitfox.svg.SVGUniverse;
|
---|
60 |
|
---|
61 | /**
|
---|
62 | * Helper class to support the application with images.
|
---|
63 | *
|
---|
64 | * How to use:
|
---|
65 | *
|
---|
66 | * <code>ImageIcon icon = new ImageProvider(name).setMaxWidth(24).setMaxHeight(24).get();</code>
|
---|
67 | * (there are more options, see below)
|
---|
68 | *
|
---|
69 | * short form:
|
---|
70 | * <code>ImageIcon icon = ImageProvider.get(name);</code>
|
---|
71 | *
|
---|
72 | * @author imi
|
---|
73 | */
|
---|
74 | public class ImageProvider {
|
---|
75 |
|
---|
76 | /**
|
---|
77 | * Position of an overlay icon
|
---|
78 | * @author imi
|
---|
79 | */
|
---|
80 | public static enum OverlayPosition {
|
---|
81 | NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
|
---|
82 | }
|
---|
83 |
|
---|
84 | /**
|
---|
85 | * Supported image types
|
---|
86 | */
|
---|
87 | public static enum ImageType {
|
---|
88 | /** Scalable vector graphics */
|
---|
89 | SVG,
|
---|
90 | /** Everything else, e.g. png, gif (must be supported by Java) */
|
---|
91 | OTHER
|
---|
92 | }
|
---|
93 |
|
---|
94 | protected Collection<String> dirs;
|
---|
95 | protected String id;
|
---|
96 | protected String subdir;
|
---|
97 | protected String name;
|
---|
98 | protected File archive;
|
---|
99 | protected String inArchiveDir;
|
---|
100 | protected int width = -1;
|
---|
101 | protected int height = -1;
|
---|
102 | protected int maxWidth = -1;
|
---|
103 | protected int maxHeight = -1;
|
---|
104 | protected boolean optional;
|
---|
105 | protected boolean suppressWarnings;
|
---|
106 | protected Collection<ClassLoader> additionalClassLoaders;
|
---|
107 |
|
---|
108 | private static SVGUniverse svgUniverse;
|
---|
109 |
|
---|
110 | /**
|
---|
111 | * The icon cache
|
---|
112 | */
|
---|
113 | private static final Map<String, ImageResource> cache = new HashMap<>();
|
---|
114 |
|
---|
115 | /**
|
---|
116 | * Caches the image data for rotated versions of the same image.
|
---|
117 | */
|
---|
118 | private static final Map<Image, Map<Long, ImageResource>> ROTATE_CACHE = new HashMap<>();
|
---|
119 |
|
---|
120 | private static final ExecutorService IMAGE_FETCHER = Executors.newSingleThreadExecutor();
|
---|
121 |
|
---|
122 | public interface ImageCallback {
|
---|
123 | void finished(ImageIcon result);
|
---|
124 | }
|
---|
125 |
|
---|
126 | /**
|
---|
127 | * Constructs a new {@code ImageProvider} from a filename in a given directory.
|
---|
128 | * @param subdir subdirectory the image lies in
|
---|
129 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
130 | * both extensions are tried.
|
---|
131 | */
|
---|
132 | public ImageProvider(String subdir, String name) {
|
---|
133 | this.subdir = subdir;
|
---|
134 | this.name = name;
|
---|
135 | }
|
---|
136 |
|
---|
137 | /**
|
---|
138 | * Constructs a new {@code ImageProvider} from a filename.
|
---|
139 | * @param name the name of the image. If it does not end with '.png' or '.svg',
|
---|
140 | * both extensions are tried.
|
---|
141 | */
|
---|
142 | public ImageProvider(String name) {
|
---|
143 | this.name = name;
|
---|
144 | }
|
---|
145 |
|
---|
146 | /**
|
---|
147 | * Directories to look for the image.
|
---|
148 | * @param dirs The directories to look for.
|
---|
149 | * @return the current object, for convenience
|
---|
150 | */
|
---|
151 | public ImageProvider setDirs(Collection<String> dirs) {
|
---|
152 | this.dirs = dirs;
|
---|
153 | return this;
|
---|
154 | }
|
---|
155 |
|
---|
156 | /**
|
---|
157 | * Set an id used for caching.
|
---|
158 | * If name starts with <tt>http://</tt> Id is not used for the cache.
|
---|
159 | * (A URL is unique anyway.)
|
---|
160 | * @return the current object, for convenience
|
---|
161 | */
|
---|
162 | public ImageProvider setId(String id) {
|
---|
163 | this.id = id;
|
---|
164 | return this;
|
---|
165 | }
|
---|
166 |
|
---|
167 | /**
|
---|
168 | * Specify a zip file where the image is located.
|
---|
169 | *
|
---|
170 | * (optional)
|
---|
171 | * @return the current object, for convenience
|
---|
172 | */
|
---|
173 | public ImageProvider setArchive(File archive) {
|
---|
174 | this.archive = archive;
|
---|
175 | return this;
|
---|
176 | }
|
---|
177 |
|
---|
178 | /**
|
---|
179 | * Specify a base path inside the zip file.
|
---|
180 | *
|
---|
181 | * The subdir and name will be relative to this path.
|
---|
182 | *
|
---|
183 | * (optional)
|
---|
184 | * @return the current object, for convenience
|
---|
185 | */
|
---|
186 | public ImageProvider setInArchiveDir(String inArchiveDir) {
|
---|
187 | this.inArchiveDir = inArchiveDir;
|
---|
188 | return this;
|
---|
189 | }
|
---|
190 |
|
---|
191 | /**
|
---|
192 | * Set the dimensions of the image.
|
---|
193 | *
|
---|
194 | * If not specified, the original size of the image is used.
|
---|
195 | * The width part of the dimension can be -1. Then it will only set the height but
|
---|
196 | * keep the aspect ratio. (And the other way around.)
|
---|
197 | * @return the current object, for convenience
|
---|
198 | */
|
---|
199 | public ImageProvider setSize(Dimension size) {
|
---|
200 | this.width = size.width;
|
---|
201 | this.height = size.height;
|
---|
202 | return this;
|
---|
203 | }
|
---|
204 |
|
---|
205 | /**
|
---|
206 | * @see #setSize
|
---|
207 | * @return the current object, for convenience
|
---|
208 | */
|
---|
209 | public ImageProvider setWidth(int width) {
|
---|
210 | this.width = width;
|
---|
211 | return this;
|
---|
212 | }
|
---|
213 |
|
---|
214 | /**
|
---|
215 | * @see #setSize
|
---|
216 | * @return the current object, for convenience
|
---|
217 | */
|
---|
218 | public ImageProvider setHeight(int height) {
|
---|
219 | this.height = height;
|
---|
220 | return this;
|
---|
221 | }
|
---|
222 |
|
---|
223 | /**
|
---|
224 | * Limit the maximum size of the image.
|
---|
225 | *
|
---|
226 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
227 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
228 | *
|
---|
229 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
230 | * @return the current object, for convenience
|
---|
231 | */
|
---|
232 | public ImageProvider setMaxSize(Dimension maxSize) {
|
---|
233 | this.maxWidth = maxSize.width;
|
---|
234 | this.maxHeight = maxSize.height;
|
---|
235 | return this;
|
---|
236 | }
|
---|
237 |
|
---|
238 | /**
|
---|
239 | * Convenience method, see {@link #setMaxSize(Dimension)}.
|
---|
240 | * @return the current object, for convenience
|
---|
241 | */
|
---|
242 | public ImageProvider setMaxSize(int maxSize) {
|
---|
243 | return this.setMaxSize(new Dimension(maxSize, maxSize));
|
---|
244 | }
|
---|
245 |
|
---|
246 | /**
|
---|
247 | * @see #setMaxSize
|
---|
248 | * @return the current object, for convenience
|
---|
249 | */
|
---|
250 | public ImageProvider setMaxWidth(int maxWidth) {
|
---|
251 | this.maxWidth = maxWidth;
|
---|
252 | return this;
|
---|
253 | }
|
---|
254 |
|
---|
255 | /**
|
---|
256 | * @see #setMaxSize
|
---|
257 | * @return the current object, for convenience
|
---|
258 | */
|
---|
259 | public ImageProvider setMaxHeight(int maxHeight) {
|
---|
260 | this.maxHeight = maxHeight;
|
---|
261 | return this;
|
---|
262 | }
|
---|
263 |
|
---|
264 | /**
|
---|
265 | * Decide, if an exception should be thrown, when the image cannot be located.
|
---|
266 | *
|
---|
267 | * Set to true, when the image URL comes from user data and the image may be missing.
|
---|
268 | *
|
---|
269 | * @param optional true, if JOSM should <b>not</b> throw a RuntimeException
|
---|
270 | * in case the image cannot be located.
|
---|
271 | * @return the current object, for convenience
|
---|
272 | */
|
---|
273 | public ImageProvider setOptional(boolean optional) {
|
---|
274 | this.optional = optional;
|
---|
275 | return this;
|
---|
276 | }
|
---|
277 |
|
---|
278 | /**
|
---|
279 | * Suppresses warning on the command line in case the image cannot be found.
|
---|
280 | *
|
---|
281 | * In combination with setOptional(true);
|
---|
282 | * @return the current object, for convenience
|
---|
283 | */
|
---|
284 | public ImageProvider setSuppressWarnings(boolean suppressWarnings) {
|
---|
285 | this.suppressWarnings = suppressWarnings;
|
---|
286 | return this;
|
---|
287 | }
|
---|
288 |
|
---|
289 | /**
|
---|
290 | * Add a collection of additional class loaders to search image for.
|
---|
291 | * @return the current object, for convenience
|
---|
292 | */
|
---|
293 | public ImageProvider setAdditionalClassLoaders(Collection<ClassLoader> additionalClassLoaders) {
|
---|
294 | this.additionalClassLoaders = additionalClassLoaders;
|
---|
295 | return this;
|
---|
296 | }
|
---|
297 |
|
---|
298 | /**
|
---|
299 | * Execute the image request.
|
---|
300 | * @return the requested image or null if the request failed
|
---|
301 | */
|
---|
302 | public ImageIcon get() {
|
---|
303 | ImageResource ir = getIfAvailableImpl(additionalClassLoaders);
|
---|
304 | if (ir == null) {
|
---|
305 | if (!optional) {
|
---|
306 | String ext = name.indexOf('.') != -1 ? "" : ".???";
|
---|
307 | throw new RuntimeException(tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.", name + ext));
|
---|
308 | } else {
|
---|
309 | if (!suppressWarnings) {
|
---|
310 | Main.error(tr("Failed to locate image ''{0}''", name));
|
---|
311 | }
|
---|
312 | return null;
|
---|
313 | }
|
---|
314 | }
|
---|
315 | if (maxWidth != -1 || maxHeight != -1)
|
---|
316 | return ir.getImageIconBounded(new Dimension(maxWidth, maxHeight));
|
---|
317 | else
|
---|
318 | return ir.getImageIcon(new Dimension(width, height));
|
---|
319 | }
|
---|
320 |
|
---|
321 | /**
|
---|
322 | * Load the image in a background thread.
|
---|
323 | *
|
---|
324 | * This method returns immediately and runs the image request
|
---|
325 | * asynchronously.
|
---|
326 | *
|
---|
327 | * @param callback a callback. It is called, when the image is ready.
|
---|
328 | * This can happen before the call to this method returns or it may be
|
---|
329 | * invoked some time (seconds) later. If no image is available, a null
|
---|
330 | * value is returned to callback (just like {@link #get}).
|
---|
331 | */
|
---|
332 | public void getInBackground(final ImageCallback callback) {
|
---|
333 | if (name.startsWith("http://") || name.startsWith("wiki://")) {
|
---|
334 | Runnable fetch = new Runnable() {
|
---|
335 | @Override
|
---|
336 | public void run() {
|
---|
337 | ImageIcon result = get();
|
---|
338 | callback.finished(result);
|
---|
339 | }
|
---|
340 | };
|
---|
341 | IMAGE_FETCHER.submit(fetch);
|
---|
342 | } else {
|
---|
343 | ImageIcon result = get();
|
---|
344 | callback.finished(result);
|
---|
345 | }
|
---|
346 | }
|
---|
347 |
|
---|
348 | /**
|
---|
349 | * Load an image with a given file name.
|
---|
350 | *
|
---|
351 | * @param subdir subdirectory the image lies in
|
---|
352 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
353 | * @return The requested Image.
|
---|
354 | * @throws RuntimeException if the image cannot be located
|
---|
355 | */
|
---|
356 | public static ImageIcon get(String subdir, String name) {
|
---|
357 | return new ImageProvider(subdir, name).get();
|
---|
358 | }
|
---|
359 |
|
---|
360 | /**
|
---|
361 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
362 | * @return the requested image or null if the request failed
|
---|
363 | * @see #get(String, String)
|
---|
364 | */
|
---|
365 | public static ImageIcon get(String name) {
|
---|
366 | return new ImageProvider(name).get();
|
---|
367 | }
|
---|
368 |
|
---|
369 | /**
|
---|
370 | * Load an image with a given file name, but do not throw an exception
|
---|
371 | * when the image cannot be found.
|
---|
372 | *
|
---|
373 | * @param subdir subdirectory the image lies in
|
---|
374 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
375 | * @return the requested image or null if the request failed
|
---|
376 | * @see #get(String, String)
|
---|
377 | */
|
---|
378 | public static ImageIcon getIfAvailable(String subdir, String name) {
|
---|
379 | return new ImageProvider(subdir, name).setOptional(true).get();
|
---|
380 | }
|
---|
381 |
|
---|
382 | /**
|
---|
383 | * @param name The icon name (base name with or without '.png' or '.svg' extension)
|
---|
384 | * @return the requested image or null if the request failed
|
---|
385 | * @see #getIfAvailable(String, String)
|
---|
386 | */
|
---|
387 | public static ImageIcon getIfAvailable(String name) {
|
---|
388 | return new ImageProvider(name).setOptional(true).get();
|
---|
389 | }
|
---|
390 |
|
---|
391 | /**
|
---|
392 | * {@code data:[<mediatype>][;base64],<data>}
|
---|
393 | * @see <a href="http://tools.ietf.org/html/rfc2397">RFC2397</a>
|
---|
394 | */
|
---|
395 | private static final Pattern dataUrlPattern = Pattern.compile(
|
---|
396 | "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
|
---|
397 |
|
---|
398 | private ImageResource getIfAvailableImpl(Collection<ClassLoader> additionalClassLoaders) {
|
---|
399 | synchronized (cache) {
|
---|
400 | // This method is called from different thread and modifying HashMap concurrently can result
|
---|
401 | // for example in loops in map entries (ie freeze when such entry is retrieved)
|
---|
402 | // Yes, it did happen to me :-)
|
---|
403 | if (name == null)
|
---|
404 | return null;
|
---|
405 |
|
---|
406 | if (name.startsWith("data:")) {
|
---|
407 | String url = name;
|
---|
408 | ImageResource ir = cache.get(url);
|
---|
409 | if (ir != null) return ir;
|
---|
410 | ir = getIfAvailableDataUrl(url);
|
---|
411 | if (ir != null) {
|
---|
412 | cache.put(url, ir);
|
---|
413 | }
|
---|
414 | return ir;
|
---|
415 | }
|
---|
416 |
|
---|
417 | ImageType type = name.toLowerCase().endsWith(".svg") ? ImageType.SVG : ImageType.OTHER;
|
---|
418 |
|
---|
419 | if (name.startsWith("http://") || name.startsWith("https://")) {
|
---|
420 | String url = name;
|
---|
421 | ImageResource ir = cache.get(url);
|
---|
422 | if (ir != null) return ir;
|
---|
423 | ir = getIfAvailableHttp(url, type);
|
---|
424 | if (ir != null) {
|
---|
425 | cache.put(url, ir);
|
---|
426 | }
|
---|
427 | return ir;
|
---|
428 | } else if (name.startsWith("wiki://")) {
|
---|
429 | ImageResource ir = cache.get(name);
|
---|
430 | if (ir != null) return ir;
|
---|
431 | ir = getIfAvailableWiki(name, type);
|
---|
432 | if (ir != null) {
|
---|
433 | cache.put(name, ir);
|
---|
434 | }
|
---|
435 | return ir;
|
---|
436 | }
|
---|
437 |
|
---|
438 | if (subdir == null) {
|
---|
439 | subdir = "";
|
---|
440 | } else if (!subdir.isEmpty()) {
|
---|
441 | subdir += "/";
|
---|
442 | }
|
---|
443 | String[] extensions;
|
---|
444 | if (name.indexOf('.') != -1) {
|
---|
445 | extensions = new String[] { "" };
|
---|
446 | } else {
|
---|
447 | extensions = new String[] { ".png", ".svg"};
|
---|
448 | }
|
---|
449 | final int ARCHIVE = 0, LOCAL = 1;
|
---|
450 | for (int place : new Integer[] { ARCHIVE, LOCAL }) {
|
---|
451 | for (String ext : extensions) {
|
---|
452 |
|
---|
453 | if (".svg".equals(ext)) {
|
---|
454 | type = ImageType.SVG;
|
---|
455 | } else if (".png".equals(ext)) {
|
---|
456 | type = ImageType.OTHER;
|
---|
457 | }
|
---|
458 |
|
---|
459 | String fullName = subdir + name + ext;
|
---|
460 | String cacheName = fullName;
|
---|
461 | /* cache separately */
|
---|
462 | if (dirs != null && !dirs.isEmpty()) {
|
---|
463 | cacheName = "id:" + id + ":" + fullName;
|
---|
464 | if(archive != null) {
|
---|
465 | cacheName += ":" + archive.getName();
|
---|
466 | }
|
---|
467 | }
|
---|
468 |
|
---|
469 | ImageResource ir = cache.get(cacheName);
|
---|
470 | if (ir != null) return ir;
|
---|
471 |
|
---|
472 | switch (place) {
|
---|
473 | case ARCHIVE:
|
---|
474 | if (archive != null) {
|
---|
475 | ir = getIfAvailableZip(fullName, archive, inArchiveDir, type);
|
---|
476 | if (ir != null) {
|
---|
477 | cache.put(cacheName, ir);
|
---|
478 | return ir;
|
---|
479 | }
|
---|
480 | }
|
---|
481 | break;
|
---|
482 | case LOCAL:
|
---|
483 | // getImageUrl() does a ton of "stat()" calls and gets expensive
|
---|
484 | // and redundant when you have a whole ton of objects. So,
|
---|
485 | // index the cache by the name of the icon we're looking for
|
---|
486 | // and don't bother to create a URL unless we're actually
|
---|
487 | // creating the image.
|
---|
488 | URL path = getImageUrl(fullName, dirs, additionalClassLoaders);
|
---|
489 | if (path == null) {
|
---|
490 | continue;
|
---|
491 | }
|
---|
492 | ir = getIfAvailableLocalURL(path, type);
|
---|
493 | if (ir != null) {
|
---|
494 | cache.put(cacheName, ir);
|
---|
495 | return ir;
|
---|
496 | }
|
---|
497 | break;
|
---|
498 | }
|
---|
499 | }
|
---|
500 | }
|
---|
501 | return null;
|
---|
502 | }
|
---|
503 | }
|
---|
504 |
|
---|
505 | private static ImageResource getIfAvailableHttp(String url, ImageType type) {
|
---|
506 | MirroredInputStream is = null;
|
---|
507 | try {
|
---|
508 | is = new MirroredInputStream(url,
|
---|
509 | new File(Main.pref.getCacheDirectory(), "images").getPath());
|
---|
510 | switch (type) {
|
---|
511 | case SVG:
|
---|
512 | URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(is.getFile()).toString());
|
---|
513 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
514 | return svg == null ? null : new ImageResource(svg);
|
---|
515 | case OTHER:
|
---|
516 | BufferedImage img = null;
|
---|
517 | try {
|
---|
518 | img = ImageIO.read(Utils.fileToURL(is.getFile()));
|
---|
519 | } catch (IOException e) {
|
---|
520 | Main.warn("IOException while reading HTTP image: "+e.getMessage());
|
---|
521 | }
|
---|
522 | return img == null ? null : new ImageResource(img);
|
---|
523 | default:
|
---|
524 | throw new AssertionError();
|
---|
525 | }
|
---|
526 | } catch (IOException e) {
|
---|
527 | return null;
|
---|
528 | } finally {
|
---|
529 | Utils.close(is);
|
---|
530 | }
|
---|
531 | }
|
---|
532 |
|
---|
533 | private static ImageResource getIfAvailableDataUrl(String url) {
|
---|
534 | try {
|
---|
535 | Matcher m = dataUrlPattern.matcher(url);
|
---|
536 | if (m.matches()) {
|
---|
537 | String mediatype = m.group(1);
|
---|
538 | String base64 = m.group(2);
|
---|
539 | String data = m.group(3);
|
---|
540 | byte[] bytes;
|
---|
541 | if (";base64".equals(base64)) {
|
---|
542 | bytes = Base64.decodeBase64(data);
|
---|
543 | } else {
|
---|
544 | try {
|
---|
545 | bytes = URLDecoder.decode(data, "UTF-8").getBytes(Utils.UTF_8);
|
---|
546 | } catch (IllegalArgumentException ex) {
|
---|
547 | Main.warn("Unable to decode URL data part: "+ex.getMessage() + " (" + data + ")");
|
---|
548 | return null;
|
---|
549 | }
|
---|
550 | }
|
---|
551 | if (mediatype != null && mediatype.contains("image/svg+xml")) {
|
---|
552 | String s = new String(bytes, Utils.UTF_8);
|
---|
553 | URI uri = getSvgUniverse().loadSVG(new StringReader(s), URLEncoder.encode(s, "UTF-8"));
|
---|
554 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
555 | if (svg == null) {
|
---|
556 | Main.warn("Unable to process svg: "+s);
|
---|
557 | return null;
|
---|
558 | }
|
---|
559 | return new ImageResource(svg);
|
---|
560 | } else {
|
---|
561 | try {
|
---|
562 | return new ImageResource(ImageIO.read(new ByteArrayInputStream(bytes)));
|
---|
563 | } catch (IOException e) {
|
---|
564 | Main.warn("IOException while reading image: "+e.getMessage());
|
---|
565 | }
|
---|
566 | }
|
---|
567 | }
|
---|
568 | return null;
|
---|
569 | } catch (UnsupportedEncodingException ex) {
|
---|
570 | throw new RuntimeException(ex.getMessage(), ex);
|
---|
571 | }
|
---|
572 | }
|
---|
573 |
|
---|
574 | private static ImageResource getIfAvailableWiki(String name, ImageType type) {
|
---|
575 | final Collection<String> defaultBaseUrls = Arrays.asList(
|
---|
576 | "http://wiki.openstreetmap.org/w/images/",
|
---|
577 | "http://upload.wikimedia.org/wikipedia/commons/",
|
---|
578 | "http://wiki.openstreetmap.org/wiki/File:"
|
---|
579 | );
|
---|
580 | final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
|
---|
581 |
|
---|
582 | final String fn = name.substring(name.lastIndexOf('/') + 1);
|
---|
583 |
|
---|
584 | ImageResource result = null;
|
---|
585 | for (String b : baseUrls) {
|
---|
586 | String url;
|
---|
587 | if (b.endsWith(":")) {
|
---|
588 | url = getImgUrlFromWikiInfoPage(b, fn);
|
---|
589 | if (url == null) {
|
---|
590 | continue;
|
---|
591 | }
|
---|
592 | } else {
|
---|
593 | final String fn_md5 = Utils.md5Hex(fn);
|
---|
594 | url = b + fn_md5.substring(0,1) + "/" + fn_md5.substring(0,2) + "/" + fn;
|
---|
595 | }
|
---|
596 | result = getIfAvailableHttp(url, type);
|
---|
597 | if (result != null) {
|
---|
598 | break;
|
---|
599 | }
|
---|
600 | }
|
---|
601 | return result;
|
---|
602 | }
|
---|
603 |
|
---|
604 | private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
|
---|
605 | ZipFile zipFile = null;
|
---|
606 | try {
|
---|
607 | zipFile = new ZipFile(archive);
|
---|
608 | if (inArchiveDir == null || inArchiveDir.equals(".")) {
|
---|
609 | inArchiveDir = "";
|
---|
610 | } else if (!inArchiveDir.isEmpty()) {
|
---|
611 | inArchiveDir += "/";
|
---|
612 | }
|
---|
613 | String entryName = inArchiveDir + fullName;
|
---|
614 | ZipEntry entry = zipFile.getEntry(entryName);
|
---|
615 | if(entry != null)
|
---|
616 | {
|
---|
617 | int size = (int)entry.getSize();
|
---|
618 | int offs = 0;
|
---|
619 | byte[] buf = new byte[size];
|
---|
620 | InputStream is = null;
|
---|
621 | try {
|
---|
622 | is = zipFile.getInputStream(entry);
|
---|
623 | switch (type) {
|
---|
624 | case SVG:
|
---|
625 | URI uri = getSvgUniverse().loadSVG(is, entryName);
|
---|
626 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
627 | return svg == null ? null : new ImageResource(svg);
|
---|
628 | case OTHER:
|
---|
629 | while(size > 0)
|
---|
630 | {
|
---|
631 | int l = is.read(buf, offs, size);
|
---|
632 | offs += l;
|
---|
633 | size -= l;
|
---|
634 | }
|
---|
635 | BufferedImage img = null;
|
---|
636 | try {
|
---|
637 | img = ImageIO.read(new ByteArrayInputStream(buf));
|
---|
638 | } catch (IOException e) {
|
---|
639 | Main.warn(e);
|
---|
640 | }
|
---|
641 | return img == null ? null : new ImageResource(img);
|
---|
642 | default:
|
---|
643 | throw new AssertionError();
|
---|
644 | }
|
---|
645 | } finally {
|
---|
646 | Utils.close(is);
|
---|
647 | }
|
---|
648 | }
|
---|
649 | } catch (Exception e) {
|
---|
650 | Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
|
---|
651 | } finally {
|
---|
652 | Utils.close(zipFile);
|
---|
653 | }
|
---|
654 | return null;
|
---|
655 | }
|
---|
656 |
|
---|
657 | private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
|
---|
658 | switch (type) {
|
---|
659 | case SVG:
|
---|
660 | URI uri = getSvgUniverse().loadSVG(path);
|
---|
661 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
662 | return svg == null ? null : new ImageResource(svg);
|
---|
663 | case OTHER:
|
---|
664 | BufferedImage img = null;
|
---|
665 | try {
|
---|
666 | img = ImageIO.read(path);
|
---|
667 | } catch (IOException e) {
|
---|
668 | Main.warn(e);
|
---|
669 | }
|
---|
670 | return img == null ? null : new ImageResource(img);
|
---|
671 | default:
|
---|
672 | throw new AssertionError();
|
---|
673 | }
|
---|
674 | }
|
---|
675 |
|
---|
676 | private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
|
---|
677 | if (path != null && path.startsWith("resource://")) {
|
---|
678 | String p = path.substring("resource://".length());
|
---|
679 | Collection<ClassLoader> classLoaders = new ArrayList<>(PluginHandler.getResourceClassLoaders());
|
---|
680 | if (additionalClassLoaders != null) {
|
---|
681 | classLoaders.addAll(additionalClassLoaders);
|
---|
682 | }
|
---|
683 | for (ClassLoader source : classLoaders) {
|
---|
684 | URL res;
|
---|
685 | if ((res = source.getResource(p + name)) != null)
|
---|
686 | return res;
|
---|
687 | }
|
---|
688 | } else {
|
---|
689 | File f = new File(path, name);
|
---|
690 | if ((path != null || f.isAbsolute()) && f.exists())
|
---|
691 | return Utils.fileToURL(f);
|
---|
692 | }
|
---|
693 | return null;
|
---|
694 | }
|
---|
695 |
|
---|
696 | private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
|
---|
697 | URL u = null;
|
---|
698 |
|
---|
699 | // Try passed directories first
|
---|
700 | if (dirs != null) {
|
---|
701 | for (String name : dirs) {
|
---|
702 | try {
|
---|
703 | u = getImageUrl(name, imageName, additionalClassLoaders);
|
---|
704 | if (u != null)
|
---|
705 | return u;
|
---|
706 | } catch (SecurityException e) {
|
---|
707 | Main.warn(tr(
|
---|
708 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}",
|
---|
709 | name, e.toString()));
|
---|
710 | }
|
---|
711 |
|
---|
712 | }
|
---|
713 | }
|
---|
714 | // Try user-preference directory
|
---|
715 | String dir = Main.pref.getPreferencesDir() + "images";
|
---|
716 | try {
|
---|
717 | u = getImageUrl(dir, imageName, additionalClassLoaders);
|
---|
718 | if (u != null)
|
---|
719 | return u;
|
---|
720 | } catch (SecurityException e) {
|
---|
721 | Main.warn(tr(
|
---|
722 | "Failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
|
---|
723 | .toString()));
|
---|
724 | }
|
---|
725 |
|
---|
726 | // Absolute path?
|
---|
727 | u = getImageUrl(null, imageName, additionalClassLoaders);
|
---|
728 | if (u != null)
|
---|
729 | return u;
|
---|
730 |
|
---|
731 | // Try plugins and josm classloader
|
---|
732 | u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
|
---|
733 | if (u != null)
|
---|
734 | return u;
|
---|
735 |
|
---|
736 | // Try all other resource directories
|
---|
737 | for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
|
---|
738 | u = getImageUrl(location + "images", imageName, additionalClassLoaders);
|
---|
739 | if (u != null)
|
---|
740 | return u;
|
---|
741 | u = getImageUrl(location, imageName, additionalClassLoaders);
|
---|
742 | if (u != null)
|
---|
743 | return u;
|
---|
744 | }
|
---|
745 |
|
---|
746 | return null;
|
---|
747 | }
|
---|
748 |
|
---|
749 | /**
|
---|
750 | * Reads the wiki page on a certain file in html format in order to find the real image URL.
|
---|
751 | */
|
---|
752 | private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
|
---|
753 |
|
---|
754 | /** Quit parsing, when a certain condition is met */
|
---|
755 | class SAXReturnException extends SAXException {
|
---|
756 | private final String result;
|
---|
757 |
|
---|
758 | public SAXReturnException(String result) {
|
---|
759 | this.result = result;
|
---|
760 | }
|
---|
761 |
|
---|
762 | public String getResult() {
|
---|
763 | return result;
|
---|
764 | }
|
---|
765 | }
|
---|
766 |
|
---|
767 | try {
|
---|
768 | final XMLReader parser = XMLReaderFactory.createXMLReader();
|
---|
769 | parser.setContentHandler(new DefaultHandler() {
|
---|
770 | @Override
|
---|
771 | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
|
---|
772 | if (localName.equalsIgnoreCase("img")) {
|
---|
773 | String val = atts.getValue("src");
|
---|
774 | if (val.endsWith(fn))
|
---|
775 | throw new SAXReturnException(val); // parsing done, quit early
|
---|
776 | }
|
---|
777 | }
|
---|
778 | });
|
---|
779 |
|
---|
780 | parser.setEntityResolver(new EntityResolver() {
|
---|
781 | @Override
|
---|
782 | public InputSource resolveEntity (String publicId, String systemId) {
|
---|
783 | return new InputSource(new ByteArrayInputStream(new byte[0]));
|
---|
784 | }
|
---|
785 | });
|
---|
786 |
|
---|
787 | parser.parse(new InputSource(new MirroredInputStream(
|
---|
788 | base + fn,
|
---|
789 | new File(Main.pref.getPreferencesDir(), "images").toString()
|
---|
790 | )));
|
---|
791 | } catch (SAXReturnException r) {
|
---|
792 | return r.getResult();
|
---|
793 | } catch (Exception e) {
|
---|
794 | Main.warn("Parsing " + base + fn + " failed:\n" + e);
|
---|
795 | return null;
|
---|
796 | }
|
---|
797 | Main.warn("Parsing " + base + fn + " failed: Unexpected content.");
|
---|
798 | return null;
|
---|
799 | }
|
---|
800 |
|
---|
801 | public static Cursor getCursor(String name, String overlay) {
|
---|
802 | ImageIcon img = get("cursor", name);
|
---|
803 | if (overlay != null) {
|
---|
804 | img = overlay(img, ImageProvider.get("cursor/modifier/" + overlay), OverlayPosition.SOUTHEAST);
|
---|
805 | }
|
---|
806 | Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
|
---|
807 | name.equals("crosshair") ? new Point(10, 10) : new Point(3, 2), "Cursor");
|
---|
808 | return c;
|
---|
809 | }
|
---|
810 |
|
---|
811 | /**
|
---|
812 | * Decorate one icon with an overlay icon.
|
---|
813 | *
|
---|
814 | * @param ground the base image
|
---|
815 | * @param overlay the overlay image (can be smaller than the base image)
|
---|
816 | * @param pos position of the overlay image inside the base image (positioned
|
---|
817 | * in one of the corners)
|
---|
818 | * @return an icon that represent the overlay of the two given icons. The second icon is layed
|
---|
819 | * on the first relative to the given position.
|
---|
820 | */
|
---|
821 | public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
|
---|
822 | GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
|
---|
823 | .getDefaultConfiguration();
|
---|
824 | int w = ground.getIconWidth();
|
---|
825 | int h = ground.getIconHeight();
|
---|
826 | int wo = overlay.getIconWidth();
|
---|
827 | int ho = overlay.getIconHeight();
|
---|
828 | BufferedImage img = conf.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
|
---|
829 | Graphics g = img.createGraphics();
|
---|
830 | ground.paintIcon(null, g, 0, 0);
|
---|
831 | int x = 0, y = 0;
|
---|
832 | switch (pos) {
|
---|
833 | case NORTHWEST:
|
---|
834 | x = 0;
|
---|
835 | y = 0;
|
---|
836 | break;
|
---|
837 | case NORTHEAST:
|
---|
838 | x = w - wo;
|
---|
839 | y = 0;
|
---|
840 | break;
|
---|
841 | case SOUTHWEST:
|
---|
842 | x = 0;
|
---|
843 | y = h - ho;
|
---|
844 | break;
|
---|
845 | case SOUTHEAST:
|
---|
846 | x = w - wo;
|
---|
847 | y = h - ho;
|
---|
848 | break;
|
---|
849 | }
|
---|
850 | overlay.paintIcon(null, g, x, y);
|
---|
851 | return new ImageIcon(img);
|
---|
852 | }
|
---|
853 |
|
---|
854 | /** 90 degrees in radians units */
|
---|
855 | static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
|
---|
856 |
|
---|
857 | /**
|
---|
858 | * Creates a rotated version of the input image.
|
---|
859 | *
|
---|
860 | * @param img the image to be rotated.
|
---|
861 | * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
|
---|
862 | * will mod it with 360 before using it. More over for caching performance, it will be rounded to
|
---|
863 | * an entire value between 0 and 360.
|
---|
864 | *
|
---|
865 | * @return the image after rotating.
|
---|
866 | * @since 6172
|
---|
867 | */
|
---|
868 | public static Image createRotatedImage(Image img, double rotatedAngle) {
|
---|
869 | return createRotatedImage(img, rotatedAngle, ImageResource.DEFAULT_DIMENSION);
|
---|
870 | }
|
---|
871 |
|
---|
872 | /**
|
---|
873 | * Creates a rotated version of the input image, scaled to the given dimension.
|
---|
874 | *
|
---|
875 | * @param img the image to be rotated.
|
---|
876 | * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
|
---|
877 | * will mod it with 360 before using it. More over for caching performance, it will be rounded to
|
---|
878 | * an entire value between 0 and 360.
|
---|
879 | * @param dimension The requested dimensions. Use (-1,-1) for the original size
|
---|
880 | * and (width, -1) to set the width, but otherwise scale the image proportionally.
|
---|
881 | * @return the image after rotating and scaling.
|
---|
882 | * @since 6172
|
---|
883 | */
|
---|
884 | public static Image createRotatedImage(Image img, double rotatedAngle, Dimension dimension) {
|
---|
885 | CheckParameterUtil.ensureParameterNotNull(img, "img");
|
---|
886 |
|
---|
887 | // convert rotatedAngle to an integer value from 0 to 360
|
---|
888 | Long originalAngle = Math.round(rotatedAngle % 360);
|
---|
889 | if (rotatedAngle != 0 && originalAngle == 0) {
|
---|
890 | originalAngle = 360L;
|
---|
891 | }
|
---|
892 |
|
---|
893 | ImageResource imageResource = null;
|
---|
894 |
|
---|
895 | synchronized (ROTATE_CACHE) {
|
---|
896 | Map<Long, ImageResource> cacheByAngle = ROTATE_CACHE.get(img);
|
---|
897 | if (cacheByAngle == null) {
|
---|
898 | ROTATE_CACHE.put(img, cacheByAngle = new HashMap<>());
|
---|
899 | }
|
---|
900 |
|
---|
901 | imageResource = cacheByAngle.get(originalAngle);
|
---|
902 |
|
---|
903 | if (imageResource == null) {
|
---|
904 | // convert originalAngle to a value from 0 to 90
|
---|
905 | double angle = originalAngle % 90;
|
---|
906 | if (originalAngle != 0.0 && angle == 0.0) {
|
---|
907 | angle = 90.0;
|
---|
908 | }
|
---|
909 |
|
---|
910 | double radian = Math.toRadians(angle);
|
---|
911 |
|
---|
912 | new ImageIcon(img); // load completely
|
---|
913 | int iw = img.getWidth(null);
|
---|
914 | int ih = img.getHeight(null);
|
---|
915 | int w;
|
---|
916 | int h;
|
---|
917 |
|
---|
918 | if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
|
---|
919 | w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
|
---|
920 | h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
|
---|
921 | } else {
|
---|
922 | w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
|
---|
923 | h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
|
---|
924 | }
|
---|
925 | Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
---|
926 | cacheByAngle.put(originalAngle, imageResource = new ImageResource(image));
|
---|
927 | Graphics g = image.getGraphics();
|
---|
928 | Graphics2D g2d = (Graphics2D) g.create();
|
---|
929 |
|
---|
930 | // calculate the center of the icon.
|
---|
931 | int cx = iw / 2;
|
---|
932 | int cy = ih / 2;
|
---|
933 |
|
---|
934 | // move the graphics center point to the center of the icon.
|
---|
935 | g2d.translate(w / 2, h / 2);
|
---|
936 |
|
---|
937 | // rotate the graphics about the center point of the icon
|
---|
938 | g2d.rotate(Math.toRadians(originalAngle));
|
---|
939 |
|
---|
940 | g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
---|
941 | g2d.drawImage(img, -cx, -cy, null);
|
---|
942 |
|
---|
943 | g2d.dispose();
|
---|
944 | new ImageIcon(image); // load completely
|
---|
945 | }
|
---|
946 | return imageResource.getImageIcon(dimension).getImage();
|
---|
947 | }
|
---|
948 | }
|
---|
949 |
|
---|
950 | /**
|
---|
951 | * Creates a scaled down version of the input image to fit maximum dimensions. (Keeps aspect ratio)
|
---|
952 | *
|
---|
953 | * @param img the image to be scaled down.
|
---|
954 | * @param maxSize the maximum size in pixels (both for width and height)
|
---|
955 | *
|
---|
956 | * @return the image after scaling.
|
---|
957 | * @since 6172
|
---|
958 | */
|
---|
959 | public static Image createBoundedImage(Image img, int maxSize) {
|
---|
960 | return new ImageResource(img).getImageIconBounded(new Dimension(maxSize, maxSize)).getImage();
|
---|
961 | }
|
---|
962 |
|
---|
963 | /**
|
---|
964 | * Replies the icon for an OSM primitive type
|
---|
965 | * @param type the type
|
---|
966 | * @return the icon
|
---|
967 | */
|
---|
968 | public static ImageIcon get(OsmPrimitiveType type) {
|
---|
969 | CheckParameterUtil.ensureParameterNotNull(type, "type");
|
---|
970 | return get("data", type.getAPIName());
|
---|
971 | }
|
---|
972 |
|
---|
973 | public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
|
---|
974 | float realWidth = svg.getWidth();
|
---|
975 | float realHeight = svg.getHeight();
|
---|
976 | int width = Math.round(realWidth);
|
---|
977 | int height = Math.round(realHeight);
|
---|
978 | Double scaleX = null, scaleY = null;
|
---|
979 | if (dim.width != -1) {
|
---|
980 | width = dim.width;
|
---|
981 | scaleX = (double) width / realWidth;
|
---|
982 | if (dim.height == -1) {
|
---|
983 | scaleY = scaleX;
|
---|
984 | height = (int) Math.round(realHeight * scaleY);
|
---|
985 | } else {
|
---|
986 | height = dim.height;
|
---|
987 | scaleY = (double) height / realHeight;
|
---|
988 | }
|
---|
989 | } else if (dim.height != -1) {
|
---|
990 | height = dim.height;
|
---|
991 | scaleX = scaleY = (double) height / realHeight;
|
---|
992 | width = (int) Math.round(realWidth * scaleX);
|
---|
993 | }
|
---|
994 | if (width == 0 || height == 0) {
|
---|
995 | return null;
|
---|
996 | }
|
---|
997 | BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
|
---|
998 | Graphics2D g = img.createGraphics();
|
---|
999 | g.setClip(0, 0, width, height);
|
---|
1000 | if (scaleX != null && scaleY != null) {
|
---|
1001 | g.scale(scaleX, scaleY);
|
---|
1002 | }
|
---|
1003 | g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
---|
1004 | try {
|
---|
1005 | svg.render(g);
|
---|
1006 | } catch (SVGException ex) {
|
---|
1007 | return null;
|
---|
1008 | }
|
---|
1009 | return img;
|
---|
1010 | }
|
---|
1011 |
|
---|
1012 | private static SVGUniverse getSvgUniverse() {
|
---|
1013 | if (svgUniverse == null) {
|
---|
1014 | svgUniverse = new SVGUniverse();
|
---|
1015 | }
|
---|
1016 | return svgUniverse;
|
---|
1017 | }
|
---|
1018 | }
|
---|