3c89d43e7e8d829f58817296271eeee1a7fe011b
[jalview.git] / src / jalview / gui / FeatureRenderer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.util.*;
21 import java.util.concurrent.ConcurrentHashMap;
22
23 import java.awt.*;
24 import java.awt.event.*;
25 import java.awt.image.*;
26 import java.beans.PropertyChangeListener;
27 import java.beans.PropertyChangeSupport;
28
29 import javax.swing.*;
30
31 import jalview.datamodel.*;
32 import jalview.schemes.GraduatedColor;
33
34 /**
35  * DOCUMENT ME!
36  * 
37  * @author $author$
38  * @version $Revision$
39  */
40 public class FeatureRenderer implements jalview.api.FeatureRenderer
41 {
42   AlignmentPanel ap;
43
44   AlignViewport av;
45
46   Color resBoxColour;
47
48   /**
49    * global transparency for feature
50    */
51   float transparency = 1.0f;
52
53   FontMetrics fm;
54
55   int charOffset;
56
57   Map featureColours = new ConcurrentHashMap();
58
59   // A higher level for grouping features of a
60   // particular type
61   Map featureGroups = new ConcurrentHashMap();
62
63   // This is actually an Integer held in the hashtable,
64   // Retrieved using the key feature type
65   Object currentColour;
66
67   String[] renderOrder;
68
69   PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
70
71   Vector allfeatures;
72
73   /**
74    * Creates a new FeatureRenderer object.
75    * 
76    * @param av
77    *          DOCUMENT ME!
78    */
79   public FeatureRenderer(AlignmentPanel ap)
80   {
81     this.ap = ap;
82     this.av = ap.av;
83   }
84
85   public class FeatureRendererSettings implements Cloneable
86   {
87     String[] renderOrder;
88
89     Map featureGroups;
90
91     Map featureColours;
92
93     float transparency;
94
95     Map featureOrder;
96
97     public FeatureRendererSettings(String[] renderOrder,
98             Hashtable featureGroups, Hashtable featureColours,
99             float transparency, Hashtable featureOrder)
100     {
101       super();
102       this.renderOrder = renderOrder;
103       this.featureGroups = featureGroups;
104       this.featureColours = featureColours;
105       this.transparency = transparency;
106       this.featureOrder = featureOrder;
107     }
108
109     /**
110      * create an independent instance of the feature renderer settings
111      * 
112      * @param fr
113      */
114     public FeatureRendererSettings(FeatureRenderer fr)
115     {
116       renderOrder = null;
117       featureGroups = new ConcurrentHashMap();
118       featureColours = new ConcurrentHashMap();
119       featureOrder = new ConcurrentHashMap();
120       if (fr.renderOrder != null)
121       {
122         this.renderOrder = new String[fr.renderOrder.length];
123         System.arraycopy(fr.renderOrder, 0, renderOrder, 0,
124                 fr.renderOrder.length);
125       }
126       if (fr.featureGroups != null)
127       {
128         this.featureGroups = new ConcurrentHashMap(fr.featureGroups);
129       }
130       if (fr.featureColours != null)
131       {
132         this.featureColours = new ConcurrentHashMap(fr.featureColours);
133       }
134       Iterator en = fr.featureColours.keySet().iterator();
135       while (en.hasNext())
136       {
137         Object next = en.next();
138         Object val = featureColours.get(next);
139         if (val instanceof GraduatedColor)
140         {
141           featureColours
142                   .put(next, new GraduatedColor((GraduatedColor) val));
143         }
144       }
145       this.transparency = fr.transparency;
146       if (fr.featureOrder != null)
147       {
148         this.featureOrder = new ConcurrentHashMap(fr.featureOrder);
149       }
150     }
151   }
152
153   public FeatureRendererSettings getSettings()
154   {
155     return new FeatureRendererSettings(this);
156   }
157
158   public void transferSettings(FeatureRendererSettings fr)
159   {
160     this.renderOrder = fr.renderOrder;
161     this.featureGroups = fr.featureGroups;
162     this.featureColours = fr.featureColours;
163     this.transparency = fr.transparency;
164     this.featureOrder = fr.featureOrder;
165   }
166
167   public void transferSettings(FeatureRenderer fr)
168   {
169     FeatureRendererSettings frs = new FeatureRendererSettings(fr);
170     this.renderOrder = frs.renderOrder;
171     this.featureGroups = frs.featureGroups;
172     this.featureColours = frs.featureColours;
173     this.transparency = frs.transparency;
174     this.featureOrder = frs.featureOrder;
175     if (av != null && av != fr.av)
176     {
177       // copy over the displayed feature settings
178       if (fr.av != null)
179       {
180         if (fr.av.featuresDisplayed != null)
181         {
182           // update display settings
183           if (av.featuresDisplayed == null)
184           {
185             av.featuresDisplayed = new Hashtable(fr.av.featuresDisplayed);
186           }
187           else
188           {
189             av.featuresDisplayed.clear();
190             Enumeration en = fr.av.featuresDisplayed.keys();
191             while (en.hasMoreElements())
192             {
193               av.featuresDisplayed.put(en.nextElement(), Boolean.TRUE);
194             }
195
196           }
197         }
198       }
199     }
200   }
201
202   BufferedImage offscreenImage;
203
204   boolean offscreenRender = false;
205
206   public Color findFeatureColour(Color initialCol, SequenceI seq, int res)
207   {
208     return new Color(findFeatureColour(initialCol.getRGB(), seq, res));
209   }
210
211   /**
212    * This is used by the Molecule Viewer and Overview to get the accurate
213    * colourof the rendered sequence
214    */
215   public synchronized int findFeatureColour(int initialCol, SequenceI seq,
216           int column)
217   {
218     if (!av.showSequenceFeatures)
219     {
220       return initialCol;
221     }
222
223     if (seq != lastSeq)
224     {
225       lastSeq = seq;
226       sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
227       if (sequenceFeatures != null)
228       {
229         sfSize = sequenceFeatures.length;
230       }
231     }
232
233     if (sequenceFeatures != lastSeq.getDatasetSequence()
234             .getSequenceFeatures())
235     {
236       sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
237       if (sequenceFeatures != null)
238       {
239         sfSize = sequenceFeatures.length;
240       }
241     }
242
243     if (sequenceFeatures == null || sfSize == 0)
244     {
245       return initialCol;
246     }
247
248     if (jalview.util.Comparison.isGap(lastSeq.getCharAt(column)))
249     {
250       return Color.white.getRGB();
251     }
252
253     // Only bother making an offscreen image if transparency is applied
254     if (transparency != 1.0f && offscreenImage == null)
255     {
256       offscreenImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
257     }
258
259     currentColour = null;
260     // TODO: non-threadsafe - each rendering thread needs its own instance of
261     // the feature renderer - or this should be synchronized.
262     offscreenRender = true;
263
264     if (offscreenImage != null)
265     {
266       offscreenImage.setRGB(0, 0, initialCol);
267       drawSequence(offscreenImage.getGraphics(), lastSeq, column, column, 0);
268
269       return offscreenImage.getRGB(0, 0);
270     }
271     else
272     {
273       drawSequence(null, lastSeq, lastSeq.findPosition(column), -1, -1);
274
275       if (currentColour == null)
276       {
277         return initialCol;
278       }
279       else
280       {
281         return ((Integer) currentColour).intValue();
282       }
283     }
284
285   }
286
287   /**
288    * DOCUMENT ME!
289    * 
290    * @param g
291    *          DOCUMENT ME!
292    * @param seq
293    *          DOCUMENT ME!
294    * @param sg
295    *          DOCUMENT ME!
296    * @param start
297    *          DOCUMENT ME!
298    * @param end
299    *          DOCUMENT ME!
300    * @param x1
301    *          DOCUMENT ME!
302    * @param y1
303    *          DOCUMENT ME!
304    * @param width
305    *          DOCUMENT ME!
306    * @param height
307    *          DOCUMENT ME!
308    */
309   // String type;
310   // SequenceFeature sf;
311   SequenceI lastSeq;
312
313   SequenceFeature[] sequenceFeatures;
314
315   int sfSize, sfindex, spos, epos;
316
317   /**
318    * show scores as heights
319    */
320   protected boolean varyHeight = false;
321
322   synchronized public void drawSequence(Graphics g, SequenceI seq,
323           int start, int end, int y1)
324   {
325
326     if (seq.getDatasetSequence().getSequenceFeatures() == null
327             || seq.getDatasetSequence().getSequenceFeatures().length == 0)
328     {
329       return;
330     }
331
332     if (g != null)
333     {
334       fm = g.getFontMetrics();
335     }
336
337     if (av.featuresDisplayed == null || renderOrder == null
338             || newFeatureAdded)
339     {
340       findAllFeatures();
341       if (av.featuresDisplayed.size() < 1)
342       {
343         return;
344       }
345
346       sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
347     }
348
349     if (lastSeq == null
350             || seq != lastSeq
351             || seq.getDatasetSequence().getSequenceFeatures() != sequenceFeatures)
352     {
353       lastSeq = seq;
354       sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
355     }
356
357     if (transparency != 1 && g != null)
358     {
359       Graphics2D g2 = (Graphics2D) g;
360       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
361               transparency));
362     }
363
364     if (!offscreenRender)
365     {
366       spos = lastSeq.findPosition(start);
367       epos = lastSeq.findPosition(end);
368     }
369
370     sfSize = sequenceFeatures.length;
371     String type;
372     for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
373     {
374       type = renderOrder[renderIndex];
375
376       if (type == null || !av.featuresDisplayed.containsKey(type))
377       {
378         continue;
379       }
380
381       // loop through all features in sequence to find
382       // current feature to render
383       for (sfindex = 0; sfindex < sfSize; sfindex++)
384       {
385         if (!sequenceFeatures[sfindex].type.equals(type))
386         {
387           continue;
388         }
389
390         if (featureGroups != null
391                 && sequenceFeatures[sfindex].featureGroup != null
392                 && sequenceFeatures[sfindex].featureGroup.length() != 0
393                 && featureGroups
394                         .containsKey(sequenceFeatures[sfindex].featureGroup)
395                 && !((Boolean) featureGroups
396                         .get(sequenceFeatures[sfindex].featureGroup))
397                         .booleanValue())
398         {
399           continue;
400         }
401
402         if (!offscreenRender
403                 && (sequenceFeatures[sfindex].getBegin() > epos || sequenceFeatures[sfindex]
404                         .getEnd() < spos))
405         {
406           continue;
407         }
408
409         if (offscreenRender && offscreenImage == null)
410         {
411           if (sequenceFeatures[sfindex].begin <= start
412                   && sequenceFeatures[sfindex].end >= start)
413           {
414             // this is passed out to the overview and other sequence renderers
415             // (e.g. molecule viewer) to get displayed colour for rendered
416             // sequence
417             currentColour = new Integer(
418                     getColour(sequenceFeatures[sfindex]).getRGB());
419             // used to be retreived from av.featuresDisplayed
420             // currentColour = av.featuresDisplayed
421             // .get(sequenceFeatures[sfindex].type);
422
423           }
424         }
425         else if (sequenceFeatures[sfindex].type.equals("disulfide bond"))
426         {
427
428           renderFeature(g, seq,
429                   seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
430                   seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
431                   getColour(sequenceFeatures[sfindex])
432                   // new Color(((Integer) av.featuresDisplayed
433                   // .get(sequenceFeatures[sfindex].type)).intValue())
434                   , start, end, y1);
435           renderFeature(g, seq,
436                   seq.findIndex(sequenceFeatures[sfindex].end) - 1,
437                   seq.findIndex(sequenceFeatures[sfindex].end) - 1,
438                   getColour(sequenceFeatures[sfindex])
439                   // new Color(((Integer) av.featuresDisplayed
440                   // .get(sequenceFeatures[sfindex].type)).intValue())
441                   , start, end, y1);
442
443         }
444         else if (showFeature(sequenceFeatures[sfindex]))
445         {
446           if (av.showSeqFeaturesHeight
447                   && sequenceFeatures[sfindex].score != Float.NaN)
448           {
449             renderScoreFeature(g, seq,
450                     seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
451                     seq.findIndex(sequenceFeatures[sfindex].end) - 1,
452                     getColour(sequenceFeatures[sfindex]), start, end, y1,
453                     normaliseScore(sequenceFeatures[sfindex]));
454           }
455           else
456           {
457             renderFeature(g, seq,
458                     seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
459                     seq.findIndex(sequenceFeatures[sfindex].end) - 1,
460                     getColour(sequenceFeatures[sfindex]), start, end, y1);
461           }
462         }
463
464       }
465
466     }
467
468     if (transparency != 1.0f && g != null)
469     {
470       Graphics2D g2 = (Graphics2D) g;
471       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
472               1.0f));
473     }
474   }
475
476   Hashtable minmax = new Hashtable();
477
478   /**
479    * normalise a score against the max/min bounds for the feature type.
480    * 
481    * @param sequenceFeature
482    * @return byte[] { signed, normalised signed (-127 to 127) or unsigned
483    *         (0-255) value.
484    */
485   private final byte[] normaliseScore(SequenceFeature sequenceFeature)
486   {
487     float[] mm = ((float[][]) minmax.get(sequenceFeature.type))[0];
488     final byte[] r = new byte[]
489     { 0, (byte) 255 };
490     if (mm != null)
491     {
492       if (r[0] != 0 || mm[0] < 0.0)
493       {
494         r[0] = 1;
495         r[1] = (byte) ((int) 128.0 + 127.0 * (sequenceFeature.score / mm[1]));
496       }
497       else
498       {
499         r[1] = (byte) ((int) 255.0 * (sequenceFeature.score / mm[1]));
500       }
501     }
502     return r;
503   }
504
505   char s;
506
507   int i;
508
509   void renderFeature(Graphics g, SequenceI seq, int fstart, int fend,
510           Color featureColour, int start, int end, int y1)
511   {
512
513     if (((fstart <= end) && (fend >= start)))
514     {
515       if (fstart < start)
516       { // fix for if the feature we have starts before the sequence start,
517         fstart = start; // but the feature end is still valid!!
518       }
519
520       if (fend >= end)
521       {
522         fend = end;
523       }
524       int pady = (y1 + av.charHeight) - av.charHeight / 5;
525       for (i = fstart; i <= fend; i++)
526       {
527         s = seq.getCharAt(i);
528
529         if (jalview.util.Comparison.isGap(s))
530         {
531           continue;
532         }
533
534         g.setColor(featureColour);
535
536         g.fillRect((i - start) * av.charWidth, y1, av.charWidth,
537                 av.charHeight);
538
539         if (offscreenRender || !av.validCharWidth)
540         {
541           continue;
542         }
543
544         g.setColor(Color.white);
545         charOffset = (av.charWidth - fm.charWidth(s)) / 2;
546         g.drawString(String.valueOf(s), charOffset
547                 + (av.charWidth * (i - start)), pady);
548
549       }
550     }
551   }
552
553   void renderScoreFeature(Graphics g, SequenceI seq, int fstart, int fend,
554           Color featureColour, int start, int end, int y1, byte[] bs)
555   {
556
557     if (((fstart <= end) && (fend >= start)))
558     {
559       if (fstart < start)
560       { // fix for if the feature we have starts before the sequence start,
561         fstart = start; // but the feature end is still valid!!
562       }
563
564       if (fend >= end)
565       {
566         fend = end;
567       }
568       int pady = (y1 + av.charHeight) - av.charHeight / 5;
569       int ystrt = 0, yend = av.charHeight;
570       if (bs[0] != 0)
571       {
572         // signed - zero is always middle of residue line.
573         if (bs[1] < 128)
574         {
575           yend = av.charHeight * (128 - bs[1]) / 512;
576           ystrt = av.charHeight - yend / 2;
577         }
578         else
579         {
580           ystrt = av.charHeight / 2;
581           yend = av.charHeight * (bs[1] - 128) / 512;
582         }
583       }
584       else
585       {
586         yend = av.charHeight * bs[1] / 255;
587         ystrt = av.charHeight - yend;
588
589       }
590       for (i = fstart; i <= fend; i++)
591       {
592         s = seq.getCharAt(i);
593
594         if (jalview.util.Comparison.isGap(s))
595         {
596           continue;
597         }
598
599         g.setColor(featureColour);
600         int x = (i - start) * av.charWidth;
601         g.drawRect(x, y1, av.charWidth, av.charHeight);
602         g.fillRect(x, y1 + ystrt, av.charWidth, yend);
603
604         if (offscreenRender || !av.validCharWidth)
605         {
606           continue;
607         }
608
609         g.setColor(Color.black);
610         charOffset = (av.charWidth - fm.charWidth(s)) / 2;
611         g.drawString(String.valueOf(s), charOffset
612                 + (av.charWidth * (i - start)), pady);
613
614       }
615     }
616   }
617
618   boolean newFeatureAdded = false;
619
620   /**
621    * Called when alignment in associated view has new/modified features to
622    * discover and display.
623    * 
624    */
625   public void featuresAdded()
626   {
627     lastSeq = null;
628     findAllFeatures();
629   }
630
631   boolean findingFeatures = false;
632
633   /**
634    * search the alignment for all new features, give them a colour and display
635    * them. Then fires a PropertyChangeEvent on the changeSupport object.
636    * 
637    */
638   void findAllFeatures()
639   {
640     synchronized (firing)
641     {
642       if (firing.equals(Boolean.FALSE))
643       {
644         firing = Boolean.TRUE;
645         findAllFeatures(true); // add all new features as visible
646         changeSupport.firePropertyChange("changeSupport", null, null);
647         firing = Boolean.FALSE;
648       }
649     }
650   }
651
652   /**
653    * Searches alignment for all features and updates colours
654    * 
655    * @param newMadeVisible
656    *          if true newly added feature types will be rendered immediatly
657    */
658   synchronized void findAllFeatures(boolean newMadeVisible)
659   {
660     newFeatureAdded = false;
661
662     if (findingFeatures)
663     {
664       newFeatureAdded = true;
665       return;
666     }
667
668     findingFeatures = true;
669
670     if (av.featuresDisplayed == null)
671     {
672       av.featuresDisplayed = new Hashtable();
673     }
674
675     allfeatures = new Vector();
676     Vector oldfeatures = new Vector();
677     if (renderOrder != null)
678     {
679       for (int i = 0; i < renderOrder.length; i++)
680       {
681         if (renderOrder[i] != null)
682         {
683           oldfeatures.addElement(renderOrder[i]);
684         }
685       }
686     }
687     if (minmax == null)
688     {
689       minmax = new Hashtable();
690     }
691     AlignmentI alignment = av.getAlignment();
692     for (int i = 0; i < alignment.getHeight(); i++)
693     {
694       SequenceFeature[] features = alignment.getSequenceAt(i)
695               .getDatasetSequence().getSequenceFeatures();
696
697       if (features == null)
698       {
699         continue;
700       }
701
702       int index = 0;
703       while (index < features.length)
704       {
705         if (!av.featuresDisplayed.containsKey(features[index].getType()))
706         {
707
708           if (featureGroups.containsKey(features[index].getType()))
709           {
710             boolean visible = ((Boolean) featureGroups
711                     .get(features[index].featureGroup)).booleanValue();
712
713             if (!visible)
714             {
715               index++;
716               continue;
717             }
718           }
719
720           if (!(features[index].begin == 0 && features[index].end == 0))
721           {
722             // If beginning and end are 0, the feature is for the whole sequence
723             // and we don't want to render the feature in the normal way
724
725             if (newMadeVisible
726                     && !oldfeatures.contains(features[index].getType()))
727             {
728               // this is a new feature type on the alignment. Mark it for
729               // display.
730               av.featuresDisplayed.put(features[index].getType(),
731                       new Integer(getColour(features[index].getType())
732                               .getRGB()));
733               setOrder(features[index].getType(), 0);
734             }
735           }
736         }
737         if (!allfeatures.contains(features[index].getType()))
738         {
739           allfeatures.addElement(features[index].getType());
740         }
741         if (features[index].score != Float.NaN)
742         {
743           int nonpos = features[index].getBegin() >= 1 ? 0 : 1;
744           float[][] mm = (float[][]) minmax.get(features[index].getType());
745           if (mm == null)
746           {
747             mm = new float[][]
748             { null, null };
749             minmax.put(features[index].getType(), mm);
750           }
751           if (mm[nonpos] == null)
752           {
753             mm[nonpos] = new float[]
754             { features[index].score, features[index].score };
755
756           }
757           else
758           {
759             if (mm[nonpos][0] > features[index].score)
760             {
761               mm[nonpos][0] = features[index].score;
762             }
763             if (mm[nonpos][1] < features[index].score)
764             {
765               mm[nonpos][1] = features[index].score;
766             }
767           }
768         }
769         index++;
770       }
771     }
772     updateRenderOrder(allfeatures);
773     findingFeatures = false;
774   }
775
776   protected Boolean firing = Boolean.FALSE;
777
778   /**
779    * replaces the current renderOrder with the unordered features in
780    * allfeatures. The ordering of any types in both renderOrder and allfeatures
781    * is preserved, and all new feature types are rendered on top of the existing
782    * types, in the order given by getOrder or the order given in allFeatures.
783    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
784    * eliminate the float storage for computing/recalling the persistent ordering
785    * New Cability: updates min/max for colourscheme range if its dynamic
786    * 
787    * @param allFeatures
788    */
789   private void updateRenderOrder(Vector allFeatures)
790   {
791     Vector allfeatures = new Vector(allFeatures);
792     String[] oldRender = renderOrder;
793     renderOrder = new String[allfeatures.size()];
794     Object mmrange, fc = null;
795     boolean initOrders = (featureOrder == null);
796     int opos = 0;
797     if (oldRender != null && oldRender.length > 0)
798     {
799       for (int j = 0; j < oldRender.length; j++)
800       {
801         if (oldRender[j] != null)
802         {
803           if (initOrders)
804           {
805             setOrder(oldRender[j], (1 - (1 + (float) j)
806                     / (float) oldRender.length));
807           }
808           if (allfeatures.contains(oldRender[j]))
809           {
810             renderOrder[opos++] = oldRender[j]; // existing features always
811             // appear below new features
812             allfeatures.removeElement(oldRender[j]);
813             if (minmax != null)
814             {
815               mmrange = minmax.get(oldRender[j]);
816               if (mmrange != null)
817               {
818                 fc = featureColours.get(oldRender[j]);
819                 if (fc != null && fc instanceof GraduatedColor
820                         && ((GraduatedColor) fc).isAutoScale())
821                 {
822                   ((GraduatedColor) fc).updateBounds(
823                           ((float[][]) mmrange)[0][0],
824                           ((float[][]) mmrange)[0][1]);
825                 }
826               }
827             }
828           }
829         }
830       }
831     }
832     if (allfeatures.size() == 0)
833     {
834       // no new features - leave order unchanged.
835       return;
836     }
837     int i = allfeatures.size() - 1;
838     int iSize = i;
839     boolean sort = false;
840     String[] newf = new String[allfeatures.size()];
841     float[] sortOrder = new float[allfeatures.size()];
842     Enumeration en = allfeatures.elements();
843     // sort remaining elements
844     while (en.hasMoreElements())
845     {
846       newf[i] = en.nextElement().toString();
847       if (minmax != null)
848       {
849         // update from new features minmax if necessary
850         mmrange = minmax.get(newf[i]);
851         if (mmrange != null)
852         {
853           fc = featureColours.get(newf[i]);
854           if (fc != null && fc instanceof GraduatedColor
855                   && ((GraduatedColor) fc).isAutoScale())
856           {
857             ((GraduatedColor) fc).updateBounds(((float[][]) mmrange)[0][0],
858                     ((float[][]) mmrange)[0][1]);
859           }
860         }
861       }
862       if (initOrders || !featureOrder.containsKey(newf[i]))
863       {
864         int denom = initOrders ? allfeatures.size() : featureOrder.size();
865         // new unordered feature - compute persistent ordering at head of
866         // existing features.
867         setOrder(newf[i], i / (float) denom);
868       }
869       // set order from newly found feature from persisted ordering.
870       sortOrder[i] = 2 - ((Float) featureOrder.get(newf[i])).floatValue();
871       if (i < iSize)
872       {
873         // only sort if we need to
874         sort = sort || sortOrder[i] > sortOrder[i + 1];
875       }
876       i--;
877     }
878     if (iSize > 1 && sort)
879     {
880       jalview.util.QuickSort.sort(sortOrder, newf);
881     }
882     sortOrder = null;
883     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
884   }
885
886   /**
887    * get a feature style object for the given type string. Creates a
888    * java.awt.Color for a featureType with no existing colourscheme. TODO:
889    * replace return type with object implementing standard abstract colour/style
890    * interface
891    * 
892    * @param featureType
893    * @return java.awt.Color or GraduatedColor
894    */
895   public Object getFeatureStyle(String featureType)
896   {
897     Object fc = featureColours.get(featureType);
898     if (fc == null)
899     {
900       jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme();
901       Color col = ucs.createColourFromName(featureType);
902       featureColours.put(featureType, fc = col);
903     }
904     return fc;
905   }
906
907   /**
908    * return a nominal colour for this feature
909    * 
910    * @param featureType
911    * @return standard color, or maximum colour for graduated colourscheme
912    */
913   public Color getColour(String featureType)
914   {
915     Object fc = getFeatureStyle(featureType);
916
917     if (fc instanceof Color)
918     {
919       return (Color) fc;
920     }
921     else
922     {
923       if (fc instanceof GraduatedColor)
924       {
925         return ((GraduatedColor) fc).getMaxColor();
926       }
927     }
928     throw new Error("Implementation Error: Unrecognised render object "
929             + fc.getClass() + " for features of type " + featureType);
930   }
931
932   /**
933    * calculate the render colour for a specific feature using current feature
934    * settings.
935    * 
936    * @param feature
937    * @return render colour for the given feature
938    */
939   public Color getColour(SequenceFeature feature)
940   {
941     Object fc = getFeatureStyle(feature.getType());
942     if (fc instanceof Color)
943     {
944       return (Color) fc;
945     }
946     else
947     {
948       if (fc instanceof GraduatedColor)
949       {
950         return ((GraduatedColor) fc).findColor(feature);
951       }
952     }
953     throw new Error("Implementation Error: Unrecognised render object "
954             + fc.getClass() + " for features of type " + feature.getType());
955   }
956
957   private boolean showFeature(SequenceFeature sequenceFeature)
958   {
959     Object fc = getFeatureStyle(sequenceFeature.type);
960     if (fc instanceof GraduatedColor)
961     {
962       return ((GraduatedColor) fc).isColored(sequenceFeature);
963     }
964     else
965     {
966       return true;
967     }
968   }
969
970   // // /////////////
971   // // Feature Editing Dialog
972   // // Will be refactored in next release.
973
974   static String lastFeatureAdded;
975
976   static String lastFeatureGroupAdded;
977
978   static String lastDescriptionAdded;
979
980   Object oldcol, fcol;
981
982   int featureIndex = 0;
983
984   boolean amendFeatures(final SequenceI[] sequences,
985           final SequenceFeature[] features, boolean newFeatures,
986           final AlignmentPanel ap)
987   {
988
989     featureIndex = 0;
990
991     final JPanel bigPanel = new JPanel(new BorderLayout());
992     final JComboBox overlaps;
993     final JTextField name = new JTextField(25);
994     final JTextField source = new JTextField(25);
995     final JTextArea description = new JTextArea(3, 25);
996     final JSpinner start = new JSpinner();
997     final JSpinner end = new JSpinner();
998     start.setPreferredSize(new Dimension(80, 20));
999     end.setPreferredSize(new Dimension(80, 20));
1000     final FeatureRenderer me = this;
1001     final JLabel colour = new JLabel();
1002     colour.setOpaque(true);
1003     // colour.setBorder(BorderFactory.createEtchedBorder());
1004     colour.setMaximumSize(new Dimension(30, 16));
1005     colour.addMouseListener(new MouseAdapter()
1006     {
1007       FeatureColourChooser fcc = null;
1008
1009       public void mousePressed(MouseEvent evt)
1010       {
1011         if (fcol instanceof Color)
1012         {
1013           Color col = JColorChooser.showDialog(Desktop.desktop,
1014                   "Select Feature Colour", ((Color) fcol));
1015           if (col != null)
1016           {
1017             fcol = col;
1018             updateColourButton(bigPanel, colour, col);
1019           }
1020         }
1021         else
1022         {
1023
1024           if (fcc == null)
1025           {
1026             final String type = features[featureIndex].getType();
1027             fcc = new FeatureColourChooser(me, type);
1028             fcc.setRequestFocusEnabled(true);
1029             fcc.requestFocus();
1030
1031             fcc.addActionListener(new ActionListener()
1032             {
1033
1034               public void actionPerformed(ActionEvent e)
1035               {
1036                 fcol = fcc.getLastColour();
1037                 fcc = null;
1038                 setColour(type, fcol);
1039                 updateColourButton(bigPanel, colour, fcol);
1040               }
1041             });
1042
1043           }
1044         }
1045       }
1046     });
1047     JPanel tmp = new JPanel();
1048     JPanel panel = new JPanel(new GridLayout(3, 1));
1049
1050     // /////////////////////////////////////
1051     // /MULTIPLE FEATURES AT SELECTED RESIDUE
1052     if (!newFeatures && features.length > 1)
1053     {
1054       panel = new JPanel(new GridLayout(4, 1));
1055       tmp = new JPanel();
1056       tmp.add(new JLabel("Select Feature: "));
1057       overlaps = new JComboBox();
1058       for (int i = 0; i < features.length; i++)
1059       {
1060         overlaps.addItem(features[i].getType() + "/"
1061                 + features[i].getBegin() + "-" + features[i].getEnd()
1062                 + " (" + features[i].getFeatureGroup() + ")");
1063       }
1064
1065       tmp.add(overlaps);
1066
1067       overlaps.addItemListener(new ItemListener()
1068       {
1069         public void itemStateChanged(ItemEvent e)
1070         {
1071           int index = overlaps.getSelectedIndex();
1072           if (index != -1)
1073           {
1074             featureIndex = index;
1075             name.setText(features[index].getType());
1076             description.setText(features[index].getDescription());
1077             source.setText(features[index].getFeatureGroup());
1078             start.setValue(new Integer(features[index].getBegin()));
1079             end.setValue(new Integer(features[index].getEnd()));
1080
1081             SearchResults highlight = new SearchResults();
1082             highlight.addResult(sequences[0], features[index].getBegin(),
1083                     features[index].getEnd());
1084
1085             ap.seqPanel.seqCanvas.highlightSearchResults(highlight);
1086
1087           }
1088           Object col = getFeatureStyle(name.getText());
1089           if (col == null)
1090           {
1091             col = new jalview.schemes.UserColourScheme()
1092                     .createColourFromName(name.getText());
1093           }
1094           oldcol = fcol = col;
1095           updateColourButton(bigPanel, colour, col);
1096         }
1097       });
1098
1099       panel.add(tmp);
1100     }
1101     // ////////
1102     // ////////////////////////////////////
1103
1104     tmp = new JPanel();
1105     panel.add(tmp);
1106     tmp.add(new JLabel("Name: ", JLabel.RIGHT));
1107     tmp.add(name);
1108
1109     tmp = new JPanel();
1110     panel.add(tmp);
1111     tmp.add(new JLabel("Group: ", JLabel.RIGHT));
1112     tmp.add(source);
1113
1114     tmp = new JPanel();
1115     panel.add(tmp);
1116     tmp.add(new JLabel("Colour: ", JLabel.RIGHT));
1117     tmp.add(colour);
1118     colour.setPreferredSize(new Dimension(150, 15));
1119     colour.setFont(new java.awt.Font("Verdana", Font.PLAIN, 9));
1120     colour.setForeground(Color.black);
1121     colour.setHorizontalAlignment(SwingConstants.CENTER);
1122     colour.setVerticalAlignment(SwingConstants.CENTER);
1123     colour.setHorizontalTextPosition(SwingConstants.CENTER);
1124     colour.setVerticalTextPosition(SwingConstants.CENTER);
1125     bigPanel.add(panel, BorderLayout.NORTH);
1126
1127     panel = new JPanel();
1128     panel.add(new JLabel("Description: ", JLabel.RIGHT));
1129     description.setFont(JvSwingUtils.getTextAreaFont());
1130     description.setLineWrap(true);
1131     panel.add(new JScrollPane(description));
1132
1133     if (!newFeatures)
1134     {
1135       bigPanel.add(panel, BorderLayout.SOUTH);
1136
1137       panel = new JPanel();
1138       panel.add(new JLabel(" Start:", JLabel.RIGHT));
1139       panel.add(start);
1140       panel.add(new JLabel("  End:", JLabel.RIGHT));
1141       panel.add(end);
1142       bigPanel.add(panel, BorderLayout.CENTER);
1143     }
1144     else
1145     {
1146       bigPanel.add(panel, BorderLayout.CENTER);
1147     }
1148
1149     if (lastFeatureAdded == null)
1150     {
1151       if (features[0].type != null)
1152       {
1153         lastFeatureAdded = features[0].type;
1154       }
1155       else
1156       {
1157         lastFeatureAdded = "feature_1";
1158       }
1159     }
1160
1161     if (lastFeatureGroupAdded == null)
1162     {
1163       if (features[0].featureGroup != null)
1164       {
1165         lastFeatureGroupAdded = features[0].featureGroup;
1166       }
1167       else
1168       {
1169         lastFeatureGroupAdded = "Jalview";
1170       }
1171     }
1172
1173     if (newFeatures)
1174     {
1175       name.setText(lastFeatureAdded);
1176       source.setText(lastFeatureGroupAdded);
1177     }
1178     else
1179     {
1180       name.setText(features[0].getType());
1181       source.setText(features[0].getFeatureGroup());
1182     }
1183
1184     start.setValue(new Integer(features[0].getBegin()));
1185     end.setValue(new Integer(features[0].getEnd()));
1186     description.setText(features[0].getDescription());
1187     updateColourButton(bigPanel, colour,
1188             (oldcol = fcol = getFeatureStyle(name.getText())));
1189     Object[] options;
1190     if (!newFeatures)
1191     {
1192       options = new Object[]
1193       { "Amend", "Delete", "Cancel" };
1194     }
1195     else
1196     {
1197       options = new Object[]
1198       { "OK", "Cancel" };
1199     }
1200
1201     String title = newFeatures ? "Create New Sequence Feature(s)"
1202             : "Amend/Delete Features for " + sequences[0].getName();
1203
1204     int reply = JOptionPane.showInternalOptionDialog(Desktop.desktop,
1205             bigPanel, title, JOptionPane.YES_NO_CANCEL_OPTION,
1206             JOptionPane.QUESTION_MESSAGE, null, options, "OK");
1207
1208     jalview.io.FeaturesFile ffile = new jalview.io.FeaturesFile();
1209
1210     if (reply == JOptionPane.OK_OPTION && name.getText().length() > 0)
1211     {
1212       // This ensures that the last sequence
1213       // is refreshed and new features are rendered
1214       lastSeq = null;
1215       lastFeatureAdded = name.getText().trim();
1216       lastFeatureGroupAdded = source.getText().trim();
1217       lastDescriptionAdded = description.getText().replaceAll("\n", " ");
1218       // TODO: determine if the null feature group is valid
1219       if (lastFeatureGroupAdded.length() < 1)
1220         lastFeatureGroupAdded = null;
1221     }
1222
1223     if (!newFeatures)
1224     {
1225       SequenceFeature sf = features[featureIndex];
1226
1227       if (reply == JOptionPane.NO_OPTION)
1228       {
1229         sequences[0].getDatasetSequence().deleteFeature(sf);
1230       }
1231       else if (reply == JOptionPane.YES_OPTION)
1232       {
1233         sf.type = lastFeatureAdded;
1234         sf.featureGroup = lastFeatureGroupAdded;
1235         sf.description = lastDescriptionAdded;
1236
1237         setColour(sf.type, fcol);
1238         av.featuresDisplayed.put(sf.type, getColour(sf.type));
1239
1240         try
1241         {
1242           sf.begin = ((Integer) start.getValue()).intValue();
1243           sf.end = ((Integer) end.getValue()).intValue();
1244         } catch (NumberFormatException ex)
1245         {
1246         }
1247
1248         ffile.parseDescriptionHTML(sf, false);
1249       }
1250     }
1251     else
1252     // NEW FEATURES ADDED
1253     {
1254       if (reply == JOptionPane.OK_OPTION && lastFeatureAdded.length() > 0)
1255       {
1256         for (int i = 0; i < sequences.length; i++)
1257         {
1258           features[i].type = lastFeatureAdded;
1259           if (lastFeatureGroupAdded != null)
1260             features[i].featureGroup = lastFeatureGroupAdded;
1261           features[i].description = lastDescriptionAdded;
1262           sequences[i].addSequenceFeature(features[i]);
1263           ffile.parseDescriptionHTML(features[i], false);
1264         }
1265
1266         if (av.featuresDisplayed == null)
1267         {
1268           av.featuresDisplayed = new Hashtable();
1269         }
1270
1271         if (lastFeatureGroupAdded != null)
1272         {
1273           if (featureGroups == null)
1274             featureGroups = new Hashtable();
1275           featureGroups.put(lastFeatureGroupAdded, new Boolean(true));
1276         }
1277         setColour(lastFeatureAdded, fcol);
1278         av.featuresDisplayed.put(lastFeatureAdded,
1279                 getColour(lastFeatureAdded));
1280
1281         findAllFeatures(false);
1282
1283         ap.paintAlignment(true);
1284
1285         return true;
1286       }
1287       else
1288       {
1289         return false;
1290       }
1291     }
1292
1293     ap.paintAlignment(true);
1294
1295     return true;
1296   }
1297
1298   /**
1299    * update the amend feature button dependent on the given style
1300    * 
1301    * @param bigPanel
1302    * @param col
1303    * @param col2
1304    */
1305   protected void updateColourButton(JPanel bigPanel, JLabel colour,
1306           Object col2)
1307   {
1308     colour.removeAll();
1309     colour.setIcon(null);
1310     colour.setToolTipText(null);
1311     colour.setText("");
1312
1313     if (col2 instanceof Color)
1314     {
1315       colour.setBackground((Color) col2);
1316     }
1317     else
1318     {
1319       colour.setBackground(bigPanel.getBackground());
1320       colour.setForeground(Color.black);
1321       FeatureSettings.renderGraduatedColor(colour, (GraduatedColor) col2);
1322       // colour.setForeground(colour.getBackground());
1323     }
1324   }
1325
1326   public void setColour(String featureType, Object col)
1327   {
1328     // overwrite
1329     // Color _col = (col instanceof Color) ? ((Color) col) : (col instanceof
1330     // GraduatedColor) ? ((GraduatedColor) col).getMaxColor() : null;
1331     // Object c = featureColours.get(featureType);
1332     // if (c == null || c instanceof Color || (c instanceof GraduatedColor &&
1333     // !((GraduatedColor)c).getMaxColor().equals(_col)))
1334     {
1335       featureColours.put(featureType, col);
1336     }
1337   }
1338
1339   public void setTransparency(float value)
1340   {
1341     transparency = value;
1342   }
1343
1344   public float getTransparency()
1345   {
1346     return transparency;
1347   }
1348
1349   /**
1350    * Replace current ordering with new ordering
1351    * 
1352    * @param data
1353    *          { String(Type), Colour(Type), Boolean(Displayed) }
1354    */
1355   public void setFeaturePriority(Object[][] data)
1356   {
1357     setFeaturePriority(data, true);
1358   }
1359
1360   /**
1361    * 
1362    * @param data
1363    *          { String(Type), Colour(Type), Boolean(Displayed) }
1364    * @param visibleNew
1365    *          when true current featureDisplay list will be cleared
1366    */
1367   public void setFeaturePriority(Object[][] data, boolean visibleNew)
1368   {
1369     if (visibleNew)
1370     {
1371       if (av.featuresDisplayed != null)
1372       {
1373         av.featuresDisplayed.clear();
1374       }
1375       else
1376       {
1377         av.featuresDisplayed = new Hashtable();
1378       }
1379     }
1380     if (data == null)
1381     {
1382       return;
1383     }
1384
1385     // The feature table will display high priority
1386     // features at the top, but theses are the ones
1387     // we need to render last, so invert the data
1388     renderOrder = new String[data.length];
1389
1390     if (data.length > 0)
1391     {
1392       for (int i = 0; i < data.length; i++)
1393       {
1394         String type = data[i][0].toString();
1395         setColour(type, data[i][1]); // todo : typesafety - feature color
1396         // interface object
1397         if (((Boolean) data[i][2]).booleanValue())
1398         {
1399           av.featuresDisplayed.put(type, new Integer(getColour(type)
1400                   .getRGB()));
1401         }
1402
1403         renderOrder[data.length - i - 1] = type;
1404       }
1405     }
1406
1407   }
1408
1409   Map featureOrder = null;
1410
1411   /**
1412    * analogous to colour - store a normalized ordering for all feature types in
1413    * this rendering context.
1414    * 
1415    * @param type
1416    *          Feature type string
1417    * @param position
1418    *          normalized priority - 0 means always appears on top, 1 means
1419    *          always last.
1420    */
1421   public float setOrder(String type, float position)
1422   {
1423     if (featureOrder == null)
1424     {
1425       featureOrder = new Hashtable();
1426     }
1427     featureOrder.put(type, new Float(position));
1428     return position;
1429   }
1430
1431   /**
1432    * get the global priority (0 (top) to 1 (bottom))
1433    * 
1434    * @param type
1435    * @return [0,1] or -1 for a type without a priority
1436    */
1437   public float getOrder(String type)
1438   {
1439     if (featureOrder != null)
1440     {
1441       if (featureOrder.containsKey(type))
1442       {
1443         return ((Float) featureOrder.get(type)).floatValue();
1444       }
1445     }
1446     return -1;
1447   }
1448
1449   /**
1450    * @param listener
1451    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
1452    */
1453   public void addPropertyChangeListener(PropertyChangeListener listener)
1454   {
1455     changeSupport.addPropertyChangeListener(listener);
1456   }
1457
1458   /**
1459    * @param listener
1460    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
1461    */
1462   public void removePropertyChangeListener(PropertyChangeListener listener)
1463   {
1464     changeSupport.removePropertyChangeListener(listener);
1465   }
1466 }