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.gui.JalviewColourChooser.ColourChooserListener;
29 import jalview.renderer.AnnotationRenderer;
30 import jalview.renderer.AwtRenderPanelI;
31 import jalview.schemes.FeatureColour;
32 import jalview.schemes.ResidueProperties;
33 import jalview.util.Comparison;
34 import jalview.util.MessageManager;
35 import jalview.viewmodel.ViewportListenerI;
36 import jalview.viewmodel.ViewportRanges;
38 import java.awt.AlphaComposite;
39 import java.awt.Color;
40 import java.awt.Dimension;
41 import java.awt.FontMetrics;
42 import java.awt.Graphics;
43 import java.awt.Graphics2D;
44 import java.awt.Image;
45 import java.awt.Rectangle;
46 import java.awt.RenderingHints;
47 import java.awt.event.ActionEvent;
48 import java.awt.event.ActionListener;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.MouseEvent;
52 import java.awt.event.MouseListener;
53 import java.awt.event.MouseMotionListener;
54 import java.awt.event.MouseWheelEvent;
55 import java.awt.event.MouseWheelListener;
56 import java.awt.image.BufferedImage;
57 import java.beans.PropertyChangeEvent;
58 import java.util.ArrayList;
59 import java.util.Collections;
60 import java.util.List;
62 import javax.swing.JColorChooser;
63 import javax.swing.JDialog;
64 import javax.swing.JMenuItem;
65 import javax.swing.JPanel;
66 import javax.swing.JPopupMenu;
67 import javax.swing.Scrollable;
68 import javax.swing.ToolTipManager;
71 * AnnotationPanel displays visible portion of annotation rows below unwrapped
77 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
78 MouseListener, MouseWheelListener, MouseMotionListener,
79 ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
81 String HELIX = MessageManager.getString("label.helix");
83 String SHEET = MessageManager.getString("label.sheet");
86 * For RNA secondary structure "stems" aka helices
88 String STEM = MessageManager.getString("label.rna_helix");
90 String LABEL = MessageManager.getString("label.label");
92 String REMOVE = MessageManager.getString("label.remove_annotation");
94 String COLOUR = MessageManager.getString("action.colour");
96 public final Color HELIX_COLOUR = Color.red.darker();
98 public final Color SHEET_COLOUR = Color.green.darker().darker();
100 public final Color STEM_COLOUR = Color.blue.darker();
103 public AlignViewport av;
107 public int activeRow = -1;
109 public BufferedImage image;
111 public volatile BufferedImage fadedImage;
115 public FontMetrics fm;
117 public int imgWidth = 0;
119 boolean fastPaint = false;
121 // Used For mouse Dragging and resizing graphs
122 int graphStretch = -1;
124 int graphStretchY = -1;
126 int min; // used by mouseDragged to see if user
128 int max; // used by mouseDragged to see if user
130 boolean mouseDragging = false;
132 // for editing cursor
137 public final AnnotationRenderer renderer;
139 private MouseWheelListener[] _mwl;
142 * Creates a new AnnotationPanel object.
147 public AnnotationPanel(AlignmentPanel ap)
149 ToolTipManager.sharedInstance().registerComponent(this);
150 ToolTipManager.sharedInstance().setInitialDelay(0);
151 ToolTipManager.sharedInstance().setDismissDelay(10000);
154 this.setLayout(null);
155 addMouseListener(this);
156 addMouseMotionListener(this);
157 ap.annotationScroller.getVerticalScrollBar()
158 .addAdjustmentListener(this);
159 // save any wheel listeners on the scroller, so we can propagate scroll
161 _mwl = ap.annotationScroller.getMouseWheelListeners();
162 // and then set our own listener to consume all mousewheel events
163 ap.annotationScroller.addMouseWheelListener(this);
164 renderer = new AnnotationRenderer();
166 av.getRanges().addPropertyChangeListener(this);
169 public AnnotationPanel(AlignViewport av)
172 renderer = new AnnotationRenderer();
176 public void mouseWheelMoved(MouseWheelEvent e)
181 double wheelRotation = e.getPreciseWheelRotation();
182 if (wheelRotation > 0)
184 av.getRanges().scrollRight(true);
186 else if (wheelRotation < 0)
188 av.getRanges().scrollRight(false);
193 // TODO: find the correct way to let the event bubble up to
194 // ap.annotationScroller
195 for (MouseWheelListener mwl : _mwl)
199 mwl.mouseWheelMoved(e);
210 public Dimension getPreferredScrollableViewportSize()
212 return getPreferredSize();
216 public int getScrollableBlockIncrement(Rectangle visibleRect,
217 int orientation, int direction)
223 public boolean getScrollableTracksViewportHeight()
229 public boolean getScrollableTracksViewportWidth()
235 public int getScrollableUnitIncrement(Rectangle visibleRect,
236 int orientation, int direction)
245 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
249 public void adjustmentValueChanged(AdjustmentEvent evt)
251 // update annotation label display
252 ap.getAlabels().setScrollOffset(-evt.getValue());
256 * Calculates the height of the annotation displayed in the annotation panel.
257 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
258 * all annotation associated components are updated correctly.
261 public int adjustPanelHeight()
263 int height = av.calcPanelHeight();
264 this.setPreferredSize(new Dimension(1, height));
267 // revalidate only when the alignment panel is fully constructed
281 public void actionPerformed(ActionEvent evt)
283 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
288 Annotation[] anot = aa[activeRow].annotations;
290 if (anot.length < av.getColumnSelection().getMax())
292 Annotation[] temp = new Annotation[av.getColumnSelection().getMax()
294 System.arraycopy(anot, 0, temp, 0, anot.length);
296 aa[activeRow].annotations = anot;
299 String action = evt.getActionCommand();
300 if (action.equals(REMOVE))
302 for (int index : av.getColumnSelection().getSelected())
304 if (av.getAlignment().getHiddenColumns().isVisible(index))
310 else if (action.equals(LABEL))
312 String exMesg = collectAnnotVals(anot, LABEL);
313 String label = JvOptionPane.showInputDialog(this,
314 MessageManager.getString("label.enter_label"), exMesg);
321 if ((label.length() > 0) && !aa[activeRow].hasText)
323 aa[activeRow].hasText = true;
326 for (int index : av.getColumnSelection().getSelected())
328 if (!av.getAlignment().getHiddenColumns().isVisible(index))
333 if (anot[index] == null)
335 anot[index] = new Annotation(label, "", ' ', 0);
339 anot[index].displayCharacter = label;
343 else if (action.equals(COLOUR))
345 final Annotation[] fAnot = anot;
346 String title = MessageManager
347 .getString("label.select_foreground_colour");
348 ColourChooserListener listener = new ColourChooserListener()
351 public void colourSelected(Color c)
353 HiddenColumns hiddenColumns = av.getAlignment().getHiddenColumns();
354 for (int index : av.getColumnSelection().getSelected())
356 if (hiddenColumns.isVisible(index))
358 if (fAnot[index] == null)
360 fAnot[index] = new Annotation("", "", ' ', 0);
362 fAnot[index].colour = c;
366 JalviewColourChooser.showColourChooser(this,
367 title, Color.black, listener);
370 // HELIX, SHEET or STEM
373 String symbol = "\u03B1"; // alpha
375 if (action.equals(HELIX))
379 else if (action.equals(SHEET))
382 symbol = "\u03B2"; // beta
385 // Added by LML to color stems
386 else if (action.equals(STEM))
389 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
390 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
393 if (!aa[activeRow].hasIcons)
395 aa[activeRow].hasIcons = true;
398 String label = JvOptionPane.showInputDialog(MessageManager
399 .getString("label.enter_label_for_the_structure"), symbol);
406 if ((label.length() > 0) && !aa[activeRow].hasText)
408 aa[activeRow].hasText = true;
409 if (action.equals(STEM))
411 aa[activeRow].showAllColLabels = true;
414 for (int index : av.getColumnSelection().getSelected())
416 if (!av.getAlignment().getHiddenColumns().isVisible(index))
421 if (anot[index] == null)
423 anot[index] = new Annotation(label, "", type, 0);
426 anot[index].secondaryStructure = type != 'S' ? type
427 : label.length() == 0 ? ' ' : label.charAt(0);
428 anot[index].displayCharacter = label;
433 av.getAlignment().validateAnnotation(aa[activeRow]);
434 ap.alignmentChanged();
435 ap.alignFrame.setMenusForViewport();
443 * Returns any existing annotation concatenated as a string. For each
444 * annotation, takes the description, if any, else the secondary structure
445 * character (if type is HELIX, SHEET or STEM), else the display character (if
452 private String collectAnnotVals(Annotation[] anots, String type)
454 // TODO is this method wanted? why? 'last' is not used
456 StringBuilder collatedInput = new StringBuilder(64);
458 ColumnSelection viscols = av.getColumnSelection();
459 HiddenColumns hidden = av.getAlignment().getHiddenColumns();
462 * the selection list (read-only view) is in selection order, not
463 * column order; make a copy so we can sort it
465 List<Integer> selected = new ArrayList<>(viscols.getSelected());
466 Collections.sort(selected);
467 for (int index : selected)
469 // always check for current display state - just in case
470 if (!hidden.isVisible(index))
474 String tlabel = null;
475 if (anots[index] != null)
476 { // LML added stem code
477 if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
478 || type.equals(LABEL))
480 tlabel = anots[index].description;
481 if (tlabel == null || tlabel.length() < 1)
483 if (type.equals(HELIX) || type.equals(SHEET)
484 || type.equals(STEM))
486 tlabel = "" + anots[index].secondaryStructure;
490 tlabel = "" + anots[index].displayCharacter;
494 if (tlabel != null && !tlabel.equals(last))
496 if (last.length() > 0)
498 collatedInput.append(" ");
500 collatedInput.append(tlabel);
504 return collatedInput.toString();
514 public void mousePressed(MouseEvent evt)
517 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
526 final int y = evt.getY();
527 for (int i = 0; i < aa.length; i++)
531 height += aa[i].height;
540 else if (aa[i].graph > 0)
552 * isPopupTrigger fires in mousePressed on Mac,
553 * not until mouseRelease on Windows
555 if (evt.isPopupTrigger() && activeRow != -1)
557 showPopupMenu(y, evt.getX());
561 ap.getScalePanel().mousePressed(evt);
565 * Construct and display a context menu at the right-click position
570 void showPopupMenu(final int y, int x)
572 if (av.getColumnSelection() == null
573 || av.getColumnSelection().isEmpty())
578 JPopupMenu pop = new JPopupMenu(
579 MessageManager.getString("label.structure_type"));
582 * Just display the needed structure options
584 if (av.getAlignment().isNucleotide())
586 item = new JMenuItem(STEM);
587 item.addActionListener(this);
592 item = new JMenuItem(HELIX);
593 item.addActionListener(this);
595 item = new JMenuItem(SHEET);
596 item.addActionListener(this);
599 item = new JMenuItem(LABEL);
600 item.addActionListener(this);
602 item = new JMenuItem(COLOUR);
603 item.addActionListener(this);
605 item = new JMenuItem(REMOVE);
606 item.addActionListener(this);
608 pop.show(this, x, y);
618 public void mouseReleased(MouseEvent evt)
622 mouseDragging = false;
623 ap.getScalePanel().mouseReleased(evt);
626 * isPopupTrigger is set in mouseReleased on Windows
627 * (in mousePressed on Mac)
629 if (evt.isPopupTrigger() && activeRow != -1)
631 showPopupMenu(evt.getY(), evt.getX());
643 public void mouseEntered(MouseEvent evt)
645 ap.getScalePanel().mouseEntered(evt);
655 public void mouseExited(MouseEvent evt)
657 ap.getScalePanel().mouseExited(evt);
667 public void mouseDragged(MouseEvent evt)
669 if (graphStretch > -1)
672 .getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
674 if (av.getAlignment()
675 .getAlignmentAnnotation()[graphStretch].graphHeight < 0)
678 .getAlignmentAnnotation()[graphStretch].graphHeight = 0;
680 graphStretchY = evt.getY();
682 ap.paintAlignment(false, false);
686 ap.getScalePanel().mouseDragged(evt);
691 * Constructs the tooltip, and constructs and displays a status message, for
692 * the current mouse position
697 public void mouseMoved(MouseEvent evt)
699 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
703 this.setToolTipText(null);
710 for (int i = 0; i < aa.length; i++)
714 height += aa[i].height;
717 if (evt.getY() < height)
726 this.setToolTipText(null);
730 int column = (evt.getX() / av.getCharWidth())
731 + av.getRanges().getStartRes();
733 if (av.hasHiddenColumns())
735 column = av.getAlignment().getHiddenColumns()
736 .visibleToAbsoluteColumn(column);
739 AlignmentAnnotation ann = aa[row];
740 if (row > -1 && ann.annotations != null
741 && column < ann.annotations.length)
743 buildToolTip(ann, column, aa);
744 setStatusMessage(column, ann);
748 this.setToolTipText(null);
749 ap.alignFrame.statusBar.setText(" ");
754 * Builds a tooltip for the annotation at the current mouse position.
760 void buildToolTip(AlignmentAnnotation ann, int column,
761 AlignmentAnnotation[] anns)
763 if (ann.graphGroup > -1)
765 StringBuilder tip = new StringBuilder(32);
766 tip.append("<html>");
767 for (int i = 0; i < anns.length; i++)
769 if (anns[i].graphGroup == ann.graphGroup
770 && anns[i].annotations[column] != null)
772 tip.append(anns[i].label);
773 String description = anns[i].annotations[column].description;
774 if (description != null && description.length() > 0)
776 tip.append(" ").append(description);
781 if (tip.length() != 6)
783 tip.setLength(tip.length() - 4);
784 this.setToolTipText(tip.toString() + "</html>");
787 else if (ann.annotations[column] != null)
789 String description = ann.annotations[column].description;
790 if (description != null && description.length() > 0)
792 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
796 this.setToolTipText(null); // no tooltip if null or empty description
801 // clear the tooltip.
802 this.setToolTipText(null);
807 * Constructs and displays the status bar message
812 void setStatusMessage(int column, AlignmentAnnotation ann)
815 * show alignment column and annotation description if any
817 StringBuilder text = new StringBuilder(32);
818 text.append(MessageManager.getString("label.column")).append(" ")
821 if (ann.annotations[column] != null)
823 String description = ann.annotations[column].description;
824 if (description != null && description.trim().length() > 0)
826 text.append(" ").append(description);
831 * if the annotation is sequence-specific, show the sequence number
832 * in the alignment, and (if not a gap) the residue and position
834 SequenceI seqref = ann.sequenceRef;
837 int seqIndex = av.getAlignment().findIndex(seqref);
840 text.append(", ").append(MessageManager.getString("label.sequence"))
841 .append(" ").append(seqIndex + 1);
842 char residue = seqref.getCharAt(column);
843 if (!Comparison.isGap(residue))
847 if (av.getAlignment().isNucleotide())
849 name = ResidueProperties.nucleotideName
850 .get(String.valueOf(residue));
851 text.append(" Nucleotide: ")
852 .append(name != null ? name : residue);
856 name = 'X' == residue ? "X"
857 : ('*' == residue ? "STOP"
858 : ResidueProperties.aa2Triplet
859 .get(String.valueOf(residue)));
860 text.append(" Residue: ").append(name != null ? name : residue);
862 int residuePos = seqref.findPosition(column);
863 text.append(" (").append(residuePos).append(")");
868 ap.alignFrame.statusBar.setText(text.toString());
878 public void mouseClicked(MouseEvent evt)
880 // if (activeRow != -1)
882 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
883 // AlignmentAnnotation anot = aa[activeRow];
887 // TODO mouseClicked-content and drawCursor are quite experimental!
888 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
891 int pady = av.getCharHeight() / 5;
893 graphics.setColor(Color.black);
894 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
896 if (av.validCharWidth)
898 graphics.setColor(Color.white);
900 char s = seq.getCharAt(res);
902 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
903 graphics.drawString(String.valueOf(s), charOffset + x1,
904 (y1 + av.getCharHeight()) - pady);
909 private volatile boolean imageFresh = false;
918 public void paintComponent(Graphics g)
920 super.paintComponent(g);
922 g.setColor(Color.white);
923 g.fillRect(0, 0, getWidth(), getHeight());
927 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
928 || (getVisibleRect().height != g.getClipBounds().height))
930 g.drawImage(image, 0, 0, this);
935 imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
936 + 1) * av.getCharWidth();
941 if (image == null || imgWidth != image.getWidth(this)
942 || image.getHeight(this) != getHeight())
946 image = new BufferedImage(imgWidth,
947 ap.getAnnotationPanel().getHeight(),
948 BufferedImage.TYPE_INT_RGB);
949 } catch (OutOfMemoryError oom)
954 } catch (Exception x)
959 "Couldn't allocate memory to redraw screen. Please restart Jalview",
963 gg = (Graphics2D) image.getGraphics();
967 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
968 RenderingHints.VALUE_ANTIALIAS_ON);
971 gg.setFont(av.getFont());
972 fm = gg.getFontMetrics();
973 gg.setColor(Color.white);
974 gg.fillRect(0, 0, imgWidth, image.getHeight());
978 drawComponent(gg, av.getRanges().getStartRes(),
979 av.getRanges().getEndRes() + 1);
981 g.drawImage(image, 0, 0, this);
985 * set true to enable redraw timing debug output on stderr
987 private final boolean debugRedraw = false;
990 * non-Thread safe repaint
993 * repaint with horizontal shift in alignment
995 public void fastPaint(int horizontal)
997 if ((horizontal == 0) || gg == null
998 || av.getAlignment().getAlignmentAnnotation() == null
999 || av.getAlignment().getAlignmentAnnotation().length < 1
1000 || av.isCalcInProgress())
1006 int sr = av.getRanges().getStartRes();
1007 int er = av.getRanges().getEndRes() + 1;
1010 gg.copyArea(0, 0, imgWidth, getHeight(),
1011 -horizontal * av.getCharWidth(), 0);
1013 if (horizontal > 0) // scrollbar pulled right, image to the left
1015 transX = (er - sr - horizontal) * av.getCharWidth();
1016 sr = er - horizontal;
1018 else if (horizontal < 0)
1020 er = sr - horizontal;
1023 gg.translate(transX, 0);
1025 drawComponent(gg, sr, er);
1027 gg.translate(-transX, 0);
1031 // Call repaint on alignment panel so that repaints from other alignment
1032 // panel components can be aggregated. Otherwise performance of the overview
1033 // window and others may be adversely affected.
1034 av.getAlignPanel().repaint();
1037 private volatile boolean lastImageGood = false;
1049 public void drawComponent(Graphics g, int startRes, int endRes)
1051 BufferedImage oldFaded = fadedImage;
1052 if (av.isCalcInProgress())
1056 lastImageGood = false;
1059 // We'll keep a record of the old image,
1060 // and draw a faded image until the calculation
1063 && (fadedImage == null || fadedImage.getWidth() != imgWidth
1064 || fadedImage.getHeight() != image.getHeight()))
1066 // System.err.println("redraw faded image ("+(fadedImage==null ?
1067 // "null image" : "") + " lastGood="+lastImageGood+")");
1068 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1069 BufferedImage.TYPE_INT_RGB);
1071 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1073 fadedG.setColor(Color.white);
1074 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1076 fadedG.setComposite(
1077 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1078 fadedG.drawImage(image, 0, 0, this);
1081 // make sure we don't overwrite the last good faded image until all
1082 // calculations have finished
1083 lastImageGood = false;
1088 if (fadedImage != null)
1090 oldFaded = fadedImage;
1095 g.setColor(Color.white);
1096 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1098 g.setFont(av.getFont());
1101 fm = g.getFontMetrics();
1104 if ((av.getAlignment().getAlignmentAnnotation() == null)
1105 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1107 g.setColor(Color.white);
1108 g.fillRect(0, 0, getWidth(), getHeight());
1109 g.setColor(Color.black);
1110 if (av.validCharWidth)
1112 g.drawString(MessageManager
1113 .getString("label.alignment_has_no_annotations"), 20, 15);
1118 lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1120 if (!lastImageGood && fadedImage == null)
1122 fadedImage = oldFaded;
1127 public FontMetrics getFontMetrics()
1133 public Image getFadedImage()
1139 public int getFadedImageWidth()
1144 private int[] bounds = new int[2];
1147 public int[] getVisibleVRange()
1149 if (ap != null && ap.getAlabels() != null)
1151 int sOffset = -ap.getAlabels().getScrollOffset();
1152 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1153 bounds[0] = sOffset;
1154 bounds[1] = visHeight;
1164 * Try to ensure any references held are nulled
1166 public void dispose()
1176 * I created the renderer so I will dispose of it
1178 if (renderer != null)
1185 public void propertyChange(PropertyChangeEvent evt)
1187 // Respond to viewport range changes (e.g. alignment panel was scrolled)
1188 // Both scrolling and resizing change viewport ranges: scrolling changes
1189 // both start and end points, but resize only changes end values.
1190 // Here we only want to fastpaint on a scroll, with resize using a normal
1191 // paint, so scroll events are identified as changes to the horizontal or
1192 // vertical start value.
1193 if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1195 fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1197 else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1199 fastPaint(((int[]) evt.getNewValue())[0]
1200 - ((int[]) evt.getOldValue())[0]);
1202 else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))