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.HiddenColumns;
27 import jalview.datamodel.SequenceI;
28 import jalview.renderer.AnnotationRenderer;
29 import jalview.renderer.AwtRenderPanelI;
30 import jalview.schemes.ResidueProperties;
31 import jalview.util.Comparison;
32 import jalview.util.MessageManager;
33 import jalview.viewmodel.ViewportListenerI;
34 import jalview.viewmodel.ViewportRanges;
36 import java.awt.AlphaComposite;
37 import java.awt.Color;
38 import java.awt.Dimension;
39 import java.awt.FontMetrics;
40 import java.awt.Graphics;
41 import java.awt.Graphics2D;
42 import java.awt.Image;
43 import java.awt.Rectangle;
44 import java.awt.RenderingHints;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.AdjustmentEvent;
48 import java.awt.event.AdjustmentListener;
49 import java.awt.event.MouseEvent;
50 import java.awt.event.MouseListener;
51 import java.awt.event.MouseMotionListener;
52 import java.awt.event.MouseWheelEvent;
53 import java.awt.event.MouseWheelListener;
54 import java.awt.image.BufferedImage;
55 import java.beans.PropertyChangeEvent;
56 import java.util.ArrayList;
57 import java.util.Collections;
58 import java.util.List;
60 import javax.swing.JColorChooser;
61 import javax.swing.JDialog;
62 import javax.swing.JMenuItem;
63 import javax.swing.JPanel;
64 import javax.swing.JPopupMenu;
65 import javax.swing.Scrollable;
66 import javax.swing.ToolTipManager;
69 * AnnotationPanel displays visible portion of annotation rows below unwrapped
75 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
76 MouseListener, MouseWheelListener, MouseMotionListener,
77 ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
79 String HELIX = MessageManager.getString("label.helix");
81 String SHEET = MessageManager.getString("label.sheet");
84 * For RNA secondary structure "stems" aka helices
86 String STEM = MessageManager.getString("label.rna_helix");
88 String LABEL = MessageManager.getString("label.label");
90 String REMOVE = MessageManager.getString("label.remove_annotation");
92 String COLOUR = MessageManager.getString("action.colour");
94 public final Color HELIX_COLOUR = Color.red.darker();
96 public final Color SHEET_COLOUR = Color.green.darker().darker();
98 public final Color STEM_COLOUR = Color.blue.darker();
101 public AlignViewport av;
105 public int activeRow = -1;
107 public BufferedImage image;
109 public volatile BufferedImage fadedImage;
113 public FontMetrics fm;
115 public int imgWidth = 0;
117 boolean fastPaint = false;
119 // Used For mouse Dragging and resizing graphs
120 int graphStretch = -1;
122 int graphStretchY = -1;
124 int min; // used by mouseDragged to see if user
126 int max; // used by mouseDragged to see if user
128 boolean mouseDragging = false;
130 // for editing cursor
135 public final AnnotationRenderer renderer;
137 private MouseWheelListener[] _mwl;
140 * Creates a new AnnotationPanel object.
145 public AnnotationPanel(AlignmentPanel ap)
147 ToolTipManager.sharedInstance().registerComponent(this);
148 ToolTipManager.sharedInstance().setInitialDelay(0);
149 ToolTipManager.sharedInstance().setDismissDelay(10000);
152 this.setLayout(null);
153 addMouseListener(this);
154 addMouseMotionListener(this);
155 ap.annotationScroller.getVerticalScrollBar()
156 .addAdjustmentListener(this);
157 // save any wheel listeners on the scroller, so we can propagate scroll
159 _mwl = ap.annotationScroller.getMouseWheelListeners();
160 // and then set our own listener to consume all mousewheel events
161 ap.annotationScroller.addMouseWheelListener(this);
162 renderer = new AnnotationRenderer();
164 av.getRanges().addPropertyChangeListener(this);
167 public AnnotationPanel(AlignViewport av)
170 renderer = new AnnotationRenderer();
174 public void mouseWheelMoved(MouseWheelEvent e)
179 double wheelRotation = e.getPreciseWheelRotation();
180 if (wheelRotation > 0)
182 av.getRanges().scrollRight(true);
184 else if (wheelRotation < 0)
186 av.getRanges().scrollRight(false);
191 // TODO: find the correct way to let the event bubble up to
192 // ap.annotationScroller
193 for (MouseWheelListener mwl : _mwl)
197 mwl.mouseWheelMoved(e);
208 public Dimension getPreferredScrollableViewportSize()
210 return getPreferredSize();
214 public int getScrollableBlockIncrement(Rectangle visibleRect,
215 int orientation, int direction)
221 public boolean getScrollableTracksViewportHeight()
227 public boolean getScrollableTracksViewportWidth()
233 public int getScrollableUnitIncrement(Rectangle visibleRect,
234 int orientation, int direction)
243 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
247 public void adjustmentValueChanged(AdjustmentEvent evt)
249 // update annotation label display
250 ap.getAlabels().setScrollOffset(-evt.getValue());
254 * Calculates the height of the annotation displayed in the annotation panel.
255 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
256 * all annotation associated components are updated correctly.
259 public int adjustPanelHeight()
261 int height = av.calcPanelHeight();
262 this.setPreferredSize(new Dimension(1, height));
265 // revalidate only when the alignment panel is fully constructed
279 public void actionPerformed(ActionEvent evt)
281 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
286 Annotation[] anot = aa[activeRow].annotations;
288 if (anot.length < av.getColumnSelection().getMax())
290 Annotation[] temp = new Annotation[av.getColumnSelection().getMax()
292 System.arraycopy(anot, 0, temp, 0, anot.length);
294 aa[activeRow].annotations = anot;
297 String action = evt.getActionCommand();
298 if (action.equals(REMOVE))
300 for (int index : av.getColumnSelection().getSelected())
302 if (av.getAlignment().getHiddenColumns().isVisible(index))
308 else if (action.equals(LABEL))
310 String exMesg = collectAnnotVals(anot, LABEL);
311 String label = JvOptionPane.showInputDialog(this,
312 MessageManager.getString("label.enter_label"), exMesg);
319 if ((label.length() > 0) && !aa[activeRow].hasText)
321 aa[activeRow].hasText = true;
324 for (int index : av.getColumnSelection().getSelected())
326 if (!av.getAlignment().getHiddenColumns().isVisible(index))
331 if (anot[index] == null)
333 anot[index] = new Annotation(label, "", ' ', 0);
337 anot[index].displayCharacter = label;
341 else if (action.equals(COLOUR))
343 final Annotation[] fAnot = anot;
344 JColorChooser colorChooser = new JColorChooser();
345 colorChooser.setColor(Color.black);
346 String title = MessageManager.getString("label.select_foreground_colour");
347 ActionListener listener = new ActionListener() {
349 public void actionPerformed(ActionEvent e)
351 HiddenColumns hiddenColumns = av.getAlignment().getHiddenColumns();
352 for (int index : av.getColumnSelection().getSelected())
354 if (hiddenColumns.isVisible(index))
356 if (fAnot[index] == null)
358 fAnot[index] = new Annotation("", "", ' ', 0);
360 fAnot[index].colour = colorChooser.getColor();
364 JDialog dialog = JColorChooser.createDialog(this, title, true, colorChooser, listener, null);
365 dialog.setVisible(true);
368 // HELIX, SHEET or STEM
371 String symbol = "\u03B1"; // alpha
373 if (action.equals(HELIX))
377 else if (action.equals(SHEET))
380 symbol = "\u03B2"; // beta
383 // Added by LML to color stems
384 else if (action.equals(STEM))
387 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
388 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
391 if (!aa[activeRow].hasIcons)
393 aa[activeRow].hasIcons = true;
396 String label = JvOptionPane.showInputDialog(MessageManager
397 .getString("label.enter_label_for_the_structure"), symbol);
404 if ((label.length() > 0) && !aa[activeRow].hasText)
406 aa[activeRow].hasText = true;
407 if (action.equals(STEM))
409 aa[activeRow].showAllColLabels = true;
412 for (int index : av.getColumnSelection().getSelected())
414 if (!av.getAlignment().getHiddenColumns().isVisible(index))
419 if (anot[index] == null)
421 anot[index] = new Annotation(label, "", type, 0);
424 anot[index].secondaryStructure = type != 'S' ? type
425 : label.length() == 0 ? ' ' : label.charAt(0);
426 anot[index].displayCharacter = label;
431 av.getAlignment().validateAnnotation(aa[activeRow]);
432 ap.alignmentChanged();
433 ap.alignFrame.setMenusForViewport();
441 * Returns any existing annotation concatenated as a string. For each
442 * annotation, takes the description, if any, else the secondary structure
443 * character (if type is HELIX, SHEET or STEM), else the display character (if
450 private String collectAnnotVals(Annotation[] anots, String type)
452 // TODO is this method wanted? why? 'last' is not used
454 StringBuilder collatedInput = new StringBuilder(64);
456 ColumnSelection viscols = av.getColumnSelection();
457 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
460 * the selection list (read-only view) is in selection order, not
461 * column order; make a copy so we can sort it
463 List<Integer> selected = new ArrayList<>(viscols.getSelected());
464 Collections.sort(selected);
465 for (int index : selected)
467 // always check for current display state - just in case
468 if (!hidden.isVisible(index))
472 String tlabel = null;
473 if (anots[index] != null)
474 { // LML added stem code
475 if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
476 || type.equals(LABEL))
478 tlabel = anots[index].description;
479 if (tlabel == null || tlabel.length() < 1)
481 if (type.equals(HELIX) || type.equals(SHEET)
482 || type.equals(STEM))
484 tlabel = "" + anots[index].secondaryStructure;
488 tlabel = "" + anots[index].displayCharacter;
492 if (tlabel != null && !tlabel.equals(last))
494 if (last.length() > 0)
496 collatedInput.append(" ");
498 collatedInput.append(tlabel);
502 return collatedInput.toString();
512 public void mousePressed(MouseEvent evt)
515 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
524 final int y = evt.getY();
525 for (int i = 0; i < aa.length; i++)
529 height += aa[i].height;
538 else if (aa[i].graph > 0)
550 * isPopupTrigger fires in mousePressed on Mac,
551 * not until mouseRelease on Windows
553 if (evt.isPopupTrigger() && activeRow != -1)
555 showPopupMenu(y, evt.getX());
559 ap.getScalePanel().mousePressed(evt);
563 * Construct and display a context menu at the right-click position
568 void showPopupMenu(final int y, int x)
570 if (av.getColumnSelection() == null
571 || av.getColumnSelection().isEmpty())
576 JPopupMenu pop = new JPopupMenu(
577 MessageManager.getString("label.structure_type"));
580 * Just display the needed structure options
582 if (av.getAlignment().isNucleotide())
584 item = new JMenuItem(STEM);
585 item.addActionListener(this);
590 item = new JMenuItem(HELIX);
591 item.addActionListener(this);
593 item = new JMenuItem(SHEET);
594 item.addActionListener(this);
597 item = new JMenuItem(LABEL);
598 item.addActionListener(this);
600 item = new JMenuItem(COLOUR);
601 item.addActionListener(this);
603 item = new JMenuItem(REMOVE);
604 item.addActionListener(this);
606 pop.show(this, x, y);
616 public void mouseReleased(MouseEvent evt)
620 mouseDragging = false;
621 ap.getScalePanel().mouseReleased(evt);
624 * isPopupTrigger is set in mouseReleased on Windows
625 * (in mousePressed on Mac)
627 if (evt.isPopupTrigger() && activeRow != -1)
629 showPopupMenu(evt.getY(), evt.getX());
641 public void mouseEntered(MouseEvent evt)
643 ap.getScalePanel().mouseEntered(evt);
653 public void mouseExited(MouseEvent evt)
655 ap.getScalePanel().mouseExited(evt);
665 public void mouseDragged(MouseEvent evt)
667 if (graphStretch > -1)
670 .getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
672 if (av.getAlignment()
673 .getAlignmentAnnotation()[graphStretch].graphHeight < 0)
676 .getAlignmentAnnotation()[graphStretch].graphHeight = 0;
678 graphStretchY = evt.getY();
680 ap.paintAlignment(false, false);
684 ap.getScalePanel().mouseDragged(evt);
689 * Constructs the tooltip, and constructs and displays a status message, for
690 * the current mouse position
695 public void mouseMoved(MouseEvent evt)
697 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
701 this.setToolTipText(null);
708 for (int i = 0; i < aa.length; i++)
712 height += aa[i].height;
715 if (evt.getY() < height)
724 this.setToolTipText(null);
728 int column = (evt.getX() / av.getCharWidth())
729 + av.getRanges().getStartRes();
731 if (av.hasHiddenColumns())
733 column = av.getAlignment().getHiddenColumns()
734 .visibleToAbsoluteColumn(column);
737 AlignmentAnnotation ann = aa[row];
738 if (row > -1 && ann.annotations != null
739 && column < ann.annotations.length)
741 buildToolTip(ann, column, aa);
742 setStatusMessage(column, ann);
746 this.setToolTipText(null);
747 ap.alignFrame.statusBar.setText(" ");
752 * Builds a tooltip for the annotation at the current mouse position.
758 void buildToolTip(AlignmentAnnotation ann, int column,
759 AlignmentAnnotation[] anns)
761 if (ann.graphGroup > -1)
763 StringBuilder tip = new StringBuilder(32);
764 tip.append("<html>");
765 for (int i = 0; i < anns.length; i++)
767 if (anns[i].graphGroup == ann.graphGroup
768 && anns[i].annotations[column] != null)
770 tip.append(anns[i].label);
771 String description = anns[i].annotations[column].description;
772 if (description != null && description.length() > 0)
774 tip.append(" ").append(description);
779 if (tip.length() != 6)
781 tip.setLength(tip.length() - 4);
782 this.setToolTipText(tip.toString() + "</html>");
785 else if (ann.annotations[column] != null)
787 String description = ann.annotations[column].description;
788 if (description != null && description.length() > 0)
790 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
794 this.setToolTipText(null); // no tooltip if null or empty description
799 // clear the tooltip.
800 this.setToolTipText(null);
805 * Constructs and displays the status bar message
810 void setStatusMessage(int column, AlignmentAnnotation ann)
813 * show alignment column and annotation description if any
815 StringBuilder text = new StringBuilder(32);
816 text.append(MessageManager.getString("label.column")).append(" ")
819 if (ann.annotations[column] != null)
821 String description = ann.annotations[column].description;
822 if (description != null && description.trim().length() > 0)
824 text.append(" ").append(description);
829 * if the annotation is sequence-specific, show the sequence number
830 * in the alignment, and (if not a gap) the residue and position
832 SequenceI seqref = ann.sequenceRef;
835 int seqIndex = av.getAlignment().findIndex(seqref);
838 text.append(", ").append(MessageManager.getString("label.sequence"))
839 .append(" ").append(seqIndex + 1);
840 char residue = seqref.getCharAt(column);
841 if (!Comparison.isGap(residue))
845 if (av.getAlignment().isNucleotide())
847 name = ResidueProperties.nucleotideName
848 .get(String.valueOf(residue));
849 text.append(" Nucleotide: ")
850 .append(name != null ? name : residue);
854 name = 'X' == residue ? "X"
855 : ('*' == residue ? "STOP"
856 : ResidueProperties.aa2Triplet
857 .get(String.valueOf(residue)));
858 text.append(" Residue: ").append(name != null ? name : residue);
860 int residuePos = seqref.findPosition(column);
861 text.append(" (").append(residuePos).append(")");
866 ap.alignFrame.statusBar.setText(text.toString());
876 public void mouseClicked(MouseEvent evt)
878 // if (activeRow != -1)
880 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
881 // AlignmentAnnotation anot = aa[activeRow];
885 // TODO mouseClicked-content and drawCursor are quite experimental!
886 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
889 int pady = av.getCharHeight() / 5;
891 graphics.setColor(Color.black);
892 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
894 if (av.validCharWidth)
896 graphics.setColor(Color.white);
898 char s = seq.getCharAt(res);
900 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
901 graphics.drawString(String.valueOf(s), charOffset + x1,
902 (y1 + av.getCharHeight()) - pady);
907 private volatile boolean imageFresh = false;
916 public void paintComponent(Graphics g)
918 super.paintComponent(g);
920 g.setColor(Color.white);
921 g.fillRect(0, 0, getWidth(), getHeight());
925 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
926 || (getVisibleRect().height != g.getClipBounds().height))
928 g.drawImage(image, 0, 0, this);
933 imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
934 + 1) * av.getCharWidth();
939 if (image == null || imgWidth != image.getWidth(this)
940 || image.getHeight(this) != getHeight())
944 image = new BufferedImage(imgWidth,
945 ap.getAnnotationPanel().getHeight(),
946 BufferedImage.TYPE_INT_RGB);
947 } catch (OutOfMemoryError oom)
952 } catch (Exception x)
957 "Couldn't allocate memory to redraw screen. Please restart Jalview",
961 gg = (Graphics2D) image.getGraphics();
965 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
966 RenderingHints.VALUE_ANTIALIAS_ON);
969 gg.setFont(av.getFont());
970 fm = gg.getFontMetrics();
971 gg.setColor(Color.white);
972 gg.fillRect(0, 0, imgWidth, image.getHeight());
976 drawComponent(gg, av.getRanges().getStartRes(),
977 av.getRanges().getEndRes() + 1);
979 g.drawImage(image, 0, 0, this);
983 * set true to enable redraw timing debug output on stderr
985 private final boolean debugRedraw = false;
988 * non-Thread safe repaint
991 * repaint with horizontal shift in alignment
993 public void fastPaint(int horizontal)
995 if ((horizontal == 0) || gg == null
996 || av.getAlignment().getAlignmentAnnotation() == null
997 || av.getAlignment().getAlignmentAnnotation().length < 1
998 || av.isCalcInProgress())
1004 int sr = av.getRanges().getStartRes();
1005 int er = av.getRanges().getEndRes() + 1;
1008 gg.copyArea(0, 0, imgWidth, getHeight(),
1009 -horizontal * av.getCharWidth(), 0);
1011 if (horizontal > 0) // scrollbar pulled right, image to the left
1013 transX = (er - sr - horizontal) * av.getCharWidth();
1014 sr = er - horizontal;
1016 else if (horizontal < 0)
1018 er = sr - horizontal;
1021 gg.translate(transX, 0);
1023 drawComponent(gg, sr, er);
1025 gg.translate(-transX, 0);
1029 // Call repaint on alignment panel so that repaints from other alignment
1030 // panel components can be aggregated. Otherwise performance of the overview
1031 // window and others may be adversely affected.
1032 av.getAlignPanel().repaint();
1035 private volatile boolean lastImageGood = false;
1047 public void drawComponent(Graphics g, int startRes, int endRes)
1049 BufferedImage oldFaded = fadedImage;
1050 if (av.isCalcInProgress())
1054 lastImageGood = false;
1057 // We'll keep a record of the old image,
1058 // and draw a faded image until the calculation
1061 && (fadedImage == null || fadedImage.getWidth() != imgWidth
1062 || fadedImage.getHeight() != image.getHeight()))
1064 // System.err.println("redraw faded image ("+(fadedImage==null ?
1065 // "null image" : "") + " lastGood="+lastImageGood+")");
1066 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1067 BufferedImage.TYPE_INT_RGB);
1069 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1071 fadedG.setColor(Color.white);
1072 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1074 fadedG.setComposite(
1075 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1076 fadedG.drawImage(image, 0, 0, this);
1079 // make sure we don't overwrite the last good faded image until all
1080 // calculations have finished
1081 lastImageGood = false;
1086 if (fadedImage != null)
1088 oldFaded = fadedImage;
1093 g.setColor(Color.white);
1094 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1096 g.setFont(av.getFont());
1099 fm = g.getFontMetrics();
1102 if ((av.getAlignment().getAlignmentAnnotation() == null)
1103 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1105 g.setColor(Color.white);
1106 g.fillRect(0, 0, getWidth(), getHeight());
1107 g.setColor(Color.black);
1108 if (av.validCharWidth)
1110 g.drawString(MessageManager
1111 .getString("label.alignment_has_no_annotations"), 20, 15);
1116 lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1118 if (!lastImageGood && fadedImage == null)
1120 fadedImage = oldFaded;
1125 public FontMetrics getFontMetrics()
1131 public Image getFadedImage()
1137 public int getFadedImageWidth()
1142 private int[] bounds = new int[2];
1145 public int[] getVisibleVRange()
1147 if (ap != null && ap.getAlabels() != null)
1149 int sOffset = -ap.getAlabels().getScrollOffset();
1150 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1151 bounds[0] = sOffset;
1152 bounds[1] = visHeight;
1162 * Try to ensure any references held are nulled
1164 public void dispose()
1174 * I created the renderer so I will dispose of it
1176 if (renderer != null)
1183 public void propertyChange(PropertyChangeEvent evt)
1185 // Respond to viewport range changes (e.g. alignment panel was scrolled)
1186 // Both scrolling and resizing change viewport ranges: scrolling changes
1187 // both start and end points, but resize only changes end values.
1188 // Here we only want to fastpaint on a scroll, with resize using a normal
1189 // paint, so scroll events are identified as changes to the horizontal or
1190 // vertical start value.
1191 if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1193 fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1195 else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1197 fastPaint(((int[]) evt.getNewValue())[0]
1198 - ((int[]) evt.getOldValue())[0]);
1200 else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))