View Javadoc

1   /*
2    * ObjectLab, http://www.objectlab.co.uk/open is supporting JTreeMap.
3    * 
4    * Based in London, we are world leaders in the design and development 
5    * of bespoke applications for the securities financing markets.
6    * 
7    * <a href="http://www.objectlab.co.uk/open">Click here to learn more</a>
8    *           ___  _     _           _   _          _
9    *          / _ \| |__ (_) ___  ___| |_| |    __ _| |__
10   *         | | | | '_ \| |/ _ \/ __| __| |   / _` | '_ \
11   *         | |_| | |_) | |  __/ (__| |_| |__| (_| | |_) |
12   *          \___/|_.__// |\___|\___|\__|_____\__,_|_.__/
13   *                   |__/
14   *
15   *                     www.ObjectLab.co.uk
16   *
17   * $Id: ResourceManager.java 75 2006-10-24 23:00:51Z benoitx $
18   * 
19   * Copyright 2006 the original author or authors.
20   *
21   * Licensed under the Apache License, Version 2.0 (the "License"); you may not
22   * use this file except in compliance with the License. You may obtain a copy of
23   * the License at
24   *
25   * http://www.apache.org/licenses/LICENSE-2.0
26   *
27   * Unless required by applicable law or agreed to in writing, software
28   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
29   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
30   * License for the specific language governing permissions and limitations under
31   * the License.
32   */
33  package net.sf.jtreemap.ktreemap.example;
34  
35  import java.io.File;
36  import java.io.FileInputStream;
37  import java.io.InputStream;
38  import java.lang.reflect.Method;
39  import java.net.MalformedURLException;
40  import java.net.URL;
41  import java.util.HashMap;
42  import java.util.Iterator;
43  import org.eclipse.jface.resource.ImageDescriptor;
44  import org.eclipse.swt.SWT;
45  import org.eclipse.swt.graphics.*;
46  import org.eclipse.swt.widgets.*;
47  
48  /**
49   * Utility class for managing OS resources associated with SWT controls such as
50   * colors, fonts, images, etc. !!! IMPORTANT !!! Application code must
51   * explicitly invoke the <code>dispose()</code> method to release the
52   * operating system resources managed by cached objects when those objects and
53   * OS resources are no longer needed (e.g. on application shutdown) This class
54   * may be freely distributed as part of any application or plugin.
55   * <p>
56   * Copyright (c) 2003, Instantiations, Inc. <br>
57   * All Rights Reserved
58   *
59   * @version $Revision: 75 $
60   * @author scheglov_ke
61   * @author Dan Rubel
62   */
63  public class ResourceManager {
64  
65    // Image support
66    private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>();
67  
68    // Color support
69    private static HashMap<RGB, Color> m_ColorMap = new HashMap<RGB, Color>();
70    private static HashMap<ImageDescriptor, Image> m_DescriptorImageMap = new HashMap<ImageDescriptor, Image>();
71  
72    // Font support
73    private static HashMap<String, Font> m_FontMap = new HashMap<String, Font>();
74    private static HashMap<Font, Font> m_FontToBoldFontMap = new HashMap<Font, Font>();
75    private static HashMap<Font, Font> m_FontToItalicFontMap = new HashMap<Font, Font>();
76  
77    // Cursor support
78    private static HashMap<Integer, Cursor> m_IdToCursorMap = new HashMap<Integer, Cursor>();
79    private static HashMap<Image, HashMap<Image, Image>> m_ImageToDecoratorMap = new HashMap<Image, HashMap<Image, Image>>();
80  
81    // Plugin images support
82    private static HashMap<URL, Image> m_URLImageMap = new HashMap<URL, Image>();
83  
84    /**
85     * @param baseImage
86     * @param decorator
87     * @return the decorating image
88     */
89    public static Image decorateImage(Image baseImage, Image decorator) {
90      HashMap<Image, Image> decoratedMap = m_ImageToDecoratorMap.get(baseImage);
91      if (decoratedMap == null) {
92        decoratedMap = new HashMap<Image, Image>();
93        m_ImageToDecoratorMap.put(baseImage, decoratedMap);
94      }
95      Image result = decoratedMap.get(decorator);
96      if (result == null) {
97        ImageData bid = baseImage.getImageData();
98        ImageData did = decorator.getImageData();
99        result = new Image(Display.getCurrent(), bid.width, bid.height);
100       GC gc = new GC(result);
101       //
102       gc.drawImage(baseImage, 0, 0);
103       gc.drawImage(decorator, bid.width - did.width - 1, bid.height
104           - did.height - 1);
105       //
106       gc.dispose();
107       decoratedMap.put(decorator, result);
108     }
109     return result;
110   }
111 
112   /**
113    * Dispose of cached objects and their underlying OS resources. This should
114    * only be called when the cached objects are no longer needed (e.g. on
115    * application shutdown)
116    */
117   public static void dispose() {
118     disposeColors();
119     disposeFonts();
120     disposeImages();
121     disposeCursors();
122   }
123 
124   /**
125    * dispose colors
126    */
127   public static void disposeColors() {
128     for (Iterator<Color> iter = m_ColorMap.values().iterator(); iter.hasNext();)
129       iter.next().dispose();
130     m_ColorMap.clear();
131   }
132 
133   /**
134    * dispose cursors
135    */
136   public static void disposeCursors() {
137     for (Iterator<Cursor> iter = m_IdToCursorMap.values().iterator(); iter
138         .hasNext();)
139       iter.next().dispose();
140     m_IdToCursorMap.clear();
141   }
142 
143   /**
144    * dispose fonts
145    */
146   public static void disposeFonts() {
147     for (Iterator<Font> iter = m_FontMap.values().iterator(); iter.hasNext();)
148       iter.next().dispose();
149     m_FontMap.clear();
150     for (Iterator<Font> iter = m_FontToBoldFontMap.values().iterator(); iter
151         .hasNext();)
152       iter.next().dispose();
153     m_FontToBoldFontMap.clear();
154     for (Iterator<Font> iter = m_FontToItalicFontMap.values().iterator(); iter
155         .hasNext();)
156       iter.next().dispose();
157     m_FontToItalicFontMap.clear();
158   }
159 
160   /**
161    * dispose images
162    */
163   public static void disposeImages() {
164     for (Iterator<Image> iter = m_ClassImageMap.values().iterator(); iter
165         .hasNext();)
166       iter.next().dispose();
167     m_ClassImageMap.clear();
168     for (Iterator<Image> iter = m_DescriptorImageMap.values().iterator(); iter
169         .hasNext();)
170       iter.next().dispose();
171     m_DescriptorImageMap.clear();
172   }
173 
174   /**
175    * @param bar
176    */
177   // CoolBar support
178   public static void fixCoolBarSize(CoolBar bar) {
179     CoolItem[] items = bar.getItems();
180     // ensure that each item has control (at least empty one)
181     for (int i = 0; i < items.length; i++) {
182       CoolItem item = items[i];
183       if (item.getControl() == null) item.setControl(new Canvas(bar, SWT.NONE) {
184         @Override
185         public Point computeSize(int wHint, int hHint, boolean changed) {
186           return new Point(20, 20);
187         }
188       });
189     }
190     // compute size for each item
191     for (int i = 0; i < items.length; i++) {
192       CoolItem item = items[i];
193       Control control = item.getControl();
194       control.pack();
195       Point size = control.getSize();
196       item.setSize(item.computeSize(size.x, size.y));
197     }
198   }
199 
200   /**
201    * @param baseFont
202    * @return the bold font
203    */
204   public static Font getBoldFont(Font baseFont) {
205     Font font = m_FontToBoldFontMap.get(baseFont);
206     if (font == null) {
207       FontData fontDatas[] = baseFont.getFontData();
208       FontData data = fontDatas[0];
209       font = new Font(Display.getCurrent(), data.getName(), data.getHeight(),
210           SWT.BOLD);
211       m_FontToBoldFontMap.put(baseFont, font);
212     }
213     return font;
214   }
215 
216   /**
217    * @param systemColorID
218    * @return the systemColor
219    */
220   public static Color getColor(int systemColorID) {
221     Display display = Display.getCurrent();
222     return display.getSystemColor(systemColorID);
223   }
224 
225   /**
226    * @param r
227    * @param g
228    * @param b
229    * @return the color
230    */
231   public static Color getColor(int r, int g, int b) {
232     return getColor(new RGB(r, g, b));
233   }
234 
235   /**
236    * @param rgb
237    * @return the color
238    */
239   public static Color getColor(RGB rgb) {
240     Color color = m_ColorMap.get(rgb);
241     if (color == null) {
242       Display display = Display.getCurrent();
243       color = new Color(display, rgb);
244       m_ColorMap.put(rgb, color);
245     }
246     return color;
247   }
248 
249   /**
250    * @param id
251    * @return the cursor
252    */
253   public static Cursor getCursor(int id) {
254     Integer key = new Integer(id);
255     Cursor cursor = m_IdToCursorMap.get(key);
256     if (cursor == null) {
257       cursor = new Cursor(Display.getDefault(), id);
258       m_IdToCursorMap.put(key, cursor);
259     }
260     return cursor;
261   }
262 
263   /**
264    * @param name
265    * @param height
266    * @param style
267    * @return the font
268    */
269   public static Font getFont(String name, int height, int style) {
270     String fullName = name + "|" + height + "|" + style;
271     Font font = m_FontMap.get(fullName);
272     if (font == null) {
273       font = new Font(Display.getCurrent(), name, height, style);
274       m_FontMap.put(fullName, font);
275     }
276     return font;
277   }
278 
279   /**
280    * @param clazz
281    * @param path
282    * @return the image
283    */
284   public static Image getImage(Class clazz, String path) {
285     String key = clazz.getName() + "|" + path;
286     Image image = m_ClassImageMap.get(key);
287     if (image == null) {
288       if (path.length() > 0 && path.charAt(0) == '/') {
289         String newPath = path.substring(1, path.length());
290         image = getImage(clazz.getClassLoader().getResourceAsStream(newPath));
291       } else {
292         image = getImage(clazz.getResourceAsStream(path));
293       }
294       m_ClassImageMap.put(key, image);
295     }
296     return image;
297   }
298 
299   /**
300    * @param descriptor
301    * @return the image
302    */
303   public static Image getImage(ImageDescriptor descriptor) {
304     if (descriptor == null) return null;
305     Image image = m_DescriptorImageMap.get(descriptor);
306     if (image == null) {
307       image = descriptor.createImage();
308       m_DescriptorImageMap.put(descriptor, image);
309     }
310     return image;
311   }
312 
313   /**
314    * @param path
315    * @return the image
316    */
317   public static Image getImage(String path) {
318     String key = ResourceManager.class.getName() + "|" + path;
319     Image image = m_ClassImageMap.get(key);
320     if (image == null) {
321       try {
322         FileInputStream fis = new FileInputStream(path);
323         image = getImage(fis);
324         m_ClassImageMap.put(key, image);
325         fis.close();
326       } catch (Exception e) {
327         return null;
328       }
329     }
330     return image;
331   }
332 
333   /**
334    * @param clazz
335    * @param path
336    * @return the ImageDescriptor
337    */
338   public static ImageDescriptor getImageDescriptor(Class clazz, String path) {
339     return ImageDescriptor.createFromFile(clazz, path);
340   }
341 
342   /**
343    * @param path
344    * @return the ImageDescriptor
345    */
346   public static ImageDescriptor getImageDescriptor(String path) {
347     try {
348       return ImageDescriptor.createFromURL((new File(path)).toURL());
349     } catch (MalformedURLException e) {
350       return null;
351     }
352   }
353 
354   /**
355    * @param baseFont
356    * @return the italic font
357    */
358   public static Font getItalicFont(Font baseFont) {
359     Font font = m_FontToItalicFontMap.get(baseFont);
360     if (font == null) {
361       FontData fontDatas[] = baseFont.getFontData();
362       FontData data = fontDatas[0];
363       font = new Font(Display.getCurrent(), data.getName(), data.getHeight(),
364           SWT.ITALIC);
365       m_FontToItalicFontMap.put(baseFont, font);
366     }
367     return font;
368   }
369 
370   /**
371    * @param plugin
372    * @param name
373    * @return the image
374    */
375   public static Image getPluginImage(Object plugin, String name) {
376     try {
377       try {
378         URL url = getPluginImageURL(plugin, name);
379         if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url);
380         InputStream is = url.openStream();
381         Image image;
382         try {
383           image = getImage(is);
384           m_URLImageMap.put(url, image);
385         } finally {
386           is.close();
387         }
388         return image;
389       } catch (Throwable e) {
390         // ignore
391       }
392     } catch (Throwable e) {
393       // ignore
394     }
395     return null;
396   }
397 
398   /**
399    * @param plugin
400    * @param name
401    * @return the ImageDescriptor
402    */
403   public static ImageDescriptor getPluginImageDescriptor(Object plugin,
404       String name) {
405     try {
406       try {
407         URL url = getPluginImageURL(plugin, name);
408         return ImageDescriptor.createFromURL(url);
409       } catch (Throwable e) {
410         // ignore
411       }
412     } catch (Throwable e) {
413       // ignore
414     }
415     return null;
416   }
417 
418   private static Image getImage(InputStream is) {
419     Display display = Display.getCurrent();
420     ImageData data = new ImageData(is);
421     if (data.transparentPixel > 0) return new Image(display, data, data
422         .getTransparencyMask());
423     return new Image(display, data);
424   }
425 
426   private static URL getPluginImageURL(Object plugin, String name)
427       throws Exception {
428     Class pluginClass = Class.forName("org.eclipse.core.runtime.Plugin");
429     Method getDescriptorMethod = pluginClass.getMethod("getDescriptor",
430         (Class[]) null);
431     Class pluginDescriptorClass = Class
432         .forName("org.eclipse.core.runtime.IPluginDescriptor");
433     Method getInstallURLMethod = pluginDescriptorClass.getMethod(
434         "getInstallURL", (Class[]) null);
435     //
436     Object pluginDescriptor = getDescriptorMethod.invoke(plugin,
437         (Object[]) null);
438     URL installURL = (URL) getInstallURLMethod.invoke(pluginDescriptor,
439         (Object[]) null);
440     URL url = new URL(installURL, name);
441     return url;
442   }
443 }
444 /*
445  *                 ObjectLab is supporing JTreeMap
446  * 
447  * Based in London, we are world leaders in the design and development 
448  * of bespoke applications for the securities financing markets.
449  * 
450  * <a href="http://www.objectlab.co.uk/open">Click here to learn more about us</a>
451  *           ___  _     _           _   _          _
452  *          / _ \| |__ (_) ___  ___| |_| |    __ _| |__
453  *         | | | | '_ \| |/ _ \/ __| __| |   / _` | '_ \
454  *         | |_| | |_) | |  __/ (__| |_| |__| (_| | |_) |
455  *          \___/|_.__// |\___|\___|\__|_____\__,_|_.__/
456  *                   |__/
457  *
458  *                     www.ObjectLab.co.uk
459  */