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;
32 import jalview.viewmodel.ViewportListenerI;
34 import java.awt.AlphaComposite;
35 import java.awt.Color;
36 import java.awt.Dimension;
37 import java.awt.FontMetrics;
38 import java.awt.Graphics;
39 import java.awt.Graphics2D;
40 import java.awt.Image;
41 import java.awt.Rectangle;
42 import java.awt.RenderingHints;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.awt.event.AdjustmentEvent;
46 import java.awt.event.AdjustmentListener;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseListener;
49 import java.awt.event.MouseMotionListener;
50 import java.awt.event.MouseWheelEvent;
51 import java.awt.event.MouseWheelListener;
52 import java.awt.image.BufferedImage;
53 import java.beans.PropertyChangeEvent;
54 import java.util.ArrayList;
55 import java.util.Collections;
56 import java.util.List;
58 import javax.swing.JColorChooser;
59 import javax.swing.JMenuItem;
60 import javax.swing.JPanel;
61 import javax.swing.JPopupMenu;
62 import javax.swing.Scrollable;
63 import javax.swing.ToolTipManager;
66 * AnnotationPanel displays visible portion of annotation rows below unwrapped
72 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
73 MouseListener, MouseWheelListener, MouseMotionListener,
74 ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
76 String HELIX = MessageManager.getString("label.helix");
78 String SHEET = MessageManager.getString("label.sheet");
81 * For RNA secondary structure "stems" aka helices
83 String STEM = MessageManager.getString("label.rna_helix");
85 String LABEL = MessageManager.getString("label.label");
87 String REMOVE = MessageManager.getString("label.remove_annotation");
89 String COLOUR = MessageManager.getString("action.colour");
91 public final Color HELIX_COLOUR = Color.red.darker();
93 public final Color SHEET_COLOUR = Color.green.darker().darker();
95 public final Color STEM_COLOUR = Color.blue.darker();
98 public AlignViewport av;
102 public int activeRow = -1;
104 public BufferedImage image;
106 public volatile BufferedImage fadedImage;
110 public FontMetrics fm;
112 public int imgWidth = 0;
114 boolean fastPaint = false;
116 // Used For mouse Dragging and resizing graphs
117 int graphStretch = -1;
119 int graphStretchY = -1;
121 int min; // used by mouseDragged to see if user
123 int max; // used by mouseDragged to see if user
125 boolean mouseDragging = false;
127 // for editing cursor
132 public final AnnotationRenderer renderer;
134 private MouseWheelListener[] _mwl;
137 * Creates a new AnnotationPanel object.
142 public AnnotationPanel(AlignmentPanel ap)
144 ToolTipManager.sharedInstance().registerComponent(this);
145 ToolTipManager.sharedInstance().setInitialDelay(0);
146 ToolTipManager.sharedInstance().setDismissDelay(10000);
149 this.setLayout(null);
150 addMouseListener(this);
151 addMouseMotionListener(this);
152 ap.annotationScroller.getVerticalScrollBar()
153 .addAdjustmentListener(this);
154 // save any wheel listeners on the scroller, so we can propagate scroll
156 _mwl = ap.annotationScroller.getMouseWheelListeners();
157 // and then set our own listener to consume all mousewheel events
158 ap.annotationScroller.addMouseWheelListener(this);
159 renderer = new AnnotationRenderer();
161 av.getRanges().addPropertyChangeListener(this);
164 public AnnotationPanel(AlignViewport av)
167 renderer = new AnnotationRenderer();
171 public void mouseWheelMoved(MouseWheelEvent e)
176 if (e.getWheelRotation() > 0)
178 av.getRanges().scrollRight(true);
182 av.getRanges().scrollRight(false);
187 // TODO: find the correct way to let the event bubble up to
188 // ap.annotationScroller
189 for (MouseWheelListener mwl : _mwl)
193 mwl.mouseWheelMoved(e);
204 public Dimension getPreferredScrollableViewportSize()
206 return getPreferredSize();
210 public int getScrollableBlockIncrement(Rectangle visibleRect,
211 int orientation, int direction)
217 public boolean getScrollableTracksViewportHeight()
223 public boolean getScrollableTracksViewportWidth()
229 public int getScrollableUnitIncrement(Rectangle visibleRect,
230 int orientation, int direction)
239 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
243 public void adjustmentValueChanged(AdjustmentEvent evt)
245 // update annotation label display
246 ap.getAlabels().setScrollOffset(-evt.getValue());
250 * Calculates the height of the annotation displayed in the annotation panel.
251 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
252 * all annotation associated components are updated correctly.
255 public int adjustPanelHeight()
257 int height = av.calcPanelHeight();
258 this.setPreferredSize(new Dimension(1, height));
261 // revalidate only when the alignment panel is fully constructed
275 public void actionPerformed(ActionEvent evt)
277 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
282 Annotation[] anot = aa[activeRow].annotations;
284 if (anot.length < av.getColumnSelection().getMax())
286 Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
287 System.arraycopy(anot, 0, temp, 0, anot.length);
289 aa[activeRow].annotations = anot;
292 String action = evt.getActionCommand();
293 if (action.equals(REMOVE))
295 for (int index : av.getColumnSelection().getSelected())
297 if (av.getColumnSelection().isVisible(index))
303 else if (action.equals(LABEL))
305 String exMesg = collectAnnotVals(anot, LABEL);
306 String label = JvOptionPane.showInputDialog(this,
307 MessageManager.getString("label.enter_label"), exMesg);
314 if ((label.length() > 0) && !aa[activeRow].hasText)
316 aa[activeRow].hasText = true;
319 for (int index : av.getColumnSelection().getSelected())
321 if (!av.getColumnSelection().isVisible(index))
326 if (anot[index] == null)
328 anot[index] = new Annotation(label, "", ' ', 0);
332 anot[index].displayCharacter = label;
336 else if (action.equals(COLOUR))
338 Color col = JColorChooser.showDialog(this,
339 MessageManager.getString("label.select_foreground_colour"),
342 for (int index : av.getColumnSelection().getSelected())
344 if (!av.getColumnSelection().isVisible(index))
349 if (anot[index] == null)
351 anot[index] = new Annotation("", "", ' ', 0);
354 anot[index].colour = col;
358 // HELIX, SHEET or STEM
361 String symbol = "\u03B1"; // alpha
363 if (action.equals(HELIX))
367 else if (action.equals(SHEET))
370 symbol = "\u03B2"; // beta
373 // Added by LML to color stems
374 else if (action.equals(STEM))
377 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
378 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
381 if (!aa[activeRow].hasIcons)
383 aa[activeRow].hasIcons = true;
386 String label = JvOptionPane.showInputDialog(MessageManager
387 .getString("label.enter_label_for_the_structure"), symbol);
394 if ((label.length() > 0) && !aa[activeRow].hasText)
396 aa[activeRow].hasText = true;
397 if (action.equals(STEM))
399 aa[activeRow].showAllColLabels = true;
402 for (int index : av.getColumnSelection().getSelected())
404 if (!av.getColumnSelection().isVisible(index))
409 if (anot[index] == null)
411 anot[index] = new Annotation(label, "", type, 0);
414 anot[index].secondaryStructure = type != 'S' ? type : label
415 .length() == 0 ? ' ' : label.charAt(0);
416 anot[index].displayCharacter = label;
421 av.getAlignment().validateAnnotation(aa[activeRow]);
422 ap.alignmentChanged();
423 ap.alignFrame.setMenusForViewport();
431 * Returns any existing annotation concatenated as a string. For each
432 * annotation, takes the description, if any, else the secondary structure
433 * character (if type is HELIX, SHEET or STEM), else the display character (if
440 private String collectAnnotVals(Annotation[] anots, String type)
442 // TODO is this method wanted? why? 'last' is not used
444 StringBuilder collatedInput = new StringBuilder(64);
446 ColumnSelection viscols = av.getColumnSelection();
449 * the selection list (read-only view) is in selection order, not
450 * column order; make a copy so we can sort it
452 List<Integer> selected = new ArrayList<Integer>(viscols.getSelected());
453 Collections.sort(selected);
454 for (int index : selected)
456 // always check for current display state - just in case
457 if (!viscols.isVisible(index))
461 String tlabel = null;
462 if (anots[index] != null)
463 { // LML added stem code
464 if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
465 || type.equals(LABEL))
467 tlabel = anots[index].description;
468 if (tlabel == null || tlabel.length() < 1)
470 if (type.equals(HELIX) || type.equals(SHEET)
471 || type.equals(STEM))
473 tlabel = "" + anots[index].secondaryStructure;
477 tlabel = "" + anots[index].displayCharacter;
481 if (tlabel != null && !tlabel.equals(last))
483 if (last.length() > 0)
485 collatedInput.append(" ");
487 collatedInput.append(tlabel);
491 return collatedInput.toString();
501 public void mousePressed(MouseEvent evt)
504 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
513 final int y = evt.getY();
514 for (int i = 0; i < aa.length; i++)
518 height += aa[i].height;
527 else if (aa[i].graph > 0)
539 * isPopupTrigger fires in mousePressed on Mac,
540 * not until mouseRelease on Windows
542 if (evt.isPopupTrigger() && activeRow != -1)
544 showPopupMenu(y, evt.getX());
548 ap.getScalePanel().mousePressed(evt);
552 * Construct and display a context menu at the right-click position
557 void showPopupMenu(final int y, int x)
559 if (av.getColumnSelection() == null
560 || av.getColumnSelection().isEmpty())
565 JPopupMenu pop = new JPopupMenu(
566 MessageManager.getString("label.structure_type"));
569 * Just display the needed structure options
571 if (av.getAlignment().isNucleotide())
573 item = new JMenuItem(STEM);
574 item.addActionListener(this);
579 item = new JMenuItem(HELIX);
580 item.addActionListener(this);
582 item = new JMenuItem(SHEET);
583 item.addActionListener(this);
586 item = new JMenuItem(LABEL);
587 item.addActionListener(this);
589 item = new JMenuItem(COLOUR);
590 item.addActionListener(this);
592 item = new JMenuItem(REMOVE);
593 item.addActionListener(this);
595 pop.show(this, x, y);
605 public void mouseReleased(MouseEvent evt)
609 mouseDragging = false;
610 ap.getScalePanel().mouseReleased(evt);
613 * isPopupTrigger is set in mouseReleased on Windows
614 * (in mousePressed on Mac)
616 if (evt.isPopupTrigger() && activeRow != -1)
618 showPopupMenu(evt.getY(), evt.getX());
630 public void mouseEntered(MouseEvent evt)
632 ap.getScalePanel().mouseEntered(evt);
642 public void mouseExited(MouseEvent evt)
644 ap.getScalePanel().mouseExited(evt);
654 public void mouseDragged(MouseEvent evt)
656 if (graphStretch > -1)
658 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
660 if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
662 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
664 graphStretchY = evt.getY();
666 ap.paintAlignment(true);
670 ap.getScalePanel().mouseDragged(evt);
675 * Constructs the tooltip, and constructs and displays a status message, for
676 * the current mouse position
681 public void mouseMoved(MouseEvent evt)
683 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
687 this.setToolTipText(null);
694 for (int i = 0; i < aa.length; i++)
698 height += aa[i].height;
701 if (evt.getY() < height)
710 this.setToolTipText(null);
714 int column = (evt.getX() / av.getCharWidth())
715 + av.getRanges().getStartRes();
717 if (av.hasHiddenColumns())
719 column = av.getColumnSelection().adjustForHiddenColumns(column);
722 AlignmentAnnotation ann = aa[row];
723 if (row > -1 && ann.annotations != null
724 && column < ann.annotations.length)
726 buildToolTip(ann, column, aa);
727 setStatusMessage(column, ann);
731 this.setToolTipText(null);
732 ap.alignFrame.statusBar.setText(" ");
737 * Builds a tooltip for the annotation at the current mouse position.
743 void buildToolTip(AlignmentAnnotation ann, int column,
744 AlignmentAnnotation[] anns)
746 if (ann.graphGroup > -1)
748 StringBuilder tip = new StringBuilder(32);
749 tip.append("<html>");
750 for (int i = 0; i < anns.length; i++)
752 if (anns[i].graphGroup == ann.graphGroup
753 && anns[i].annotations[column] != null)
755 tip.append(anns[i].label);
756 String description = anns[i].annotations[column].description;
757 if (description != null && description.length() > 0)
759 tip.append(" ").append(description);
764 if (tip.length() != 6)
766 tip.setLength(tip.length() - 4);
767 this.setToolTipText(tip.toString() + "</html>");
770 else if (ann.annotations[column] != null)
772 String description = ann.annotations[column].description;
773 if (description != null && description.length() > 0)
775 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
780 // clear the tooltip.
781 this.setToolTipText(null);
786 * Constructs and displays the status bar message
791 void setStatusMessage(int column, AlignmentAnnotation ann)
794 * show alignment column and annotation description if any
796 StringBuilder text = new StringBuilder(32);
797 text.append(MessageManager.getString("label.column")).append(" ")
800 if (ann.annotations[column] != null)
802 String description = ann.annotations[column].description;
803 if (description != null && description.trim().length() > 0)
805 text.append(" ").append(description);
810 * if the annotation is sequence-specific, show the sequence number
811 * in the alignment, and (if not a gap) the residue and position
813 SequenceI seqref = ann.sequenceRef;
816 int seqIndex = av.getAlignment().findIndex(seqref);
820 .append(MessageManager.getString("label.sequence"))
821 .append(" ").append(seqIndex + 1);
822 char residue = seqref.getCharAt(column);
823 if (!Comparison.isGap(residue))
827 if (av.getAlignment().isNucleotide())
829 name = ResidueProperties.nucleotideName.get(String
831 text.append(" Nucleotide: ").append(
832 name != null ? name : residue);
836 name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
837 : ResidueProperties.aa2Triplet.get(String
839 text.append(" Residue: ").append(name != null ? name : residue);
841 int residuePos = seqref.findPosition(column);
842 text.append(" (").append(residuePos).append(")");
847 ap.alignFrame.statusBar.setText(text.toString());
857 public void mouseClicked(MouseEvent evt)
859 // if (activeRow != -1)
861 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
862 // AlignmentAnnotation anot = aa[activeRow];
866 // TODO mouseClicked-content and drawCursor are quite experimental!
867 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
870 int pady = av.getCharHeight() / 5;
872 graphics.setColor(Color.black);
873 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
875 if (av.validCharWidth)
877 graphics.setColor(Color.white);
879 char s = seq.getCharAt(res);
881 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
882 graphics.drawString(String.valueOf(s), charOffset + x1,
883 (y1 + av.getCharHeight()) - pady);
888 private volatile boolean imageFresh = false;
897 public void paintComponent(Graphics g)
899 g.setColor(Color.white);
900 g.fillRect(0, 0, getWidth(), getHeight());
904 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
905 || (getVisibleRect().height != g.getClipBounds().height))
907 g.drawImage(image, 0, 0, this);
912 imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes() + 1)
918 if (image == null || imgWidth != image.getWidth(this)
919 || image.getHeight(this) != getHeight())
923 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
924 .getHeight(), BufferedImage.TYPE_INT_RGB);
925 } catch (OutOfMemoryError oom)
930 } catch (Exception x)
935 "Couldn't allocate memory to redraw screen. Please restart Jalview",
939 gg = (Graphics2D) image.getGraphics();
943 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
944 RenderingHints.VALUE_ANTIALIAS_ON);
947 gg.setFont(av.getFont());
948 fm = gg.getFontMetrics();
949 gg.setColor(Color.white);
950 gg.fillRect(0, 0, imgWidth, image.getHeight());
954 drawComponent(gg, av.getRanges().getStartRes(), av.getRanges()
957 g.drawImage(image, 0, 0, this);
961 * set true to enable redraw timing debug output on stderr
963 private final boolean debugRedraw = false;
966 * non-Thread safe repaint
969 * repaint with horizontal shift in alignment
971 public void fastPaint(int horizontal)
973 if ((horizontal == 0) || gg == null
974 || av.getAlignment().getAlignmentAnnotation() == null
975 || av.getAlignment().getAlignmentAnnotation().length < 1
976 || av.isCalcInProgress())
981 long stime = System.currentTimeMillis();
982 gg.copyArea(0, 0, imgWidth, getHeight(),
983 -horizontal * av.getCharWidth(), 0);
984 long mtime = System.currentTimeMillis();
985 int sr = av.getRanges().getStartRes();
986 int er = av.getRanges().getEndRes() + 1;
989 if (horizontal > 0) // scrollbar pulled right, image to the left
991 transX = (er - sr - horizontal) * av.getCharWidth();
992 sr = er - horizontal;
994 else if (horizontal < 0)
996 er = sr - horizontal;
999 gg.translate(transX, 0);
1001 drawComponent(gg, sr, er);
1003 gg.translate(-transX, 0);
1004 long dtime = System.currentTimeMillis();
1007 long rtime = System.currentTimeMillis();
1010 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
1011 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1012 + "\tRepaint call:\t" + (rtime - dtime));
1017 private volatile boolean lastImageGood = false;
1029 public void drawComponent(Graphics g, int startRes, int endRes)
1031 BufferedImage oldFaded = fadedImage;
1032 if (av.isCalcInProgress())
1036 lastImageGood = false;
1039 // We'll keep a record of the old image,
1040 // and draw a faded image until the calculation
1043 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1044 .getHeight() != image.getHeight()))
1046 // System.err.println("redraw faded image ("+(fadedImage==null ?
1047 // "null image" : "") + " lastGood="+lastImageGood+")");
1048 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1049 BufferedImage.TYPE_INT_RGB);
1051 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1053 fadedG.setColor(Color.white);
1054 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1056 fadedG.setComposite(AlphaComposite.getInstance(
1057 AlphaComposite.SRC_OVER, .3f));
1058 fadedG.drawImage(image, 0, 0, this);
1061 // make sure we don't overwrite the last good faded image until all
1062 // calculations have finished
1063 lastImageGood = false;
1068 if (fadedImage != null)
1070 oldFaded = fadedImage;
1075 g.setColor(Color.white);
1076 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1078 g.setFont(av.getFont());
1081 fm = g.getFontMetrics();
1084 if ((av.getAlignment().getAlignmentAnnotation() == null)
1085 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1087 g.setColor(Color.white);
1088 g.fillRect(0, 0, getWidth(), getHeight());
1089 g.setColor(Color.black);
1090 if (av.validCharWidth)
1092 g.drawString(MessageManager
1093 .getString("label.alignment_has_no_annotations"), 20, 15);
1098 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1100 if (!lastImageGood && fadedImage == null)
1102 fadedImage = oldFaded;
1107 public FontMetrics getFontMetrics()
1113 public Image getFadedImage()
1119 public int getFadedImageWidth()
1124 private int[] bounds = new int[2];
1127 public int[] getVisibleVRange()
1129 if (ap != null && ap.getAlabels() != null)
1131 int sOffset = -ap.getAlabels().getScrollOffset();
1132 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1133 bounds[0] = sOffset;
1134 bounds[1] = visHeight;
1144 * Try to ensure any references held are nulled
1146 public void dispose()
1156 * I created the renderer so I will dispose of it
1158 if (renderer != null)
1165 public void propertyChange(PropertyChangeEvent evt)
1167 // Respond to viewport range changes (e.g. alignment panel was scrolled)
1168 if (evt.getPropertyName().equals("startres")
1169 || evt.getPropertyName().equals("endres"))
1171 fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());