Skip to main content
summaryrefslogtreecommitdiffstats
blob: 38dab08e6016aeef5659bbc5431c2976e0a84ae5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/*******************************************************************************
 * Copyright (c) 2011 Google, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Google, Inc. - initial API and implementation
 *******************************************************************************/
package org.eclipse.emf.cdo.releng.internal.setup.ui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Utility class for managing OS resources associated with SWT controls such as colors, fonts, images, etc.
 * <p>
 * !!! IMPORTANT !!! Application code must explicitly invoke the <code>dispose()</code> method to release the
 * operating system resources managed by cached objects when those objects and OS resources are no longer
 * needed (e.g. on application shutdown)
 * <p>
 * This class may be freely distributed as part of any application or plugin.
 * <p>
 * @author scheglov_ke
 * @author Dan Rubel
 */
public class SWTResourceManager
{
  // //////////////////////////////////////////////////////////////////////////
  //
  // Color
  //
  // //////////////////////////////////////////////////////////////////////////
  private static Map<RGB, Color> m_colorMap = new HashMap<RGB, Color>();

  /**
   * Returns the system {@link Color} matching the specific ID.
   * 
   * @param systemColorID
   *            the ID value for the color
   * @return the system {@link Color} matching the specific ID
   */
  public static Color getColor(int systemColorID)
  {
    Display display = Display.getCurrent();
    return display.getSystemColor(systemColorID);
  }

  /**
   * Returns a {@link Color} given its red, green and blue component values.
   * 
   * @param r
   *            the red component of the color
   * @param g
   *            the green component of the color
   * @param b
   *            the blue component of the color
   * @return the {@link Color} matching the given red, green and blue component values
   */
  public static Color getColor(int r, int g, int b)
  {
    return getColor(new RGB(r, g, b));
  }

  /**
   * Returns a {@link Color} given its RGB value.
   * 
   * @param rgb
   *            the {@link RGB} value of the color
   * @return the {@link Color} matching the RGB value
   */
  public static Color getColor(RGB rgb)
  {
    Color color = m_colorMap.get(rgb);
    if (color == null)
    {
      Display display = Display.getCurrent();
      color = new Color(display, rgb);
      m_colorMap.put(rgb, color);
    }
    return color;
  }

  /**
   * Dispose of all the cached {@link Color}'s.
   */
  public static void disposeColors()
  {
    for (Color color : m_colorMap.values())
    {
      color.dispose();
    }
    m_colorMap.clear();
  }

  // //////////////////////////////////////////////////////////////////////////
  //
  // Image
  //
  // //////////////////////////////////////////////////////////////////////////
  /**
   * Maps image paths to images.
   */
  private static Map<String, Image> m_imageMap = new HashMap<String, Image>();

  /**
   * Returns an {@link Image} encoded by the specified {@link InputStream}.
   * 
   * @param stream
   *            the {@link InputStream} encoding the image data
   * @return the {@link Image} encoded by the specified input stream
   */
  protected static Image getImage(InputStream stream) throws IOException
  {
    try
    {
      Display display = Display.getCurrent();
      ImageData data = new ImageData(stream);
      if (data.transparentPixel > 0)
      {
        return new Image(display, data, data.getTransparencyMask());
      }
      return new Image(display, data);
    }
    finally
    {
      stream.close();
    }
  }

  /**
   * Returns an {@link Image} stored in the file at the specified path.
   * 
   * @param path
   *            the path to the image file
   * @return the {@link Image} stored in the file at the specified path
   */
  public static Image getImage(String path)
  {
    Image image = m_imageMap.get(path);
    if (image == null)
    {
      try
      {
        image = getImage(new FileInputStream(path));
        m_imageMap.put(path, image);
      }
      catch (Exception e)
      {
        image = getMissingImage();
        m_imageMap.put(path, image);
      }
    }
    return image;
  }

  /**
   * Returns an {@link Image} stored in the file at the specified path relative to the specified class.
   * 
   * @param clazz
   *            the {@link Class} relative to which to find the image
   * @param path
   *            the path to the image file, if starts with <code>'/'</code>
   * @return the {@link Image} stored in the file at the specified path
   */
  public static Image getImage(Class<?> clazz, String path)
  {
    String key = clazz.getName() + '|' + path;
    Image image = m_imageMap.get(key);
    if (image == null)
    {
      try
      {
        image = getImage(clazz.getResourceAsStream(path));
        m_imageMap.put(key, image);
      }
      catch (Exception e)
      {
        image = getMissingImage();
        m_imageMap.put(key, image);
      }
    }
    return image;
  }

  private static final int MISSING_IMAGE_SIZE = 10;

