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