1 | // License: GPL. Copyright 2007 by Immanuel Scholz and others
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.Component;
|
---|
7 | import java.awt.Cursor;
|
---|
8 | import java.awt.Dimension;
|
---|
9 | import java.awt.Graphics;
|
---|
10 | import java.awt.Graphics2D;
|
---|
11 | import java.awt.GraphicsConfiguration;
|
---|
12 | import java.awt.GraphicsEnvironment;
|
---|
13 | import java.awt.Image;
|
---|
14 | import java.awt.Point;
|
---|
15 | import java.awt.RenderingHints;
|
---|
16 | import java.awt.Toolkit;
|
---|
17 | import java.awt.Transparency;
|
---|
18 | import java.awt.image.BufferedImage;
|
---|
19 | import java.io.ByteArrayInputStream;
|
---|
20 | import java.io.File;
|
---|
21 | import java.io.IOException;
|
---|
22 | import java.io.InputStream;
|
---|
23 | import java.io.StringReader;
|
---|
24 | import java.io.UnsupportedEncodingException;
|
---|
25 | import java.net.MalformedURLException;
|
---|
26 | import java.net.URI;
|
---|
27 | import java.net.URL;
|
---|
28 | import java.net.URLDecoder;
|
---|
29 | import java.util.ArrayList;
|
---|
30 | import java.util.Arrays;
|
---|
31 | import java.util.Collection;
|
---|
32 | import java.util.HashMap;
|
---|
33 | import java.util.Map;
|
---|
34 | import java.util.regex.Matcher;
|
---|
35 | import java.util.regex.Pattern;
|
---|
36 | import java.util.zip.ZipEntry;
|
---|
37 | import java.util.zip.ZipFile;
|
---|
38 |
|
---|
39 | import javax.imageio.ImageIO;
|
---|
40 | import javax.swing.Icon;
|
---|
41 | import javax.swing.ImageIcon;
|
---|
42 |
|
---|
43 | import org.apache.commons.codec.binary.Base64;
|
---|
44 | import org.openstreetmap.josm.Main;
|
---|
45 | import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
|
---|
46 | import org.openstreetmap.josm.io.MirroredInputStream;
|
---|
47 | import org.openstreetmap.josm.plugins.PluginHandler;
|
---|
48 | import org.xml.sax.Attributes;
|
---|
49 | import org.xml.sax.EntityResolver;
|
---|
50 | import org.xml.sax.InputSource;
|
---|
51 | import org.xml.sax.SAXException;
|
---|
52 | import org.xml.sax.XMLReader;
|
---|
53 | import org.xml.sax.helpers.DefaultHandler;
|
---|
54 | import org.xml.sax.helpers.XMLReaderFactory;
|
---|
55 |
|
---|
56 | import com.kitfox.svg.SVGDiagram;
|
---|
57 | import com.kitfox.svg.SVGException;
|
---|
58 | import com.kitfox.svg.SVGUniverse;
|
---|
59 |
|
---|
60 | /**
|
---|
61 | * Helper class to support the application with images.
|
---|
62 | *
|
---|
63 | * How to use:
|
---|
64 | *
|
---|
65 | * <code>ImageIcon icon = new ImageProvider(name).setMaxWidth(24).setMaxHeight(24).get();</code>
|
---|
66 | * (there are more options, see below)
|
---|
67 | *
|
---|
68 | * short form:
|
---|
69 | * <code>ImageIcon icon = ImageProvider.get(name);</code>
|
---|
70 | *
|
---|
71 | * @author imi
|
---|
72 | */
|
---|
73 | public class ImageProvider {
|
---|
74 |
|
---|
75 | /**
|
---|
76 | * Position of an overlay icon
|
---|
77 | * @author imi
|
---|
78 | */
|
---|
79 | public static enum OverlayPosition {
|
---|
80 | NORTHWEST, NORTHEAST, SOUTHWEST, SOUTHEAST
|
---|
81 | }
|
---|
82 |
|
---|
83 | public static enum ImageType {
|
---|
84 | SVG, // scalable vector graphics
|
---|
85 | OTHER // everything else, e.g. png, gif (must be supported by Java)
|
---|
86 | }
|
---|
87 |
|
---|
88 | protected Collection<String> dirs;
|
---|
89 | protected String id;
|
---|
90 | protected String subdir;
|
---|
91 | protected String name;
|
---|
92 | protected File archive;
|
---|
93 | protected int width = -1;
|
---|
94 | protected int height = -1;
|
---|
95 | protected int maxWidth = -1;
|
---|
96 | protected int maxHeight = -1;
|
---|
97 | protected boolean optional;
|
---|
98 |
|
---|
99 | private static SVGUniverse svgUniverse;
|
---|
100 |
|
---|
101 | /**
|
---|
102 | * The icon cache
|
---|
103 | */
|
---|
104 | private static Map<String, ImageResource> cache = new HashMap<String, ImageResource>();
|
---|
105 |
|
---|
106 | /**
|
---|
107 | * @param subdir Subdirectory the image lies in.
|
---|
108 | * @param name The name of the image. If it does not end with '.png' or '.svg',
|
---|
109 | * both extensions are tried.
|
---|
110 | */
|
---|
111 | public ImageProvider(String subdir, String name) {
|
---|
112 | this.subdir = subdir;
|
---|
113 | this.name = name;
|
---|
114 | }
|
---|
115 |
|
---|
116 | public ImageProvider(String name) {
|
---|
117 | this.name = name;
|
---|
118 | }
|
---|
119 |
|
---|
120 | /**
|
---|
121 | * Directories to look for the image.
|
---|
122 | */
|
---|
123 | public ImageProvider setDirs(Collection<String> dirs) {
|
---|
124 | this.dirs = dirs;
|
---|
125 | return this;
|
---|
126 | }
|
---|
127 |
|
---|
128 | /**
|
---|
129 | * An id used for caching. Id is not used for cache if name starts with http://. (URL is unique anyway.)
|
---|
130 | */
|
---|
131 | public ImageProvider setId(String id) {
|
---|
132 | this.id = id;
|
---|
133 | return this;
|
---|
134 | }
|
---|
135 |
|
---|
136 | /**
|
---|
137 | * A zip file where the image is located.
|
---|
138 | */
|
---|
139 | public ImageProvider setArchive(File archive) {
|
---|
140 | this.archive = archive;
|
---|
141 | return this;
|
---|
142 | }
|
---|
143 |
|
---|
144 | /**
|
---|
145 | * The dimensions of the image.
|
---|
146 | *
|
---|
147 | * If not specified, the original size of the image is used.
|
---|
148 | * The width part of the dimension can be -1. Then it will only set the height but
|
---|
149 | * keep the aspect ratio. (And the other way around.)
|
---|
150 | */
|
---|
151 | public ImageProvider setSize(Dimension size) {
|
---|
152 | this.width = size.width;
|
---|
153 | this.height = size.height;
|
---|
154 | return this;
|
---|
155 | }
|
---|
156 |
|
---|
157 | /**
|
---|
158 | * see setSize
|
---|
159 | */
|
---|
160 | public ImageProvider setWidth(int width) {
|
---|
161 | this.width = width;
|
---|
162 | return this;
|
---|
163 | }
|
---|
164 |
|
---|
165 | /**
|
---|
166 | * see setSize
|
---|
167 | */
|
---|
168 | public ImageProvider setHeight(int height) {
|
---|
169 | this.height = height;
|
---|
170 | return this;
|
---|
171 | }
|
---|
172 |
|
---|
173 | /**
|
---|
174 | * The maximum size of the image.
|
---|
175 | *
|
---|
176 | * It will shrink the image if necessary, but keep the aspect ratio.
|
---|
177 | * The given width or height can be -1 which means this direction is not bounded.
|
---|
178 | *
|
---|
179 | * 'size' and 'maxSize' are not compatible, you should set only one of them.
|
---|
180 | */
|
---|
181 | public ImageProvider setMaxSize(Dimension maxSize) {
|
---|
182 | this.maxWidth = maxSize.width;
|
---|
183 | this.maxHeight = maxSize.height;
|
---|
184 | return this;
|
---|
185 | }
|
---|
186 |
|
---|
187 | /**
|
---|
188 | * see setMaxSize
|
---|
189 | */
|
---|
190 | public ImageProvider setMaxWidth(int maxWidth) {
|
---|
191 | this.maxWidth = maxWidth;
|
---|
192 | return this;
|
---|
193 | }
|
---|
194 |
|
---|
195 | /**
|
---|
196 | * see setMaxSize
|
---|
197 | */
|
---|
198 | public ImageProvider setMaxHeight(int maxHeight) {
|
---|
199 | this.maxHeight = maxHeight;
|
---|
200 | return this;
|
---|
201 | }
|
---|
202 |
|
---|
203 | /**
|
---|
204 | * The image URL comes from user data and the image may be missing.
|
---|
205 | *
|
---|
206 | * Set true, if JOSM should *not* throw a RuntimeException in case the image cannot be located.
|
---|
207 | */
|
---|
208 | public ImageProvider setOptional(boolean optional) {
|
---|
209 | this.optional = optional;
|
---|
210 | return this;
|
---|
211 | }
|
---|
212 |
|
---|
213 | /**
|
---|
214 | * Execute the image request.
|
---|
215 | */
|
---|
216 | public ImageIcon get() {
|
---|
217 | return get(true);
|
---|
218 | }
|
---|
219 |
|
---|
220 | /**
|
---|
221 | * Execute the image request.
|
---|
222 | * @param warn If the requested image has been set as optional and is not found, prints an error message on System.err.
|
---|
223 | */
|
---|
224 | public ImageIcon get(boolean warn) {
|
---|
225 | return get(warn, null);
|
---|
226 | }
|
---|
227 |
|
---|
228 | /**
|
---|
229 | * Execute the image request.
|
---|
230 | * @param additionalClassLoaders A collection of additional class loaders to search image for.
|
---|
231 | */
|
---|
232 | public ImageIcon get(Collection<ClassLoader> additionalClassLoaders) {
|
---|
233 | return get(true, additionalClassLoaders);
|
---|
234 | }
|
---|
235 |
|
---|
236 | /**
|
---|
237 | * Execute the image request.
|
---|
238 | * @param warn If the requested image has been set as optional and is not found, prints an error message on System.err.
|
---|
239 | * @param additionalClassLoaders A collection of additional class loaders to search image for.
|
---|
240 | */
|
---|
241 | public ImageIcon get(boolean warn, Collection<ClassLoader> additionalClassLoaders) {
|
---|
242 | ImageResource ir = getIfAvailableImpl(additionalClassLoaders);
|
---|
243 | if (ir == null) {
|
---|
244 | if (!optional) {
|
---|
245 | String ext = name.indexOf('.') != -1 ? "" : ".???";
|
---|
246 | throw new RuntimeException(tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.", name + ext));
|
---|
247 | } else {
|
---|
248 | if (warn) {
|
---|
249 | System.err.println(tr("Failed to locate image ''{0}''", name));
|
---|
250 | }
|
---|
251 | return null;
|
---|
252 | }
|
---|
253 | }
|
---|
254 | if (maxWidth != -1 || maxHeight != -1)
|
---|
255 | return ir.getImageIconBounded(new Dimension(maxWidth, maxHeight));
|
---|
256 | else
|
---|
257 | return ir.getImageIcon(new Dimension(width, height));
|
---|
258 | }
|
---|
259 |
|
---|
260 | /**
|
---|
261 | * Return an image from the specified location. Throws a RuntimeException if
|
---|
262 | * the image cannot be located.
|
---|
263 | *
|
---|
264 | * @param subdir The position of the directory, e.g. 'layer'
|
---|
265 | * @param name The icons name (with or without '.png' or '.svg' extension)
|
---|
266 | * @return The requested Image.
|
---|
267 | */
|
---|
268 | public static ImageIcon get(String subdir, String name) {
|
---|
269 | return new ImageProvider(subdir, name).get();
|
---|
270 | }
|
---|
271 |
|
---|
272 | public static ImageIcon get(String name) {
|
---|
273 | return new ImageProvider(name).get();
|
---|
274 | }
|
---|
275 |
|
---|
276 | public static ImageIcon getIfAvailable(String name) {
|
---|
277 | return new ImageProvider(name).setOptional(true).get();
|
---|
278 | }
|
---|
279 |
|
---|
280 | public static ImageIcon getIfAvailable(String subdir, String name) {
|
---|
281 | return new ImageProvider(subdir, name).setOptional(true).get();
|
---|
282 | }
|
---|
283 |
|
---|
284 | /**
|
---|
285 | * {@code data:[<mediatype>][;base64],<data>}
|
---|
286 | * @see RFC2397
|
---|
287 | */
|
---|
288 | private static final Pattern dataUrlPattern = Pattern.compile(
|
---|
289 | "^data:([a-zA-Z]+/[a-zA-Z+]+)?(;base64)?,(.+)$");
|
---|
290 |
|
---|
291 | private ImageResource getIfAvailableImpl(Collection<ClassLoader> additionalClassLoaders) {
|
---|
292 | if (name == null)
|
---|
293 | return null;
|
---|
294 |
|
---|
295 | try {
|
---|
296 | if (name.startsWith("data:")) {
|
---|
297 | Matcher m = dataUrlPattern.matcher(name);
|
---|
298 | if (m.matches()) {
|
---|
299 | String mediatype = m.group(1);
|
---|
300 | String base64 = m.group(2);
|
---|
301 | String data = m.group(3);
|
---|
302 | byte[] bytes = ";base64".equals(base64)
|
---|
303 | ? Base64.decodeBase64(data)
|
---|
304 | : URLDecoder.decode(data, "utf-8").getBytes();
|
---|
305 | if (mediatype != null && mediatype.contains("image/svg+xml")) {
|
---|
306 | URI uri = getSvgUniverse().loadSVG(new StringReader(new String(bytes)), name);
|
---|
307 | return new ImageResource(getSvgUniverse().getDiagram(uri));
|
---|
308 | } else {
|
---|
309 | try {
|
---|
310 | return new ImageResource(ImageIO.read(new ByteArrayInputStream(bytes)));
|
---|
311 | } catch (IOException e) {}
|
---|
312 | }
|
---|
313 | }
|
---|
314 | }
|
---|
315 | } catch (UnsupportedEncodingException ex) {
|
---|
316 | throw new RuntimeException(ex.getMessage(), ex);
|
---|
317 | } catch (IOException ex) {
|
---|
318 | throw new RuntimeException(ex.getMessage(), ex);
|
---|
319 | }
|
---|
320 |
|
---|
321 | ImageType type = name.toLowerCase().endsWith(".svg") ? ImageType.SVG : ImageType.OTHER;
|
---|
322 |
|
---|
323 | if (name.startsWith("http://")) {
|
---|
324 | String url = name;
|
---|
325 | ImageResource ir = cache.get(url);
|
---|
326 | if (ir != null) return ir;
|
---|
327 | ir = getIfAvailableHttp(url, type);
|
---|
328 | if (ir != null) {
|
---|
329 | cache.put(url, ir);
|
---|
330 | }
|
---|
331 | return ir;
|
---|
332 | } else if (name.startsWith("wiki://")) {
|
---|
333 | ImageResource ir = cache.get(name);
|
---|
334 | if (ir != null) return ir;
|
---|
335 | ir = getIfAvailableWiki(name, type);
|
---|
336 | if (ir != null) {
|
---|
337 | cache.put(name, ir);
|
---|
338 | }
|
---|
339 | return ir;
|
---|
340 | }
|
---|
341 |
|
---|
342 | if (subdir == null) {
|
---|
343 | subdir = "";
|
---|
344 | } else if (!subdir.equals("")) {
|
---|
345 | subdir += "/";
|
---|
346 | }
|
---|
347 | String[] extensions;
|
---|
348 | if (name.indexOf('.') != -1) {
|
---|
349 | extensions = new String[] { "" };
|
---|
350 | } else {
|
---|
351 | extensions = new String[] { ".png", ".svg"};
|
---|
352 | }
|
---|
353 | final int ARCHIVE = 0, LOCAL = 1;
|
---|
354 | for (int place : new Integer[] { ARCHIVE, LOCAL }) {
|
---|
355 | for (String ext : extensions) {
|
---|
356 |
|
---|
357 | if (".svg".equals(ext)) {
|
---|
358 | type = ImageType.SVG;
|
---|
359 | } else if (".png".equals(ext)) {
|
---|
360 | type = ImageType.OTHER;
|
---|
361 | }
|
---|
362 |
|
---|
363 | String full_name = subdir + name + ext;
|
---|
364 | String cache_name = full_name;
|
---|
365 | /* cache separately */
|
---|
366 | if (dirs != null && dirs.size() > 0) {
|
---|
367 | cache_name = "id:" + id + ":" + full_name;
|
---|
368 | if(archive != null) {
|
---|
369 | cache_name += ":" + archive.getName();
|
---|
370 | }
|
---|
371 | }
|
---|
372 |
|
---|
373 | ImageResource ir = cache.get(cache_name);
|
---|
374 | if (ir != null) return ir;
|
---|
375 |
|
---|
376 | switch (place) {
|
---|
377 | case ARCHIVE:
|
---|
378 | if (archive != null) {
|
---|
379 | ir = getIfAvailableZip(full_name, archive, type);
|
---|
380 | if (ir != null) {
|
---|
381 | cache.put(cache_name, ir);
|
---|
382 | return ir;
|
---|
383 | }
|
---|
384 | }
|
---|
385 | break;
|
---|
386 | case LOCAL:
|
---|
387 | // getImageUrl() does a ton of "stat()" calls and gets expensive
|
---|
388 | // and redundant when you have a whole ton of objects. So,
|
---|
389 | // index the cache by the name of the icon we're looking for
|
---|
390 | // and don't bother to create a URL unless we're actually
|
---|
391 | // creating the image.
|
---|
392 | URL path = getImageUrl(full_name, dirs, additionalClassLoaders);
|
---|
393 | if (path == null) {
|
---|
394 | continue;
|
---|
395 | }
|
---|
396 | ir = getIfAvailableLocalURL(path, type);
|
---|
397 | if (ir != null) {
|
---|
398 | cache.put(cache_name, ir);
|
---|
399 | return ir;
|
---|
400 | }
|
---|
401 | break;
|
---|
402 | }
|
---|
403 | }
|
---|
404 | }
|
---|
405 | return null;
|
---|
406 | }
|
---|
407 |
|
---|
408 | private static ImageResource getIfAvailableHttp(String url, ImageType type) {
|
---|
409 | try {
|
---|
410 | MirroredInputStream is = new MirroredInputStream(url,
|
---|
411 | new File(Main.pref.getCacheDirectory(), "images").getPath());
|
---|
412 | switch (type) {
|
---|
413 | case SVG:
|
---|
414 | URI uri = getSvgUniverse().loadSVG(is, is.getFile().toURI().toURL().toString());
|
---|
415 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
416 | return svg == null ? null : new ImageResource(svg);
|
---|
417 | case OTHER:
|
---|
418 | BufferedImage img = null;
|
---|
419 | try {
|
---|
420 | img = ImageIO.read(is.getFile().toURI().toURL());
|
---|
421 | } catch (IOException e) {}
|
---|
422 | return img == null ? null : new ImageResource(img);
|
---|
423 | default:
|
---|
424 | throw new AssertionError();
|
---|
425 | }
|
---|
426 | } catch (IOException e) {
|
---|
427 | return null;
|
---|
428 | }
|
---|
429 | }
|
---|
430 |
|
---|
431 | private static ImageResource getIfAvailableWiki(String name, ImageType type) {
|
---|
432 | final Collection<String> defaultBaseUrls = Arrays.asList(
|
---|
433 | "http://wiki.openstreetmap.org/w/images/",
|
---|
434 | "http://upload.wikimedia.org/wikipedia/commons/",
|
---|
435 | "http://wiki.openstreetmap.org/wiki/File:"
|
---|
436 | );
|
---|
437 | final Collection<String> baseUrls = Main.pref.getCollection("image-provider.wiki.urls", defaultBaseUrls);
|
---|
438 |
|
---|
439 | final String fn = name.substring(name.lastIndexOf('/') + 1);
|
---|
440 |
|
---|
441 | ImageResource result = null;
|
---|
442 | for (String b : baseUrls) {
|
---|
443 | String url;
|
---|
444 | if (b.endsWith(":")) {
|
---|
445 | url = getImgUrlFromWikiInfoPage(b, fn);
|
---|
446 | if (url == null) {
|
---|
447 | continue;
|
---|
448 | }
|
---|
449 | } else {
|
---|
450 | final String fn_md5 = Utils.md5Hex(fn);
|
---|
451 | url = b + fn_md5.substring(0,1) + "/" + fn_md5.substring(0,2) + "/" + fn;
|
---|
452 | }
|
---|
453 | result = getIfAvailableHttp(url, type);
|
---|
454 | if (result != null) {
|
---|
455 | break;
|
---|
456 | }
|
---|
457 | }
|
---|
458 | return result;
|
---|
459 | }
|
---|
460 |
|
---|
461 | private static ImageResource getIfAvailableZip(String full_name, File archive, ImageType type) {
|
---|
462 | ZipFile zipFile = null;
|
---|
463 | try
|
---|
464 | {
|
---|
465 | zipFile = new ZipFile(archive);
|
---|
466 | ZipEntry entry = zipFile.getEntry(full_name);
|
---|
467 | if(entry != null)
|
---|
468 | {
|
---|
469 | int size = (int)entry.getSize();
|
---|
470 | int offs = 0;
|
---|
471 | byte[] buf = new byte[size];
|
---|
472 | InputStream is = null;
|
---|
473 | try {
|
---|
474 | is = zipFile.getInputStream(entry);
|
---|
475 | switch (type) {
|
---|
476 | case SVG:
|
---|
477 | URI uri = getSvgUniverse().loadSVG(is, full_name);
|
---|
478 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
479 | return svg == null ? null : new ImageResource(svg);
|
---|
480 | case OTHER:
|
---|
481 | while(size > 0)
|
---|
482 | {
|
---|
483 | int l = is.read(buf, offs, size);
|
---|
484 | offs += l;
|
---|
485 | size -= l;
|
---|
486 | }
|
---|
487 | BufferedImage img = null;
|
---|
488 | try {
|
---|
489 | img = ImageIO.read(new ByteArrayInputStream(buf));
|
---|
490 | } catch (IOException e) {}
|
---|
491 | return img == null ? null : new ImageResource(img);
|
---|
492 | default:
|
---|
493 | throw new AssertionError();
|
---|
494 | }
|
---|
495 | } finally {
|
---|
496 | if (is != null) {
|
---|
497 | is.close();
|
---|
498 | }
|
---|
499 | }
|
---|
500 | }
|
---|
501 | } catch (Exception e) {
|
---|
502 | System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
|
---|
503 | } finally {
|
---|
504 | if (zipFile != null) {
|
---|
505 | try {
|
---|
506 | zipFile.close();
|
---|
507 | } catch (IOException ex) {
|
---|
508 | }
|
---|
509 | }
|
---|
510 | }
|
---|
511 | return null;
|
---|
512 | }
|
---|
513 |
|
---|
514 | private static ImageResource getIfAvailableLocalURL(URL path, ImageType type) {
|
---|
515 | switch (type) {
|
---|
516 | case SVG:
|
---|
517 | URI uri = getSvgUniverse().loadSVG(path);
|
---|
518 | SVGDiagram svg = getSvgUniverse().getDiagram(uri);
|
---|
519 | return svg == null ? null : new ImageResource(svg);
|
---|
520 | case OTHER:
|
---|
521 | BufferedImage img = null;
|
---|
522 | try {
|
---|
523 | img = ImageIO.read(path);
|
---|
524 | } catch (IOException e) {}
|
---|
525 | return img == null ? null : new ImageResource(img);
|
---|
526 | default:
|
---|
527 | throw new AssertionError();
|
---|
528 | }
|
---|
529 | }
|
---|
530 |
|
---|
531 | private static URL getImageUrl(String path, String name, Collection<ClassLoader> additionalClassLoaders) {
|
---|
532 | if (path != null && path.startsWith("resource://")) {
|
---|
533 | String p = path.substring("resource://".length());
|
---|
534 | Collection<ClassLoader> classLoaders = new ArrayList<ClassLoader>(PluginHandler.getResourceClassLoaders());
|
---|
535 | if (additionalClassLoaders != null) {
|
---|
536 | classLoaders.addAll(additionalClassLoaders);
|
---|
537 | }
|
---|
538 | for (ClassLoader source : classLoaders) {
|
---|
539 | URL res;
|
---|
540 | if ((res = source.getResource(p + name)) != null)
|
---|
541 | return res;
|
---|
542 | }
|
---|
543 | } else {
|
---|
544 | try {
|
---|
545 | File f = new File(path, name);
|
---|
546 | if (f.exists())
|
---|
547 | return f.toURI().toURL();
|
---|
548 | } catch (MalformedURLException e) {
|
---|
549 | }
|
---|
550 | }
|
---|
551 | return null;
|
---|
552 | }
|
---|
553 |
|
---|
554 | private static URL getImageUrl(String imageName, Collection<String> dirs, Collection<ClassLoader> additionalClassLoaders) {
|
---|
555 | URL u = null;
|
---|
556 |
|
---|
557 | // Try passed directories first
|
---|
558 | if (dirs != null) {
|
---|
559 | for (String name : dirs) {
|
---|
560 | try {
|
---|
561 | u = getImageUrl(name, imageName, additionalClassLoaders);
|
---|
562 | if (u != null)
|
---|
563 | return u;
|
---|
564 | } catch (SecurityException e) {
|
---|
565 | System.out.println(tr(
|
---|
566 | "Warning: failed to access directory ''{0}'' for security reasons. Exception was: {1}",
|
---|
567 | name, e.toString()));
|
---|
568 | }
|
---|
569 |
|
---|
570 | }
|
---|
571 | }
|
---|
572 | // Try user-preference directory
|
---|
573 | String dir = Main.pref.getPreferencesDir() + "images";
|
---|
574 | try {
|
---|
575 | u = getImageUrl(dir, imageName, additionalClassLoaders);
|
---|
576 | if (u != null)
|
---|
577 | return u;
|
---|
578 | } catch (SecurityException e) {
|
---|
579 | System.out.println(tr(
|
---|
580 | "Warning: failed to access directory ''{0}'' for security reasons. Exception was: {1}", dir, e
|
---|
581 | .toString()));
|
---|
582 | }
|
---|
583 |
|
---|
584 | // Absolute path?
|
---|
585 | u = getImageUrl(null, imageName, additionalClassLoaders);
|
---|
586 | if (u != null)
|
---|
587 | return u;
|
---|
588 |
|
---|
589 | // Try plugins and josm classloader
|
---|
590 | u = getImageUrl("resource://images/", imageName, additionalClassLoaders);
|
---|
591 | if (u != null)
|
---|
592 | return u;
|
---|
593 |
|
---|
594 | // Try all other resource directories
|
---|
595 | for (String location : Main.pref.getAllPossiblePreferenceDirs()) {
|
---|
596 | u = getImageUrl(location + "images", imageName, additionalClassLoaders);
|
---|
597 | if (u != null)
|
---|
598 | return u;
|
---|
599 | u = getImageUrl(location, imageName, additionalClassLoaders);
|
---|
600 | if (u != null)
|
---|
601 | return u;
|
---|
602 | }
|
---|
603 |
|
---|
604 | return null;
|
---|
605 | }
|
---|
606 |
|
---|
607 | /**
|
---|
608 | * Reads the wiki page on a certain file in html format in order to find the real image URL.
|
---|
609 | */
|
---|
610 | private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {
|
---|
611 |
|
---|
612 | /** Quit parsing, when a certain condition is met */
|
---|
613 | class SAXReturnException extends SAXException {
|
---|
614 | private String result;
|
---|
615 |
|
---|
616 | public SAXReturnException(String result) {
|
---|
617 | this.result = result;
|
---|
618 | }
|
---|
619 |
|
---|
620 | public String getResult() {
|
---|
621 | return result;
|
---|
622 | }
|
---|
623 | }
|
---|
624 |
|
---|
625 | try {
|
---|
626 | final XMLReader parser = XMLReaderFactory.createXMLReader();
|
---|
627 | parser.setContentHandler(new DefaultHandler() {
|
---|
628 | @Override
|
---|
629 | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
|
---|
630 | System.out.println();
|
---|
631 | if (localName.equalsIgnoreCase("img")) {
|
---|
632 | String val = atts.getValue("src");
|
---|
633 | if (val.endsWith(fn))
|
---|
634 | throw new SAXReturnException(val); // parsing done, quit early
|
---|
635 | }
|
---|
636 | }
|
---|
637 | });
|
---|
638 |
|
---|
639 | parser.setEntityResolver(new EntityResolver() {
|
---|
640 | public InputSource resolveEntity (String publicId, String systemId) {
|
---|
641 | return new InputSource(new ByteArrayInputStream(new byte[0]));
|
---|
642 | }
|
---|
643 | });
|
---|
644 |
|
---|
645 | parser.parse(new InputSource(new MirroredInputStream(
|
---|
646 | base + fn,
|
---|
647 | new File(Main.pref.getPreferencesDir(), "images").toString()
|
---|
648 | )));
|
---|
649 | } catch (SAXReturnException r) {
|
---|
650 | return r.getResult();
|
---|
651 | } catch (Exception e) {
|
---|
652 | System.out.println("INFO: parsing " + base + fn + " failed:\n" + e);
|
---|
653 | return null;
|
---|
654 | }
|
---|
655 | System.out.println("INFO: parsing " + base + fn + " failed: Unexpected content.");
|
---|
656 | return null;
|
---|
657 | }
|
---|
658 |
|
---|
659 | public static Cursor getCursor(String name, String overlay) {
|
---|
660 | ImageIcon img = get("cursor", name);
|
---|
661 | if (overlay != null) {
|
---|
662 | img = overlay(img, "cursor/modifier/" + overlay, OverlayPosition.SOUTHEAST);
|
---|
663 | }
|
---|
664 | Cursor c = Toolkit.getDefaultToolkit().createCustomCursor(img.getImage(),
|
---|
665 | name.equals("crosshair") ? new Point(10, 10) : new Point(3, 2), "Cursor");
|
---|
666 | return c;
|
---|
667 | }
|
---|
668 |
|
---|
669 | /**
|
---|
670 | * @return an icon that represent the overlay of the two given icons. The second icon is layed
|
---|
671 | * on the first relative to the given position.
|
---|
672 | */
|
---|
673 | public static ImageIcon overlay(Icon ground, String overlayImage, OverlayPosition pos) {
|
---|
674 | return overlay(ground, ImageProvider.get(overlayImage), pos);
|
---|
675 | }
|
---|
676 |
|
---|
677 | public static ImageIcon overlay(Icon ground, Icon overlay, OverlayPosition pos) {
|
---|
678 | GraphicsConfiguration conf = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
|
---|
679 | .getDefaultConfiguration();
|
---|
680 | int w = ground.getIconWidth();
|
---|
681 | int h = ground.getIconHeight();
|
---|
682 | int wo = overlay.getIconWidth();
|
---|
683 | int ho = overlay.getIconHeight();
|
---|
684 | BufferedImage img = conf.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
|
---|
685 | Graphics g = img.createGraphics();
|
---|
686 | ground.paintIcon(null, g, 0, 0);
|
---|
687 | int x = 0, y = 0;
|
---|
688 | switch (pos) {
|
---|
689 | case NORTHWEST:
|
---|
690 | x = 0;
|
---|
691 | y = 0;
|
---|
692 | break;
|
---|
693 | case NORTHEAST:
|
---|
694 | x = w - wo;
|
---|
695 | y = 0;
|
---|
696 | break;
|
---|
697 | case SOUTHWEST:
|
---|
698 | x = 0;
|
---|
699 | y = h - ho;
|
---|
700 | break;
|
---|
701 | case SOUTHEAST:
|
---|
702 | x = w - wo;
|
---|
703 | y = h - ho;
|
---|
704 | break;
|
---|
705 | }
|
---|
706 | overlay.paintIcon(null, g, x, y);
|
---|
707 | return new ImageIcon(img);
|
---|
708 | }
|
---|
709 |
|
---|
710 | /*
|
---|
711 | * from: http://www.jidesoft.com/blog/2008/02/29/rotate-an-icon-in-java/ License:
|
---|
712 | * "feel free to use"
|
---|
713 | */
|
---|
714 | final static double DEGREE_90 = 90.0 * Math.PI / 180.0;
|
---|
715 |
|
---|
716 | /**
|
---|
717 | * Creates a rotated version of the input image.
|
---|
718 | *
|
---|
719 | * @param c The component to get properties useful for painting, e.g. the foreground or
|
---|
720 | * background color.
|
---|
721 | * @param icon the image to be rotated.
|
---|
722 | * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we
|
---|
723 | * will mod it with 360 before using it.
|
---|
724 | *
|
---|
725 | * @return the image after rotating.
|
---|
726 | */
|
---|
727 | public static Image createRotatedImage(Component c, Image img, double rotatedAngle) {
|
---|
728 | // convert rotatedAngle to a value from 0 to 360
|
---|
729 | double originalAngle = rotatedAngle % 360;
|
---|
730 | if (rotatedAngle != 0 && originalAngle == 0) {
|
---|
731 | originalAngle = 360.0;
|
---|
732 | }
|
---|
733 |
|
---|
734 | // convert originalAngle to a value from 0 to 90
|
---|
735 | double angle = originalAngle % 90;
|
---|
736 | if (originalAngle != 0.0 && angle == 0.0) {
|
---|
737 | angle = 90.0;
|
---|
738 | }
|
---|
739 |
|
---|
740 | double radian = Math.toRadians(angle);
|
---|
741 |
|
---|
742 | new ImageIcon(img); // load completely
|
---|
743 | int iw = img.getWidth(null);
|
---|
744 | int ih = img.getHeight(null);
|
---|
745 | int w;
|
---|
746 | int h;
|
---|
747 |
|
---|
748 | if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
|
---|
749 | w = (int) (iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian));
|
---|
750 | h = (int) (iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian));
|
---|
751 | } else {
|
---|
752 | w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
|
---|
753 | h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
|
---|
754 | }
|
---|
755 | BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
|
---|
756 | Graphics g = image.getGraphics();
|
---|
757 | Graphics2D g2d = (Graphics2D) g.create();
|
---|
758 |
|
---|
759 | // calculate the center of the icon.
|
---|
760 | int cx = iw / 2;
|
---|
761 | int cy = ih / 2;
|
---|
762 |
|
---|
763 | // move the graphics center point to the center of the icon.
|
---|
764 | g2d.translate(w / 2, h / 2);
|
---|
765 |
|
---|
766 | // rotate the graphics about the center point of the icon
|
---|
767 | g2d.rotate(Math.toRadians(originalAngle));
|
---|
768 |
|
---|
769 | g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
---|
770 | g2d.drawImage(img, -cx, -cy, c);
|
---|
771 |
|
---|
772 | g2d.dispose();
|
---|
773 | new ImageIcon(image); // load completely
|
---|
774 | return image;
|
---|
775 | }
|
---|
776 |
|
---|
777 | /**
|
---|
778 | * Replies the icon for an OSM primitive type
|
---|
779 | * @param type the type
|
---|
780 | * @return the icon
|
---|
781 | */
|
---|
782 | public static ImageIcon get(OsmPrimitiveType type) throws IllegalArgumentException {
|
---|
783 | CheckParameterUtil.ensureParameterNotNull(type, "type");
|
---|
784 | return get("data", type.getAPIName());
|
---|
785 | }
|
---|
786 |
|
---|
787 | public static BufferedImage createImageFromSvg(SVGDiagram svg, Dimension dim) {
|
---|
788 | float realWidth = svg.getWidth();
|
---|
789 | float realHeight = svg.getHeight();
|
---|
790 | int width = Math.round(realWidth);
|
---|
791 | int height = Math.round(realHeight);
|
---|
792 | Double scaleX = null, scaleY = null;
|
---|
793 | if (dim.width != -1) {
|
---|
794 | width = dim.width;
|
---|
795 | scaleX = (double) width / realWidth;
|
---|
796 | if (dim.height == -1) {
|
---|
797 | scaleY = scaleX;
|
---|
798 | height = (int) Math.round(realHeight * scaleY);
|
---|
799 | } else {
|
---|
800 | height = dim.height;
|
---|
801 | scaleY = (double) height / realHeight;
|
---|
802 | }
|
---|
803 | } else if (dim.height != -1) {
|
---|
804 | height = dim.height;
|
---|
805 | scaleX = scaleY = (double) height / realHeight;
|
---|
806 | width = (int) Math.round(realWidth * scaleX);
|
---|
807 | }
|
---|
808 | BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
|
---|
809 | Graphics2D g = img.createGraphics();
|
---|
810 | g.setClip(0, 0, width, height);
|
---|
811 | if (scaleX != null) {
|
---|
812 | g.scale(scaleX, scaleY);
|
---|
813 | }
|
---|
814 | g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
---|
815 | try {
|
---|
816 | svg.render(g);
|
---|
817 | } catch (SVGException ex) {
|
---|
818 | return null;
|
---|
819 | }
|
---|
820 | return img;
|
---|
821 | }
|
---|
822 |
|
---|
823 | private static SVGUniverse getSvgUniverse() {
|
---|
824 | if (svgUniverse == null) {
|
---|
825 | svgUniverse = new SVGUniverse();
|
---|
826 | }
|
---|
827 | return svgUniverse;
|
---|
828 | }
|
---|
829 | }
|
---|