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