JAL-2362 return correct lower-case colour; Javadoc; unit test
[jalview.git] / src / jalview / schemes / UserColourScheme.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 package jalview.schemes;
22
23 import jalview.datamodel.AnnotatedCollectionI;
24 import jalview.datamodel.SequenceCollectionI;
25 import jalview.datamodel.SequenceI;
26
27 import java.awt.Color;
28 import java.util.Map;
29 import java.util.StringTokenizer;
30
31 public class UserColourScheme extends ResidueColourScheme
32 {
33   Color[] lowerCaseColours;
34
35   protected String schemeName;
36
37   public UserColourScheme()
38   {
39     super(ResidueProperties.aaIndex);
40   }
41
42   public UserColourScheme(Color[] newColors)
43   {
44     super(ResidueProperties.aaIndex);
45     colors = newColors;
46   }
47
48   @Override
49   public ColourSchemeI applyTo(AnnotatedCollectionI sg,
50           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
51   {
52     UserColourScheme usc = new UserColourScheme(colors);
53     if (lowerCaseColours != null)
54     {
55       usc.schemeName = new String(schemeName);
56       usc.lowerCaseColours = new Color[lowerCaseColours.length];
57       System.arraycopy(lowerCaseColours, 0, usc.lowerCaseColours, 0,
58               lowerCaseColours.length);
59     }
60     return usc;
61   }
62
63   public UserColourScheme(String colour)
64   {
65     super(ResidueProperties.aaIndex);
66     Color col = getColourFromString(colour);
67
68     if (col == null)
69     {
70       System.out.println("Making colour from name: " + colour);
71       col = createColourFromName(colour);
72     }
73
74     colors = new Color[24];
75     for (int i = 0; i < 24; i++)
76     {
77       colors[i] = col;
78     }
79     schemeName = colour;
80   }
81
82   public Color[] getColours()
83   {
84     return colors;
85   }
86
87   public Color[] getLowerCaseColours()
88   {
89     return lowerCaseColours;
90   }
91
92   public void setName(String name)
93   {
94     schemeName = name;
95   }
96
97   public String getName()
98   {
99     return schemeName;
100   }
101
102   /**
103    * Parses a string into a Color, where the accepted formats are
104    * <ul>
105    * <li>an AWT colour name e.g. white</li>
106    * <li>a hex colour value (without prefix) e.g. ff0000</li>
107    * <li>an rgb triple e.g. 100,50,150</li>
108    * </ul>
109    * 
110    * @param colour
111    * @return the parsed colour, or null if parsing fails
112    */
113   public static Color getColourFromString(String colour)
114   {
115     if (colour == null)
116     {
117       return null;
118     }
119     colour = colour.trim();
120
121     Color col = null;
122     try
123     {
124       int value = Integer.parseInt(colour, 16);
125       col = new Color(value);
126     } catch (NumberFormatException ex)
127     {
128     }
129
130     if (col == null)
131     {
132       col = ColourSchemeProperty.getAWTColorFromName(colour);
133     }
134
135     if (col == null)
136     {
137       try
138       {
139         String[] tokens = colour.split(",");
140         if (tokens.length == 3)
141         {
142           int r = Integer.parseInt(tokens[0].trim());
143           int g = Integer.parseInt(tokens[1].trim());
144           int b = Integer.parseInt(tokens[2].trim());
145           col = new Color(r, g, b);
146         }
147       } catch (Exception ex)
148       {
149         // non-numeric token or out of 0-255 range
150       }
151     }
152
153     return col;
154   }
155
156   public static Color createColourFromName(String name)
157   {
158     int r, g, b;
159
160     int lsize = name.length();
161     int start = 0, end = lsize / 3;
162
163     int rgbOffset = Math.abs(name.hashCode() % 10) * 15;
164
165     r = Math.abs(name.substring(start, end).hashCode() + rgbOffset) % 210 + 20;
166     start = end;
167     end += lsize / 3;
168     if (end > lsize)
169     {
170       end = lsize;
171     }
172
173     g = Math.abs(name.substring(start, end).hashCode() + rgbOffset) % 210 + 20;
174
175     b = Math.abs(name.substring(end).hashCode() + rgbOffset) % 210 + 20;
176
177     Color color = new Color(r, g, b);
178
179     return color;
180   }
181
182   /**
183    * Parse and save residue colours specified as (for example)
184    * 
185    * <pre>
186    *     D,E=red; K,R,H=0022FF; c=100,50,75
187    * </pre>
188    * 
189    * This should be a semi-colon separated list of colours, which may be defined
190    * by colour name, hex value or comma-separated RGB triple. Each colour is
191    * defined for a comma-separated list of amino acid single letter codes. (Note
192    * that this also allows a colour scheme to be defined for ACGT, but not for
193    * U.)
194    * 
195    * @param paramValue
196    */
197   public void parseAppletParameter(String paramValue)
198   {
199     // TODO: need a function to generate appletParameter colour string from a
200     // UCS
201     StringTokenizer st = new StringTokenizer(paramValue, ";");
202     StringTokenizer st2;
203     String token = null, colour, residues;
204     try
205     {
206       while (st.hasMoreElements())
207       {
208         token = st.nextToken().trim();
209         residues = token.substring(0, token.indexOf("="));
210         colour = token.substring(token.indexOf("=") + 1);
211
212         st2 = new StringTokenizer(residues, " ,");
213         while (st2.hasMoreTokens())
214         {
215           String residue = st2.nextToken();
216
217           int colIndex = ResidueProperties.aaIndex[residue.charAt(0)];
218           if (colIndex == -1)
219           {
220             continue;
221           }
222
223           if (residue.equalsIgnoreCase("lowerCase"))
224           {
225             if (lowerCaseColours == null)
226             {
227               lowerCaseColours = new Color[23];
228             }
229             for (int i = 0; i < 23; i++)
230             {
231               if (lowerCaseColours[i] == null)
232               {
233                 lowerCaseColours[i] = getColourFromString(colour);
234               }
235             }
236
237             continue;
238           }
239
240           if (residue.equals(residue.toLowerCase()))
241           {
242             if (lowerCaseColours == null)
243             {
244               lowerCaseColours = new Color[23];
245             }
246             lowerCaseColours[colIndex] = getColourFromString(colour);
247           }
248           else
249           {
250             colors[colIndex] = getColourFromString(colour);
251           }
252         }
253       }
254     } catch (Exception ex)
255     {
256       System.out.println("Error parsing userDefinedColours:\n" + token
257               + "\n" + ex);
258     }
259
260   }
261
262   @Override
263   public Color findColour(char c, int j, SequenceI seq)
264   {
265     Color currentColour;
266     int index = ResidueProperties.aaIndex[c];
267
268     if ((threshold == 0) || aboveThreshold(c, j))
269     {
270       if (lowerCaseColours != null && 'a' <= c && c <= 'z')
271       {
272         currentColour = lowerCaseColours[index];
273       }
274       else
275       {
276         currentColour = colors[index];
277       }
278     }
279     else
280     {
281       currentColour = Color.white;
282     }
283
284     if (conservationColouring)
285     {
286       currentColour = applyConservation(currentColour, j);
287     }
288
289     return currentColour;
290   }
291
292   public void setLowerCaseColours(Color[] lcolours)
293   {
294     lowerCaseColours = lcolours;
295   }
296
297   /**
298    * Returns the colour for the given residue character. If the residue is
299    * lower-case, and there is a specific colour defined for lower case, that
300    * colour is returned, else the colour for the upper case residue.
301    */
302   @Override
303   public Color findColour(char c)
304   {
305     if ('a' <= c && c <= 'z' && lowerCaseColours != null)
306     {
307       Color colour = lowerCaseColours[symbolIndex[c]];
308       if (colour != null)
309       {
310         return colour;
311       }
312     }
313     return super.findColour(c);
314   }
315
316 }