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.Collections;
53 import java.util.List;
55 import javax.swing.JColorChooser;
56 import javax.swing.JMenuItem;
57 import javax.swing.JOptionPane;
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;
127 // for editing cursor
132 public final AnnotationRenderer renderer;
134 private MouseWheelListener[] _mwl;
137 * Creates a new AnnotationPanel object.
142 public AnnotationPanel(AlignmentPanel ap)
145 MAC = jalview.util.Platform.isAMac();
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();
165 public AnnotationPanel(AlignViewport av)
168 renderer = new AnnotationRenderer();
172 public void mouseWheelMoved(MouseWheelEvent e)
177 if (e.getWheelRotation() > 0)
179 ap.scrollRight(true);
183 ap.scrollRight(false);
188 // TODO: find the correct way to let the event bubble up to
189 // ap.annotationScroller
190 for (MouseWheelListener mwl : _mwl)
194 mwl.mouseWheelMoved(e);
205 public Dimension getPreferredScrollableViewportSize()
207 return getPreferredSize();
211 public int getScrollableBlockIncrement(Rectangle visibleRect,
212 int orientation, int direction)
218 public boolean getScrollableTracksViewportHeight()
224 public boolean getScrollableTracksViewportWidth()
230 public int getScrollableUnitIncrement(Rectangle visibleRect,
231 int orientation, int direction)
240 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
244 public void adjustmentValueChanged(AdjustmentEvent evt)
246 // update annotation label display
247 ap.getAlabels().setScrollOffset(-evt.getValue());
251 * Calculates the height of the annotation displayed in the annotation panel.
252 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
253 * all annotation associated components are updated correctly.
256 public int adjustPanelHeight()
258 int height = av.calcPanelHeight();
259 this.setPreferredSize(new Dimension(1, height));
262 // revalidate only when the alignment panel is fully constructed
276 public void actionPerformed(ActionEvent evt)
278 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
283 Annotation[] anot = aa[activeRow].annotations;
285 if (anot.length < av.getColumnSelection().getMax())
287 Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
288 System.arraycopy(anot, 0, temp, 0, anot.length);
290 aa[activeRow].annotations = anot;
293 String action = evt.getActionCommand();
294 if (action.equals(REMOVE))
296 for (int index : av.getColumnSelection().getSelected())
298 if (av.getColumnSelection().isVisible(index))
304 else if (action.equals(LABEL))
306 String exMesg = collectAnnotVals(anot, LABEL);
307 String label = JOptionPane.showInputDialog(this,
308 MessageManager.getString("label.enter_label"), exMesg);
315 if ((label.length() > 0) && !aa[activeRow].hasText)
317 aa[activeRow].hasText = true;
320 for (int index : av.getColumnSelection().getSelected())
322 if (!av.getColumnSelection().isVisible(index))
327 if (anot[index] == null)
329 anot[index] = new Annotation(label, "", ' ', 0);
333 anot[index].displayCharacter = label;
337 else if (action.equals(COLOUR))
339 Color col = JColorChooser.showDialog(this,
340 MessageManager.getString("label.select_foreground_colour"),
343 for (int index : av.getColumnSelection().getSelected())
345 if (!av.getColumnSelection().isVisible(index))
350 if (anot[index] == null)
352 anot[index] = new Annotation("", "", ' ', 0);
355 anot[index].colour = col;
359 // HELIX, SHEET or STEM
362 String symbol = "\u03B1"; // alpha
364 if (action.equals(HELIX))
368 else if (action.equals(SHEET))
371 symbol = "\u03B2"; // beta
374 // Added by LML to color stems
375 else if (action.equals(STEM))
378 int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
379 symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
382 if (!aa[activeRow].hasIcons)
384 aa[activeRow].hasIcons = true;
387 String label = JOptionPane.showInputDialog(MessageManager
388 .getString("label.enter_label_for_the_structure"), symbol);
395 if ((label.length() > 0) && !aa[activeRow].hasText)
397 aa[activeRow].hasText = true;
398 if (action.equals(STEM))
400 aa[activeRow].showAllColLabels = true;
403 for (int index : av.getColumnSelection().getSelected())
405 if (!av.getColumnSelection().isVisible(index))
410 if (anot[index] == null)
412 anot[index] = new Annotation(label, "", type, 0);
415 anot[index].secondaryStructure = type != 'S' ? type : label
416 .length() == 0 ? ' ' : label.charAt(0);
417 anot[index].displayCharacter = label;
422 av.getAlignment().validateAnnotation(aa[activeRow]);
423 ap.alignmentChanged();
424 ap.alignFrame.setMenusForViewport();
432 * Returns any existing annotation concatenated as a string. For each
433 * annotation, takes the description, if any, else the secondary structure
434 * character (if type is HELIX, SHEET or STEM), else the display character (if
441 private String collectAnnotVals(Annotation[] anots, String type)
443 // TODO is this method wanted? why? 'last' is not used
445 StringBuilder collatedInput = new StringBuilder(64);
447 ColumnSelection viscols = av.getColumnSelection();
448 // TODO: refactor and save av.getColumnSelection for efficiency
449 List<Integer> selected = 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)
462 || type.equals(STEM) || 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)
535 if (evt.isPopupTrigger() && activeRow != -1)
537 showPopupMenu(y, evt.getX());
541 ap.getScalePanel().mousePressed(evt);
546 * Construct and display a context menu at the right-click position
551 void showPopupMenu(final int y, int x)
553 if (av.getColumnSelection() == null
554 || av.getColumnSelection().isEmpty())
559 JPopupMenu pop = new JPopupMenu(
560 MessageManager.getString("label.structure_type"));
563 * Just display the needed structure options
565 if (av.getAlignment().isNucleotide())
567 item = new JMenuItem(STEM);
568 item.addActionListener(this);
573 item = new JMenuItem(HELIX);
574 item.addActionListener(this);
576 item = new JMenuItem(SHEET);
577 item.addActionListener(this);
580 item = new JMenuItem(LABEL);
581 item.addActionListener(this);
583 item = new JMenuItem(COLOUR);
584 item.addActionListener(this);
586 item = new JMenuItem(REMOVE);
587 item.addActionListener(this);
589 pop.show(this, x, y);
599 public void mouseReleased(MouseEvent evt)
603 mouseDragging = false;
604 ap.getScalePanel().mouseReleased(evt);
606 if (evt.isPopupTrigger() && activeRow != -1)
608 showPopupMenu(evt.getY(), evt.getX());
620 public void mouseEntered(MouseEvent evt)
622 ap.getScalePanel().mouseEntered(evt);
632 public void mouseExited(MouseEvent evt)
634 ap.getScalePanel().mouseExited(evt);
644 public void mouseDragged(MouseEvent evt)
646 if (graphStretch > -1)
648 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
650 if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
652 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
654 graphStretchY = evt.getY();
656 ap.paintAlignment(true);
660 ap.getScalePanel().mouseDragged(evt);
665 * Constructs the tooltip, and constructs and displays a status message, for
666 * the current mouse position
671 public void mouseMoved(MouseEvent evt)
673 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
677 this.setToolTipText(null);
684 for (int i = 0; i < aa.length; i++)
688 height += aa[i].height;
691 if (evt.getY() < height)
700 this.setToolTipText(null);
704 int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
706 if (av.hasHiddenColumns())
708 column = av.getColumnSelection().adjustForHiddenColumns(column);
711 AlignmentAnnotation ann = aa[row];
712 if (row > -1 && ann.annotations != null
713 && column < ann.annotations.length)
715 buildToolTip(ann, column, aa);
716 setStatusMessage(column, ann);
720 this.setToolTipText(null);
721 ap.alignFrame.statusBar.setText(" ");
726 * Builds a tooltip for the annotation at the current mouse position.
732 void buildToolTip(AlignmentAnnotation ann, int column,
733 AlignmentAnnotation[] anns)
735 if (ann.graphGroup > -1)
737 StringBuilder tip = new StringBuilder(32);
738 tip.append("<html>");
739 for (int i = 0; i < anns.length; i++)
741 if (anns[i].graphGroup == ann.graphGroup
742 && anns[i].annotations[column] != null)
744 tip.append(anns[i].label);
745 String description = anns[i].annotations[column].description;
746 if (description != null && description.length() > 0)
748 tip.append(" ").append(description);
753 if (tip.length() != 6)
755 tip.setLength(tip.length() - 4);
756 this.setToolTipText(tip.toString() + "</html>");
759 else if (ann.annotations[column] != null)
761 String description = ann.annotations[column].description;
762 if (description != null && description.length() > 0)
764 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
769 // clear the tooltip.
770 this.setToolTipText(null);
775 * Constructs and displays the status bar message
780 void setStatusMessage(int column, AlignmentAnnotation ann)
783 * show alignment column and annotation description if any
785 StringBuilder text = new StringBuilder(32);
786 text.append(MessageManager.getString("label.column")).append(" ")
789 if (ann.annotations[column] != null)
791 String description = ann.annotations[column].description;
792 if (description != null && description.trim().length() > 0)
794 text.append(" ").append(description);
799 * if the annotation is sequence-specific, show the sequence number
800 * in the alignment, and (if not a gap) the residue and position
802 SequenceI seqref = ann.sequenceRef;
805 int seqIndex = av.getAlignment().findIndex(seqref);
809 .append(MessageManager.getString("label.sequence"))
811 .append(seqIndex + 1);
812 char residue = seqref.getCharAt(column);
813 if (!Comparison.isGap(residue))
817 if (av.getAlignment().isNucleotide())
819 name = ResidueProperties.nucleotideName.get(String
821 text.append(" Nucleotide: ").append(
822 name != null ? name : residue);
826 name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
827 : ResidueProperties.aa2Triplet.get(String
829 text.append(" Residue: ").append(name != null ? name : residue);
831 int residuePos = seqref.findPosition(column);
832 text.append(" (").append(residuePos).append(")");
837 ap.alignFrame.statusBar.setText(text.toString());
847 public void mouseClicked(MouseEvent evt)
849 // if (activeRow != -1)
851 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
852 // AlignmentAnnotation anot = aa[activeRow];
856 // TODO mouseClicked-content and drawCursor are quite experimental!
857 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
860 int pady = av.getCharHeight() / 5;
862 graphics.setColor(Color.black);
863 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
865 if (av.validCharWidth)
867 graphics.setColor(Color.white);
869 char s = seq.getCharAt(res);
871 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
872 graphics.drawString(String.valueOf(s), charOffset + x1,
873 (y1 + av.getCharHeight()) - pady);
878 private volatile boolean imageFresh = false;
887 public void paintComponent(Graphics g)
889 g.setColor(Color.white);
890 g.fillRect(0, 0, getWidth(), getHeight());
894 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
895 || (getVisibleRect().height != g.getClipBounds().height))
897 g.drawImage(image, 0, 0, this);
902 imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
907 if (image == null || imgWidth != image.getWidth(this)
908 || image.getHeight(this) != getHeight())
912 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
913 .getHeight(), BufferedImage.TYPE_INT_RGB);
914 } catch (OutOfMemoryError oom)
919 } catch (Exception x)
924 "Couldn't allocate memory to redraw screen. Please restart Jalview",
928 gg = (Graphics2D) image.getGraphics();
932 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
933 RenderingHints.VALUE_ANTIALIAS_ON);
936 gg.setFont(av.getFont());
937 fm = gg.getFontMetrics();
938 gg.setColor(Color.white);
939 gg.fillRect(0, 0, imgWidth, image.getHeight());
943 drawComponent(gg, av.startRes, av.endRes + 1);
945 g.drawImage(image, 0, 0, this);
949 * set true to enable redraw timing debug output on stderr
951 private final boolean debugRedraw = false;
954 * non-Thread safe repaint
957 * repaint with horizontal shift in alignment
959 public void fastPaint(int horizontal)
961 if ((horizontal == 0) || gg == null
962 || av.getAlignment().getAlignmentAnnotation() == null
963 || av.getAlignment().getAlignmentAnnotation().length < 1
964 || av.isCalcInProgress())
969 long stime = System.currentTimeMillis();
970 gg.copyArea(0, 0, imgWidth, getHeight(),
971 -horizontal * av.getCharWidth(), 0);
972 long mtime = System.currentTimeMillis();
973 int sr = av.startRes;
974 int er = av.endRes + 1;
977 if (horizontal > 0) // scrollbar pulled right, image to the left
979 transX = (er - sr - horizontal) * av.getCharWidth();
980 sr = er - horizontal;
982 else if (horizontal < 0)
984 er = sr - horizontal;
987 gg.translate(transX, 0);
989 drawComponent(gg, sr, er);
991 gg.translate(-transX, 0);
992 long dtime = System.currentTimeMillis();
995 long rtime = System.currentTimeMillis();
998 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
999 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1000 + "\tRepaint call:\t" + (rtime - dtime));
1005 private volatile boolean lastImageGood = false;
1017 public void drawComponent(Graphics g, int startRes, int endRes)
1019 BufferedImage oldFaded = fadedImage;
1020 if (av.isCalcInProgress())
1024 lastImageGood = false;
1027 // We'll keep a record of the old image,
1028 // and draw a faded image until the calculation
1031 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1032 .getHeight() != image.getHeight()))
1034 // System.err.println("redraw faded image ("+(fadedImage==null ?
1035 // "null image" : "") + " lastGood="+lastImageGood+")");
1036 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1037 BufferedImage.TYPE_INT_RGB);
1039 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1041 fadedG.setColor(Color.white);
1042 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1044 fadedG.setComposite(AlphaComposite.getInstance(
1045 AlphaComposite.SRC_OVER, .3f));
1046 fadedG.drawImage(image, 0, 0, this);
1049 // make sure we don't overwrite the last good faded image until all
1050 // calculations have finished
1051 lastImageGood = false;
1056 if (fadedImage != null)
1058 oldFaded = fadedImage;
1063 g.setColor(Color.white);
1064 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1066 g.setFont(av.getFont());
1069 fm = g.getFontMetrics();
1072 if ((av.getAlignment().getAlignmentAnnotation() == null)
1073 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1075 g.setColor(Color.white);
1076 g.fillRect(0, 0, getWidth(), getHeight());
1077 g.setColor(Color.black);
1078 if (av.validCharWidth)
1080 g.drawString(MessageManager
1081 .getString("label.alignment_has_no_annotations"), 20, 15);
1086 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1088 if (!lastImageGood && fadedImage == null)
1090 fadedImage = oldFaded;
1095 public FontMetrics getFontMetrics()
1101 public Image getFadedImage()
1107 public int getFadedImageWidth()
1112 private int[] bounds = new int[2];
1115 public int[] getVisibleVRange()
1117 if (ap != null && ap.getAlabels() != null)
1119 int sOffset = -ap.getAlabels().getScrollOffset();
1120 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1121 bounds[0] = sOffset;
1122 bounds[1] = visHeight;