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