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.util.Comparison;
30 import jalview.util.MessageManager;
32 import java.awt.AlphaComposite;
33 import java.awt.Color;
34 import java.awt.Dimension;
35 import java.awt.FontMetrics;
36 import java.awt.Graphics;
37 import java.awt.Graphics2D;
38 import java.awt.Image;
39 import java.awt.Rectangle;
40 import java.awt.RenderingHints;
41 import java.awt.event.ActionEvent;
42 import java.awt.event.ActionListener;
43 import java.awt.event.AdjustmentEvent;
44 import java.awt.event.AdjustmentListener;
45 import java.awt.event.MouseEvent;
46 import java.awt.event.MouseListener;
47 import java.awt.event.MouseMotionListener;
48 import java.awt.event.MouseWheelEvent;
49 import java.awt.event.MouseWheelListener;
50 import java.awt.image.BufferedImage;
52 import javax.swing.JColorChooser;
53 import javax.swing.JMenuItem;
54 import javax.swing.JOptionPane;
55 import javax.swing.JPanel;
56 import javax.swing.JPopupMenu;
57 import javax.swing.Scrollable;
58 import javax.swing.ToolTipManager;
61 * AnnotationPanel displays visible portion of annotation rows below unwrapped
67 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
68 MouseListener, MouseWheelListener, MouseMotionListener,
69 ActionListener, AdjustmentListener, Scrollable
71 String HELIX = MessageManager.getString("label.helix");
73 String SHEET = MessageManager.getString("label.sheet");
76 * For RNA secondary structure "stems" aka helices
78 String STEM = MessageManager.getString("label.rna_helix");
80 String LABEL = MessageManager.getString("label.label");
82 String REMOVE = MessageManager.getString("label.remove_annotation");
84 String COLOUR = MessageManager.getString("action.colour");
86 public final Color HELIX_COLOUR = Color.red.darker();
88 public final Color SHEET_COLOUR = Color.green.darker().darker();
90 public final Color STEM_COLOUR = Color.blue.darker();
93 public AlignViewport av;
97 public int activeRow = -1;
99 public BufferedImage image;
101 public volatile BufferedImage fadedImage;
105 public FontMetrics fm;
107 public int imgWidth = 0;
109 boolean fastPaint = false;
111 // Used For mouse Dragging and resizing graphs
112 int graphStretch = -1;
114 int graphStretchY = -1;
116 int min; // used by mouseDragged to see if user
118 int max; // used by mouseDragged to see if user
120 boolean mouseDragging = false;
124 // for editing cursor
129 public final AnnotationRenderer renderer;
131 private MouseWheelListener[] _mwl;
134 * Creates a new AnnotationPanel object.
139 public AnnotationPanel(AlignmentPanel ap)
142 MAC = jalview.util.Platform.isAMac();
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();
162 public AnnotationPanel(AlignViewport av)
165 renderer = new AnnotationRenderer();
169 public void mouseWheelMoved(MouseWheelEvent e)
174 if (e.getWheelRotation() > 0)
176 ap.scrollRight(true);
180 ap.scrollRight(false);
185 // TODO: find the correct way to let the event bubble up to
186 // ap.annotationScroller
187 for (MouseWheelListener mwl : _mwl)
191 mwl.mouseWheelMoved(e);
202 public Dimension getPreferredScrollableViewportSize()
204 return getPreferredSize();
208 public int getScrollableBlockIncrement(Rectangle visibleRect,
209 int orientation, int direction)
215 public boolean getScrollableTracksViewportHeight()
221 public boolean getScrollableTracksViewportWidth()
227 public int getScrollableUnitIncrement(Rectangle visibleRect,
228 int orientation, int direction)
237 * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
241 public void adjustmentValueChanged(AdjustmentEvent evt)
243 // update annotation label display
244 ap.getAlabels().setScrollOffset(-evt.getValue());
248 * Calculates the height of the annotation displayed in the annotation panel.
249 * Callers should normally call the ap.adjustAnnotationHeight method to ensure
250 * all annotation associated components are updated correctly.
253 public int adjustPanelHeight()
255 int height = av.calcPanelHeight();
256 this.setPreferredSize(new Dimension(1, height));
259 // revalidate only when the alignment panel is fully constructed
273 public void actionPerformed(ActionEvent evt)
275 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
280 Annotation[] anot = aa[activeRow].annotations;
282 if (anot.length < av.getColumnSelection().getMax())
284 Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
285 System.arraycopy(anot, 0, temp, 0, anot.length);
287 aa[activeRow].annotations = anot;
290 if (evt.getActionCommand().equals(REMOVE))
292 for (int sel : av.getColumnSelection().getSelected())
297 else if (evt.getActionCommand().equals(LABEL))
299 String exMesg = collectAnnotVals(anot, LABEL);
300 String label = JOptionPane.showInputDialog(this,
301 MessageManager.getString("label.enter_label"), exMesg);
308 if ((label.length() > 0) && !aa[activeRow].hasText)
310 aa[activeRow].hasText = true;
313 for (int index : av.getColumnSelection().getSelected())
315 if (!av.getColumnSelection().isVisible(index))
320 if (anot[index] == null)
322 anot[index] = new Annotation(label, "", ' ', 0); // TODO: verify that
329 anot[index].displayCharacter = label;
333 else if (evt.getActionCommand().equals(COLOUR))
335 Color col = JColorChooser.showDialog(this,
336 MessageManager.getString("label.select_foreground_colour"),
339 for (int index : av.getColumnSelection().getSelected())
341 if (!av.getColumnSelection().isVisible(index))
346 if (anot[index] == null)
348 anot[index] = new Annotation("", "", ' ', 0);
351 anot[index].colour = col;
355 // HELIX, SHEET or STEM
358 String symbol = "\u03B1"; // alpha
360 if (evt.getActionCommand().equals(HELIX))
364 else if (evt.getActionCommand().equals(SHEET))
367 symbol = "\u03B2"; // beta
370 // Added by LML to color stems
371 else if (evt.getActionCommand().equals(STEM))
374 symbol = "(";// "\u03C3"; // sigma
377 if (!aa[activeRow].hasIcons)
379 aa[activeRow].hasIcons = true;
382 symbol = getCurrentAnnotationCharacter(anot, symbol);
384 String label = JOptionPane.showInputDialog(MessageManager
385 .getString("label.enter_label_for_the_structure"), symbol);
392 if ((label.length() > 0) && !aa[activeRow].hasText)
394 aa[activeRow].hasText = true;
395 if (evt.getActionCommand().equals(STEM))
397 aa[activeRow].showAllColLabels = true;
400 for (int index : av.getColumnSelection().getSelected())
402 if (!av.getColumnSelection().isVisible(index))
407 if (anot[index] == null)
409 anot[index] = new Annotation(label, "", type, 0);
412 anot[index].secondaryStructure = type != 'S' ? type : label
413 .length() == 0 ? ' ' : label.charAt(0);
414 anot[index].displayCharacter = label;
419 av.getAlignment().validateAnnotation(aa[activeRow]);
420 ap.alignmentChanged();
421 ap.alignFrame.setMenusForViewport();
429 * Returns the current annotation symbol (if any) within the visible selected
430 * columns (first symbol found left to right in selection). If none is found,
431 * the supplied default value is returned.
434 * @param defaultValue
437 String getCurrentAnnotationCharacter(Annotation[] annotations,
440 String result = defaultValue;
441 for (int index : av.getColumnSelection().getSelected())
443 if (!av.getColumnSelection().isVisible(index))
448 Annotation annotation = annotations[index];
449 if (annotation != null)
451 String displayed = annotation.displayCharacter;
452 if (displayed != null && displayed.length() > 0)
454 result = displayed.substring(0, 1);
462 private String collectAnnotVals(Annotation[] anot, String label2)
464 String collatedInput = "";
466 ColumnSelection viscols = av.getColumnSelection();
467 // TODO: refactor and save av.getColumnSelection for efficiency
468 for (int index : viscols.getSelected())
470 // always check for current display state - just in case
471 if (!viscols.isVisible(index))
475 String tlabel = null;
476 if (anot[index] != null)
477 { // LML added stem code
478 if (label2.equals(HELIX) || label2.equals(SHEET)
479 || label2.equals(STEM) || label2.equals(LABEL))
481 tlabel = anot[index].description;
482 if (tlabel == null || tlabel.length() < 1)
484 if (label2.equals(HELIX) || label2.equals(SHEET)
485 || label2.equals(STEM))
487 tlabel = "" + anot[index].secondaryStructure;
491 tlabel = "" + anot[index].displayCharacter;
495 if (tlabel != null && !tlabel.equals(last))
497 if (last.length() > 0)
499 collatedInput += " ";
501 collatedInput += tlabel;
505 return collatedInput;
515 public void mousePressed(MouseEvent evt)
518 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
527 for (int i = 0; i < aa.length; i++)
531 height += aa[i].height;
534 if (evt.getY() < height)
540 else if (aa[i].graph > 0)
544 graphStretchY = evt.getY();
551 if (evt.isPopupTrigger() && activeRow != -1)
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, evt.getX(), evt.getY());
594 ap.getScalePanel().mousePressed(evt);
605 public void mouseReleased(MouseEvent evt)
609 mouseDragging = false;
610 ap.getScalePanel().mouseReleased(evt);
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))
815 int residuePos = seqref.findPosition(column);
816 text.append(": ").append(residue).append(" (")
817 .append(residuePos).append(")");
822 ap.alignFrame.statusBar.setText(text.toString());
832 public void mouseClicked(MouseEvent evt)
834 // if (activeRow != -1)
836 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
837 // AlignmentAnnotation anot = aa[activeRow];
841 // TODO mouseClicked-content and drawCursor are quite experimental!
842 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
845 int pady = av.getCharHeight() / 5;
847 graphics.setColor(Color.black);
848 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
850 if (av.validCharWidth)
852 graphics.setColor(Color.white);
854 char s = seq.getCharAt(res);
856 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
857 graphics.drawString(String.valueOf(s), charOffset + x1,
858 (y1 + av.getCharHeight()) - pady);
863 private volatile boolean imageFresh = false;
872 public void paintComponent(Graphics g)
874 g.setColor(Color.white);
875 g.fillRect(0, 0, getWidth(), getHeight());
879 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
880 || (getVisibleRect().height != g.getClipBounds().height))
882 g.drawImage(image, 0, 0, this);
887 imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
892 if (image == null || imgWidth != image.getWidth(this)
893 || image.getHeight(this) != getHeight())
897 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
898 .getHeight(), BufferedImage.TYPE_INT_RGB);
899 } catch (OutOfMemoryError oom)
904 } catch (Exception x)
909 "Couldn't allocate memory to redraw screen. Please restart Jalview",
913 gg = (Graphics2D) image.getGraphics();
917 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
918 RenderingHints.VALUE_ANTIALIAS_ON);
921 gg.setFont(av.getFont());
922 fm = gg.getFontMetrics();
923 gg.setColor(Color.white);
924 gg.fillRect(0, 0, imgWidth, image.getHeight());
928 drawComponent(gg, av.startRes, av.endRes + 1);
930 g.drawImage(image, 0, 0, this);
934 * set true to enable redraw timing debug output on stderr
936 private final boolean debugRedraw = false;
939 * non-Thread safe repaint
942 * repaint with horizontal shift in alignment
944 public void fastPaint(int horizontal)
946 if ((horizontal == 0) || gg == null
947 || av.getAlignment().getAlignmentAnnotation() == null
948 || av.getAlignment().getAlignmentAnnotation().length < 1
949 || av.isCalcInProgress())
954 long stime = System.currentTimeMillis();
955 gg.copyArea(0, 0, imgWidth, getHeight(),
956 -horizontal * av.getCharWidth(), 0);
957 long mtime = System.currentTimeMillis();
958 int sr = av.startRes;
959 int er = av.endRes + 1;
962 if (horizontal > 0) // scrollbar pulled right, image to the left
964 transX = (er - sr - horizontal) * av.getCharWidth();
965 sr = er - horizontal;
967 else if (horizontal < 0)
969 er = sr - horizontal;
972 gg.translate(transX, 0);
974 drawComponent(gg, sr, er);
976 gg.translate(-transX, 0);
977 long dtime = System.currentTimeMillis();
980 long rtime = System.currentTimeMillis();
983 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
984 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
985 + "\tRepaint call:\t" + (rtime - dtime));
990 private volatile boolean lastImageGood = false;
1002 public void drawComponent(Graphics g, int startRes, int endRes)
1004 BufferedImage oldFaded = fadedImage;
1005 if (av.isCalcInProgress())
1009 lastImageGood = false;
1012 // We'll keep a record of the old image,
1013 // and draw a faded image until the calculation
1016 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1017 .getHeight() != image.getHeight()))
1019 // System.err.println("redraw faded image ("+(fadedImage==null ?
1020 // "null image" : "") + " lastGood="+lastImageGood+")");
1021 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1022 BufferedImage.TYPE_INT_RGB);
1024 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1026 fadedG.setColor(Color.white);
1027 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1029 fadedG.setComposite(AlphaComposite.getInstance(
1030 AlphaComposite.SRC_OVER, .3f));
1031 fadedG.drawImage(image, 0, 0, this);
1034 // make sure we don't overwrite the last good faded image until all
1035 // calculations have finished
1036 lastImageGood = false;
1041 if (fadedImage != null)
1043 oldFaded = fadedImage;
1048 g.setColor(Color.white);
1049 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1051 g.setFont(av.getFont());
1054 fm = g.getFontMetrics();
1057 if ((av.getAlignment().getAlignmentAnnotation() == null)
1058 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1060 g.setColor(Color.white);
1061 g.fillRect(0, 0, getWidth(), getHeight());
1062 g.setColor(Color.black);
1063 if (av.validCharWidth)
1065 g.drawString(MessageManager
1066 .getString("label.alignment_has_no_annotations"), 20, 15);
1071 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1073 if (!lastImageGood && fadedImage == null)
1075 fadedImage = oldFaded;
1080 public FontMetrics getFontMetrics()
1086 public Image getFadedImage()
1092 public int getFadedImageWidth()
1097 private int[] bounds = new int[2];
1100 public int[] getVisibleVRange()
1102 if (ap != null && ap.getAlabels() != null)
1104 int sOffset = -ap.getAlabels().getScrollOffset();
1105 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1106 bounds[0] = sOffset;
1107 bounds[1] = visHeight;