2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.SequenceI;
27 import jalview.renderer.AnnotationRenderer;
28 import jalview.renderer.AwtRenderPanelI;
29 import jalview.schemes.ResidueProperties;
30 import jalview.util.Comparison;
31 import jalview.util.MessageManager;
33 import java.awt.AlphaComposite;
34 import java.awt.Color;
35 import java.awt.Dimension;
36 import java.awt.FontMetrics;
37 import java.awt.Graphics;
38 import java.awt.Graphics2D;
39 import java.awt.Image;
40 import java.awt.Rectangle;
41 import java.awt.RenderingHints;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.AdjustmentEvent;
45 import java.awt.event.AdjustmentListener;
46 import java.awt.event.MouseEvent;
47 import java.awt.event.MouseListener;
48 import java.awt.event.MouseMotionListener;
49 import java.awt.event.MouseWheelEvent;
50 import java.awt.event.MouseWheelListener;
51 import java.awt.image.BufferedImage;
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.List;
56 import javax.swing.JColorChooser;
57 import javax.swing.JMenuItem;
58 import javax.swing.JOptionPane;
59 import javax.swing.JPanel;
60 import javax.swing.JPopupMenu;
61 import javax.swing.Scrollable;
62 import javax.swing.ToolTipManager;
65 * AnnotationPanel displays visible portion of annotation rows below unwrapped
71 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
72 MouseListener, MouseWheelListener, MouseMotionListener,
73 ActionListener, AdjustmentListener, Scrollable
75 String HELIX = MessageManager.getString("label.helix");
77 String SHEET = MessageManager.getString("label.sheet");
80 * For RNA secondary structure "stems" aka helices
82 String STEM = MessageManager.getString("label.rna_helix");
84 String LABEL = MessageManager.getString("label.label");
86 String REMOVE = MessageManager.getString("label.remove_annotation");
88 String COLOUR = MessageManager.getString("action.colour");
90 public final Color HELIX_COLOUR = Color.red.darker();
92 public final Color SHEET_COLOUR = Color.green.darker().darker();
94 public final Color STEM_COLOUR = Color.blue.darker();
97 public AlignViewport av;
101 public int activeRow = -1;
103 public BufferedImage image;
105 public volatile BufferedImage fadedImage;
109 public FontMetrics fm;
111 public int imgWidth = 0;
113 boolean fastPaint = false;
115 // Used For mouse Dragging and resizing graphs
116 int graphStretch = -1;
118 int graphStretchY = -1;
120 int min; // used by mouseDragged to see if user
122 int max; // used by mouseDragged to see if user
124 boolean mouseDragging = false;
126 // for editing cursor
131 public final AnnotationRenderer renderer;
133 private MouseWheelListener[] _mwl;
136 * Creates a new AnnotationPanel object.
141 public AnnotationPanel(AlignmentPanel ap)
143 ToolTipManager.sharedInstance().registerComponent(this);
144 ToolTipManager.sharedInstance().setInitialDelay(0);
145 ToolTipManager.sharedInstance().setDismissDelay(10000);
148 this.setLayout(null);
149 addMouseListener(this);
150 addMouseMotionListener(this);
151 ap.annotationScroller.getVerticalScrollBar()
152 .addAdjustmentListener(this);
153 // save any wheel listeners on the scroller, so we can propagate scroll
155 _mwl = ap.annotationScroller.getMouseWheelListeners();
156 // and then set our own listener to consume all mousewheel events
157 ap.annotationScroller.addMouseWheelListener(this);
158 renderer = new AnnotationRenderer();
161 public AnnotationPanel(AlignViewport av)
164 renderer = new AnnotationRenderer();
168 public void mouseWheelMoved(MouseWheelEvent e)
173 if (e.getWheelRotation() > 0)
175 ap.scrollRight(true);
179 ap.scrollRight(false);
184 // TODO: find the correct way to let the event bubble up to
185 // ap.annotationScroller
186 for (MouseWheelListener mwl : _mwl)
190 mwl.mouseWheelMoved(e);
201 public Dimension getPreferredScrollableViewportSize()
203 return getPreferredSize();
207 public int getScrollableBlockIncrement(Rectangle visibleRect,
208 int orientation, int direction)
214 public boolean getScrollableTracksViewportHeight()
220 public boolean getScrollableTracksViewportWidth()
226 public int getScrollableUnitIncrement(Rectangle visibleRect,
227 int orientation, int direction)
236 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
240 public void adjustmentValueChanged(AdjustmentEvent evt)
242 // update annotation label display
243 ap.getAlabels().setScrollOffset(-evt.getValue());
247 * Calculates the height of the annotation displayed in the annotation panel.
248 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
249 * all annotation associated components are updated correctly.
252 public int adjustPanelHeight()
254 int height = av.calcPanelHeight();
255 this.setPreferredSize(new Dimension(1, height));
258 // revalidate only when the alignment panel is fully constructed
272 public void actionPerformed(ActionEvent evt)
274 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
279 Annotation[] anot = aa[activeRow].annotations;
281 if (anot.length < av.getColumnSelection().getMax())
283 Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
284 System.arraycopy(anot, 0, temp, 0, anot.length);
286 aa[activeRow].annotations = anot;
289 String action = evt.getActionCommand();
290 if (action.equals(REMOVE))
292 for (int index : av.getColumnSelection().getSelected())
294 if (av.getColumnSelection().isVisible(index))
300 else if (action.equals(LABEL))
302 String exMesg = collectAnnotVals(anot, LABEL);
303 String label = JvOptionPane.showInputDialog(this,
304 MessageManager.getString("label.enter_label"), exMesg);
311 if ((label.length() > 0) && !aa[activeRow].hasText)
313 aa[activeRow].hasText = true;
316 for (int index : av.getColumnSelection().getSelected())
318 if (!av.getColumnSelection().isVisible(index))
323 if (anot[index] == null)
325 anot[index] = new Annotation(label, "", ' ', 0);
329 anot[index].displayCharacter = label;
333 else if (action.equals(COLOUR))
335 Color col = JColorChooser.showDialog(this,
336 MessageManager.getString("label.select_foreground_colour"),
339 for (int index : av.getColumnSelection().getSelected())
341 if (!av.getColumnSelection().isVisible(index))
346 if (anot[index] == null)
348 anot[index] = new Annotation("", "", ' ', 0);
351 anot[index].colour = col;
355 // HELIX, SHEET or STEM
358 String symbol = "\u03B1"; // alpha
360 if (action.equals(HELIX))
364 else if (action.equals(SHEET))
367 symbol = "\u03B2"; // beta
370 // Added by LML to color stems
371 else if (action.equals(STEM))
374 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
375 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
378 if (!aa[activeRow].hasIcons)
380 aa[activeRow].hasIcons = true;
383 String label = JvOptionPane.showInputDialog(MessageManager
384 .getString("label.enter_label_for_the_structure"), symbol);
391 if ((label.length() > 0) && !aa[activeRow].hasText)
393 aa[activeRow].hasText = true;
394 if (action.equals(STEM))
396 aa[activeRow].showAllColLabels = true;
399 for (int index : av.getColumnSelection().getSelected())
401 if (!av.getColumnSelection().isVisible(index))
406 if (anot[index] == null)
408 anot[index] = new Annotation(label, "", type, 0);
411 anot[index].secondaryStructure = type != 'S' ? type : label
412 .length() == 0 ? ' ' : label.charAt(0);
413 anot[index].displayCharacter = label;
418 av.getAlignment().validateAnnotation(aa[activeRow]);
419 ap.alignmentChanged();
420 ap.alignFrame.setMenusForViewport();
428 * Returns any existing annotation concatenated as a string. For each
429 * annotation, takes the description, if any, else the secondary structure
430 * character (if type is HELIX, SHEET or STEM), else the display character (if
437 private String collectAnnotVals(Annotation[] anots, String type)
439 // TODO is this method wanted? why? 'last' is not used
441 StringBuilder collatedInput = new StringBuilder(64);
443 ColumnSelection viscols = av.getColumnSelection();
446 * the selection list (read-only view) is in selection order, not
447 * column order; make a copy so we can sort it
449 List<Integer> selected = new ArrayList<Integer>(viscols.getSelected());
450 Collections.sort(selected);
451 for (int index : selected)
453 // always check for current display state - just in case
454 if (!viscols.isVisible(index))
458 String tlabel = null;
459 if (anots[index] != null)
460 { // LML added stem code
461 if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
462 || type.equals(LABEL))
464 tlabel = anots[index].description;
465 if (tlabel == null || tlabel.length() < 1)
467 if (type.equals(HELIX) || type.equals(SHEET)
468 || type.equals(STEM))
470 tlabel = "" + anots[index].secondaryStructure;
474 tlabel = "" + anots[index].displayCharacter;
478 if (tlabel != null && !tlabel.equals(last))
480 if (last.length() > 0)
482 collatedInput.append(" ");
484 collatedInput.append(tlabel);
488 return collatedInput.toString();
498 public void mousePressed(MouseEvent evt)
501 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
510 final int y = evt.getY();
511 for (int i = 0; i < aa.length; i++)
515 height += aa[i].height;
524 else if (aa[i].graph > 0)
536 * isPopupTrigger fires in mousePressed on Mac,
537 * not until mouseRelease on Windows
539 if (evt.isPopupTrigger() && activeRow != -1)
541 showPopupMenu(y, evt.getX());
545 ap.getScalePanel().mousePressed(evt);
549 * Construct and display a context menu at the right-click position
554 void showPopupMenu(final int y, int x)
556 if (av.getColumnSelection() == null
557 || av.getColumnSelection().isEmpty())
562 JPopupMenu pop = new JPopupMenu(
563 MessageManager.getString("label.structure_type"));
566 * Just display the needed structure options
568 if (av.getAlignment().isNucleotide())
570 item = new JMenuItem(STEM);
571 item.addActionListener(this);
576 item = new JMenuItem(HELIX);
577 item.addActionListener(this);
579 item = new JMenuItem(SHEET);
580 item.addActionListener(this);
583 item = new JMenuItem(LABEL);
584 item.addActionListener(this);
586 item = new JMenuItem(COLOUR);
587 item.addActionListener(this);
589 item = new JMenuItem(REMOVE);
590 item.addActionListener(this);
592 pop.show(this, x, y);
602 public void mouseReleased(MouseEvent evt)
606 mouseDragging = false;
607 ap.getScalePanel().mouseReleased(evt);
610 * isPopupTrigger is set in mouseReleased on Windows
611 * (in mousePressed on Mac)
613 if (evt.isPopupTrigger() && activeRow != -1)
615 showPopupMenu(evt.getY(), evt.getX());
627 public void mouseEntered(MouseEvent evt)
629 ap.getScalePanel().mouseEntered(evt);
639 public void mouseExited(MouseEvent evt)
641 ap.getScalePanel().mouseExited(evt);
651 public void mouseDragged(MouseEvent evt)
653 if (graphStretch > -1)
655 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
657 if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
659 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
661 graphStretchY = evt.getY();
663 ap.paintAlignment(true);
667 ap.getScalePanel().mouseDragged(evt);
672 * Constructs the tooltip, and constructs and displays a status message, for
673 * the current mouse position
678 public void mouseMoved(MouseEvent evt)
680 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
684 this.setToolTipText(null);
691 for (int i = 0; i < aa.length; i++)
695 height += aa[i].height;
698 if (evt.getY() < height)
707 this.setToolTipText(null);
711 int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
713 if (av.hasHiddenColumns())
715 column = av.getColumnSelection().adjustForHiddenColumns(column);
718 AlignmentAnnotation ann = aa[row];
719 if (row > -1 && ann.annotations != null
720 && column < ann.annotations.length)
722 buildToolTip(ann, column, aa);
723 setStatusMessage(column, ann);
727 this.setToolTipText(null);
728 ap.alignFrame.statusBar.setText(" ");
733 * Builds a tooltip for the annotation at the current mouse position.
739 void buildToolTip(AlignmentAnnotation ann, int column,
740 AlignmentAnnotation[] anns)
742 if (ann.graphGroup > -1)
744 StringBuilder tip = new StringBuilder(32);
745 tip.append("<html>");
746 for (int i = 0; i < anns.length; i++)
748 if (anns[i].graphGroup == ann.graphGroup
749 && anns[i].annotations[column] != null)
751 tip.append(anns[i].label);
752 String description = anns[i].annotations[column].description;
753 if (description != null && description.length() > 0)
755 tip.append(" ").append(description);
760 if (tip.length() != 6)
762 tip.setLength(tip.length() - 4);
763 this.setToolTipText(tip.toString() + "</html>");
766 else if (ann.annotations[column] != null)
768 String description = ann.annotations[column].description;
769 if (description != null && description.length() > 0)
771 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
776 // clear the tooltip.
777 this.setToolTipText(null);
782 * Constructs and displays the status bar message
787 void setStatusMessage(int column, AlignmentAnnotation ann)
790 * show alignment column and annotation description if any
792 StringBuilder text = new StringBuilder(32);
793 text.append(MessageManager.getString("label.column")).append(" ")
796 if (ann.annotations[column] != null)
798 String description = ann.annotations[column].description;
799 if (description != null && description.trim().length() > 0)
801 text.append(" ").append(description);
806 * if the annotation is sequence-specific, show the sequence number
807 * in the alignment, and (if not a gap) the residue and position
809 SequenceI seqref = ann.sequenceRef;
812 int seqIndex = av.getAlignment().findIndex(seqref);
816 .append(MessageManager.getString("label.sequence"))
817 .append(" ").append(seqIndex + 1);
818 char residue = seqref.getCharAt(column);
819 if (!Comparison.isGap(residue))
823 if (av.getAlignment().isNucleotide())
825 name = ResidueProperties.nucleotideName.get(String
827 text.append(" Nucleotide: ").append(
828 name != null ? name : residue);
832 name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
833 : ResidueProperties.aa2Triplet.get(String
835 text.append(" Residue: ").append(name != null ? name : residue);
837 int residuePos = seqref.findPosition(column);
838 text.append(" (").append(residuePos).append(")");
843 ap.alignFrame.statusBar.setText(text.toString());
853 public void mouseClicked(MouseEvent evt)
855 // if (activeRow != -1)
857 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
858 // AlignmentAnnotation anot = aa[activeRow];
862 // TODO mouseClicked-content and drawCursor are quite experimental!
863 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
866 int pady = av.getCharHeight() / 5;
868 graphics.setColor(Color.black);
869 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
871 if (av.validCharWidth)
873 graphics.setColor(Color.white);
875 char s = seq.getCharAt(res);
877 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
878 graphics.drawString(String.valueOf(s), charOffset + x1,
879 (y1 + av.getCharHeight()) - pady);
884 private volatile boolean imageFresh = false;
893 public void paintComponent(Graphics g)
895 g.setColor(Color.white);
896 g.fillRect(0, 0, getWidth(), getHeight());
900 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
901 || (getVisibleRect().height != g.getClipBounds().height))
903 g.drawImage(image, 0, 0, this);
908 imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
913 if (image == null || imgWidth != image.getWidth(this)
914 || image.getHeight(this) != getHeight())
918 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
919 .getHeight(), BufferedImage.TYPE_INT_RGB);
920 } catch (OutOfMemoryError oom)
925 } catch (Exception x)
930 "Couldn't allocate memory to redraw screen. Please restart Jalview",
934 gg = (Graphics2D) image.getGraphics();
938 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
939 RenderingHints.VALUE_ANTIALIAS_ON);
942 gg.setFont(av.getFont());
943 fm = gg.getFontMetrics();
944 gg.setColor(Color.white);
945 gg.fillRect(0, 0, imgWidth, image.getHeight());
949 drawComponent(gg, av.startRes, av.endRes + 1);
951 g.drawImage(image, 0, 0, this);
955 * set true to enable redraw timing debug output on stderr
957 private final boolean debugRedraw = false;
960 * non-Thread safe repaint
963 * repaint with horizontal shift in alignment
965 public void fastPaint(int horizontal)
967 if ((horizontal == 0) || gg == null
968 || av.getAlignment().getAlignmentAnnotation() == null
969 || av.getAlignment().getAlignmentAnnotation().length < 1
970 || av.isCalcInProgress())
975 long stime = System.currentTimeMillis();
976 gg.copyArea(0, 0, imgWidth, getHeight(),
977 -horizontal * av.getCharWidth(), 0);
978 long mtime = System.currentTimeMillis();
979 int sr = av.startRes;
980 int er = av.endRes + 1;
983 if (horizontal > 0) // scrollbar pulled right, image to the left
985 transX = (er - sr - horizontal) * av.getCharWidth();
986 sr = er - horizontal;
988 else if (horizontal < 0)
990 er = sr - horizontal;
993 gg.translate(transX, 0);
995 drawComponent(gg, sr, er);
997 gg.translate(-transX, 0);
998 long dtime = System.currentTimeMillis();
1001 long rtime = System.currentTimeMillis();
1004 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
1005 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1006 + "\tRepaint call:\t" + (rtime - dtime));
1011 private volatile boolean lastImageGood = false;
1023 public void drawComponent(Graphics g, int startRes, int endRes)
1025 BufferedImage oldFaded = fadedImage;
1026 if (av.isCalcInProgress())
1030 lastImageGood = false;
1033 // We'll keep a record of the old image,
1034 // and draw a faded image until the calculation
1037 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1038 .getHeight() != image.getHeight()))
1040 // System.err.println("redraw faded image ("+(fadedImage==null ?
1041 // "null image" : "") + " lastGood="+lastImageGood+")");
1042 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1043 BufferedImage.TYPE_INT_RGB);
1045 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1047 fadedG.setColor(Color.white);
1048 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1050 fadedG.setComposite(AlphaComposite.getInstance(
1051 AlphaComposite.SRC_OVER, .3f));
1052 fadedG.drawImage(image, 0, 0, this);
1055 // make sure we don't overwrite the last good faded image until all
1056 // calculations have finished
1057 lastImageGood = false;
1062 if (fadedImage != null)
1064 oldFaded = fadedImage;
1069 g.setColor(Color.white);
1070 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1072 g.setFont(av.getFont());
1075 fm = g.getFontMetrics();
1078 if ((av.getAlignment().getAlignmentAnnotation() == null)
1079 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1081 g.setColor(Color.white);
1082 g.fillRect(0, 0, getWidth(), getHeight());
1083 g.setColor(Color.black);
1084 if (av.validCharWidth)
1086 g.drawString(MessageManager
1087 .getString("label.alignment_has_no_annotations"), 20, 15);
1092 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1094 if (!lastImageGood && fadedImage == null)
1096 fadedImage = oldFaded;
1101 public FontMetrics getFontMetrics()
1107 public Image getFadedImage()
1113 public int getFadedImageWidth()
1118 private int[] bounds = new int[2];
1121 public int[] getVisibleVRange()
1123 if (ap != null && ap.getAlabels() != null)
1125 int sOffset = -ap.getAlabels().getScrollOffset();
1126 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1127 bounds[0] = sOffset;
1128 bounds[1] = visHeight;
1138 * Try to ensure any references held are nulled
1140 public void dispose()
1150 * I created the renderer so I will dispose of it
1152 if (renderer != null)