]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms.ui/src/org/argeo/cms/ui/util/AbstractCmsTheme.java
Expose servlet context helpers.
[lgpl/argeo-commons.git] / org.argeo.cms.ui / src / org / argeo / cms / ui / util / AbstractCmsTheme.java
1 package org.argeo.cms.ui.util;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import org.argeo.cms.ui.CmsTheme;
9 import org.eclipse.swt.graphics.Image;
10 import org.eclipse.swt.graphics.ImageData;
11 import org.eclipse.swt.widgets.Display;
12
13 /** Centralises some generic {@link CmsTheme} patterns. */
14 public abstract class AbstractCmsTheme implements CmsTheme {
15 private Map<String, Image> imageCache = new HashMap<>();
16
17 private Map<String, Map<Integer, String>> iconPaths = new HashMap<>();
18
19 private Integer defaultIconSize = 16;
20
21 public Image getImage(String path) {
22 if (!imageCache.containsKey(path)) {
23 try (InputStream in = getResourceAsStream(path)) {
24 if (in == null)
25 return null;
26 ImageData imageData = new ImageData(in);
27 Image image = new Image(Display.getDefault(), imageData);
28 imageCache.put(path, image);
29 } catch (IOException e) {
30 throw new IllegalStateException(e);
31 }
32 }
33 return imageCache.get(path);
34 }
35
36 @Override
37 public Image getIcon(String name, Integer preferredSize) {
38 if (preferredSize == null)
39 preferredSize = defaultIconSize;
40 Map<Integer, String> subCache;
41 if (!iconPaths.containsKey(name))
42 subCache = new HashMap<>();
43 else
44 subCache = iconPaths.get(name);
45 Image image = null;
46 if (!subCache.containsKey(preferredSize)) {
47 Image bestMatchSoFar = null;
48 paths: for (String p : getImagesPaths()) {
49 int lastSlash = p.lastIndexOf('/');
50 String fileName = p;
51 if (lastSlash >= 0)
52 fileName = p.substring(lastSlash + 1);
53 int lastDot = fileName.lastIndexOf('.');
54 if (lastDot >= 0)
55 fileName = fileName.substring(0, lastDot);
56 if (fileName.equals(name)) {// matched
57 Image img = getImage(p);
58 int width = img.getBounds().width;
59 if (width == preferredSize) {// perfect match
60 subCache.put(preferredSize, p);
61 image = img;
62 break paths;
63 }
64 if (bestMatchSoFar == null) {
65 bestMatchSoFar = img;
66 } else {
67 if (Math.abs(width - preferredSize) < Math
68 .abs(bestMatchSoFar.getBounds().width - preferredSize))
69 bestMatchSoFar = img;
70 }
71 }
72 }
73
74 if (image == null)
75 image = bestMatchSoFar;
76 } else {
77 image = getImage(subCache.get(preferredSize));
78 }
79
80 if (image != null && !iconPaths.containsKey(name))
81 iconPaths.put(name, subCache);
82
83 return image;
84 }
85
86 @Override
87 public Integer getDefaultIconSize() {
88 return defaultIconSize;
89 }
90
91 }