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 index : av.getColumnSelection().getSelected())
294 if (av.getColumnSelection().isVisible(index))
300 else if (evt.getActionCommand().equals(LABEL))
302 String exMesg = collectAnnotVals(anot, LABEL);
303 String label = JOptionPane.showInputDialog(this,
304 MessageManager.getString("label.enter_label"), exMesg);
311 if ((label.length() > 0) && !aa[activeRow].hasText)
313 aa[activeRow].hasText = true;
316 for (int index : av.getColumnSelection().getSelected())
318 if (!av.getColumnSelection().isVisible(index))
323 if (anot[index] == null)
325 anot[index] = new Annotation(label, "", ' ', 0); // TODO: verify that
332 anot[index].displayCharacter = label;
336 else if (evt.getActionCommand().equals(COLOUR))
338 Color col = JColorChooser.showDialog(this,
339 MessageManager.getString("label.select_foreground_colour"),
342 for (int index : av.getColumnSelection().getSelected())
344 if (!av.getColumnSelection().isVisible(index))
349 if (anot[index] == null)
351 anot[index] = new Annotation("", "", ' ', 0);
354 anot[index].colour = col;
358 // HELIX, SHEET or STEM
361 String symbol = "\u03B1";
363 if (evt.getActionCommand().equals(HELIX))
367 else if (evt.getActionCommand().equals(SHEET))
373 // Added by LML to color stems
374 else if (evt.getActionCommand().equals(STEM))
380 if (!aa[activeRow].hasIcons)
382 aa[activeRow].hasIcons = true;
385 String label = JOptionPane.showInputDialog(MessageManager
386 .getString("label.enter_label_for_the_structure"), symbol);
393 if ((label.length() > 0) && !aa[activeRow].hasText)
395 aa[activeRow].hasText = true;
396 if (evt.getActionCommand().equals(STEM))
398 aa[activeRow].showAllColLabels = true;
401 for (int index : av.getColumnSelection().getSelected())
403 if (!av.getColumnSelection().isVisible(index))
408 if (anot[index] == null)
410 anot[index] = new Annotation(label, "", type, 0);
413 anot[index].secondaryStructure = type != 'S' ? type : label
414 .length() == 0 ? ' ' : label.charAt(0);
415 anot[index].displayCharacter = label;
420 av.getAlignment().validateAnnotation(aa[activeRow]);
421 ap.alignmentChanged();
422 ap.alignFrame.setMenusForViewport();
430 * Returns any existing annotation concatenated as a string. For each
431 * annotation, takes the description, if any, else the secondary structure
432 * character (if type is HELIX, SHEET or STEM), else the display character (if
439 private String collectAnnotVals(Annotation[] anots, String type)
441 // TODO is this method wanted? why? 'last' is not used
443 StringBuilder collatedInput = new StringBuilder(64);
445 ColumnSelection viscols = av.getColumnSelection();
446 // TODO: refactor and save av.getColumnSelection for efficiency
447 for (int index : viscols.getSelected())
449 // always check for current display state - just in case
450 if (!viscols.isVisible(index))
454 String tlabel = null;
455 if (anots[index] != null)
456 { // LML added stem code
457 if (type.equals(HELIX) || type.equals(SHEET)
458 || type.equals(STEM) || type.equals(LABEL))
460 tlabel = anots[index].description;
461 if (tlabel == null || tlabel.length() < 1)
463 if (type.equals(HELIX) || type.equals(SHEET)
464 || type.equals(STEM))
466 tlabel = "" + anots[index].secondaryStructure;
470 tlabel = "" + anots[index].displayCharacter;
474 if (tlabel != null && !tlabel.equals(last))
476 if (last.length() > 0)
478 collatedInput.append(" ");
480 collatedInput.append(tlabel);
484 return collatedInput.toString();
494 public void mousePressed(MouseEvent evt)
497 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
506 for (int i = 0; i < aa.length; i++)
510 height += aa[i].height;
513 if (evt.getY() < height)
519 else if (aa[i].graph > 0)
523 graphStretchY = evt.getY();
530 if (evt.isPopupTrigger() && activeRow != -1)
532 if (av.getColumnSelection() == null)
537 JPopupMenu pop = new JPopupMenu(
538 MessageManager.getString("label.structure_type"));
541 * Just display the needed structure options
543 if (av.getAlignment().isNucleotide() == true)
545 item = new JMenuItem(STEM);
546 item.addActionListener(this);
551 item = new JMenuItem(HELIX);
552 item.addActionListener(this);
554 item = new JMenuItem(SHEET);
555 item.addActionListener(this);
558 item = new JMenuItem(LABEL);
559 item.addActionListener(this);
561 item = new JMenuItem(COLOUR);
562 item.addActionListener(this);
564 item = new JMenuItem(REMOVE);
565 item.addActionListener(this);
567 pop.show(this, evt.getX(), evt.getY());
577 ap.getScalePanel().mousePressed(evt);
588 public void mouseReleased(MouseEvent evt)
592 mouseDragging = false;
593 ap.getScalePanel().mouseReleased(evt);
603 public void mouseEntered(MouseEvent evt)
605 ap.getScalePanel().mouseEntered(evt);
615 public void mouseExited(MouseEvent evt)
617 ap.getScalePanel().mouseExited(evt);
627 public void mouseDragged(MouseEvent evt)
629 if (graphStretch > -1)
631 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
633 if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
635 av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
637 graphStretchY = evt.getY();
639 ap.paintAlignment(true);
643 ap.getScalePanel().mouseDragged(evt);
648 * Constructs the tooltip, and constructs and displays a status message, for
649 * the current mouse position
654 public void mouseMoved(MouseEvent evt)
656 AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
660 this.setToolTipText(null);
667 for (int i = 0; i < aa.length; i++)
671 height += aa[i].height;
674 if (evt.getY() < height)
683 this.setToolTipText(null);
687 int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
689 if (av.hasHiddenColumns())
691 column = av.getColumnSelection().adjustForHiddenColumns(column);
694 AlignmentAnnotation ann = aa[row];
695 if (row > -1 && ann.annotations != null
696 && column < ann.annotations.length)
698 buildToolTip(ann, column, aa);
699 setStatusMessage(column, ann);
703 this.setToolTipText(null);
704 ap.alignFrame.statusBar.setText(" ");
709 * Builds a tooltip for the annotation at the current mouse position.
715 void buildToolTip(AlignmentAnnotation ann, int column,
716 AlignmentAnnotation[] anns)
718 if (ann.graphGroup > -1)
720 StringBuilder tip = new StringBuilder(32);
721 tip.append("<html>");
722 for (int i = 0; i < anns.length; i++)
724 if (anns[i].graphGroup == ann.graphGroup
725 && anns[i].annotations[column] != null)
727 tip.append(anns[i].label);
728 String description = anns[i].annotations[column].description;
729 if (description != null && description.length() > 0)
731 tip.append(" ").append(description);
736 if (tip.length() != 6)
738 tip.setLength(tip.length() - 4);
739 this.setToolTipText(tip.toString() + "</html>");
742 else if (ann.annotations[column] != null)
744 String description = ann.annotations[column].description;
745 if (description != null && description.length() > 0)
747 this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
752 // clear the tooltip.
753 this.setToolTipText(null);
758 * Constructs and displays the status bar message
763 void setStatusMessage(int column, AlignmentAnnotation ann)
766 * show alignment column and annotation description if any
768 StringBuilder text = new StringBuilder(32);
769 text.append(MessageManager.getString("label.column")).append(" ")
772 if (ann.annotations[column] != null)
774 String description = ann.annotations[column].description;
775 if (description != null && description.trim().length() > 0)
777 text.append(" ").append(description);
782 * if the annotation is sequence-specific, show the sequence number
783 * in the alignment, and (if not a gap) the residue and position
785 SequenceI seqref = ann.sequenceRef;
788 int seqIndex = av.getAlignment().findIndex(seqref);
792 .append(MessageManager.getString("label.sequence"))
794 .append(seqIndex + 1);
795 char residue = seqref.getCharAt(column);
796 if (!Comparison.isGap(residue))
798 int residuePos = seqref.findPosition(column);
799 text.append(": ").append(residue).append(" (")
800 .append(residuePos).append(")");
805 ap.alignFrame.statusBar.setText(text.toString());
815 public void mouseClicked(MouseEvent evt)
817 // if (activeRow != -1)
819 // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
820 // AlignmentAnnotation anot = aa[activeRow];
824 // TODO mouseClicked-content and drawCursor are quite experimental!
825 public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
828 int pady = av.getCharHeight() / 5;
830 graphics.setColor(Color.black);
831 graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
833 if (av.validCharWidth)
835 graphics.setColor(Color.white);
837 char s = seq.getCharAt(res);
839 charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
840 graphics.drawString(String.valueOf(s), charOffset + x1,
841 (y1 + av.getCharHeight()) - pady);
846 private volatile boolean imageFresh = false;
855 public void paintComponent(Graphics g)
857 g.setColor(Color.white);
858 g.fillRect(0, 0, getWidth(), getHeight());
862 if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
863 || (getVisibleRect().height != g.getClipBounds().height))
865 g.drawImage(image, 0, 0, this);
870 imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
875 if (image == null || imgWidth != image.getWidth(this)
876 || image.getHeight(this) != getHeight())
880 image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
881 .getHeight(), BufferedImage.TYPE_INT_RGB);
882 } catch (OutOfMemoryError oom)
887 } catch (Exception x)
892 "Couldn't allocate memory to redraw screen. Please restart Jalview",
896 gg = (Graphics2D) image.getGraphics();
900 gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
901 RenderingHints.VALUE_ANTIALIAS_ON);
904 gg.setFont(av.getFont());
905 fm = gg.getFontMetrics();
906 gg.setColor(Color.white);
907 gg.fillRect(0, 0, imgWidth, image.getHeight());
911 drawComponent(gg, av.startRes, av.endRes + 1);
913 g.drawImage(image, 0, 0, this);
917 * set true to enable redraw timing debug output on stderr
919 private final boolean debugRedraw = false;
922 * non-Thread safe repaint
925 * repaint with horizontal shift in alignment
927 public void fastPaint(int horizontal)
929 if ((horizontal == 0) || gg == null
930 || av.getAlignment().getAlignmentAnnotation() == null
931 || av.getAlignment().getAlignmentAnnotation().length < 1
932 || av.isCalcInProgress())
937 long stime = System.currentTimeMillis();
938 gg.copyArea(0, 0, imgWidth, getHeight(),
939 -horizontal * av.getCharWidth(), 0);
940 long mtime = System.currentTimeMillis();
941 int sr = av.startRes;
942 int er = av.endRes + 1;
945 if (horizontal > 0) // scrollbar pulled right, image to the left
947 transX = (er - sr - horizontal) * av.getCharWidth();
948 sr = er - horizontal;
950 else if (horizontal < 0)
952 er = sr - horizontal;
955 gg.translate(transX, 0);
957 drawComponent(gg, sr, er);
959 gg.translate(-transX, 0);
960 long dtime = System.currentTimeMillis();
963 long rtime = System.currentTimeMillis();
966 System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
967 + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
968 + "\tRepaint call:\t" + (rtime - dtime));
973 private volatile boolean lastImageGood = false;
985 public void drawComponent(Graphics g, int startRes, int endRes)
987 BufferedImage oldFaded = fadedImage;
988 if (av.isCalcInProgress())
992 lastImageGood = false;
995 // We'll keep a record of the old image,
996 // and draw a faded image until the calculation
999 && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1000 .getHeight() != image.getHeight()))
1002 // System.err.println("redraw faded image ("+(fadedImage==null ?
1003 // "null image" : "") + " lastGood="+lastImageGood+")");
1004 fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1005 BufferedImage.TYPE_INT_RGB);
1007 Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1009 fadedG.setColor(Color.white);
1010 fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1012 fadedG.setComposite(AlphaComposite.getInstance(
1013 AlphaComposite.SRC_OVER, .3f));
1014 fadedG.drawImage(image, 0, 0, this);
1017 // make sure we don't overwrite the last good faded image until all
1018 // calculations have finished
1019 lastImageGood = false;
1024 if (fadedImage != null)
1026 oldFaded = fadedImage;
1031 g.setColor(Color.white);
1032 g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1034 g.setFont(av.getFont());
1037 fm = g.getFontMetrics();
1040 if ((av.getAlignment().getAlignmentAnnotation() == null)
1041 || (av.getAlignment().getAlignmentAnnotation().length < 1))
1043 g.setColor(Color.white);
1044 g.fillRect(0, 0, getWidth(), getHeight());
1045 g.setColor(Color.black);
1046 if (av.validCharWidth)
1048 g.drawString(MessageManager
1049 .getString("label.alignment_has_no_annotations"), 20, 15);
1054 lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1056 if (!lastImageGood && fadedImage == null)
1058 fadedImage = oldFaded;
1063 public FontMetrics getFontMetrics()
1069 public Image getFadedImage()
1075 public int getFadedImageWidth()
1080 private int[] bounds = new int[2];
1083 public int[] getVisibleVRange()
1085 if (ap != null && ap.getAlabels() != null)
1087 int sOffset = -ap.getAlabels().getScrollOffset();
1088 int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1089 bounds[0] = sOffset;
1090 bounds[1] = visHeight;