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 sequenceFeatures[sfindex].featureGroup.length()!=0
273 && featureGroups.containsKey(sequenceFeatures[sfindex].featureGroup)
275 ! ( (Boolean) featureGroups.get(sequenceFeatures[sfindex].
282 if (!offscreenRender && (sequenceFeatures[sfindex].getBegin() > epos
283 || sequenceFeatures[sfindex].getEnd() < spos))
288 if (offscreenRender && offscreenImage == null)
290 if (sequenceFeatures[sfindex].begin <= start &&
291 sequenceFeatures[sfindex].end >= start)
293 currentColour = av.featuresDisplayed.get(sequenceFeatures[sfindex].
297 else if (sequenceFeatures[sfindex].type.equals("disulfide bond"))
300 renderFeature(g, seq,
301 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
302 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
303 new Color( ( (Integer) av.featuresDisplayed.get(
304 sequenceFeatures[sfindex].type)).intValue()),
306 renderFeature(g, seq,
307 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
308 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
309 new Color( ( (Integer) av.featuresDisplayed.get(
310 sequenceFeatures[sfindex].type)).intValue()),
316 renderFeature(g, seq,
317 seq.findIndex(sequenceFeatures[sfindex].begin) - 1,
318 seq.findIndex(sequenceFeatures[sfindex].end) - 1,
319 getColour(sequenceFeatures[sfindex].type),
327 if (transparency != 1.0f && g != null)
329 Graphics2D g2 = (Graphics2D) g;
331 AlphaComposite.getInstance(
332 AlphaComposite.SRC_OVER, 1.0f));
338 void renderFeature(Graphics g, SequenceI seq,
339 int fstart, int fend, Color featureColour, int start,
343 if ( ( (fstart <= end) && (fend >= start)))
346 { // fix for if the feature we have starts before the sequence start,
347 fstart = start; // but the feature end is still valid!!
354 int pady = (y1 + av.charHeight) - av.charHeight / 5;
355 for (i = fstart; i <= fend; i++)
357 s = seq.getCharAt(i);
359 if (jalview.util.Comparison.isGap(s))
364 g.setColor(featureColour);
366 g.fillRect( (i - start) * av.charWidth, y1, av.charWidth, av.charHeight);
368 if (offscreenRender || !av.validCharWidth)
373 g.setColor(Color.white);
374 charOffset = (av.charWidth - fm.charWidth(s)) / 2;
375 g.drawString(String.valueOf(s),
376 charOffset + (av.charWidth * (i - start)),
383 boolean newFeatureAdded = false;
385 * Called when alignment in associated view has new/modified features
386 * to discover and display.
389 public void featuresAdded()
395 boolean findingFeatures = false;
397 * search the alignment for all new features, give them a colour and display
398 * them. Then fires a PropertyChangeEvent on the changeSupport object.
401 synchronized void findAllFeatures()
403 findAllFeatures(true); // add all new features as visible
406 changeSupport.firePropertyChange("changeSupport",null,null);
411 * Searches alignment for all features and updates colours
413 * @param newMadeVisible
414 * if true newly added feature types will be rendered immediatly
416 synchronized void findAllFeatures(boolean newMadeVisible) {
417 newFeatureAdded = false;
421 newFeatureAdded = true;
425 findingFeatures = true;
427 if (av.featuresDisplayed == null)
429 av.featuresDisplayed = new Hashtable();
432 allfeatures = new Vector();
433 Vector oldfeatures = new Vector();
434 if (renderOrder!=null)
436 for (int i=0; i<renderOrder.length; i++) {
437 if (renderOrder[i]!=null)
439 oldfeatures.addElement(renderOrder[i]);
443 for (int i = 0; i < av.alignment.getHeight(); i++)
445 SequenceFeature[] features
446 = av.alignment.getSequenceAt(i).getDatasetSequence().
447 getSequenceFeatures();
449 if (features == null)
455 while (index < features.length)
457 if (!av.featuresDisplayed.containsKey(features[index].getType()))
459 if (! (features[index].begin == 0 && features[index].end == 0))
461 // If beginning and end are 0, the feature is for the whole sequence
462 // and we don't want to render the feature in the normal way
464 if (newMadeVisible && !oldfeatures.contains(features[index].getType())) {
465 // this is a new feature type on the alignment. Mark it for
467 av.featuresDisplayed.put(features[index].getType(),
468 new Integer(getColour(features[index].
469 getType()).getRGB()));
470 setOrder(features[index].getType(),0);
474 if (!allfeatures.contains(features[index].getType()))
476 allfeatures.addElement(features[index].getType());
481 updateRenderOrder(allfeatures);
482 findingFeatures = false;
484 protected boolean firing=false;
486 * replaces the current renderOrder with the unordered features in allfeatures.
487 * The ordering of any types in both renderOrder and allfeatures is preserved,
488 * and all new feature types are rendered on top of the existing types, in
489 * the order given by getOrder or the order given in allFeatures.
490 * Note. this operates directly on the featureOrder hash for efficiency. TODO:
491 * eliminate the float storage for computing/recalling the persistent ordering
495 private void updateRenderOrder(Vector allFeatures) {
496 Vector allfeatures = new Vector(allFeatures);
497 String[] oldRender = renderOrder;
498 renderOrder = new String[allfeatures.size()];
499 boolean initOrders=(featureOrder==null);
501 if (oldRender!=null && oldRender.length>0)
503 for (int j=0; j<oldRender.length; j++)
505 if (oldRender[j]!=null)
509 setOrder(oldRender[j], (1-(1+(float)j)/(float) oldRender.length));
511 if (allfeatures.contains(oldRender[j])) {
512 renderOrder[opos++] = oldRender[j]; // existing features always
513 // appear below new features
514 allfeatures.removeElement(oldRender[j]);
519 if (allfeatures.size()==0) {
520 // no new features - leave order unchanged.
523 int i=allfeatures.size()-1;
526 String[] newf = new String[allfeatures.size()];
527 float[] sortOrder = new float[allfeatures.size()];
528 Enumeration en = allfeatures.elements();
529 // sort remaining elements
530 while (en.hasMoreElements())
532 newf[i] = en.nextElement().toString();
533 if (initOrders || !featureOrder.containsKey(newf[i]))
535 int denom = initOrders ? allfeatures.size() : featureOrder.size();
536 // new unordered feature - compute persistent ordering at head of
537 // existing features.
538 setOrder(newf[i], i/(float) denom);
540 // set order from newly found feature from persisted ordering.
541 sortOrder[i] = 2-((Float) featureOrder.get(newf[i])).floatValue();
544 // only sort if we need to
545 sort = sort || sortOrder[i]>sortOrder[i+1];
550 jalview.util.QuickSort.sort(sortOrder, newf);
552 System.arraycopy(newf, 0, renderOrder, opos, newf.length);
554 public Color getColour(String featureType)
556 if (featureColours.get(featureType) == null)
558 jalview.schemes.UserColourScheme ucs = new
559 jalview.schemes.UserColourScheme();
560 Color col = ucs.createColourFromName(featureType);
561 featureColours.put(featureType, col);
565 return (Color) featureColours.get(featureType);
568 static String lastFeatureAdded;
569 static String lastFeatureGroupAdded;
570 static String lastDescriptionAdded;
572 public boolean createNewFeatures(SequenceI[] sequences,
573 SequenceFeature[] features)
575 return amendFeatures(sequences, features, true, null);
578 int featureIndex = 0;
579 boolean amendFeatures(final SequenceI[] sequences,
580 final SequenceFeature[] features,
582 final AlignmentPanel ap)
588 JPanel bigPanel = new JPanel(new BorderLayout());
589 final JComboBox overlaps;
590 final JTextField name = new JTextField(25);
591 final JTextField source = new JTextField(25);
592 final JTextArea description = new JTextArea(3, 25);
593 final JSpinner start = new JSpinner();
594 final JSpinner end = new JSpinner();
595 start.setPreferredSize(new Dimension(80, 20));
596 end.setPreferredSize(new Dimension(80, 20));
598 final JPanel colour = new JPanel();
599 colour.setBorder(BorderFactory.createEtchedBorder());
600 colour.setMaximumSize(new Dimension(40, 10));
601 colour.addMouseListener(new MouseAdapter()
603 public void mousePressed(MouseEvent evt)
605 colour.setBackground(
606 JColorChooser.showDialog(Desktop.desktop,
607 "Select Feature Colour",
608 colour.getBackground()));
612 JPanel tmp = new JPanel();
613 JPanel panel = new JPanel(new GridLayout(3, 1));
615 ///////////////////////////////////////
616 ///MULTIPLE FEATURES AT SELECTED RESIDUE
617 if(!newFeatures && features.length>1)
619 panel = new JPanel(new GridLayout(4, 1));
621 tmp.add(new JLabel("Select Feature: "));
622 overlaps = new JComboBox();
623 for(int i=0; i<features.length; i++)
625 overlaps.addItem(features[i].getType()
626 +"/"+features[i].getBegin()+"-"+features[i].getEnd()
627 +" ("+features[i].getFeatureGroup()+")");
632 overlaps.addItemListener(new ItemListener()
634 public void itemStateChanged(ItemEvent e)
636 int index = overlaps.getSelectedIndex();
639 featureIndex = index;
640 name.setText(features[index].getType());
641 description.setText(features[index].getDescription());
642 source.setText(features[index].getFeatureGroup());
643 start.setValue(new Integer(features[index].getBegin()));
644 end.setValue(new Integer(features[index].getEnd()));
646 SearchResults highlight = new SearchResults();
647 highlight.addResult(sequences[0],
648 features[index].getBegin(),
649 features[index].getEnd());
651 ap.seqPanel.seqCanvas.highlightSearchResults(highlight);
654 Color col = getColour(name.getText());
658 jalview.schemes.UserColourScheme()
659 .createColourFromName(name.getText());
662 colour.setBackground(col);
670 //////////////////////////////////////
674 tmp.add(new JLabel("Name: ", JLabel.RIGHT));
679 tmp.add(new JLabel("Group: ", JLabel.RIGHT));
684 tmp.add(new JLabel("Colour: ", JLabel.RIGHT));
686 colour.setPreferredSize(new Dimension(150, 15));
688 bigPanel.add(panel, BorderLayout.NORTH);
690 panel = new JPanel();
691 panel.add(new JLabel("Description: ", JLabel.RIGHT));
692 description.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
693 description.setLineWrap(true);
694 panel.add(new JScrollPane(description));
698 bigPanel.add(panel, BorderLayout.SOUTH);
700 panel = new JPanel();
701 panel.add(new JLabel(" Start:", JLabel.RIGHT));
703 panel.add(new JLabel(" End:", JLabel.RIGHT));
705 bigPanel.add(panel, BorderLayout.CENTER);
709 bigPanel.add(panel, BorderLayout.CENTER);
712 if (lastFeatureAdded == null)
714 if (features[0].type != null)
716 lastFeatureAdded = features[0].type;
720 lastFeatureAdded = "feature_1";
724 if (lastFeatureGroupAdded == null)
726 if (features[0].featureGroup != null)
728 lastFeatureGroupAdded = features[0].featureGroup;
732 lastFeatureGroupAdded = "Jalview";
738 name.setText(lastFeatureAdded);
739 source.setText(lastFeatureGroupAdded);
743 name.setText(features[0].getType());
744 source.setText(features[0].getFeatureGroup());
747 start.setValue(new Integer(features[0].getBegin()));
748 end.setValue(new Integer(features[0].getEnd()));
749 description.setText(features[0].getDescription());
750 colour.setBackground(getColour(name.getText()));
756 options = new Object[]
758 "Amend", "Delete", "Cancel"};
762 options = new Object[]
767 String title = newFeatures ? "Create New Sequence Feature(s)" :
768 "Amend/Delete Features for "
769 + sequences[0].getName();
771 int reply = JOptionPane.showInternalOptionDialog(Desktop.desktop,
774 JOptionPane.YES_NO_CANCEL_OPTION,
775 JOptionPane.QUESTION_MESSAGE,
779 jalview.io.FeaturesFile ffile = new jalview.io.FeaturesFile();
781 if (reply == JOptionPane.OK_OPTION && name.getText().length()>0)
783 // This ensures that the last sequence
784 // is refreshed and new features are rendered
786 lastFeatureAdded = name.getText().trim();
787 lastFeatureGroupAdded = source.getText().trim();
788 lastDescriptionAdded = description.getText().replaceAll("\n", " ");
790 if(lastFeatureGroupAdded.length()<1)
791 lastFeatureGroupAdded = null;
796 SequenceFeature sf = features[featureIndex];
798 if (reply == JOptionPane.NO_OPTION)
800 sequences[0].getDatasetSequence().deleteFeature(sf);
802 else if (reply == JOptionPane.YES_OPTION)
804 sf.type = lastFeatureAdded;
805 sf.featureGroup = lastFeatureGroupAdded;
806 sf.description = lastDescriptionAdded;
807 setColour(sf.type, colour.getBackground());
810 sf.begin = ( (Integer) start.getValue()).intValue();
811 sf.end = ( (Integer) end.getValue()).intValue();
813 catch (NumberFormatException ex)
816 ffile.parseDescriptionHTML(sf, false);
821 if (reply == JOptionPane.OK_OPTION
822 && name.getText() != null
823 && source.getText() != null)
825 for (int i = 0; i < sequences.length; i++)
827 features[i].type = lastFeatureAdded;
828 features[i].featureGroup = lastFeatureGroupAdded;
829 features[i].description = lastDescriptionAdded;
830 sequences[i].addSequenceFeature(features[i]);
831 ffile.parseDescriptionHTML(features[i], false);
834 if (av.featuresDisplayed == null)
836 av.featuresDisplayed = new Hashtable();
839 if (featureGroups == null)
841 featureGroups = new Hashtable();
845 Color col = colour.getBackground();
846 setColour(lastFeatureAdded, colour.getBackground());
848 if(lastFeatureGroupAdded!=null)
850 featureGroups.put(lastFeatureGroupAdded, new Boolean(true));
851 av.featuresDisplayed.put(lastFeatureGroupAdded,
852 new Integer(col.getRGB()));
869 public void setColour(String featureType, Color col)
871 featureColours.put(featureType, col);
874 public void setTransparency(float value)
876 transparency = value;
879 public float getTransparency()
884 * Replace current ordering with new ordering
885 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
887 public void setFeaturePriority(Object[][] data)
889 setFeaturePriority(data, true);
893 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
894 * @param visibleNew when true current featureDisplay list will be cleared
896 public void setFeaturePriority(Object[][] data, boolean visibleNew)
900 if (av.featuresDisplayed != null)
902 av.featuresDisplayed.clear();
906 av.featuresDisplayed = new Hashtable();
914 // The feature table will display high priority
915 // features at the top, but theses are the ones
916 // we need to render last, so invert the data
917 renderOrder = new String[data.length];
921 for (int i = 0; i < data.length; i++)
923 String type = data[i][0].toString();
924 setColour(type, (Color) data[i][1]);
925 if ( ( (Boolean) data[i][2]).booleanValue())
927 av.featuresDisplayed.put(type, new Integer(getColour(type).getRGB()));
930 renderOrder[data.length - i - 1] = type;
935 Hashtable featureOrder=null;
937 * analogous to colour - store a normalized ordering for all feature types in
938 * this rendering context.
941 * Feature type string
943 * normalized priority - 0 means always appears on top, 1 means
946 public float setOrder(String type, float position)
948 if (featureOrder==null)
950 featureOrder = new Hashtable();
952 featureOrder.put(type, new Float(position));
956 * get the global priority (0 (top) to 1 (bottom))
959 * @return [0,1] or -1 for a type without a priority
961 public float getOrder(String type) {
962 if (featureOrder!=null)
964 if (featureOrder.containsKey(type))
966 return ((Float)featureOrder.get(type)).floatValue();
974 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
976 public void addPropertyChangeListener(PropertyChangeListener listener)
978 changeSupport.addPropertyChangeListener(listener);
983 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
985 public void removePropertyChangeListener(PropertyChangeListener listener)
987 changeSupport.removePropertyChangeListener(listener);