2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
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.
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.
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
24 import java.awt.event.*;
25 import java.awt.image.*;
26 import java.beans.PropertyChangeListener;
27 import java.beans.PropertyChangeSupport;
31 import jalview.datamodel.*;
39 public class FeatureRenderer
43 float transparency = 1.0f;
47 Hashtable featureColours = new Hashtable();
49 // A higher level for grouping features of a
51 Hashtable featureGroups = null;
53 // This is actually an Integer held in the hashtable,
54 // Retrieved using the key feature type
58 PropertyChangeSupport changeSupport=new PropertyChangeSupport(this);
63 * Creates a new FeatureRenderer object.
68 public FeatureRenderer(AlignViewport av)
73 public void transferSettings(FeatureRenderer fr)
75 renderOrder = fr.renderOrder;
76 featureGroups = fr.featureGroups;
77 featureColours = fr.featureColours;
78 transparency = fr.transparency;
79 featureOrder = fr.featureOrder;
82 BufferedImage offscreenImage;
83 boolean offscreenRender = false;
84 public Color findFeatureColour(Color initialCol, SequenceI seq, int res)
86 return new Color(findFeatureColour(initialCol.getRGB(),
91 * This is used by the Molecule Viewer and Overview to get the accurate
92 * colourof the rendered sequence
94 public int findFeatureColour(int initialCol, SequenceI seq, int column)
96 if (!av.showSequenceFeatures)
104 sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
105 if (sequenceFeatures!=null)
107 sfSize = sequenceFeatures.length;
111 if (sequenceFeatures!=lastSeq.getDatasetSequence().getSequenceFeatures()) {
112 sequenceFeatures = lastSeq.getDatasetSequence().getSequenceFeatures();
113 if (sequenceFeatures != null)
115 sfSize = sequenceFeatures.length;
119 if (sequenceFeatures == null)
125 if (jalview.util.Comparison.isGap(lastSeq.getCharAt(column)))
127 return Color.white.getRGB();
130 // Only bother making an offscreen image if transparency is applied
131 if (transparency != 1.0f && offscreenImage == null)
133 offscreenImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
136 currentColour = null;
138 offscreenRender = true;
140 if (offscreenImage != null)
142 offscreenImage.setRGB(0, 0, initialCol);
143 drawSequence(offscreenImage.getGraphics(),
147 return offscreenImage.getRGB(0, 0);
153 lastSeq.findPosition(column),
156 if (currentColour == null)
162 return ( (Integer) currentColour).intValue();
191 // SequenceFeature sf;
193 SequenceFeature[] sequenceFeatures;
194 int sfSize, sfindex, spos, epos;
196 public void drawSequence(Graphics g, SequenceI seq,
197 int start, int end, int y1)
199 if (seq.getDatasetSequence().getSequenceFeatures() == null
200 || seq.getDatasetSequence().getSequenceFeatures().length == 0)
207 fm = g.getFontMetrics();
210 if (av.featuresDisplayed == null
211 || renderOrder == null
215 if (av.featuresDisplayed.size() < 1)
220 sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
221 sfSize = sequenceFeatures.length;
224 if (lastSeq == null || seq != lastSeq
225 || seq.getDatasetSequence().getSequenceFeatures()!=sequenceFeatures)
228 sequenceFeatures = seq.getDatasetSequence().getSequenceFeatures();
229 sfSize = sequenceFeatures.length;
232 if (transparency != 1 && g != null)
234 Graphics2D g2 = (Graphics2D) g;
236 AlphaComposite.getInstance(
237 AlphaComposite.SRC_OVER, transparency));
240 if (!offscreenRender)
242 spos = lastSeq.findPosition(start);
243 epos = lastSeq.findPosition(end);
247 for (int renderIndex = 0; renderIndex < renderOrder.length; renderIndex++)
249 type = renderOrder[renderIndex];
251 if (type == null || !av.featuresDisplayed.containsKey(type))
256 // loop through all features in sequence to find
257 // current feature to render
258 for (sfindex = 0; sfindex < sfSize; sfindex++)
260 if (sequenceFeatures.length <= sfindex)
264 if (!sequenceFeatures[sfindex].type.equals(type))
269 if (featureGroups != null
270 && sequenceFeatures[sfindex].featureGroup != null
272 featureGroups.containsKey(sequenceFeatures[sfindex].featureGroup)
274 ! ( (Boolean) featureGroups.get(sequenceFeatures[sfindex].
281 if (!offscreenRender && (sequenceFeatures[sfindex].getBegin() > epos
282 || sequenceFeatures[sfindex].getEnd() < spos))
287 if (offscreenRender && offscreenImage == null)
289 if (sequenceFeatures[sfindex].begin <= start &&
290 sequenceFeatures[sfindex].end >= start)
292 currentColour = av.featuresDisplayed.get(sequenceFeatures[sfindex].
296 else if (sequenceFeatures[sfindex].type.equals("disulfide bond"))
299 renderFeature(g, seq,
300 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
301 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
302 new Color( ( (Integer) av.featuresDisplayed.get(
303 sequenceFeatures[sfindex].type)).intValue()),
305 renderFeature(g, seq,
306 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
307 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
308 new Color( ( (Integer) av.featuresDisplayed.get(
309 sequenceFeatures[sfindex].type)).intValue()),
315 renderFeature(g, seq,
316 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
317 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
318 getColour(sequenceFeatures[sfindex].type),
326 if (transparency != 1.0f && g != null)
328 Graphics2D g2 = (Graphics2D) g;
330 AlphaComposite.getInstance(
331 AlphaComposite.SRC_OVER, 1.0f));
337 void renderFeature(Graphics g, SequenceI seq,
338 int fstart, int fend, Color featureColour, int start,
342 if ( ( (fstart <= end) && (fend >= start)))
345 { // fix for if the feature we have starts before the sequence start,
346 fstart = start; // but the feature end is still valid!!
353 int pady = (y1 + av.charHeight) - av.charHeight / 5;
354 for (i = fstart; i <= fend; i++)
356 s = seq.getCharAt(i);
358 if (jalview.util.Comparison.isGap(s))
363 g.setColor(featureColour);
365 g.fillRect( (i - start) * av.charWidth, y1, av.charWidth, av.charHeight);
367 if (offscreenRender || !av.validCharWidth)
372 g.setColor(Color.white);
373 charOffset = (av.charWidth - fm.charWidth(s)) / 2;
374 g.drawString(String.valueOf(s),
375 charOffset + (av.charWidth * (i - start)),
382 boolean newFeatureAdded = false;
384 * Called when alignment in associated view has new/modified features
385 * to discover and display.
388 public void featuresAdded()
394 boolean findingFeatures = false;
396 * search the alignment for all new features, give them a colour and display
397 * them. Then fires a PropertyChangeEvent on the changeSupport object.
400 synchronized void findAllFeatures()
402 findAllFeatures(true); // add all new features as visible
405 changeSupport.firePropertyChange("changeSupport",null,null);
410 * Searches alignment for all features and updates colours
412 * @param newMadeVisible
413 * if true newly added feature types will be rendered immediatly
415 synchronized void findAllFeatures(boolean newMadeVisible) {
416 newFeatureAdded = false;
420 newFeatureAdded = true;
424 findingFeatures = true;
426 if (av.featuresDisplayed == null)
428 av.featuresDisplayed = new Hashtable();
431 allfeatures = new Vector();
432 Vector oldfeatures = new Vector();
433 if (renderOrder!=null)
435 for (int i=0; i<renderOrder.length; i++) {
436 if (renderOrder[i]!=null)
438 oldfeatures.addElement(renderOrder[i]);
442 for (int i = 0; i < av.alignment.getHeight(); i++)
444 SequenceFeature[] features
445 = av.alignment.getSequenceAt(i).getDatasetSequence().
446 getSequenceFeatures();
448 if (features == null)
454 while (index < features.length)
456 if (!av.featuresDisplayed.containsKey(features[index].getType()))
458 if (! (features[index].begin == 0 && features[index].end == 0))
460 // If beginning and end are 0, the feature is for the whole sequence
461 // and we don't want to render the feature in the normal way
463 if (newMadeVisible && !oldfeatures.contains(features[index].getType())) {
464 // this is a new feature type on the alignment. Mark it for
466 av.featuresDisplayed.put(features[index].getType(),
467 new Integer(getColour(features[index].
468 getType()).getRGB()));
469 setOrder(features[index].getType(),0);
473 if (!allfeatures.contains(features[index].getType()))
475 allfeatures.addElement(features[index].getType());
480 updateRenderOrder(allfeatures);
481 findingFeatures = false;
483 protected boolean firing=false;
485 * replaces the current renderOrder with the unordered features in allfeatures.
486 * The ordering of any types in both renderOrder and allfeatures is preserved,
487 * and all new feature types are rendered on top of the existing types, in
488 * the order given by getOrder or the order given in allFeatures.
489 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
490 * eliminate the float storage for computing/recalling the persistent ordering
494 private void updateRenderOrder(Vector allFeatures) {
495 Vector allfeatures = new Vector(allFeatures);
496 String[] oldRender = renderOrder;
497 renderOrder = new String[allfeatures.size()];
498 boolean initOrders=(featureOrder==null);
500 if (oldRender!=null && oldRender.length>0)
502 for (int j=0; j<oldRender.length; j++)
504 if (oldRender[j]!=null)
508 setOrder(oldRender[j], (1-(1+(float)j)/(float) oldRender.length));
510 if (allfeatures.contains(oldRender[j])) {
511 renderOrder[opos++] = oldRender[j]; // existing features always
512 // appear below new features
513 allfeatures.removeElement(oldRender[j]);
518 if (allfeatures.size()==0) {
519 // no new features - leave order unchanged.
522 int i=allfeatures.size()-1;
525 String[] newf = new String[allfeatures.size()];
526 float[] sortOrder = new float[allfeatures.size()];
527 Enumeration en = allfeatures.elements();
528 // sort remaining elements
529 while (en.hasMoreElements())
531 newf[i] = en.nextElement().toString();
532 if (initOrders || !featureOrder.containsKey(newf[i]))
534 int denom = initOrders ? allfeatures.size() : featureOrder.size();
535 // new unordered feature - compute persistent ordering at head of
536 // existing features.
537 setOrder(newf[i], i/(float) denom);
539 // set order from newly found feature from persisted ordering.
540 sortOrder[i] = 2-((Float) featureOrder.get(newf[i])).floatValue();
543 // only sort if we need to
544 sort = sort || sortOrder[i]>sortOrder[i+1];
549 jalview.util.QuickSort.sort(sortOrder, newf);
551 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
553 public Color getColour(String featureType)
555 if (featureColours.get(featureType) == null)
557 jalview.schemes.UserColourScheme ucs = new
558 jalview.schemes.UserColourScheme();
559 Color col = ucs.createColourFromName(featureType);
560 featureColours.put(featureType, col);
564 return (Color) featureColours.get(featureType);
567 static String lastFeatureAdded;
568 static String lastFeatureGroupAdded;
569 static String lastDescriptionAdded;
571 public boolean createNewFeatures(SequenceI[] sequences,
572 SequenceFeature[] features)
574 return amendFeatures(sequences, features, true, null);
577 int featureIndex = 0;
578 boolean amendFeatures(final SequenceI[] sequences,
579 final SequenceFeature[] features,
581 final AlignmentPanel ap)
587 JPanel bigPanel = new JPanel(new BorderLayout());
588 final JComboBox overlaps;
589 final JTextField name = new JTextField(25);
590 final JTextField source = new JTextField(25);
591 final JTextArea description = new JTextArea(3, 25);
592 final JSpinner start = new JSpinner();
593 final JSpinner end = new JSpinner();
594 start.setPreferredSize(new Dimension(80, 20));
595 end.setPreferredSize(new Dimension(80, 20));
597 final JPanel colour = new JPanel();
598 colour.setBorder(BorderFactory.createEtchedBorder());
599 colour.setMaximumSize(new Dimension(40, 10));
600 colour.addMouseListener(new MouseAdapter()
602 public void mousePressed(MouseEvent evt)
604 colour.setBackground(
605 JColorChooser.showDialog(Desktop.desktop,
606 "Select Feature Colour",
607 colour.getBackground()));
611 JPanel tmp = new JPanel();
612 JPanel panel = new JPanel(new GridLayout(3, 1));
614 ///////////////////////////////////////
615 ///MULTIPLE FEATURES AT SELECTED RESIDUE
616 if(!newFeatures && features.length>1)
618 panel = new JPanel(new GridLayout(4, 1));
620 tmp.add(new JLabel("Select Feature: "));
621 overlaps = new JComboBox();
622 for(int i=0; i<features.length; i++)
624 overlaps.addItem(features[i].getType()
625 +"/"+features[i].getBegin()+"-"+features[i].getEnd()
626 +" ("+features[i].getFeatureGroup()+")");
631 overlaps.addItemListener(new ItemListener()
633 public void itemStateChanged(ItemEvent e)
635 int index = overlaps.getSelectedIndex();
638 featureIndex = index;
639 name.setText(features[index].getType());
640 description.setText(features[index].getDescription());
641 source.setText(features[index].getFeatureGroup());
642 start.setValue(new Integer(features[index].getBegin()));
643 end.setValue(new Integer(features[index].getEnd()));
645 SearchResults highlight = new SearchResults();
646 highlight.addResult(sequences[0],
647 features[index].getBegin(),
648 features[index].getEnd());
650 ap.seqPanel.seqCanvas.highlightSearchResults(highlight);
653 Color col = getColour(name.getText());
657 jalview.schemes.UserColourScheme()
658 .createColourFromName(name.getText());
661 colour.setBackground(col);
669 //////////////////////////////////////
673 tmp.add(new JLabel("Name: ", JLabel.RIGHT));
678 tmp.add(new JLabel("Group: ", JLabel.RIGHT));
683 tmp.add(new JLabel("Colour: ", JLabel.RIGHT));
685 colour.setPreferredSize(new Dimension(150, 15));
687 bigPanel.add(panel, BorderLayout.NORTH);
689 panel = new JPanel();
690 panel.add(new JLabel("Description: ", JLabel.RIGHT));
691 description.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
692 description.setLineWrap(true);
693 panel.add(new JScrollPane(description));
697 bigPanel.add(panel, BorderLayout.SOUTH);
699 panel = new JPanel();
700 panel.add(new JLabel(" Start:", JLabel.RIGHT));
702 panel.add(new JLabel(" End:", JLabel.RIGHT));
704 bigPanel.add(panel, BorderLayout.CENTER);
708 bigPanel.add(panel, BorderLayout.CENTER);
711 if (lastFeatureAdded == null)
713 if (features[0].type != null)
715 lastFeatureAdded = features[0].type;
719 lastFeatureAdded = "feature_1";
723 if (lastFeatureGroupAdded == null)
725 if (features[0].featureGroup != null)
727 lastFeatureGroupAdded = features[0].featureGroup;
731 lastFeatureGroupAdded = "Jalview";
737 name.setText(lastFeatureAdded);
738 source.setText(lastFeatureGroupAdded);
742 name.setText(features[0].getType());
743 source.setText(features[0].getFeatureGroup());
746 start.setValue(new Integer(features[0].getBegin()));
747 end.setValue(new Integer(features[0].getEnd()));
748 description.setText(features[0].getDescription());
749 colour.setBackground(getColour(name.getText()));
755 options = new Object[]
757 "Amend", "Delete", "Cancel"};
761 options = new Object[]
766 String title = newFeatures ? "Create New Sequence Feature(s)" :
767 "Amend/Delete Features for "
768 + sequences[0].getName();
770 int reply = JOptionPane.showInternalOptionDialog(Desktop.desktop,
773 JOptionPane.YES_NO_CANCEL_OPTION,
774 JOptionPane.QUESTION_MESSAGE,
778 jalview.io.FeaturesFile ffile = new jalview.io.FeaturesFile();
780 if (reply == JOptionPane.OK_OPTION && name.getText().length()>0)
782 // This ensures that the last sequence
783 // is refreshed and new features are rendered
785 lastFeatureAdded = name.getText().trim();
786 lastFeatureGroupAdded = source.getText().trim();
787 lastDescriptionAdded = description.getText().replaceAll("\n", " ");
789 if(lastFeatureGroupAdded.length()<1)
790 lastFeatureGroupAdded = null;
795 SequenceFeature sf = features[featureIndex];
797 if (reply == JOptionPane.NO_OPTION)
799 sequences[0].getDatasetSequence().deleteFeature(sf);
801 else if (reply == JOptionPane.YES_OPTION)
803 sf.type = lastFeatureAdded;
804 sf.featureGroup = lastFeatureGroupAdded;
805 sf.description = lastDescriptionAdded;
806 setColour(sf.type, colour.getBackground());
809 sf.begin = ( (Integer) start.getValue()).intValue();
810 sf.end = ( (Integer) end.getValue()).intValue();
812 catch (NumberFormatException ex)
815 ffile.parseDescriptionHTML(sf, false);
820 if (reply == JOptionPane.OK_OPTION
821 && name.getText() != null
822 && source.getText() != null)
824 for (int i = 0; i < sequences.length; i++)
826 features[i].type = lastFeatureAdded;
827 features[i].featureGroup = lastFeatureGroupAdded;
828 features[i].description = lastDescriptionAdded;
829 sequences[i].addSequenceFeature(features[i]);
830 ffile.parseDescriptionHTML(features[i], false);
833 if (av.featuresDisplayed == null)
835 av.featuresDisplayed = new Hashtable();
838 if (featureGroups == null)
840 featureGroups = new Hashtable();
844 Color col = colour.getBackground();
845 setColour(lastFeatureAdded, colour.getBackground());
847 if(lastFeatureGroupAdded!=null)
849 featureGroups.put(lastFeatureGroupAdded, new Boolean(true));
850 av.featuresDisplayed.put(lastFeatureGroupAdded,
851 new Integer(col.getRGB()));
868 public void setColour(String featureType, Color col)
870 featureColours.put(featureType, col);
873 public void setTransparency(float value)
875 transparency = value;
878 public float getTransparency()
883 * Replace current ordering with new ordering
884 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
886 public void setFeaturePriority(Object[][] data)
888 setFeaturePriority(data, true);
892 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
893 * @param visibleNew when true current featureDisplay list will be cleared
895 public void setFeaturePriority(Object[][] data, boolean visibleNew)
899 if (av.featuresDisplayed != null)
901 av.featuresDisplayed.clear();
905 av.featuresDisplayed = new Hashtable();
913 // The feature table will display high priority
914 // features at the top, but theses are the ones
915 // we need to render last, so invert the data
916 renderOrder = new String[data.length];
920 for (int i = 0; i < data.length; i++)
922 String type = data[i][0].toString();
923 setColour(type, (Color) data[i][1]);
924 if ( ( (Boolean) data[i][2]).booleanValue())
926 av.featuresDisplayed.put(type, new Integer(getColour(type).getRGB()));
929 renderOrder[data.length - i - 1] = type;
934 Hashtable featureOrder=null;
936 * analogous to colour - store a normalized ordering for all feature types in
937 * this rendering context.
940 * Feature type string
942 * normalized priority - 0 means always appears on top, 1 means
945 public float setOrder(String type, float position)
947 if (featureOrder==null)
949 featureOrder = new Hashtable();
951 featureOrder.put(type, new Float(position));
955 * get the global priority (0 (top) to 1 (bottom))
958 * @return [0,1] or -1 for a type without a priority
960 public float getOrder(String type) {
961 if (featureOrder!=null)
963 if (featureOrder.containsKey(type))
965 return ((Float)featureOrder.get(type)).floatValue();
973 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
975 public void addPropertyChangeListener(PropertyChangeListener listener)
977 changeSupport.addPropertyChangeListener(listener);
982 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
984 public void removePropertyChangeListener(PropertyChangeListener listener)
986 changeSupport.removePropertyChangeListener(listener);