Import views plugins
[deliverable/tracecompass.git] / tmf / org.lttng.scope.tmf2.views.ui / src / org / lttng / scope / tmf2 / views / ui / jfx / JfxImageFactory.java
1 /*
2 * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 */
9
10 package org.lttng.scope.tmf2.views.ui.jfx;
11
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.util.HashMap;
15 import java.util.Map;
16
17 import org.eclipse.jdt.annotation.Nullable;
18
19 import javafx.scene.image.Image;
20
21 /**
22 * Factory for JavaFX {@link Image}s. This will allow caching the Image objects,
23 * allowing any class to re-use already read images.
24 *
25 * @author Alexandre Montplaisir
26 * @noreference This cache is only valid for classes within the same jar/plugin.
27 * The resource paths would not work from different plugins.
28 */
29 public final class JfxImageFactory {
30
31 private static final JfxImageFactory INSTANCE = new JfxImageFactory();
32
33 private JfxImageFactory() {}
34
35 /**
36 * Get the singleton instance of this factory.
37 *
38 * @return The instance
39 */
40 public static JfxImageFactory instance() {
41 return INSTANCE;
42 }
43
44 private final Map<String, Image> fImages = new HashMap<>();
45
46 /**
47 * Get the {@link Image} for a given path within the jar's resources.
48 *
49 * @param resourcePath
50 * The path to the image resource. It should be a standard
51 * .gif/.png/.jpg etc. file.
52 * @return The corresponding Image.
53 */
54 public synchronized @Nullable Image getImageFromResource(String resourcePath) {
55 Image image = fImages.get(resourcePath);
56 if (image == null) {
57 try (InputStream is = getClass().getResourceAsStream(resourcePath)) {
58 if (is == null) {
59 /* The image was not found, the path is invalid */
60 return null;
61 }
62 image = new Image(is);
63 } catch (IOException e) {
64 return null;
65 }
66 fImages.put(resourcePath, image);
67 }
68 return image;
69 }
70
71 }
This page took 0.043626 seconds and 5 git commands to generate.