]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms.ui/src/org/argeo/cms/ui/util/AbstractCmsTheme.java
Improve CMS web app lifecycle.
[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, ImageData> 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 imageCache.put(path, imageData);
28 } catch (IOException e) {
29 throw new IllegalStateException(e);
30 }
31 }
32 ImageData imageData = imageCache.get(path);
33 Image image = new Image(Display.getCurrent(), imageData);
34 return image;
35 }
36
37 @Override
38 public Image getIcon(String name, Integer preferredSize) {
39 if (preferredSize == null)
40 preferredSize = defaultIconSize;
41 Map<Integer, String> subCache;
42 if (!iconPaths.containsKey(name))
43 subCache = new HashMap<>();
44 else
45 subCache = iconPaths.get(name);
46 Image image = null;
47 if (!subCache.containsKey(preferredSize)) {
48 Image bestMatchSoFar = null;
49 paths: for (String p : getImagesPaths()) {
50 int lastSlash = p.lastIndexOf('/');
51 String fileName = p;
52 if (lastSlash >= 0)
53 fileName = p.substring(lastSlash + 1);
54 int lastDot = fileName.lastIndexOf('.');
55 if (lastDot >= 0)
56 fileName = fileName.substring(0, lastDot);
57 if (fileName.equals(name)) {// matched
58 Image img = getImage(p);
59 int width = img.getBounds().width;
60 if (width == preferredSize) {// perfect match
61 subCache.put(preferredSize, p);
62 image = img;
63 break paths;
64 }
65 if (bestMatchSoFar == null) {
66 bestMatchSoFar = img;
67 } else {
68 if (Math.abs(width - preferredSize) < Math
69 .abs(bestMatchSoFar.getBounds().width - preferredSize))
70 bestMatchSoFar = img;
71 }
72 }
73 }
74
75 if (image == null)
76 image = bestMatchSoFar;
77 } else {
78 image = getImage(subCache.get(preferredSize));
79 }
80
81 if (image != null && !iconPaths.containsKey(name))
82 iconPaths.put(name, subCache);
83
84 return image;
85 }
86
87 @Override
88 public Integer getDefaultIconSize() {
89 return defaultIconSize;
90 }
91
92 }