01 /*
02 * Copyright 2014-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package griffon.javafx.support.tangoicons;
17
18 import griffon.plugins.tangoicons.Tango;
19 import javafx.scene.image.Image;
20
21 import javax.annotation.Nonnull;
22 import java.net.URL;
23
24 import static griffon.plugins.tangoicons.Tango.invalidDescription;
25 import static griffon.util.GriffonNameUtils.requireNonBlank;
26 import static java.util.Objects.requireNonNull;
27
28 /**
29 * @author Andres Almiray
30 */
31 public class TangoIcon extends Image {
32 private static final String ERROR_TANGO_NULL = "Argument 'tango' must not be null.";
33 private Tango tango;
34 private int size;
35
36 public TangoIcon(@Nonnull Tango tango) {
37 this(tango, 16);
38 }
39
40 public TangoIcon(@Nonnull Tango tango, int size) {
41 super(toURL(tango, size), true);
42 this.tango = requireNonNull(tango, ERROR_TANGO_NULL);
43 this.size = size;
44 }
45
46 public TangoIcon(@Nonnull String description) {
47 super(toURL(description));
48 tango = Tango.findByDescription(description);
49
50 String[] parts = description.split(":");
51 if (parts.length == 3) {
52 try {
53 size = Integer.parseInt(parts[2]);
54 } catch (NumberFormatException e) {
55 throw invalidDescription(description, e);
56 }
57 } else {
58 size = 16;
59 }
60 }
61
62 @Nonnull
63 private static String toURL(@Nonnull Tango tango, int size) {
64 requireNonNull(tango, ERROR_TANGO_NULL);
65 String resource = tango.asResource(size);
66 URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
67 if (url == null) {
68 throw new IllegalArgumentException("Icon " + tango + ":" + size + " does not exist");
69 }
70 return url.toExternalForm();
71 }
72
73 @Nonnull
74 private static String toURL(@Nonnull String description) {
75 requireNonBlank(description, "Argument 'description' must not be blank");
76 String resource = Tango.asResource(description);
77 URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
78 if (url == null) {
79 throw new IllegalArgumentException("Icon " + description + " does not exist");
80 }
81 return url.toExternalForm();
82 }
83
84 @Nonnull
85 public Tango getTango() {
86 return tango;
87 }
88
89 public int getSize() {
90 return size;
91 }
92 }
|