Debian Codegraph @

src/com/bulenkov/iconloader/IconLoader.java

raw symbols SCIP
1 /*
2 * Copyright 2000-2014 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.bulenkov.iconloader;
18
19 import com.bulenkov.iconloader.util.*;
20 import org.jetbrains.annotations.NonNls;
21 import org.jetbrains.annotations.NotNull;
22 import org.jetbrains.annotations.Nullable;
23
24 import javax.swing.*;
25 import java.awt.*;
26 import java.awt.image.BufferedImage;
27 import java.awt.image.ImageFilter;
28 import java.lang.ref.Reference;
29 import java.lang.reflect.Field;
30 import java.net.URL;
31 import java.util.*;
32 import java.util.List;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.concurrent.ConcurrentMap;
35 import java.util.concurrent.atomic.AtomicBoolean;
36
37 /**
38 * @author Konstantin Bulenkov
39 */
40 @SuppressWarnings("UnusedDeclaration")
41 public final class IconLoader {
42 public static boolean STRICT = false;
43 private static boolean USE_DARK_ICONS = UIUtil.isUnderDarcula();
44
45 @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
46 private static final ConcurrentMap<URL, CachedImageIcon> ourIconsCache = new ConcurrentHashMap<URL, CachedImageIcon>(100, 0.9f, 2);
47
48 /**
49 * This cache contains mapping between icons and disabled icons.
50 */
51 private static final Map<Icon, Icon> ourIcon2DisabledIcon = new WeakHashMap<Icon, Icon>(200);
52
53 private static float SCALE = JBUI.scale(1f);
54 private static ImageFilter IMAGE_FILTER;
55
56 private static final ImageIcon EMPTY_ICON = new ImageIcon(UIUtil.createImage(1, 1, BufferedImage.TYPE_3BYTE_BGR)) {
57 @NonNls
58 public String toString() {
59 return "Empty icon " + super.toString();
60 }
61 };
62
63 private static AtomicBoolean ourIsActivated = new AtomicBoolean(true);
64 private static AtomicBoolean ourIsSaveRealIconPath = new AtomicBoolean(false);
65 public static final Component ourComponent = new Component() {};
66
67 private IconLoader() { }
68
69 @Deprecated
70 public static Icon getIcon(@NotNull final Image image) {
71 return new JBImageIcon(image);
72 }
73
74 public static void setUseDarkIcons(boolean useDarkIcons) {
75 USE_DARK_ICONS = useDarkIcons;
76 clearCache();
77 }
78
79 public static void setScale(float scale) {
80 if (scale != SCALE) {
81 SCALE = scale;
82 clearCache();
83 }
84 }
85
86 public static void setFilter(ImageFilter filter) {
87 if (!Registry.is("color.blindness.icon.filter")) {
88 filter = null;
89 }
90 if (IMAGE_FILTER != filter) {
91 IMAGE_FILTER = filter;
92 clearCache();
93 }
94 }
95
96 private static void clearCache() {
97 ourIconsCache.clear();
98 ourIcon2DisabledIcon.clear();
99 }
100
101 //TODO[kb] support iconsets
102 //public static Icon getIcon(@NotNull final String path, @NotNull final String darkVariantPath) {
103 // return new InvariantIcon(getIcon(path), getIcon(darkVariantPath));
104 //}
105
106 @NotNull
107 public static Icon getIcon(@NonNls @NotNull final String path) {
108 Class callerClass = ReflectionUtil.getGrandCallerClass();
109
110 assert callerClass != null : path;
111 return getIcon(path, callerClass);
112 }
113
114 @Nullable
115 private static Icon getReflectiveIcon(@NotNull String path, ClassLoader classLoader) {
116 try {
117 @NonNls String pckg = path.startsWith("AllIcons.") ? "com.intellij.icons." : "icons.";
118 Class cur = Class.forName(pckg + path.substring(0, path.lastIndexOf('.')).replace('.', '$'), true, classLoader);
119 Field field = cur.getField(path.substring(path.lastIndexOf('.') + 1));
120
121 return (Icon)field.get(null);
122 }
123 catch (Exception e) {
124 return null;
125 }
126 }
127
128 /**
129 * Might return null if icon was not found.
130 * Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String)}
131 */
132 @Nullable
133 public static Icon findIcon(@NonNls @NotNull String path) {
134 Class callerClass = ReflectionUtil.getGrandCallerClass();
135 if (callerClass == null) return null;
136 return findIcon(path, callerClass);
137 }
138
139 @NotNull
140 public static Icon getIcon(@NotNull String path, @NotNull final Class aClass) {
141 final Icon icon = findIcon(path, aClass);
142 if (icon == null) {
143 System.err.println("Icon cannot be found in '" + path + "', aClass='" + aClass + "'");
144 }
145 return icon;
146 }
147
148 public static void activate() {
149 ourIsActivated.set(true);
150 }
151
152 public static void disable() {
153 ourIsActivated.set(false);
154 }
155
156 public static boolean isLoaderDisabled() {
157 return !ourIsActivated.get();
158 }
159
160 /**
161 * This method is for test purposes only
162 */
163 static void enableSaveRealIconPath() {
164 ourIsSaveRealIconPath.set(true);
165 }
166
167 /**
168 * Might return null if icon was not found.
169 * Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String, Class)}
170 */
171 @Nullable
172 public static Icon findIcon(@NotNull final String path, @NotNull final Class aClass) {
173 return findIcon(path, aClass, false);
174 }
175
176 @Nullable
177 public static Icon findIcon(@NotNull String path, @NotNull final Class aClass, boolean computeNow) {
178 return findIcon(path, aClass, computeNow, STRICT);
179 }
180
181 @Nullable
182 public static Icon findIcon(@NotNull String path, @NotNull final Class aClass, boolean computeNow, boolean strict) {
183 String originalPath = path;
184 path = patchPath(path);
185 if (isReflectivePath(path)) return getReflectiveIcon(path, aClass.getClassLoader());
186
187 URL myURL = aClass.getResource(path);
188 if (myURL == null) {
189 if (strict) throw new RuntimeException("Can't find icon in '" + path + "' near " + aClass);
190 return null;
191 }
192 final Icon icon = findIcon(myURL);
193 if (icon instanceof CachedImageIcon) {
194 ((CachedImageIcon)icon).myOriginalPath = originalPath;
195 ((CachedImageIcon)icon).myClassLoader = aClass.getClassLoader();
196 }
197 return icon;
198 }
199
200 private static String patchPath(@NotNull String path) {
201 // for (IconPathPatcher patcher : ourPatchers) {
202 // String newPath = patcher.patchPath(path);
203 // if (newPath != null) {
204 // path = newPath;
205 // }
206 // }
207 return path;
208 }
209
210 private static boolean isReflectivePath(@NotNull String path) {
211 List<String> paths = StringUtil.split(path, ".");
212 return paths.size() > 1 && paths.get(0).endsWith("Icons");
213 }
214
215 @Nullable
216 public static Icon findIcon(URL url) {
217 return findIcon(url, true);
218 }
219
220 @Nullable
221 public static Icon findIcon(URL url, boolean useCache) {
222 if (url == null) {
223 return null;
224 }
225 CachedImageIcon icon = ourIconsCache.get(url);
226 if (icon == null) {
227 icon = new CachedImageIcon(url);
228 if (useCache) {
229 icon = ConcurrencyUtil.cacheOrGet(ourIconsCache, url, icon);
230 }
231 }
232 return icon;
233 }
234
235 @Nullable
236 public static Icon findIcon(@NotNull String path, @NotNull ClassLoader classLoader) {
237 String originalPath = path;
238 path = patchPath(path);
239 if (isReflectivePath(path)) return getReflectiveIcon(path, classLoader);
240 if (!StringUtil.startsWithChar(path, '/')) return null;
241
242 final URL url = classLoader.getResource(path.substring(1));
243 final Icon icon = findIcon(url);
244 if (icon instanceof CachedImageIcon) {
245 ((CachedImageIcon)icon).myOriginalPath = originalPath;
246 ((CachedImageIcon)icon).myClassLoader = classLoader;
247 }
248 return icon;
249 }
250
251 @Nullable
252 private static ImageIcon checkIcon(final Image image, @NotNull URL url) {
253 if (image == null || image.getHeight(LabelHolder.ourFakeComponent) < 1) { // image wasn't loaded or broken
254 return null;
255 }
256
257 final Icon icon = getIcon(image);
258 if (icon != null && !isGoodSize(icon)) {
259 return EMPTY_ICON;
260 }
261
262 return (ImageIcon)icon;
263 }
264
265 public static boolean isGoodSize(@NotNull final Icon icon) {
266 return icon.getIconWidth() > 0 && icon.getIconHeight() > 0;
267 }
268
269 /**
270 * Gets (creates if necessary) disabled icon based on the passed one.
271 *
272 * @return <code>ImageIcon</code> constructed from disabled image of passed icon.
273 */
274 @Nullable
275 public static Icon getDisabledIcon(Icon icon) {
276 if (icon instanceof LazyIcon) icon = ((LazyIcon)icon).getOrComputeIcon();
277 if (icon == null) return null;
278
279 Icon disabledIcon = ourIcon2DisabledIcon.get(icon);
280 if (disabledIcon == null) {
281 if (!isGoodSize(icon)) {
282 return EMPTY_ICON;
283 }
284 final int scale = UIUtil.isRetina() ? 2 : 1;
285 @SuppressWarnings("UndesirableClassUsage")
286 BufferedImage image = new BufferedImage(scale*icon.getIconWidth(), scale*icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
287 final Graphics2D graphics = image.createGraphics();
288
289 graphics.setColor(UIUtil.TRANSPARENT_COLOR);
290 graphics.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
291 graphics.scale(scale, scale);
292 icon.paintIcon(LabelHolder.ourFakeComponent, graphics, 0, 0);
293
294 graphics.dispose();
295
296 Image img = ImageUtil.filter(image, UIUtil.getGrayFilter());
297 if (UIUtil.isRetina()) img = RetinaImage.createFrom(img);
298
299 disabledIcon = new JBImageIcon(img);
300 ourIcon2DisabledIcon.put(icon, disabledIcon);
301 }
302 return disabledIcon;
303 }
304
305 public static Icon getTransparentIcon(@NotNull final Icon icon) {
306 return getTransparentIcon(icon, 0.5f);
307 }
308
309 public static Icon getTransparentIcon(@NotNull final Icon icon, final float alpha) {
310 return new RetrievableIcon() {
311 @Nullable
312 @Override
313 public Icon retrieveIcon() {
314 return icon;
315 }
316
317 @Override
318 public int getIconHeight() {
319 return icon.getIconHeight();
320 }
321
322 @Override
323 public int getIconWidth() {
324 return icon.getIconWidth();
325 }
326
327 @Override
328 public void paintIcon(final Component c, final Graphics g, final int x, final int y) {
329 final Graphics2D g2 = (Graphics2D)g;
330 final Composite saveComposite = g2.getComposite();
331 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
332 icon.paintIcon(c, g2, x, y);
333 g2.setComposite(saveComposite);
334 }
335 };
336 }
337
338 /**
339 * Gets a snapshot of the icon, immune to changes made by these calls:
340 * {@link IconLoader#setScale(float)}, {@link IconLoader#setFilter(ImageFilter)}, {@link IconLoader#setUseDarkIcons(boolean)}
341 *
342 * @param icon the source icon
343 * @return the icon snapshot
344 */
345 @NotNull
346 public static Icon getIconSnapshot(@NotNull Icon icon) {
347 if (icon instanceof CachedImageIcon) {
348 return ((CachedImageIcon)icon).getRealIcon();
349 }
350 return icon;
351 }
352
353 public static final class CachedImageIcon implements ScalableIcon {
354 private volatile Object myRealIcon;
355 public String myOriginalPath;
356 private ClassLoader myClassLoader;
357 @NotNull
358 private URL myUrl;
359 private volatile boolean dark;
360 private volatile float scale;
361 private volatile int numberOfPatchers = 0;
362
363 private volatile ImageFilter filter;
364 private final MyScaledIconsCache myScaledIconsCache = new MyScaledIconsCache();
365
366 public CachedImageIcon(@NotNull URL url) {
367 myUrl = url;
368 dark = USE_DARK_ICONS;
369 scale = SCALE;
370 filter = IMAGE_FILTER;
371 }
372
373 @NotNull
374 private synchronized ImageIcon getRealIcon() {
375 if (isLoaderDisabled() && (myRealIcon == null || dark != USE_DARK_ICONS || scale != SCALE || filter != IMAGE_FILTER)) return EMPTY_ICON;
376
377 if (!isValid()) {
378 myRealIcon = null;
379 dark = USE_DARK_ICONS;
380 scale = SCALE;
381 filter = IMAGE_FILTER;
382 myScaledIconsCache.clear();
383 }
384 Object realIcon = myRealIcon;
385 if (realIcon instanceof Icon) return (ImageIcon)realIcon;
386
387 ImageIcon icon;
388 if (realIcon instanceof Reference) {
389 icon = ((Reference<ImageIcon>)realIcon).get();
390 if (icon != null) return (ImageIcon)icon;
391 }
392
393 Image image = ImageLoader.loadFromUrl(myUrl, true, filter);
394 icon = checkIcon(image, myUrl);
395
396 if (icon != null) {
397 if (icon.getIconWidth() < 50 && icon.getIconHeight() < 50) {
398 realIcon = icon;
399 }
400 else {
401 realIcon = new SoftReference<ImageIcon>(icon);
402 }
403 myRealIcon = realIcon;
404 }
405
406 return icon == null ? EMPTY_ICON : icon;
407 }
408
409 private boolean isValid() {
410 return dark == USE_DARK_ICONS && scale == SCALE && filter == IMAGE_FILTER;
411 }
412
413 @Override
414 public void paintIcon(Component c, Graphics g, int x, int y) {
415 getRealIcon().paintIcon(c, g, x, y);
416 }
417
418 @Override
419 public int getIconWidth() {
420 return getRealIcon().getIconWidth();
421 }
422
423 @Override
424 public int getIconHeight() {
425 return getRealIcon().getIconHeight();
426 }
427
428 @Override
429 public String toString() {
430 return myUrl.toString();
431 }
432
433 @Override
434 public Icon scale(float scaleFactor) {
435 if (scaleFactor == 1f) {
436 return this;
437 }
438
439 if (!isValid()) getRealIcon(); // force state update & cache reset
440
441 Icon icon = myScaledIconsCache.getScaledIcon(scaleFactor);
442 if (icon != null) {
443 return icon;
444 }
445 return this;
446 }
447
448 private class MyScaledIconsCache {
449 // Map {false -> image}, {true -> image@2x}
450 private Map<Boolean, SoftReference<Image>> origImagesCache = Collections.synchronizedMap(new HashMap<Boolean, SoftReference<Image>>(2));
451
452 private static final int SCALED_ICONS_CACHE_LIMIT = 5;
453
454 // Map {effective scale -> icon}
455 private Map<Float, SoftReference<Icon>> scaledIconsCache = Collections.synchronizedMap(new LinkedHashMap<Float, SoftReference<Icon>>(SCALED_ICONS_CACHE_LIMIT) {
456 @Override
457 public boolean removeEldestEntry(Map.Entry<Float, SoftReference<Icon>> entry) {
458 return size() > SCALED_ICONS_CACHE_LIMIT;
459 }
460 });
461
462 public Image getOrigImage(boolean retina) {
463 Image img = SoftReference.dereference(origImagesCache.get(retina));
464
465 if (img == null) {
466 img = ImageLoader.loadFromUrl(myUrl, UIUtil.isUnderDarcula(), retina, filter);
467 origImagesCache.put(retina, new SoftReference<Image>(img));
468 }
469 return img;
470 }
471
472 public Icon getScaledIcon(float scale) {
473 float effectiveScale = scale * JBUI.scale(1f);
474 Icon icon = SoftReference.dereference(scaledIconsCache.get(effectiveScale));
475
476 if (icon == null) {
477 boolean needRetinaImage = (effectiveScale >= 1.5f || UIUtil.isRetina());
478 Image image = getOrigImage(needRetinaImage);
479
480 if (image != null) {
481 Image iconImage = getRealIcon().getImage();
482 int width = (int)(ImageUtil.getRealWidth(iconImage) * scale);
483 int height = (int)(ImageUtil.getRealHeight(iconImage) * scale);
484
485 Image resizedImage = Scalr.resize(ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, width, height);
486 if (UIUtil.isRetina()) resizedImage = RetinaImage.createFrom(resizedImage);
487
488 icon = getIcon(resizedImage);
489 scaledIconsCache.put(effectiveScale, new SoftReference<Icon>(icon));
490 }
491 }
492 return icon;
493 }
494
495 public void clear() {
496 scaledIconsCache.clear();
497 origImagesCache.clear();
498 }
499 }
500 }
501
502 public abstract static class LazyIcon implements Icon {
503 private boolean myWasComputed;
504 private Icon myIcon;
505 private boolean isDarkVariant = USE_DARK_ICONS;
506 private float scale = SCALE;
507 // private int numberOfPatchers = 0;
508 private ImageFilter filter = IMAGE_FILTER;
509
510 @Override
511 public void paintIcon(Component c, Graphics g, int x, int y) {
512 final Icon icon = getOrComputeIcon();
513 if (icon != null) {
514 icon.paintIcon(c, g, x, y);
515 }
516 }
517
518 @Override
519 public int getIconWidth() {
520 final Icon icon = getOrComputeIcon();
521 return icon != null ? icon.getIconWidth() : 0;
522 }
523
524 @Override
525 public int getIconHeight() {
526 final Icon icon = getOrComputeIcon();
527 return icon != null ? icon.getIconHeight() : 0;
528 }
529
530 protected final synchronized Icon getOrComputeIcon() {
531 if (!myWasComputed || isDarkVariant != USE_DARK_ICONS || scale != SCALE || filter != IMAGE_FILTER /*|| numberOfPatchers != ourPatchers.size()*/) {
532 isDarkVariant = USE_DARK_ICONS;
533 scale = SCALE;
534 filter = IMAGE_FILTER;
535 myWasComputed = true;
536 // numberOfPatchers = ourPatchers.size();
537 myIcon = compute();
538 }
539
540 return myIcon;
541 }
542
543 public final void load() {
544 getIconWidth();
545 }
546
547 protected abstract Icon compute();
548 }
549
550 private static class LabelHolder {
551 /**
552 * To get disabled icon with paint it into the image. Some icons require
553 * not null component to paint.
554 */
555 private static final JComponent ourFakeComponent = new JLabel();
556 }
557 }