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.JPanel;
59 import javax.swing.JPopupMenu;
60 import javax.swing.Scrollable;
61 import javax.swing.ToolTipManager;
64 * AnnotationPanel displays visible portion of annotation rows below unwrapped
70 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
71 MouseListener, MouseWheelListener, MouseMotionListener,
72 ActionListener, AdjustmentListener, Scrollable
74 String HELIX = MessageManager.getString("label.helix");
76 String SHEET = MessageManager.getString("label.sheet");
79 * For RNA secondary structure "stems" aka helices
81 String STEM = MessageManager.getString("label.rna_helix");
83 String LABEL = MessageManager.getString("label.label");
85 String REMOVE = MessageManager.getString("label.remove_annotation");
87 String COLOUR = MessageManager.getString("action.colour");
89 public final Color HELIX_COLOUR = Color.red.darker();
91 public final Color SHEET_COLOUR = Color.green.darker().darker();
93 public final Color STEM_COLOUR = Color.blue.darker();
96 public AlignViewport av;
100 public int activeRow = -1;
102 public BufferedImage image;
104 public volatile BufferedImage fadedImage;
108 public FontMetrics fm;
110 public int imgWidth = 0;
112 boolean fastPaint = false;
114 // Used For mouse Dragging and resizing graphs
115 int graphStretch = -1;
117 int graphStretchY = -1;
119 int min; // used by mouseDragged to see if user
121 int max; // used by mouseDragged to see if user
123 boolean mouseDragging = false;
125 // for editing cursor
130 public final AnnotationRenderer renderer;
132 private MouseWheelListener[] _mwl;
135 * Creates a new AnnotationPanel object.
140 public AnnotationPanel(AlignmentPanel ap)
142 ToolTipManager.sharedInstance().registerComponent(this);
143 ToolTipManager.sharedInstance().setInitialDelay(0);
144 ToolTipManager.sharedInstance().setDismissDelay(10000);
147 this.setLayout(null);
148 addMouseListener(this);
149 addMouseMotionListener(this);
150 ap.annotationScroller.getVerticalScrollBar()
151 .addAdjustmentListener(this);
152 // save any wheel listeners on the scroller, so we can propagate scroll
154 _mwl = ap.annotationScroller.getMouseWheelListeners();
155 // and then set our own listener to consume all mousewheel events
156 ap.annotationScroller.addMouseWheelListener(this);
157 renderer = new AnnotationRenderer();
160 public AnnotationPanel(AlignViewport av)
163 renderer = new AnnotationRenderer();
167 public void mouseWheelMoved(MouseWheelEvent e)
172 if (e.getWheelRotation() > 0)
174 ap.scrollRight(true);
178 ap.scrollRight(false);
183 // TODO: find the correct way to let the event bubble up to
184 // ap.annotationScroller
185 for (MouseWheelListener mwl : _mwl)
189 mwl.mouseWheelMoved(e);
200 public Dimension getPreferredScrollableViewportSize()
202 return getPreferredSize();
206 public int getScrollableBlockIncrement(Rectangle visibleRect,
207 int orientation, int direction)
213 public boolean getScrollableTracksViewportHeight()
219 public boolean getScrollableTracksViewportWidth()
225 public int getScrollableUnitIncrement(Rectangle visibleRect,
226 int orientation, int direction)
235 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
239 public void adjustmentValueChanged(AdjustmentEvent evt)
241 // update annotation label display
242 ap.getAlabels().setScrollOffset(-evt.getValue());
246 * Calculates the height of the annotation displayed in the annotation panel.
247 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
248 * all annotation associated components are updated correctly.
251 public int adjustPanelHeight()
253 int height = av.calcPanelHeight();
254 this.setPreferredSize(new Dimension(1, height));
257 // revalidate only when the alignment panel is fully constructed
271 public void actionPerformed(ActionEvent evt)
273 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
278 Annotation[] anot = aa[activeRow].annotations;
280 if (anot.length < av.getColumnSelection().getMax())
282 Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
283 System.arraycopy(anot, 0, temp, 0, anot.length);
285 aa[activeRow].annotations = anot;
288 String action = evt.getActionCommand();
289 if (action.equals(REMOVE))
291 for (int index : av.getColumnSelection().getSelected())
293 if (av.getColumnSelection().isVisible(index))
299 else if (action.equals(LABEL))
301 String exMesg = collectAnnotVals(anot, LABEL);
302 String label = JvOptionPane.showInputDialog(this,
303 MessageManager.getString("label.enter_label"), exMesg);
310 if ((label.length() > 0) && !aa[activeRow].hasText)
312 aa[activeRow].hasText = true;
315 for (int index : av.getColumnSelection().getSelected())
317 if (!av.getColumnSelection().isVisible(index))
322 if (anot[index] == null)
324 anot[index] = new Annotation(label, "", ' ', 0);
328 anot[index].displayCharacter = label;
332 else if (action.equals(COLOUR))
334 Color col = JColorChooser.showDialog(this,
335 MessageManager.getString("label.select_foreground_colour"),
338 for (int index : av.getColumnSelection().getSelected())
340 if (!av.getColumnSelection().isVisible(index))
345 if (anot[index] == null)
347 anot[index] = new Annotation("", "", ' ', 0);
350 anot[index].colour = col;
354 // HELIX, SHEET or STEM
357 String symbol = "\u03B1"; // alpha
359 if (action.equals(HELIX))
363 else if (action.equals(SHEET))
366 symbol = "\u03B2"; // beta
369 // Added by LML to color stems
370 else if (action.equals(STEM))
373 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
374 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
377 if (!aa[activeRow].hasIcons)
379 aa[activeRow].hasIcons = true;
382 String label = JvOptionPane.showInputDialog(MessageManager
383 .getString("label.enter_label_for_the_structure"), symbol);
390 if ((label.length() > 0) && !aa[activeRow].hasText)
392 aa[activeRow].hasText = true;
393 if (action.equals(STEM))
395 aa[activeRow].showAllColLabels = true;
398 for (int index : av.getColumnSelection().getSelected())
400 if (!av.getColumnSelection().isVisible(index))
405 if (anot[index] == null)
407 anot[index] = new Annotation(label, "", type, 0);
410 anot[index].secondaryStructure = type != 'S' ? type : label
411 .length() == 0 ? ' ' : label.charAt(0);
412 anot[index].displayCharacter = label;
417 av.getAlignment().validateAnnotation(aa[activeRow]);
418 ap.alignmentChanged();
419 ap.alignFrame.setMenusForViewport();
427 * Returns any existing annotation concatenated as a string. For each
428 * annotation, takes the description, if any, else the secondary structure
429 * character (if type is HELIX, SHEET or STEM), else the display character (if
436 private String collectAnnotVals(Annotation[] anots, String type)
438 // TODO is this method wanted? why? 'last' is not used
440 StringBuilder collatedInput = new StringBuilder(64);
442 ColumnSelection viscols = av.getColumnSelection();
445 * the selection list (read-only view) is in selection order, not
446 * column order; make a copy so we can sort it
448 List<Integer> selected = new ArrayList<Integer>(viscols.getSelected());
449 Collections.sort(selected);
450 for (int index : selected)
452 // always check for current display state - just in case
453 if (!viscols.isVisible(index))
457 String tlabel = null;
458 if (anots[index] != null)
459 { // LML added stem code
460 if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
461 || type.equals(LABEL))
463 tlabel = anots[index].description;
464 if (tlabel == null || tlabel.length() < 1)
466 if (type.equals(HELIX) || type.equals(SHEET)
467 || type.equals(STEM))
469 tlabel = "" + anots[index].secondaryStructure;
473 tlabel = "" + anots[index].displayCharacter;
477 if (tlabel != null && !tlabel.equals(last))
479 if (last.length() > 0)
481 collatedInput.append(" ");
483 collatedInput.append(tlabel);
487 return collatedInput.toString();
497 public void mousePressed(MouseEvent evt)
500 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
509 final int y = evt.getY();
510 for (int i = 0; i < aa.length; i++)
514 height += aa[i].height;
523 else if (aa[i].graph > 0)
535 * isPopupTrigger fires in mousePressed on Mac,
536 * not until mouseRelease on Windows
538 if (evt.isPopupTrigger() && activeRow != -1)
540 showPopupMenu(y, evt.getX());
544 ap.getScalePanel().mousePressed(evt);
548 * Construct and display a context menu at the right-click position
553 void showPopupMenu(final int y, int x)
555 if (av.getColumnSelection() == null
556 || av.getColumnSelection().isEmpty())
561 JPopupMenu pop = new JPopupMenu(
562 MessageManager.getString("label.structure_type"));
565 * Just display the needed structure options
567 if (av.getAlignment().isNucleotide())
569 item = new JMenuItem(STEM);
570 item.addActionListener(this);
575 item = new JMenuItem(HELIX);
576 item.addActionListener(this);
578 item = new JMenuItem(SHEET);
579 item.addActionListener(this);
582 item = new JMenuItem(LABEL);
583 item.addActionListener(this);
585 item = new JMenuItem(COLOUR);
586 item.addActionListener(this);
588 item = new JMenuItem(REMOVE);
589 item.addActionListener(this);
591 pop.show(this, x, y);
601 public void mouseReleased(MouseEvent evt)
605 mouseDragging = false;
606 ap.getScalePanel().mouseReleased(evt);
609 * isPopupTrigger is set in mouseReleased on Windows
610 * (in mousePressed on Mac)
612 if (evt.isPopupTrigger() && activeRow != -1)
614 showPopupMenu(evt.getY(), evt.getX());
626 public void mouseEntered(MouseEvent evt)
628 ap.getScalePanel().mouseEntered(evt);
638 public void mouseExited(MouseEvent evt)
640 ap.getScalePanel().mouseExited(evt);
650 public void mouseDragged(MouseEvent evt)
652 if (graphStretch > -1)
654 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
656 if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
658 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
660 graphStretchY = evt.getY();
662 ap.paintAlignment(true);
666 ap.getScalePanel().mouseDragged(evt);
671 * Constructs the tooltip, and constructs and displays a status message, for
672 * the current mouse position
677 public void mouseMoved(MouseEvent evt)
679 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
683 this.setToolTipText(null);
690 for (int i = 0; i < aa.length; i++)
694 height += aa[i].height;
697 if (evt.getY() < height)
706 this.setToolTipText(null);
710 int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
712 if (av.hasHiddenColumns())
714 column = av.getColumnSelection().adjustForHiddenColumns(column);
717 AlignmentAnnotation ann = aa[row];
718 if (row > -1 && ann.annotations != null
719 && column < ann.annotations.length)
721 buildToolTip(ann, column, aa);
722 setStatusMessage(column, ann);
726 this.setToolTipText(null);
727 ap.alignFrame.statusBar.setText(" ");
732 * Builds a tooltip for the annotation at the current mouse position.
738 void buildToolTip(AlignmentAnnotation ann, int column,
739 AlignmentAnnotation[] anns)
741 if (ann.graphGroup > -1)
743 StringBuilder tip = new StringBuilder(32);
744 tip.append("<html>");
745 for (int i = 0; i < anns.length; i++)
747 if (anns[i].graphGroup == ann.graphGroup
748 && anns[i].annotations[column] != null)
750 tip.append(anns[i].label);
751 String description = anns[i].annotations[column].description;
752 if (description != null && description.length() > 0)
754 tip.append(" ").append(description);
759 if (tip.length() != 6)
761 tip.setLength(tip.length() - 4);
762 this.setToolTipText(tip.toString() + "</html>");
765 else if (ann.annotations[column] != null)
767 String description = ann.annotations[column].description;
768 if (description != null && description.length() > 0)
770 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
775 // clear the tooltip.
776 this.setToolTipText(null);
781 * Constructs and displays the status bar message
786 void setStatusMessage(int column, AlignmentAnnotation ann)
789 * show alignment column and annotation description if any
791 StringBuilder text = new StringBuilder(32);
792 text.append(MessageManager.getString("label.column")).append(" ")
795 if (ann.annotations[column] != null)
797 String description = ann.annotations[column].description;
798 if (description != null && description.trim().length() > 0)
800 text.append(" ").append(description);
805 * if the annotation is sequence-specific, show the sequence number
806 * in the alignment, and (if not a gap) the residue and position
808 SequenceI seqref = ann.sequenceRef;
811 int seqIndex = av.getAlignment().findIndex(seqref);
815 .append(MessageManager.getString("label.sequence"))
816 .append(" ").append(seqIndex + 1);
817 char residue = seqref.getCharAt(column);
818 if (!Comparison.isGap(residue))
822 if (av.getAlignment().isNucleotide())
824 name = ResidueProperties.nucleotideName.get(String
826 text.append(" Nucleotide: ").append(
827 name != null ? name : residue);
831 name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
832 : ResidueProperties.aa2Triplet.get(String
834 text.append(" Residue: ").append(name != null ? name : residue);
836 int residuePos = seqref.findPosition(column);
837 text.append(" (").append(residuePos).append(")");
842 ap.alignFrame.statusBar.setText(text.toString());
852 public void mouseClicked(MouseEvent evt)
854 // if (activeRow != -1)
856 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
857 // AlignmentAnnotation anot = aa[activeRow];
861 // TODO mouseClicked-content and drawCursor are quite experimental!
862 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
865 int pady = av.getCharHeight() / 5;
867 graphics.setColor(Color.black);
868 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
870 if (av.validCharWidth)
872 graphics.setColor(Color.white);
874 char s = seq.getCharAt(res);
876 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
877 graphics.drawString(String.valueOf(s), charOffset + x1,
878 (y1 + av.getCharHeight()) - pady);
883 private volatile boolean imageFresh = false;
892 public void paintComponent(Graphics g)
894 g.setColor(Color.white);
895 g.fillRect(0, 0, getWidth(), getHeight());
899 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
900 || (getVisibleRect().height != g.getClipBounds().height))
902 g.drawImage(image, 0, 0, this);
907 imgWidth = (av.getEndRes() - av.getStartRes() + 1) * av.getCharWidth();
912 if (image == null || imgWidth != image.getWidth(this)
913 || image.getHeight(this) != getHeight())
917 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
918 .getHeight(), BufferedImage.TYPE_INT_RGB);
919 } catch (OutOfMemoryError oom)
924 } catch (Exception x)
929 "Couldn't allocate memory to redraw screen. Please restart Jalview",
933 gg = (Graphics2D) image.getGraphics();
937 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
938 RenderingHints.VALUE_ANTIALIAS_ON);
941 gg.setFont(av.getFont());
942 fm = gg.getFontMetrics();
943 gg.setColor(Color.white);
944 gg.fillRect(0, 0, imgWidth, image.getHeight());
948 drawComponent(gg, av.getStartRes(), av.getEndRes() + 1);
950 g.drawImage(image, 0, 0, this);
954 * set true to enable redraw timing debug output on stderr
956 private final boolean debugRedraw = false;
959 * non-Thread safe repaint
962 * repaint with horizontal shift in alignment
964 public void fastPaint(int horizontal)
966 if ((horizontal == 0) || gg == null
967 || av.getAlignment().getAlignmentAnnotation() == null
968 || av.getAlignment().getAlignmentAnnotation().length < 1
969 || av.isCalcInProgress())
974 long stime = System.currentTimeMillis();
975 gg.copyArea(0, 0, imgWidth, getHeight(),
976 -horizontal * av.getCharWidth(), 0);
977 long mtime = System.currentTimeMillis();
978 int sr = av.getStartRes();
979 int er = av.getEndRes() + 1;
982 if (horizontal > 0) // scrollbar pulled right, image to the left
984 transX = (er - sr - horizontal) * av.getCharWidth();
985 sr = er - horizontal;
987 else if (horizontal < 0)
989 er = sr - horizontal;
992 gg.translate(transX, 0);
994 drawComponent(gg, sr, er);
996 gg.translate(-transX, 0);
997 long dtime = System.currentTimeMillis();
1000 long rtime = System.currentTimeMillis();
1003 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
1004 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1005 + "\tRepaint call:\t" + (rtime - dtime));
1010 private volatile boolean lastImageGood = false;
1022 public void drawComponent(Graphics g, int startRes, int endRes)
1024 BufferedImage oldFaded = fadedImage;
1025 if (av.isCalcInProgress())
1029 lastImageGood = false;
1032 // We'll keep a record of the old image,
1033 // and draw a faded image until the calculation
1036 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1037 .getHeight() != image.getHeight()))
1039 // System.err.println("redraw faded image ("+(fadedImage==null ?
1040 // "null image" : "") + " lastGood="+lastImageGood+")");
1041 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1042 BufferedImage.TYPE_INT_RGB);
1044 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1046 fadedG.setColor(Color.white);
1047 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1049 fadedG.setComposite(AlphaComposite.getInstance(
1050 AlphaComposite.SRC_OVER, .3f));
1051 fadedG.drawImage(image, 0, 0, this);
1054 // make sure we don't overwrite the last good faded image until all
1055 // calculations have finished
1056 lastImageGood = false;
1061 if (fadedImage != null)
1063 oldFaded = fadedImage;
1068 g.setColor(Color.white);
1069 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1071 g.setFont(av.getFont());
1074 fm = g.getFontMetrics();
1077 if ((av.getAlignment().getAlignmentAnnotation() == null)
1078 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1080 g.setColor(Color.white);
1081 g.fillRect(0, 0, getWidth(), getHeight());
1082 g.setColor(Color.black);
1083 if (av.validCharWidth)
1085 g.drawString(MessageManager
1086 .getString("label.alignment_has_no_annotations"), 20, 15);
1091 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1093 if (!lastImageGood && fadedImage == null)
1095 fadedImage = oldFaded;
1100 public FontMetrics getFontMetrics()
1106 public Image getFadedImage()
1112 public int getFadedImageWidth()
1117 private int[] bounds = new int[2];
1120 public int[] getVisibleVRange()
1122 if (ap != null && ap.getAlabels() != null)
1124 int sOffset = -ap.getAlabels().getScrollOffset();
1125 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1126 bounds[0] = sOffset;
1127 bounds[1] = visHeight;
1137 * Try to ensure any references held are nulled
1139 public void dispose()
1149 * I created the renderer so I will dispose of it
1151 if (renderer != null)