JAL-2360 added UserColourScheme.toAppletParameter+test, hid
[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 import jalview.util.ColorUtils;
27
28 import java.awt.Color;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.StringTokenizer;
35
36 public class UserColourScheme extends ResidueColourScheme
37 {
38   /*
39    * lookup (by symbol index) of lower case colours (if configured)
40    */
41   Color[] lowerCaseColours;
42
43   protected String schemeName;
44
45   public UserColourScheme()
46   {
47     super(ResidueProperties.aaIndex);
48   }
49
50   public UserColourScheme(Color[] newColors)
51   {
52     super(ResidueProperties.aaIndex);
53     colors = newColors;
54   }
55
56   @Override
57   public ColourSchemeI applyTo(AnnotatedCollectionI sg,
58           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
59   {
60     UserColourScheme usc = new UserColourScheme(colors);
61     if (lowerCaseColours != null)
62     {
63       usc.schemeName = schemeName;
64       usc.lowerCaseColours = new Color[lowerCaseColours.length];
65       System.arraycopy(lowerCaseColours, 0, usc.lowerCaseColours, 0,
66               lowerCaseColours.length);
67     }
68     return usc;
69   }
70
71   /**
72    * Constructor for an animino acid colour scheme. The colour specification may
73    * be one of
74    * <ul>
75    * <li>an AWT colour name e.g. red</li>
76    * <li>an AWT hex rgb colour e.g. ff2288</li>
77    * <li>residue colours list e.g. D,E=red;K,R,H=0022FF;c=yellow</li>
78    * </ul>
79    * 
80    * @param colour
81    */
82   public UserColourScheme(String colour)
83   {
84     super(ResidueProperties.aaIndex);
85
86     if (colour.contains("="))
87     {
88       /*
89        * a list of colours per residue(s)
90        */
91       parseAppletParameter(colour);
92       return;
93     }
94
95     Color col = ColorUtils.parseColourString(colour);
96
97     if (col == null)
98     {
99       System.out.println("Making colour from name: " + colour);
100       col = ColorUtils.createColourFromName(colour);
101     }
102
103     setAll(col);
104     schemeName = colour;
105   }
106
107   /**
108    * Sets all symbols to the specified colour
109    * 
110    * @param col
111    */
112   protected void setAll(Color col)
113   {
114     if (symbolIndex == null)
115     {
116       return;
117     }
118     int max = 0;
119     for (int index : symbolIndex)
120     {
121       max = Math.max(max, index);
122     }
123     colors = new Color[max + 1];
124     for (int i = 0; i <= max; i++)
125     {
126       colors[i] = col;
127     }
128   }
129
130   public Color[] getColours()
131   {
132     return colors;
133   }
134
135   public Color[] getLowerCaseColours()
136   {
137     return lowerCaseColours;
138   }
139
140   public void setName(String name)
141   {
142     schemeName = name;
143   }
144
145   public String getName()
146   {
147     return schemeName;
148   }
149
150   /**
151    * Parse and save residue colours specified as (for example)
152    * 
153    * <pre>
154    *     D,E=red; K,R,H=0022FF; c=100,50,75
155    * </pre>
156    * 
157    * This should be a semi-colon separated list of colours, which may be defined
158    * by colour name, hex value or comma-separated RGB triple. Each colour is
159    * defined for a comma-separated list of amino acid single letter codes. (Note
160    * that this also allows a colour scheme to be defined for ACGT, but not for
161    * U.)
162    * 
163    * @param paramValue
164    */
165   void parseAppletParameter(String paramValue)
166   {
167     setAll(Color.white);
168
169     StringTokenizer st = new StringTokenizer(paramValue, ";");
170     StringTokenizer st2;
171     String token = null, colour, residues;
172     try
173     {
174       while (st.hasMoreElements())
175       {
176         token = st.nextToken().trim();
177         residues = token.substring(0, token.indexOf("="));
178         colour = token.substring(token.indexOf("=") + 1);
179
180         st2 = new StringTokenizer(residues, " ,");
181         while (st2.hasMoreTokens())
182         {
183           String residue = st2.nextToken();
184
185           int colIndex = ResidueProperties.aaIndex[residue.charAt(0)];
186           if (colIndex == -1)
187           {
188             continue;
189           }
190
191           if (residue.equalsIgnoreCase("lowerCase"))
192           {
193             if (lowerCaseColours == null)
194             {
195               lowerCaseColours = new Color[colors.length];
196             }
197             for (int i = 0; i < lowerCaseColours.length; i++)
198             {
199               if (lowerCaseColours[i] == null)
200               {
201                 lowerCaseColours[i] = ColorUtils.parseColourString(colour);
202               }
203             }
204
205             continue;
206           }
207
208           if (residue.equals(residue.toLowerCase()))
209           {
210             if (lowerCaseColours == null)
211             {
212               lowerCaseColours = new Color[colors.length];
213             }
214             lowerCaseColours[colIndex] = ColorUtils.parseColourString(colour);
215           }
216           else
217           {
218             colors[colIndex] = ColorUtils.parseColourString(colour);
219           }
220         }
221       }
222     } catch (Exception ex)
223     {
224       System.out.println("Error parsing userDefinedColours:\n" + token
225               + "\n" + ex);
226     }
227
228   }
229
230   @Override
231   public Color findColour(char c, int j, SequenceI seq)
232   {
233     Color currentColour;
234     int index = ResidueProperties.aaIndex[c];
235
236     if ((threshold == 0) || aboveThreshold(c, j))
237     {
238       if (lowerCaseColours != null && 'a' <= c && c <= 'z')
239       {
240         currentColour = lowerCaseColours[index];
241       }
242       else
243       {
244         currentColour = colors[index];
245       }
246     }
247     else
248     {
249       currentColour = Color.white;
250     }
251
252     if (conservationColouring)
253     {
254       currentColour = applyConservation(currentColour, j);
255     }
256
257     return currentColour;
258   }
259
260   public void setLowerCaseColours(Color[] lcolours)
261   {
262     lowerCaseColours = lcolours;
263   }
264
265   /**
266    * Returns the colour for the given residue character. If the residue is
267    * lower-case, and there is a specific colour defined for lower case, that
268    * colour is returned, else the colour for the upper case residue.
269    */
270   @Override
271   public Color findColour(char c)
272   {
273     if ('a' <= c && c <= 'z' && lowerCaseColours != null)
274     {
275       Color colour = lowerCaseColours[symbolIndex[c]];
276       if (colour != null)
277       {
278         return colour;
279       }
280     }
281     return super.findColour(c);
282   }
283
284   /**
285    * Answers the customised name of the colour scheme, if it has one, else
286    * "User Defined"
287    */
288   @Override
289   public String getSchemeName()
290   {
291     if (schemeName != null && schemeName.length() > 0)
292     {
293       return schemeName;
294     }
295     return JalviewColourScheme.UserDefined.toString();
296   }
297
298   /**
299    * Generate an applet colour parameter like A,C,D=12ffe9;Q,W=2393fd;w=9178dd
300    * 
301    * @return
302    */
303   public String toAppletParameter()
304   {
305     Map<Color, List<String>> colours = new HashMap<Color, List<String>>();
306
307     for (char symbol = 'A'; symbol <= 'Z'; symbol++)
308     {
309       String residue = String.valueOf(symbol);
310       int index = symbolIndex[symbol];
311       Color c = colors[index];
312       if (c != null && !c.equals(Color.white))
313       {
314         if (colours.get(c) == null)
315         {
316           colours.put(c, new ArrayList<String>());
317         }
318         colours.get(c).add(residue);
319       }
320       if (lowerCaseColours != null)
321       {
322         c = lowerCaseColours[index];
323         if (c != null && !c.equals(Color.white))
324         {
325           residue = residue.toLowerCase();
326           if (colours.get(c) == null)
327           {
328             colours.put(c, new ArrayList<String>());
329           }
330           colours.get(c).add(residue);
331         }
332       }
333     }
334     StringBuilder sb = new StringBuilder();
335     for (Entry<Color, List<String>> cols : colours.entrySet())
336     {
337       if (sb.length() > 0)
338       {
339         sb.append(";");
340       }
341       boolean first = true;
342       for (String residue : cols.getValue())
343       {
344         if (!first)
345         {
346           sb.append(",");
347         }
348         sb.append(residue);
349         first = false;
350       }
351       sb.append("=");
352       /*
353        * get color as hex value, dropping the alpha (ff) part
354        */
355       String hexString = Integer.toHexString(cols.getKey().getRGB())
356               .substring(2);
357       sb.append(hexString);
358     }
359
360     return sb.toString();
361   }
362 }