  /**
   * @return the small {@link Image} that can be used as placeholder for missing image.
   */
  private static Image getMissingImage()
  {
    Image image = new Image(Display.getCurrent(), MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
    //
    GC gc = new GC(image);
    gc.setBackground(getColor(SWT.COLOR_RED));
    gc.fillRectangle(0, 0, MISSING_IMAGE_SIZE, MISSING_IMAGE_SIZE);
    gc.dispose();
    //
    return image;
  }

  /**
   * Style constant for placing decorator image in top left corner of base image.
   */
  public static final int TOP_LEFT = 1;

  /**
   * Style constant for placing decorator image in top right corner of base image.
   */
  public static final int TOP_RIGHT = 2;

  /**
   * Style constant for placing decorator image in bottom left corner of base image.
   */
  public static final int BOTTOM_LEFT = 3;

  /**
   * Style constant for placing decorator image in bottom right corner of base image.
   */
  public static final int BOTTOM_RIGHT = 4;

  /**
   * Internal value.
   */
  protected static final int LAST_CORNER_KEY = 5;

  /**
   * Maps images to decorated images.
   */
  @SuppressWarnings("unchecked")
  private static Map<Image, Map<Image, Image>>[] m_decoratedImageMap = new Map[LAST_CORNER_KEY];

  /**
   * Returns an {@link Image} composed of a base image decorated by another image.
   * 
   * @param baseImage
   *            the base {@link Image} that should be decorated
   * @param decorator
   *            the {@link Image} to decorate the base image
   * @return {@link Image} The resulting decorated image
   */
  public static Image decorateImage(Image baseImage, Image decorator)
  {
    return decorateImage(baseImage, decorator, BOTTOM_RIGHT);
  }

  /**
   * Returns an {@link Image} composed of a base image decorated by another image.
   * 
   * @param baseImage
   *            the base {@link Image} that should be decorated
   * @param decorator
   *            the {@link Image} to decorate the base image
   * @param corner
   *            the corner to place decorator image
   * @return the resulting decorated {@link Image}
   */
  public static Image decorateImage(final Image baseImage, final Image decorator, final int corner)
  {
    if (corner <= 0 || corner >= LAST_CORNER_KEY)
    {
      throw new IllegalArgumentException("Wrong decorate corner");
    }
    Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[corner];
    if (cornerDecoratedImageMap == null)
    {
      cornerDecoratedImageMap = new HashMap<Image, Map<Image, Image>>();
      m_decoratedImageMap[corner] = cornerDecoratedImageMap;
    }
    Map<Image, Image> decoratedMap = cornerDecoratedImageMap.get(baseImage);
    if (decoratedMap == null)
    {
      decoratedMap = new HashMap<Image, Image>();
      cornerDecoratedImageMap.put(baseImage, decoratedMap);
    }
    //
    Image result = decoratedMap.get(decorator);
    if (result == null)
    {
      Rectangle bib = baseImage.getBounds();
      Rectangle dib = decorator.getBounds();
      //
      result = new Image(Display.getCurrent(), bib.width, bib.height);
      //
      GC gc = new GC(result);
      gc.drawImage(baseImage, 0, 0);
      if (corner == TOP_LEFT)
      {
        gc.drawImage(decorator, 0, 0);
      }
      else if (corner == TOP_RIGHT)
      {
        gc.drawImage(decorator, bib.width - dib.width, 0);
      }
      else if (corner == BOTTOM_LEFT)
      {
        gc.drawImage(decorator, 0, bib.height - dib.height);
      }
      else if (corner == BOTTOM_RIGHT)
      {
        gc.drawImage(decorator, bib.width - dib.width, bib.height - dib.height);
      }
      gc.dispose();
      //
      decoratedMap.put(decorator, result);
    }
    return result;
  }

  /**
   * Dispose all of the cached {@link Image}'s.
   */
  public static void disposeImages()
  {
    // dispose loaded images
    {
      for (Image image : m_imageMap.values())
      {
        image.dispose();
      }
      m_imageMap.clear();
    }
    // dispose decorated images
    for (int i = 0; i < m_decoratedImageMap.length; i++)
    {
      Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
      if (cornerDecoratedImageMap != null)
      {
        for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values())
        {
          for (Image image : decoratedMap.values())
          {
            image.dispose();
          }
          decoratedMap.clear();
        }
        cornerDecoratedImageMap.clear();
      }
    }
  }

  // //////////////////////////////////////////////////////////////////////////
  //
  // Font
  //
  // //////////////////////////////////////////////////////////////////////////
  /**
   * Maps font names to fonts.
   */
  private static Map<String, Font> m_fontMap = new HashMap<String, Font>();

  /**
   * Maps fonts to their bold versions.
   */
  private static Map<Font, Font> m_fontToBoldFontMap = new HashMap<Font, Font>();

