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 Color colour = (Color) featureColours.get(featureType);
558 jalview.schemes.UserColourScheme ucs = new
559 jalview.schemes.UserColourScheme();
560 featureColours.put(featureType,
561 colour=ucs.createColourFromName(featureType));
566 static String lastFeatureAdded;
567 static String lastFeatureGroupAdded;
568 static String lastDescriptionAdded;
570 public boolean createNewFeatures(SequenceI[] sequences,
571 SequenceFeature[] features)
573 return amendFeatures(sequences, features, true, null);
576 int featureIndex = 0;
577 boolean amendFeatures(final SequenceI[] sequences,
578 final SequenceFeature[] features,
580 final AlignmentPanel ap)
586 JPanel bigPanel = new JPanel(new BorderLayout());
587 final JComboBox overlaps;
588 final JTextField name = new JTextField(25);
589 final JTextField source = new JTextField(25);
590 final JTextArea description = new JTextArea(3, 25);
591 final JSpinner start = new JSpinner();
592 final JSpinner end = new JSpinner();
593 start.setPreferredSize(new Dimension(80, 20));
594 end.setPreferredSize(new Dimension(80, 20));
596 final JPanel colour = new JPanel();
597 colour.setBorder(BorderFactory.createEtchedBorder());
598 colour.setMaximumSize(new Dimension(40, 10));
599 colour.addMouseListener(new MouseAdapter()
601 public void mousePressed(MouseEvent evt)
603 colour.setBackground(
604 JColorChooser.showDialog(Desktop.desktop,
605 "Select Feature Colour",
606 colour.getBackground()));
610 JPanel tmp = new JPanel();
611 JPanel panel = new JPanel(new GridLayout(3, 1));
613 ///////////////////////////////////////
614 ///MULTIPLE FEATURES AT SELECTED RESIDUE
615 if(features.length>1)
617 panel = new JPanel(new GridLayout(4, 1));
619 tmp.add(new JLabel("Select Feature: "));
620 overlaps = new JComboBox();
621 for(int i=0; i<features.length; i++)
623 overlaps.addItem(features[i].getType()
624 +"/"+features[i].getBegin()+"-"+features[i].getEnd()
625 +" ("+features[i].getFeatureGroup()+")");
630 overlaps.addItemListener(new ItemListener()
632 public void itemStateChanged(ItemEvent e)
634 int index = overlaps.getSelectedIndex();
637 featureIndex = index;
638 name.setText(features[index].getType());
639 description.setText(features[index].getDescription());
640 source.setText(features[index].getFeatureGroup());
641 start.setValue(new Integer(features[index].getBegin()));
642 end.setValue(new Integer(features[index].getEnd()));
643 colour.setBackground(
644 getColour(features[index].getType()));
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));
696 name.setText(features[0].type);
697 source.setText(features[0].featureGroup);
698 start.setValue(new Integer(features[0].getBegin()));
699 end.setValue(new Integer(features[0].getEnd()));
700 colour.setBackground( getColour(features[0].type) );
701 description.setText(features[0].getDescription());
705 bigPanel.add(panel, BorderLayout.SOUTH);
707 panel = new JPanel();
708 panel.add(new JLabel(" Start:", JLabel.RIGHT));
710 panel.add(new JLabel(" End:", JLabel.RIGHT));
712 bigPanel.add(panel, BorderLayout.CENTER);
716 bigPanel.add(panel, BorderLayout.CENTER);
719 if (lastFeatureAdded == null)
721 if (features[0].type != null)
723 lastFeatureAdded = features[0].type;
727 lastFeatureAdded = "feature_1";
731 if (lastFeatureGroupAdded == null)
733 if (features[0].featureGroup != null)
735 lastFeatureGroupAdded = features[0].featureGroup;
739 lastFeatureGroupAdded = "Jalview";
747 options = new Object[]
749 "Amend", "Delete", "Cancel"};
753 options = new Object[]
758 String title = newFeatures ? "Create New Sequence Feature(s)" :
759 "Amend/Delete Features for "
760 + sequences[0].getName();
762 int reply = JOptionPane.showInternalOptionDialog(Desktop.desktop,
765 JOptionPane.YES_NO_CANCEL_OPTION,
766 JOptionPane.QUESTION_MESSAGE,
770 jalview.io.FeaturesFile ffile = new jalview.io.FeaturesFile();
772 if (reply == JOptionPane.OK_OPTION
773 && name.getText() != null
774 && source.getText() != null)
776 // This ensures that the last sequence
777 // is refreshed and new features are rendered
779 lastFeatureAdded = name.getText();
780 lastFeatureGroupAdded = source.getText();
781 lastDescriptionAdded = description.getText().replaceAll("\n", " ");
786 SequenceFeature sf = features[featureIndex];
788 if (reply == JOptionPane.NO_OPTION)
790 sequences[0].getDatasetSequence().deleteFeature(sf);
792 else if (reply == JOptionPane.YES_OPTION)
794 sf.type = lastFeatureAdded;
795 sf.featureGroup = lastFeatureGroupAdded;
796 sf.description = lastDescriptionAdded;
797 setColour(sf.type, colour.getBackground());
800 sf.begin = ( (Integer) start.getValue()).intValue();
801 sf.end = ( (Integer) end.getValue()).intValue();
803 catch (NumberFormatException ex)
806 ffile.parseDescriptionHTML(sf, false);
811 if (reply == JOptionPane.OK_OPTION
812 && name.getText() != null
813 && source.getText() != null)
815 for (int i = 0; i < sequences.length; i++)
817 features[i].type = lastFeatureAdded;
818 features[i].featureGroup = lastFeatureGroupAdded;
819 features[i].description = lastDescriptionAdded;
820 sequences[i].addSequenceFeature(features[i]);
821 ffile.parseDescriptionHTML(features[i], false);
824 if (av.featuresDisplayed == null)
826 av.featuresDisplayed = new Hashtable();
829 if (featureGroups == null)
831 featureGroups = new Hashtable();
834 featureGroups.put(lastFeatureGroupAdded, new Boolean(true));
836 Color col = colour.getBackground();
837 setColour(lastFeatureAdded, colour.getBackground());
839 av.featuresDisplayed.put(lastFeatureGroupAdded,
840 new Integer(col.getRGB()));
852 // if (name.getSelectedIndex() == -1)
854 // findAllFeatures();
860 public void setColour(String featureType, Color col)
862 featureColours.put(featureType, col);
865 public void setTransparency(float value)
867 transparency = value;
870 public float getTransparency()
875 * Replace current ordering with new ordering
876 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
878 public void setFeaturePriority(Object[][] data)
880 setFeaturePriority(data, true);
884 * @param data { String(Type), Colour(Type), Boolean(Displayed) }
885 * @param visibleNew when true current featureDisplay list will be cleared
887 public void setFeaturePriority(Object[][] data, boolean visibleNew)
891 if (av.featuresDisplayed != null)
893 av.featuresDisplayed.clear();
897 av.featuresDisplayed = new Hashtable();
905 // The feature table will display high priority
906 // features at the top, but theses are the ones
907 // we need to render last, so invert the data
908 renderOrder = new String[data.length];
912 for (int i = 0; i < data.length; i++)
914 String type = data[i][0].toString();
915 setColour(type, (Color) data[i][1]);
916 if ( ( (Boolean) data[i][2]).booleanValue())
918 av.featuresDisplayed.put(type, new Integer(getColour(type).getRGB()));
921 renderOrder[data.length - i - 1] = type;
926 Hashtable featureOrder=null;
928 * analogous to colour - store a normalized ordering for all feature types in
929 * this rendering context.
932 * Feature type string
934 * normalized priority - 0 means always appears on top, 1 means
937 public float setOrder(String type, float position)
939 if (featureOrder==null)
941 featureOrder = new Hashtable();
943 featureOrder.put(type, new Float(position));
947 * get the global priority (0 (top) to 1 (bottom))
950 * @return [0,1] or -1 for a type without a priority
952 public float getOrder(String type) {
953 if (featureOrder!=null)
955 if (featureOrder.containsKey(type))
957 return ((Float)featureOrder.get(type)).floatValue();
965 * @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
967 public void addPropertyChangeListener(PropertyChangeListener listener)
969 changeSupport.addPropertyChangeListener(listener);
974 * @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
976 public void removePropertyChangeListener(PropertyChangeListener listener)
978 changeSupport.removePropertyChangeListener(listener);