b643efbfeab1aa14cfa8321694f0c588ece4678f
[jalview.git] / src / jalview / gui / FeatureRenderer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.util.*;
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
33 /**
34  * DOCUMENT ME!
35  *
36  * @author $author$
37  * @version $Revision$
38  */
39 public class FeatureRenderer
40 {
41   AlignmentPanel ap;
42   AlignViewport av;
43   Color resBoxColour;
44   float transparency = 1.0f;
45   FontMetrics fm;
46   int charOffset;
47
48   Hashtable featureColours = new Hashtable();
49
50   // A higher level for grouping features of a
51   // particular type
52   Hashtable featureGroups = new Hashtable();
53
54   // This is actually an Integer held in the hashtable,
55   // Retrieved using the key feature type
56   Object currentColour;
57
58   String[] renderOrder;
59   PropertyChangeSupport changeSupport=new PropertyChangeSupport(this);
60
61   Vector allfeatures;
62
63   /**
64    * Creates a new FeatureRenderer object.
65    *
66    * @param av
67    *          DOCUMENT ME!
68    */
69   public FeatureRenderer(AlignmentPanel ap)
70   {
71     this.ap = ap;
72     this.av = ap.av;
73   }
74
75   public class FeatureRendererSettings implements Cloneable {
76     String[] renderOrder;
77     Hashtable featureGroups;
78     Hashtable featureColours;
79     float transparency;
80     Hashtable featureOrder;
81     public FeatureRendererSettings(String[] renderOrder,
82             Hashtable featureGroups, Hashtable featureColours,
83             float transparency, Hashtable featureOrder)
84     {
85       super();
86       this.renderOrder = renderOrder;
87       this.featureGroups = featureGroups;
88       this.featureColours = featureColours;
89       this.transparency = transparency;
90       this.featureOrder = featureOrder;
91     }
92     public FeatureRendererSettings(FeatureRenderer fr)
93     {
94       this.renderOrder = fr.renderOrder;
95       this.featureGroups = fr.featureGroups;
96       this.featureColours = fr.featureColours;
97       this.transparency = fr.transparency;
98       this.featureOrder = fr.featureOrder;
99     }
100   }
101   public FeatureRendererSettings getSettings()
102   {
103     return new FeatureRendererSettings(this);
104   }
105   public void transferSettings(FeatureRendererSettings fr)
106   {
107     this.renderOrder = fr.renderOrder;
108     this.featureGroups = fr.featureGroups;
109     this.featureColours = fr.featureColours;
110     this.transparency = fr.transparency;
111     this.featureOrder = fr.featureOrder;
112   }
113   public void transferSettings(FeatureRenderer fr)
114   {
115     this.renderOrder = fr.renderOrder;
116     this.featureGroups = fr.featureGroups;
117     this.featureColours = fr.featureColours;
118     this.transparency = fr.transparency;
119     this.featureOrder = fr.featureOrder;
120   }
121
122   BufferedImage offscreenImage;
123   boolean offscreenRender = false;
124   public Color findFeatureColour(Color initialCol, SequenceI seq, int res)
125   {
126     return new Color(findFeatureColour(initialCol.getRGB(),
127                                        seq, res));
128   }
129
130   /**
131    * This is used by the Molecule Viewer and Overview to get the accurate
132    * colourof the rendered sequence
133    */
134   public int findFeatureColour(int initialCol, SequenceI seq, int column)
135   {
136     if (!av.showSequenceFeatures)
137     {
138       return initialCol;
139     }
140
141     if (seq != lastSeq)
142     {
143       lastSeq = seq;
144       sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
145       if (sequenceFeatures!=null)
146       {
147         sfSize = sequenceFeatures.length;
148       }
149     }
150
151     if (sequenceFeatures!=lastSeq.getDatasetSequence().getSequenceFeatures()) {
152       sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
153       if (sequenceFeatures != null)
154       {
155         sfSize = sequenceFeatures.length;
156       }
157     }
158
159     if (sequenceFeatures == null || sfSize==0)
160     {
161       return initialCol;
162     }
163
164
165     if (jalview.util.Comparison.isGap(lastSeq.getCharAt(column)))
166     {
167       return Color.white.getRGB();
168     }
169
170     // Only bother making an offscreen image if transparency is applied
171     if (transparency != 1.0f && offscreenImage == null)
172     {
173       offscreenImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
174     }
175
176     currentColour = null;
177
178     offscreenRender = true;
179
180     if (offscreenImage != null)
181     {
182       offscreenImage.setRGB(0, 0, initialCol);
183       drawSequence(offscreenImage.getGraphics(),
184                    lastSeq,
185                    column, column, 0);
186
187       return offscreenImage.getRGB(0, 0);
188     }
189     else
190     {
191       drawSequence(null,
192                    lastSeq,
193                    lastSeq.findPosition(column),
194                    -1, -1);
195
196       if (currentColour == null)
197       {
198         return initialCol;
199       }
200       else
201       {
202         return ( (Integer) currentColour).intValue();
203       }
204     }
205
206   }
207
208   /**
209    * DOCUMENT ME!
210    *
211    * @param g
212    *          DOCUMENT ME!
213    * @param seq
214    *          DOCUMENT ME!
215    * @param sg
216    *          DOCUMENT ME!
217    * @param start
218    *          DOCUMENT ME!
219    * @param end
220    *          DOCUMENT ME!
221    * @param x1
222    *          DOCUMENT ME!
223    * @param y1
224    *          DOCUMENT ME!
225    * @param width
226    *          DOCUMENT ME!
227    * @param height
228    *          DOCUMENT ME!
229    */
230   // String type;
231   // SequenceFeature sf;
232   SequenceI lastSeq;
233   SequenceFeature[] sequenceFeatures;
234   int sfSize, sfindex, spos, epos;
235
236   synchronized public void drawSequence(Graphics g, SequenceI seq,
237                            int start, int end, int y1)
238   {
239
240     if (seq.getDatasetSequence().getSequenceFeatures() == null
241         || seq.getDatasetSequence().getSequenceFeatures().length == 0)
242     {
243       return;
244     }
245
246     if (g != null)
247     {
248       fm = g.getFontMetrics();
249     }
250
251     if (av.featuresDisplayed == null
252         || renderOrder == null
253         || newFeatureAdded)
254     {
255       findAllFeatures();
256       if (av.featuresDisplayed.size() < 1)
257       {
258         return;
259       }
260
261       sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
262     }
263
264     if (lastSeq == null || seq != lastSeq
265         || seq.getDatasetSequence().getSequenceFeatures()!=sequenceFeatures)
266     {
267       lastSeq = seq;
268       sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
269     }
270
271     if (transparency != 1 && g != null)
272     {
273       Graphics2D g2 = (Graphics2D) g;
274       g2.setComposite(
275           AlphaComposite.getInstance(
276               AlphaComposite.SRC_OVER, transparency));
277     }
278
279     if (!offscreenRender)
280     {
281       spos = lastSeq.findPosition(start);
282       epos = lastSeq.findPosition(end);
283     }
284
285     sfSize = sequenceFeatures.length;
286     String type;
287     for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
288     {
289       type = renderOrder[renderIndex];
290
291       if (type == null || !av.featuresDisplayed.containsKey(type))
292       {
293         continue;
294       }
295
296       // loop through all features in sequence to find
297       // current feature to render
298       for (sfindex = 0; sfindex < sfSize; sfindex++)
299       {
300         if (!sequenceFeatures[sfindex].type.equals(type))
301         {
302           continue;
303         }
304
305         if (featureGroups != null
306             && sequenceFeatures[sfindex].featureGroup != null
307             &&
308             sequenceFeatures[sfindex].featureGroup.length()!=0
309             && featureGroups.containsKey(sequenceFeatures[sfindex].featureGroup)
310             &&
311             ! ( (Boolean) featureGroups.get(sequenceFeatures[sfindex].
312                                             featureGroup)).
313             booleanValue())
314         {
315           continue;
316         }
317
318         if (!offscreenRender && (sequenceFeatures[sfindex].getBegin() > epos
319                                  || sequenceFeatures[sfindex].getEnd() < spos))
320         {
321           continue;
322         }
323
324         if (offscreenRender && offscreenImage == null)
325         {
326           if (sequenceFeatures[sfindex].begin <= start &&
327               sequenceFeatures[sfindex].end >= start)
328           {
329             currentColour = av.featuresDisplayed.get(sequenceFeatures[sfindex].
330                 type);
331           }
332         }
333         else if (sequenceFeatures[sfindex].type.equals("disulfide bond"))
334         {
335
336           renderFeature(g, seq,
337                         seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
338                         seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
339                         new Color( ( (Integer) av.featuresDisplayed.get(
340                             sequenceFeatures[sfindex].type)).intValue()),
341                         start, end, y1);
342           renderFeature(g, seq,
343                         seq.findIndex(sequenceFeatures[sfindex].end) - 1,
344                         seq.findIndex(sequenceFeatures[sfindex].end) - 1,
345                         new Color( ( (Integer) av.featuresDisplayed.get(
346                             sequenceFeatures[sfindex].type)).intValue()),
347                         start, end, y1);
348
349         }
350         else
351         {
352           renderFeature(g, seq,
353                         seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
354                         seq.findIndex(sequenceFeatures[sfindex].end) - 1,
355                         getColour(sequenceFeatures[sfindex].type),
356                         start, end, y1);
357         }
358
359       }
360
361     }
362
363     if (transparency != 1.0f && g != null)
364     {
365       Graphics2D g2 = (Graphics2D) g;
366       g2.setComposite(
367           AlphaComposite.getInstance(
368               AlphaComposite.SRC_OVER, 1.0f));
369     }
370   }
371
372   char s;
373   int i;
374   void renderFeature(Graphics g, SequenceI seq,
375                      int fstart, int fend, Color featureColour, int start,
376                      int end, int y1)
377   {
378
379     if ( ( (fstart <= end) && (fend >= start)))
380     {
381       if (fstart < start)
382       { // fix for if the feature we have starts before the sequence start,
383         fstart = start; // but the feature end is still valid!!
384       }
385
386       if (fend >= end)
387       {
388         fend = end;
389       }
390       int pady = (y1 + av.charHeight) - av.charHeight / 5;
391       for (i = fstart; i <= fend; i++)
392       {
393         s = seq.getCharAt(i);
394
395         if (jalview.util.Comparison.isGap(s))
396         {
397           continue;
398         }
399
400         g.setColor(featureColour);
401
402         g.fillRect( (i - start) * av.charWidth, y1, av.charWidth, av.charHeight);
403
404         if (offscreenRender || !av.validCharWidth)
405         {
406           continue;
407         }
408
409         g.setColor(Color.white);
410         charOffset = (av.charWidth - fm.charWidth(s)) / 2;
411         g.drawString(String.valueOf(s),
412                      charOffset + (av.charWidth * (i - start)),
413                      pady);
414
415       }
416     }
417   }
418
419   boolean newFeatureAdded = false;
420   /**
421    * Called when alignment in associated view has new/modified features
422    * to discover and display.
423    *
424    */
425   public void featuresAdded()
426   {
427     lastSeq=null;
428     findAllFeatures();
429   }
430
431   boolean findingFeatures = false;
432   /**
433    * search the alignment for all new features, give them a colour and display
434    * them. Then fires a PropertyChangeEvent on the changeSupport object.
435    *
436    */
437   void findAllFeatures()
438   {
439     synchronized (firing)
440     {
441         if (firing.equals(Boolean.FALSE)) {
442           firing=Boolean.TRUE;
443           findAllFeatures(true); // add all new features as visible
444           changeSupport.firePropertyChange("changeSupport",null,null);
445           firing=Boolean.FALSE;
446       }
447     }
448   }
449   /**
450    * Searches alignment for all features and updates colours
451    *
452    * @param newMadeVisible
453    *          if true newly added feature types will be rendered immediatly
454    */
455   synchronized void findAllFeatures(boolean newMadeVisible) {
456     newFeatureAdded = false;
457
458     if (findingFeatures)
459     {
460       newFeatureAdded = true;
461       return;
462     }
463
464     findingFeatures = true;
465
466     if (av.featuresDisplayed == null)
467     {
468       av.featuresDisplayed = new Hashtable();
469     }
470
471     allfeatures = new Vector();
472     Vector oldfeatures = new Vector();
473     if (renderOrder!=null)
474     {
475       for (int i=0; i<renderOrder.length; i++) {
476         if (renderOrder[i]!=null)
477         {
478           oldfeatures.addElement(renderOrder[i]);
479         }
480       }
481     }
482     for (int i = 0; i < av.alignment.getHeight(); i++)
483     {
484       SequenceFeature[] features
485           = av.alignment.getSequenceAt(i).getDatasetSequence().
486           getSequenceFeatures();
487
488       if (features == null)
489       {
490         continue;
491       }
492
493       int index = 0;
494       while (index < features.length)
495       {
496         if (!av.featuresDisplayed.containsKey(features[index].getType()))
497         {
498
499           if(featureGroups.containsKey(features[index].getType()))
500           {
501             boolean visible = ( (Boolean) featureGroups.get(
502                 features[index].featureGroup)).booleanValue();
503
504             if(!visible)
505             {
506               index++;
507               continue;
508             }
509           }
510
511
512           if (! (features[index].begin == 0 && features[index].end == 0))
513           {
514             // If beginning and end are 0, the feature is for the whole sequence
515             // and we don't want to render the feature in the normal way
516
517             if (newMadeVisible && !oldfeatures.contains(features[index].getType())) {
518               // this is a new feature type on the alignment. Mark it for
519               // display.
520               av.featuresDisplayed.put(features[index].getType(),
521                                      new Integer(getColour(features[index].
522                 getType()).getRGB()));
523               setOrder(features[index].getType(),0);
524             }
525            }
526         }
527         if (!allfeatures.contains(features[index].getType()))
528         {
529           allfeatures.addElement(features[index].getType());
530         }
531         index++;
532       }
533     }
534     updateRenderOrder(allfeatures);
535     findingFeatures = false;
536   }
537   protected Boolean firing=Boolean.FALSE;
538   /**
539    * replaces the current renderOrder with the unordered features in allfeatures.
540    * The ordering of any types in both renderOrder and allfeatures is preserved,
541    * and all new feature types are rendered on top of the existing types, in
542    * the order given by getOrder or the order given in allFeatures.
543    * Note. this operates directly on the featureOrder hash for efficiency. TODO:
544    * eliminate the float storage for computing/recalling the persistent ordering
545    *
546    * @param allFeatures
547    */
548   private void updateRenderOrder(Vector allFeatures) {
549     Vector allfeatures = new Vector(allFeatures);
550     String[] oldRender = renderOrder;
551     renderOrder = new String[allfeatures.size()];
552     boolean initOrders=(featureOrder==null);
553     int opos=0;
554     if (oldRender!=null && oldRender.length>0)
555     {
556       for (int j=0; j<oldRender.length; j++)
557       {
558         if (oldRender[j]!=null)
559           {
560             if (initOrders)
561             {
562               setOrder(oldRender[j], (1-(1+(float)j)/(float) oldRender.length));
563             }
564             if (allfeatures.contains(oldRender[j])) {
565               renderOrder[opos++]  = oldRender[j]; // existing features always
566                                                     // appear below new features
567               allfeatures.removeElement(oldRender[j]);
568             }
569           }
570         }
571     }
572     if (allfeatures.size()==0) {
573       // no new features - leave order unchanged.
574       return;
575     }
576     int i=allfeatures.size()-1;
577     int iSize=i;
578     boolean sort=false;
579     String[] newf = new String[allfeatures.size()];
580     float[] sortOrder = new float[allfeatures.size()];
581     Enumeration en = allfeatures.elements();
582     // sort remaining elements
583     while (en.hasMoreElements())
584     {
585       newf[i] = en.nextElement().toString();
586       if (initOrders || !featureOrder.containsKey(newf[i]))
587       {
588         int denom = initOrders ? allfeatures.size() : featureOrder.size();
589           // new unordered feature - compute persistent ordering at head of
590           // existing features.
591         setOrder(newf[i], i/(float) denom);
592       }
593       // set order from newly found feature from persisted ordering.
594       sortOrder[i] = 2-((Float) featureOrder.get(newf[i])).floatValue();
595       if (i<iSize)
596       {
597         // only sort if we need to
598         sort = sort || sortOrder[i]>sortOrder[i+1];
599       }
600       i--;
601     }
602     if (iSize>1 && sort)
603       jalview.util.QuickSort.sort(sortOrder, newf);
604     sortOrder=null;
605     System.arraycopy(newf, 0, renderOrder, opos, newf.length);
606   }
607   public Color getColour(String featureType)
608   {
609     if (!featureColours.containsKey(featureType))
610     {
611       jalview.schemes.UserColourScheme ucs = new
612           jalview.schemes.UserColourScheme();
613       Color col = ucs.createColourFromName(featureType);
614       featureColours.put(featureType, col);
615       return col;
616     }
617     else
618       return (Color) featureColours.get(featureType);
619   }
620
621   static String lastFeatureAdded;
622   static String lastFeatureGroupAdded;
623   static String lastDescriptionAdded;
624
625   int featureIndex = 0;
626   boolean amendFeatures(final SequenceI[] sequences,
627                         final SequenceFeature[] features,
628                         boolean newFeatures,
629                         final AlignmentPanel ap)
630   {
631
632     featureIndex = 0;
633
634     JPanel bigPanel = new JPanel(new BorderLayout());
635     final JComboBox overlaps;
636     final JTextField name = new JTextField(25);
637     final JTextField source = new JTextField(25);
638     final JTextArea description = new JTextArea(3, 25);
639     final JSpinner start = new JSpinner();
640     final JSpinner end = new JSpinner();
641     start.setPreferredSize(new Dimension(80, 20));
642     end.setPreferredSize(new Dimension(80, 20));
643
644     final JPanel colour = new JPanel();
645     colour.setBorder(BorderFactory.createEtchedBorder());
646     colour.setMaximumSize(new Dimension(40, 10));
647     colour.addMouseListener(new MouseAdapter()
648     {
649       public void mousePressed(MouseEvent evt)
650       {
651         Color col = JColorChooser.showDialog(Desktop.desktop,
652                                              "Select Feature Colour",
653                                              colour.getBackground());
654         if (col != null)
655           colour.setBackground(col);
656
657       }
658     });
659
660     JPanel tmp = new JPanel();
661     JPanel panel = new JPanel(new GridLayout(3, 1));
662
663     ///////////////////////////////////////
664     ///MULTIPLE FEATURES AT SELECTED RESIDUE
665     if(!newFeatures && features.length>1)
666     {
667      panel = new JPanel(new GridLayout(4, 1));
668      tmp = new JPanel();
669      tmp.add(new JLabel("Select Feature: "));
670      overlaps = new JComboBox();
671      for(int i=0; i<features.length; i++)
672      {
673        overlaps.addItem(features[i].getType()
674         +"/"+features[i].getBegin()+"-"+features[i].getEnd()
675         +" ("+features[i].getFeatureGroup()+")");
676      }
677
678      tmp.add(overlaps);
679
680      overlaps.addItemListener(new ItemListener()
681      {
682        public void itemStateChanged(ItemEvent e)
683        {
684          int index = overlaps.getSelectedIndex();
685          if (index != -1)
686          {
687            featureIndex = index;
688            name.setText(features[index].getType());
689            description.setText(features[index].getDescription());
690            source.setText(features[index].getFeatureGroup());
691            start.setValue(new Integer(features[index].getBegin()));
692            end.setValue(new Integer(features[index].getEnd()));
693
694            SearchResults highlight = new SearchResults();
695            highlight.addResult(sequences[0],
696                                features[index].getBegin(),
697                                features[index].getEnd());
698
699            ap.seqPanel.seqCanvas.highlightSearchResults(highlight);
700
701          }
702          Color col = getColour(name.getText());
703          if (col == null)
704          {
705            col = new
706                jalview.schemes.UserColourScheme()
707                .createColourFromName(name.getText());
708          }
709
710          colour.setBackground(col);
711        }
712      });
713
714
715      panel.add(tmp);
716     }
717     //////////
718     //////////////////////////////////////
719
720     tmp = new JPanel();
721     panel.add(tmp);
722     tmp.add(new JLabel("Name: ", JLabel.RIGHT));
723     tmp.add(name);
724
725     tmp = new JPanel();
726     panel.add(tmp);
727     tmp.add(new JLabel("Group: ", JLabel.RIGHT));
728     tmp.add(source);
729
730     tmp = new JPanel();
731     panel.add(tmp);
732     tmp.add(new JLabel("Colour: ", JLabel.RIGHT));
733     tmp.add(colour);
734     colour.setPreferredSize(new Dimension(150, 15));
735
736     bigPanel.add(panel, BorderLayout.NORTH);
737
738     panel = new JPanel();
739     panel.add(new JLabel("Description: ", JLabel.RIGHT));
740     description.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
741     description.setLineWrap(true);
742     panel.add(new JScrollPane(description));
743
744     if (!newFeatures)
745     {
746       bigPanel.add(panel, BorderLayout.SOUTH);
747
748       panel = new JPanel();
749       panel.add(new JLabel(" Start:", JLabel.RIGHT));
750       panel.add(start);
751       panel.add(new JLabel("  End:", JLabel.RIGHT));
752       panel.add(end);
753       bigPanel.add(panel, BorderLayout.CENTER);
754     }
755     else
756     {
757       bigPanel.add(panel, BorderLayout.CENTER);
758     }
759
760     if (lastFeatureAdded == null)
761     {
762       if (features[0].type != null)
763       {
764         lastFeatureAdded = features[0].type;
765       }
766       else
767       {
768         lastFeatureAdded = "feature_1";
769       }
770     }
771
772     if (lastFeatureGroupAdded == null)
773     {
774       if (features[0].featureGroup != null)
775       {
776         lastFeatureGroupAdded = features[0].featureGroup;
777       }
778       else
779       {
780         lastFeatureGroupAdded = "Jalview";
781       }
782     }
783
784     if(newFeatures)
785     {
786       name.setText(lastFeatureAdded);
787       source.setText(lastFeatureGroupAdded);
788     }
789     else
790     {
791       name.setText(features[0].getType());
792       source.setText(features[0].getFeatureGroup());
793     }
794
795     start.setValue(new Integer(features[0].getBegin()));
796     end.setValue(new Integer(features[0].getEnd()));
797     description.setText(features[0].getDescription());
798     colour.setBackground(getColour(name.getText()));
799
800
801     Object[] options;
802     if (!newFeatures)
803     {
804       options = new Object[]
805           {
806           "Amend", "Delete", "Cancel"};
807     }
808     else
809     {
810       options = new Object[]
811           {
812           "OK", "Cancel"};
813     }
814
815     String title = newFeatures ? "Create New Sequence Feature(s)" :
816         "Amend/Delete Features for "
817         + sequences[0].getName();
818
819     int reply = JOptionPane.showInternalOptionDialog(Desktop.desktop,
820         bigPanel,
821         title,
822         JOptionPane.YES_NO_CANCEL_OPTION,
823         JOptionPane.QUESTION_MESSAGE,
824         null,
825         options, "OK");
826
827     jalview.io.FeaturesFile ffile = new jalview.io.FeaturesFile();
828
829     if (reply == JOptionPane.OK_OPTION && name.getText().length()>0)
830     {
831       // This ensures that the last sequence
832       // is refreshed and new features are rendered
833       lastSeq = null;
834       lastFeatureAdded = name.getText().trim();
835       lastFeatureGroupAdded = source.getText().trim();
836       lastDescriptionAdded = description.getText().replaceAll("\n", " ");
837
838       if(lastFeatureGroupAdded.length()<1)
839         lastFeatureGroupAdded = null;
840     }
841
842     if (!newFeatures)
843     {
844       SequenceFeature sf = features[featureIndex];
845
846       if (reply == JOptionPane.NO_OPTION)
847       {
848         sequences[0].getDatasetSequence().deleteFeature(sf);
849       }
850       else if (reply == JOptionPane.YES_OPTION)
851       {
852         sf.type = lastFeatureAdded;
853         sf.featureGroup = lastFeatureGroupAdded;
854         sf.description = lastDescriptionAdded;
855
856         setColour(sf.type, colour.getBackground());
857         av.featuresDisplayed.put(sf.type,
858                                  new Integer(colour.getBackground().getRGB()));
859
860         try
861         {
862           sf.begin = ( (Integer) start.getValue()).intValue();
863           sf.end = ( (Integer) end.getValue()).intValue();
864         }
865         catch (NumberFormatException ex)
866         {}
867
868         ffile.parseDescriptionHTML(sf, false);
869       }
870     }
871     else //NEW FEATURES ADDED
872     {
873       if (reply == JOptionPane.OK_OPTION
874           && lastFeatureAdded.length()>0)
875       {
876         for (int i = 0; i < sequences.length; i++)
877         {
878           features[i].type = lastFeatureAdded;
879           if (lastFeatureGroupAdded!=null)
880             features[i].featureGroup = lastFeatureGroupAdded;
881           features[i].description = lastDescriptionAdded;
882           sequences[i].addSequenceFeature(features[i]);
883           ffile.parseDescriptionHTML(features[i], false);
884         }
885
886         if (av.featuresDisplayed == null)
887         {
888           av.featuresDisplayed = new Hashtable();
889         }
890
891         if (lastFeatureGroupAdded != null)
892         {
893           if (featureGroups == null)
894             featureGroups = new Hashtable();
895           featureGroups.put(lastFeatureGroupAdded, new Boolean(true));
896         }
897
898         Color col = colour.getBackground();
899         setColour(lastFeatureAdded, colour.getBackground());
900         av.featuresDisplayed.put(lastFeatureAdded,
901                                    new Integer(col.getRGB()));
902
903         findAllFeatures(false);
904
905         ap.paintAlignment(true);
906
907
908         return true;
909       }
910       else
911       {
912         return false;
913       }
914     }
915
916     ap.paintAlignment(true);
917
918     return true;
919   }
920
921   public void setColour(String featureType, Color col)
922   {
923     featureColours.put(featureType, col);
924   }
925
926   public void setTransparency(float value)
927   {
928     transparency = value;
929   }
930
931   public float getTransparency()
932   {
933     return transparency;
934   }
935   /**
936    * Replace current ordering with new ordering
937    * @param data { String(Type), Colour(Type), Boolean(Displayed) }
938    */
939   public void setFeaturePriority(Object[][] data)
940   {
941     setFeaturePriority(data, true);
942   }
943   /**
944    *
945    * @param data { String(Type), Colour(Type), Boolean(Displayed) }
946    * @param visibleNew when true current featureDisplay list will be cleared
947    */
948   public void setFeaturePriority(Object[][] data, boolean visibleNew)
949   {
950     if (visibleNew)
951       {
952       if (av.featuresDisplayed != null)
953       {
954         av.featuresDisplayed.clear();
955       }
956       else
957       {
958         av.featuresDisplayed = new Hashtable();
959       }
960     }
961     if (data==null)
962     {
963       return;
964     }
965
966     // The feature table will display high priority
967     // features at the top, but theses are the ones
968     // we need to render last, so invert the data
969     renderOrder = new String[data.length];
970
971     if (data.length > 0)
972     {
973       for (int i = 0; i < data.length; i++)
974       {
975         String type = data[i][0].toString();
976         setColour(type, (Color) data[i][1]);
977         if ( ( (Boolean) data[i][2]).booleanValue())
978         {
979           av.featuresDisplayed.put(type, new Integer(getColour(type).getRGB()));
980         }
981
982         renderOrder[data.length - i - 1] = type;
983       }
984     }
985
986   }
987   Hashtable featureOrder=null;
988   /**
989    * analogous to colour - store a normalized ordering for all feature types in
990    * this rendering context.
991    *
992    * @param type
993    *          Feature type string
994    * @param position
995    *          normalized priority - 0 means always appears on top, 1 means
996    *          always last.
997    */
998   public float setOrder(String type, float position)
999   {
1000     if (featureOrder==null)
1001     {
1002       featureOrder = new Hashtable();
1003     }
1004     featureOrder.put(type, new Float(position));
1005     return position;
1006   }
1007   /**
1008    * get the global priority (0 (top) to 1 (bottom))
1009    *
1010    * @param type
1011    * @return [0,1] or -1 for a type without a priority
1012    */
1013   public float getOrder(String type) {
1014     if (featureOrder!=null)
1015     {
1016       if (featureOrder.containsKey(type))
1017       {
1018         return ((Float)featureOrder.get(type)).floatValue();
1019       }
1020     }
1021     return -1;
1022   }
1023
1024   /**
1025    * @param listener
1026    * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
1027    */
1028   public void addPropertyChangeListener(PropertyChangeListener listener)
1029   {
1030     changeSupport.addPropertyChangeListener(listener);
1031   }
1032
1033   /**
1034    * @param listener
1035    * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
1036    */
1037   public void removePropertyChangeListener(PropertyChangeListener listener)
1038   {
1039     changeSupport.removePropertyChangeListener(listener);
1040   }
1041 }