JAL-2360 refactoring for JalviewColourScheme enum,
[jalview.git] / src / jalview / util / ColorUtils.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 /**
22  * author: Lauren Michelle Lui
23  */
24
25 package jalview.util;
26
27 import java.awt.Color;
28 import java.util.Random;
29
30 public class ColorUtils
31 {
32
33   /**
34    * Generates a random color, will mix with input color. Code taken from
35    * http://stackoverflow
36    * .com/questions/43044/algorithm-to-randomly-generate-an-aesthetically
37    * -pleasing-color-palette
38    * 
39    * @param mix
40    * @return Random color in RGB
41    */
42   public static final Color generateRandomColor(Color mix)
43   {
44     Random random = new Random();
45     int red = random.nextInt(256);
46     int green = random.nextInt(256);
47     int blue = random.nextInt(256);
48
49     // mix the color
50     if (mix != null)
51     {
52       red = (red + mix.getRed()) / 2;
53       green = (green + mix.getGreen()) / 2;
54       blue = (blue + mix.getBlue()) / 2;
55     }
56
57     Color color = new Color(red, green, blue);
58     return color;
59
60   }
61
62   /**
63    * Convert to Tk colour code format
64    * 
65    * @param colour
66    * @return
67    * @see http
68    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/colortool.html#
69    *      tkcode
70    */
71   public static final String toTkCode(Color colour)
72   {
73     String colstring = "#" + ((colour.getRed() < 16) ? "0" : "")
74             + Integer.toHexString(colour.getRed())
75             + ((colour.getGreen() < 16) ? "0" : "")
76             + Integer.toHexString(colour.getGreen())
77             + ((colour.getBlue() < 16) ? "0" : "")
78             + Integer.toHexString(colour.getBlue());
79     return colstring;
80   }
81
82   /**
83    * Returns a colour three shades darker. Note you can't guarantee that
84    * brighterThan reverses this, as darkerThan may result in black.
85    * 
86    * @param col
87    * @return
88    */
89   public static Color darkerThan(Color col)
90   {
91     return col == null ? null : col.darker().darker().darker();
92   }
93
94   /**
95    * Returns a colour three shades brighter. Note you can't guarantee that
96    * darkerThan reverses this, as brighterThan may result in white.
97    * 
98    * @param col
99    * @return
100    */
101   public static Color brighterThan(Color col)
102   {
103     return col == null ? null : col.brighter().brighter().brighter();
104   }
105
106   /**
107    * Returns a color between minColour and maxColour; the RGB values are in
108    * proportion to where 'value' lies between minValue and maxValue
109    * 
110    * @param value
111    * @param minValue
112    * @param minColour
113    * @param maxValue
114    * @param maxColour
115    * @return
116    */
117   public static Color getGraduatedColour(float value, float minValue,
118           Color minColour, float maxValue, Color maxColour)
119   {
120     if (minValue == maxValue)
121     {
122       return minColour;
123     }
124     if (value < minValue)
125     {
126       value = minValue;
127     }
128     if (value > maxValue)
129     {
130       value = maxValue;
131     }
132
133     /*
134      * prop = proportion of the way value is from minValue to maxValue
135      */
136     float prop = (value - minValue) / (maxValue - minValue);
137     float r = minColour.getRed() + prop
138             * (maxColour.getRed() - minColour.getRed());
139     float g = minColour.getGreen() + prop
140             * (maxColour.getGreen() - minColour.getGreen());
141     float b = minColour.getBlue() + prop
142             * (maxColour.getBlue() - minColour.getBlue());
143     return new Color(r / 255, g / 255, b / 255);
144   }
145
146   /**
147    * 'Fades' the given colour towards white by the specified proportion. A
148    * factor of 1 or more results in White, a factor of 0 leaves the colour
149    * unchanged, and a factor between 0 and 1 results in a proportionate change
150    * of RGB values towards (255, 255, 255).
151    * <p>
152    * A negative bleachFactor can be specified to darken the colour towards Black
153    * (0, 0, 0).
154    * 
155    * @param colour
156    * @param bleachFactor
157    * @return
158    */
159   public static Color bleachColour(Color colour, float bleachFactor)
160   {
161     if (bleachFactor >= 1f)
162     {
163       return Color.WHITE;
164     }
165     if (bleachFactor <= -1f)
166     {
167       return Color.BLACK;
168     }
169     if (bleachFactor == 0f)
170     {
171       return colour;
172     }
173
174     int red = colour.getRed();
175     int green = colour.getGreen();
176     int blue = colour.getBlue();
177
178     if (bleachFactor > 0)
179     {
180       red += (255 - red) * bleachFactor;
181       green += (255 - green) * bleachFactor;
182       blue += (255 - blue) * bleachFactor;
183       return new Color(red, green, blue);
184     }
185     else
186     {
187       float factor = 1 + bleachFactor;
188       red *= factor;
189       green *= factor;
190       blue *= factor;
191       return new Color(red, green, blue);
192     }
193   }
194
195   /**
196    * Parses a string into a Color, where the accepted formats are
197    * <ul>
198    * <li>an AWT colour name e.g. white</li>
199    * <li>a hex colour value (without prefix) e.g. ff0000</li>
200    * <li>an rgb triple e.g. 100,50,150</li>
201    * </ul>
202    * 
203    * @param colour
204    * @return the parsed colour, or null if parsing fails
205    */
206   public static Color parseColourString(String colour)
207   {
208     if (colour == null)
209     {
210       return null;
211     }
212     colour = colour.trim();
213   
214     Color col = null;
215     try
216     {
217       int value = Integer.parseInt(colour, 16);
218       col = new Color(value);
219     } catch (NumberFormatException ex)
220     {
221     }
222   
223     if (col == null)
224     {
225       col = ColorUtils.getAWTColorFromName(colour);
226     }
227   
228     if (col == null)
229     {
230       try
231       {
232         String[] tokens = colour.split(",");
233         if (tokens.length == 3)
234         {
235           int r = Integer.parseInt(tokens[0].trim());
236           int g = Integer.parseInt(tokens[1].trim());
237           int b = Integer.parseInt(tokens[2].trim());
238           col = new Color(r, g, b);
239         }
240       } catch (Exception ex)
241       {
242         // non-numeric token or out of 0-255 range
243       }
244     }
245   
246     return col;
247   }
248
249   /**
250    * Constructs a colour from a text string. The hashcode of the whole string is
251    * scaled to the range 0-135. This is added to RGB values made from the
252    * hashcode of each third of the string, and scaled to the range 20-229.
253    * 
254    * @param name
255    * @return
256    */
257   public static Color createColourFromName(String name)
258   {
259     int lsize = name.length();
260     int start = 0;
261     int end = lsize / 3;
262   
263     int rgbOffset = Math.abs(name.hashCode() % 10) * 15;
264   
265     /*
266      * red: first third
267      */
268     int r = Math.abs(name.substring(start, end).hashCode() + rgbOffset) % 210 + 20;
269     start = end;
270     end += lsize / 3;
271     if (end > lsize)
272     {
273       end = lsize;
274     }
275   
276     /*
277      * green: second third
278      */
279     int g = Math.abs(name.substring(start, end).hashCode() + rgbOffset) % 210 + 20;
280   
281     /*
282      * blue: third third
283      */
284     int b = Math.abs(name.substring(end).hashCode() + rgbOffset) % 210 + 20;
285   
286     Color color = new Color(r, g, b);
287   
288     return color;
289   }
290
291   /**
292    * Returns the Color constant for a given colour name e.g. "pink", or null if
293    * the name is not recognised
294    * 
295    * @param name
296    * @return
297    */
298   public static Color getAWTColorFromName(String name)
299   {
300     if (name == null)
301     {
302       return null;
303     }
304     Color col = null;
305     name = name.toLowerCase();
306   
307     // or make a static map; or use reflection on the field name
308     switch (name)
309     {
310     case "black":
311       col = Color.black;
312       break;
313     case "blue":
314       col = Color.blue;
315       break;
316     case "cyan":
317       col = Color.cyan;
318       break;
319     case "darkgray":
320       col = Color.darkGray;
321       break;
322     case "gray":
323       col = Color.gray;
324       break;
325     case "green":
326       col = Color.green;
327       break;
328     case "lightgray":
329       col = Color.lightGray;
330       break;
331     case "magenta":
332       col = Color.magenta;
333       break;
334     case "orange":
335       col = Color.orange;
336       break;
337     case "pink":
338       col = Color.pink;
339       break;
340     case "red":
341       col = Color.red;
342       break;
343     case "white":
344       col = Color.white;
345       break;
346     case "yellow":
347       col = Color.yellow;
348       break;
349     }
350   
351     return col;
352   }
353 }