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