  /**
   * Returns a {@link Font} based on its name, height and style.
   * 
   * @param name
   *            the name of the font
   * @param height
   *            the height of the font
   * @param style
   *            the style of the font
   * @return {@link Font} The font matching the name, height and style
   */
  public static Font getFont(String name, int height, int style)
  {
    return getFont(name, height, style, false, false);
  }

  /**
   * Returns a {@link Font} based on its name, height and style. Windows-specific strikeout and underline
   * flags are also supported.
   * 
   * @param name
   *            the name of the font
   * @param size
   *            the size of the font
   * @param style
   *            the style of the font
   * @param strikeout
   *            the strikeout flag (warning: Windows only)
   * @param underline
   *            the underline flag (warning: Windows only)
   * @return {@link Font} The font matching the name, height, style, strikeout and underline
   */
  public static Font getFont(String name, int size, int style, boolean strikeout, boolean underline)
  {
    String fontName = name + '|' + size + '|' + style + '|' + strikeout + '|' + underline;
    Font font = m_fontMap.get(fontName);
    if (font == null)
    {
      FontData fontData = new FontData(name, size, style);
      if (strikeout || underline)
      {
        try
        {
          Class<?> logFontClass = Class.forName("org.eclipse.swt.internal.win32.LOGFONT"); //$NON-NLS-1$
          Object logFont = FontData.class.getField("data").get(fontData); //$NON-NLS-1$
          if (logFont != null && logFontClass != null)
          {
            if (strikeout)
            {
              logFontClass.getField("lfStrikeOut").set(logFont, Byte.valueOf((byte)1)); //$NON-NLS-1$
            }
            if (underline)
            {
              logFontClass.getField("lfUnderline").set(logFont, Byte.valueOf((byte)1)); //$NON-NLS-1$
            }
          }
        }
        catch (Throwable e)
        {
          System.err.println("Unable to set underline or strikeout" + " (probably on a non-Windows platform). " + e); //$NON-NLS-1$ //$NON-NLS-2$
        }
      }
      font = new Font(Display.getCurrent(), fontData);
      m_fontMap.put(fontName, font);
    }
    return font;
  }

  /**
   * Returns a bold version of the given {@link Font}.
   * 
   * @param baseFont
   *            the {@link Font} for which a bold version is desired
   * @return the bold version of the given {@link Font}
   */
  public static Font getBoldFont(Font baseFont)
  {
    Font font = m_fontToBoldFontMap.get(baseFont);
    if (font == null)
    {
      FontData fontDatas[] = baseFont.getFontData();
      FontData data = fontDatas[0];
      font = new Font(Display.getCurrent(), data.getName(), data.getHeight(), SWT.BOLD);
      m_fontToBoldFontMap.put(baseFont, font);
    }
    return font;
  }

  /**
   * Dispose all of the cached {@link Font}'s.
   */
  public static void disposeFonts()
  {
    // clear fonts
    for (Font font : m_fontMap.values())
    {
      font.dispose();
    }
    m_fontMap.clear();
    // clear bold fonts
    for (Font font : m_fontToBoldFontMap.values())
    {
      font.dispose();
    }
    m_fontToBoldFontMap.clear();
  }

  // //////////////////////////////////////////////////////////////////////////
  //
  // Cursor
  //
  // //////////////////////////////////////////////////////////////////////////
  /**
   * Maps IDs to cursors.
   */
  private static Map<Integer, Cursor> m_idToCursorMap = new HashMap<Integer, Cursor>();

  /**
   * Returns the system cursor matching the specific ID.
   * 
   * @param id
   *            int The ID value for the cursor
   * @return Cursor The system cursor matching the specific ID
   */
  public static Cursor getCursor(int id)
  {
    Integer key = Integer.valueOf(id);
    Cursor cursor = m_idToCursorMap.get(key);
    if (cursor == null)
    {
      cursor = new Cursor(Display.getDefault(), id);
      m_idToCursorMap.put(key, cursor);
    }
    return cursor;
  }

  /**
   * Dispose all of the cached cursors.
   */
  public static void disposeCursors()
  {
    for (Cursor cursor : m_idToCursorMap.values())
    {
      cursor.dispose();
    }
    m_idToCursorMap.clear();
  }

  // //////////////////////////////////////////////////////////////////////////
  //
  // General
  //
  // //////////////////////////////////////////////////////////////////////////
  /**
   * Dispose of cached objects and their underlying OS resources. This should only be called when the cached
   * objects are no longer needed (e.g. on application shutdown).
   */
  public static void dispose()
  {
    disposeColors();
    disposeImages();
    disposeFonts();
    disposeCursors();
  }
}

Back to the top