93af6ec83f40402919d343286f881ef79a979c5e
[jalview.git] / src / jalview / gui / AnnotationPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import java.awt.AlphaComposite;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Image;
30 import java.awt.Rectangle;
31 import java.awt.RenderingHints;
32 import java.awt.event.ActionEvent;
33 import java.awt.event.ActionListener;
34 import java.awt.event.AdjustmentEvent;
35 import java.awt.event.AdjustmentListener;
36 import java.awt.event.MouseEvent;
37 import java.awt.event.MouseListener;
38 import java.awt.event.MouseMotionListener;
39 import java.awt.event.MouseWheelEvent;
40 import java.awt.event.MouseWheelListener;
41 import java.awt.image.BufferedImage;
42 import java.beans.PropertyChangeEvent;
43 import java.util.ArrayList;
44 import java.util.Collections;
45 import java.util.List;
46
47 import javax.swing.JMenuItem;
48 import javax.swing.JPanel;
49 import javax.swing.JPopupMenu;
50 import javax.swing.Scrollable;
51 import javax.swing.ToolTipManager;
52
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.Annotation;
56 import jalview.datamodel.ColumnSelection;
57 import jalview.datamodel.HiddenColumns;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.JalviewColourChooser.ColourChooserListener;
60 import jalview.renderer.AnnotationRenderer;
61 import jalview.renderer.AwtRenderPanelI;
62 import jalview.schemes.ResidueProperties;
63 import jalview.util.Comparison;
64 import jalview.util.MessageManager;
65 import jalview.util.Platform;
66 import jalview.viewmodel.ViewportListenerI;
67 import jalview.viewmodel.ViewportRanges;
68
69 /**
70  * AnnotationPanel displays visible portion of annotation rows below unwrapped
71  * alignment
72  * 
73  * @author $author$
74  * @version $Revision$
75  */
76 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
77         MouseListener, MouseWheelListener, MouseMotionListener,
78         ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
79 {
80   enum DragMode
81   {
82     Select, Resize, Undefined
83   };
84
85   String HELIX = MessageManager.getString("label.helix");
86
87   String SHEET = MessageManager.getString("label.sheet");
88
89   /**
90    * For RNA secondary structure "stems" aka helices
91    */
92   String STEM = MessageManager.getString("label.rna_helix");
93
94   String LABEL = MessageManager.getString("label.label");
95
96   String REMOVE = MessageManager.getString("label.remove_annotation");
97
98   String COLOUR = MessageManager.getString("action.colour");
99
100   public final Color HELIX_COLOUR = Color.red.darker();
101
102   public final Color SHEET_COLOUR = Color.green.darker().darker();
103
104   public final Color STEM_COLOUR = Color.blue.darker();
105
106   /** DOCUMENT ME!! */
107   public AlignViewport av;
108
109   AlignmentPanel ap;
110
111   public int activeRow = -1;
112
113   public BufferedImage image;
114
115   public volatile BufferedImage fadedImage;
116
117   // private Graphics2D gg;
118
119   public FontMetrics fm;
120
121   public int imgWidth = 0;
122
123   boolean fastPaint = false;
124
125   // Used For mouse Dragging and resizing graphs
126   int graphStretch = -1;
127
128   int mouseDragLastX = -1;
129
130   int mouseDragLastY = -1;
131
132   DragMode dragMode = DragMode.Undefined;
133
134   boolean mouseDragging = false;
135
136   // for editing cursor
137   int cursorX = 0;
138
139   int cursorY = 0;
140
141   public final AnnotationRenderer renderer;
142
143   private MouseWheelListener[] _mwl;
144
145   /**
146    * Creates a new AnnotationPanel object.
147    * 
148    * @param ap
149    *          DOCUMENT ME!
150    */
151   public AnnotationPanel(AlignmentPanel ap)
152   {
153     setName("AnnotationPanel");
154     ToolTipManager.sharedInstance().registerComponent(this);
155     ToolTipManager.sharedInstance().setInitialDelay(0);
156     ToolTipManager.sharedInstance().setDismissDelay(10000);
157     this.ap = ap;
158     av = ap.av;
159     this.setLayout(null);
160     addMouseListener(this);
161     addMouseMotionListener(this);
162     ap.annotationScroller.getVerticalScrollBar()
163             .addAdjustmentListener(this);
164     // save any wheel listeners on the scroller, so we can propagate scroll
165     // events to them.
166     _mwl = ap.annotationScroller.getMouseWheelListeners();
167     // and then set our own listener to consume all mousewheel events
168     ap.annotationScroller.addMouseWheelListener(this);
169     renderer = new AnnotationRenderer();
170
171     av.getRanges().addPropertyChangeListener(this);
172   }
173
174   public AnnotationPanel(AlignViewport av)
175   {
176     this.av = av;
177     renderer = new AnnotationRenderer();
178   }
179
180   @Override
181   public void mouseWheelMoved(MouseWheelEvent e)
182   {
183     if (e.isShiftDown())
184     {
185       e.consume();
186       double wheelRotation = e.getPreciseWheelRotation();
187       if (wheelRotation > 0)
188       {
189         av.getRanges().scrollRight(true);
190       }
191       else if (wheelRotation < 0)
192       {
193         av.getRanges().scrollRight(false);
194       }
195     }
196     else
197     {
198       // TODO: find the correct way to let the event bubble up to
199       // ap.annotationScroller
200       for (MouseWheelListener mwl : _mwl)
201       {
202         if (mwl != null)
203         {
204           mwl.mouseWheelMoved(e);
205         }
206         if (e.isConsumed())
207         {
208           break;
209         }
210       }
211     }
212   }
213
214   @Override
215   public Dimension getPreferredScrollableViewportSize()
216   {
217     Dimension ps = getPreferredSize();
218     return new Dimension(ps.width, adjustForAlignFrame(false, ps.height));
219   }
220
221   @Override
222   public int getScrollableBlockIncrement(Rectangle visibleRect,
223           int orientation, int direction)
224   {
225     return 30;
226   }
227
228   @Override
229   public boolean getScrollableTracksViewportHeight()
230   {
231     return false;
232   }
233
234   @Override
235   public boolean getScrollableTracksViewportWidth()
236   {
237     return true;
238   }
239
240   @Override
241   public int getScrollableUnitIncrement(Rectangle visibleRect,
242           int orientation, int direction)
243   {
244     return 30;
245   }
246
247   /*
248    * (non-Javadoc)
249    * 
250    * @see
251    * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
252    * .AdjustmentEvent)
253    */
254   @Override
255   public void adjustmentValueChanged(AdjustmentEvent evt)
256   {
257     // update annotation label display
258     ap.getAlabels().setScrollOffset(-evt.getValue());
259   }
260
261   /**
262    * Calculates the height of the annotation displayed in the annotation panel.
263    * Callers should normally call the ap.adjustAnnotationHeight method to ensure
264    * all annotation associated components are updated correctly.
265    * 
266    */
267   public int adjustPanelHeight()
268   {
269     int height = av.calcPanelHeight();
270     this.setPreferredSize(new Dimension(1, height));
271     if (ap != null)
272     {
273       // revalidate only when the alignment panel is fully constructed
274       ap.validate();
275     }
276
277     return height;
278   }
279
280   /**
281    * DOCUMENT ME!
282    * 
283    * @param evt
284    *          DOCUMENT ME!
285    */
286   @Override
287   public void actionPerformed(ActionEvent evt)
288   {
289     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
290     if (aa == null)
291     {
292       return;
293     }
294     Annotation[] anot = aa[activeRow].annotations;
295
296     if (anot.length < av.getColumnSelection().getMax())
297     {
298       Annotation[] temp = new Annotation[av.getColumnSelection().getMax()
299               + 2];
300       System.arraycopy(anot, 0, temp, 0, anot.length);
301       anot = temp;
302       aa[activeRow].annotations = anot;
303     }
304
305     String action = evt.getActionCommand();
306     if (action.equals(REMOVE))
307     {
308       for (int index : av.getColumnSelection().getSelected())
309       {
310         if (av.getAlignment().getHiddenColumns().isVisible(index))
311         {
312           anot[index] = null;
313         }
314       }
315     }
316     else if (action.equals(LABEL))
317     {
318       String exMesg = collectAnnotVals(anot, LABEL);
319       String label = JvOptionPane.showInputDialog(
320               MessageManager.getString("label.enter_label"), exMesg);
321
322       if (label == null)
323       {
324         return;
325       }
326
327       if ((label.length() > 0) && !aa[activeRow].hasText)
328       {
329         aa[activeRow].hasText = true;
330       }
331
332       for (int index : av.getColumnSelection().getSelected())
333       {
334         if (!av.getAlignment().getHiddenColumns().isVisible(index))
335         {
336           continue;
337         }
338
339         if (anot[index] == null)
340         {
341           anot[index] = new Annotation(label, "", ' ', 0);
342         }
343         else
344         {
345           anot[index].displayCharacter = label;
346         }
347       }
348     }
349     else if (action.equals(COLOUR))
350     {
351       final Annotation[] fAnot = anot;
352       String title = MessageManager
353               .getString("label.select_foreground_colour");
354       ColourChooserListener listener = new ColourChooserListener()
355       {
356         @Override
357         public void colourSelected(Color c)
358         {
359           HiddenColumns hiddenColumns = av.getAlignment()
360                   .getHiddenColumns();
361           for (int index : av.getColumnSelection().getSelected())
362           {
363             if (hiddenColumns.isVisible(index))
364             {
365               if (fAnot[index] == null)
366               {
367                 fAnot[index] = new Annotation("", "", ' ', 0);
368               }
369               fAnot[index].colour = c;
370             }
371           }
372         };
373       };
374       JalviewColourChooser.showColourChooser(this, title, Color.black,
375               listener);
376     }
377     else
378     // HELIX, SHEET or STEM
379     {
380       char type = 0;
381       String symbol = "\u03B1"; // alpha
382
383       if (action.equals(HELIX))
384       {
385         type = 'H';
386       }
387       else if (action.equals(SHEET))
388       {
389         type = 'E';
390         symbol = "\u03B2"; // beta
391       }
392
393       // Added by LML to color stems
394       else if (action.equals(STEM))
395       {
396         type = 'S';
397         int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
398         symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
399       }
400
401       if (!aa[activeRow].hasIcons)
402       {
403         aa[activeRow].hasIcons = true;
404       }
405
406       String label = JvOptionPane.showInputDialog(MessageManager
407               .getString("label.enter_label_for_the_structure"), symbol);
408
409       if (label == null)
410       {
411         return;
412       }
413
414       if ((label.length() > 0) && !aa[activeRow].hasText)
415       {
416         aa[activeRow].hasText = true;
417         if (action.equals(STEM))
418         {
419           aa[activeRow].showAllColLabels = true;
420         }
421       }
422       for (int index : av.getColumnSelection().getSelected())
423       {
424         if (!av.getAlignment().getHiddenColumns().isVisible(index))
425         {
426           continue;
427         }
428
429         if (anot[index] == null)
430         {
431           anot[index] = new Annotation(label, "", type, 0);
432         }
433
434         anot[index].secondaryStructure = type != 'S' ? type
435                 : label.length() == 0 ? ' ' : label.charAt(0);
436         anot[index].displayCharacter = label;
437
438       }
439     }
440
441     av.getAlignment().validateAnnotation(aa[activeRow]);
442     ap.alignmentChanged();
443     ap.alignFrame.setMenusForViewport();
444     adjustPanelHeight();
445     repaint();
446
447     return;
448   }
449
450   /**
451    * Returns any existing annotation concatenated as a string. For each
452    * annotation, takes the description, if any, else the secondary structure
453    * character (if type is HELIX, SHEET or STEM), else the display character (if
454    * type is LABEL).
455    * 
456    * @param anots
457    * @param type
458    * @return
459    */
460   private String collectAnnotVals(Annotation[] anots, String type)
461   {
462     // TODO is this method wanted? why? 'last' is not used
463
464     StringBuilder collatedInput = new StringBuilder(64);
465     String last = "";
466     ColumnSelection viscols = av.getColumnSelection();
467     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
468
469     /*
470      * the selection list (read-only view) is in selection order, not
471      * column order; make a copy so we can sort it
472      */
473     List<Integer> selected = new ArrayList<>(viscols.getSelected());
474     Collections.sort(selected);
475     for (int index : selected)
476     {
477       // always check for current display state - just in case
478       if (!hidden.isVisible(index))
479       {
480         continue;
481       }
482       String tlabel = null;
483       if (anots[index] != null)
484       { // LML added stem code
485         if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
486                 || type.equals(LABEL))
487         {
488           tlabel = anots[index].description;
489           if (tlabel == null || tlabel.length() < 1)
490           {
491             if (type.equals(HELIX) || type.equals(SHEET)
492                     || type.equals(STEM))
493             {
494               tlabel = "" + anots[index].secondaryStructure;
495             }
496             else
497             {
498               tlabel = "" + anots[index].displayCharacter;
499             }
500           }
501         }
502         if (tlabel != null && !tlabel.equals(last))
503         {
504           if (last.length() > 0)
505           {
506             collatedInput.append(" ");
507           }
508           collatedInput.append(tlabel);
509         }
510       }
511     }
512     return collatedInput.toString();
513   }
514
515   /**
516    * Action on right mouse pressed on Mac is to show a pop-up menu for the
517    * annotation. Action on left mouse pressed is to find which annotation is
518    * pressed and mark the start of a column selection or graph resize operation.
519    * 
520    * @param evt
521    */
522   @Override
523   public void mousePressed(MouseEvent evt)
524   {
525
526     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
527     if (aa == null)
528     {
529       return;
530     }
531     mouseDragLastX = evt.getX();
532     mouseDragLastY = evt.getY();
533
534     /*
535      * add visible annotation heights until we reach the y
536      * position, to find which annotation it is in
537      */
538     int height = 0;
539     activeRow = -1;
540
541     final int y = evt.getY();
542     for (int i = 0; i < aa.length; i++)
543     {
544       if (aa[i].visible)
545       {
546         height += aa[i].height;
547       }
548
549       if (y < height)
550       {
551         if (aa[i].editable)
552         {
553           activeRow = i;
554         }
555         else if (aa[i].graph > 0)
556         {
557           /*
558            * we have clicked on a resizable graph annotation
559            */
560           graphStretch = i;
561         }
562         break;
563       }
564     }
565
566     /*
567      * isPopupTrigger fires in mousePressed on Mac,
568      * not until mouseRelease on Windows
569      */
570     if (evt.isPopupTrigger() && activeRow != -1)
571     {
572       showPopupMenu(y, evt.getX());
573       return;
574     }
575
576     ap.getScalePanel().mousePressed(evt);
577   }
578
579   /**
580    * Construct and display a context menu at the right-click position
581    * 
582    * @param y
583    * @param x
584    */
585   void showPopupMenu(final int y, int x)
586   {
587     if (av.getColumnSelection() == null
588             || av.getColumnSelection().isEmpty())
589     {
590       return;
591     }
592
593     JPopupMenu pop = new JPopupMenu(
594             MessageManager.getString("label.structure_type"));
595     JMenuItem item;
596     /*
597      * Just display the needed structure options
598      */
599     if (av.getAlignment().isNucleotide())
600     {
601       item = new JMenuItem(STEM);
602       item.addActionListener(this);
603       pop.add(item);
604     }
605     else
606     {
607       item = new JMenuItem(HELIX);
608       item.addActionListener(this);
609       pop.add(item);
610       item = new JMenuItem(SHEET);
611       item.addActionListener(this);
612       pop.add(item);
613     }
614     item = new JMenuItem(LABEL);
615     item.addActionListener(this);
616     pop.add(item);
617     item = new JMenuItem(COLOUR);
618     item.addActionListener(this);
619     pop.add(item);
620     item = new JMenuItem(REMOVE);
621     item.addActionListener(this);
622     pop.add(item);
623     pop.show(this, x, y);
624   }
625
626   /**
627    * Action on mouse up is to clear mouse drag data and call mouseReleased on
628    * ScalePanel, to deal with defining the selection group (if any) defined by
629    * the mouse drag
630    * 
631    * @param evt
632    */
633   @Override
634   public void mouseReleased(MouseEvent evt)
635   {
636     graphStretch = -1;
637     mouseDragLastX = -1;
638     mouseDragLastY = -1;
639     mouseDragging = false;
640     if (dragMode == DragMode.Resize)
641     {
642       ap.adjustAnnotationHeight();
643     }
644     dragMode = DragMode.Undefined;
645     ap.getScalePanel().mouseReleased(evt);
646
647     /*
648      * isPopupTrigger is set in mouseReleased on Windows
649      * (in mousePressed on Mac)
650      */
651     if (evt.isPopupTrigger() && activeRow != -1)
652     {
653       showPopupMenu(evt.getY(), evt.getX());
654     }
655
656   }
657
658   /**
659    * DOCUMENT ME!
660    * 
661    * @param evt
662    *          DOCUMENT ME!
663    */
664   @Override
665   public void mouseEntered(MouseEvent evt)
666   {
667     this.mouseDragging = false;
668     ap.getScalePanel().mouseEntered(evt);
669   }
670
671   /**
672    * On leaving the panel, calls ScalePanel.mouseExited to deal with scrolling
673    * with column selection on a mouse drag
674    * 
675    * @param evt
676    */
677   @Override
678   public void mouseExited(MouseEvent evt)
679   {
680     ap.getScalePanel().mouseExited(evt);
681   }
682
683   /**
684    * Action on starting or continuing a mouse drag. There are two possible
685    * actions:
686    * <ul>
687    * <li>drag up or down on a graphed annotation increases or decreases the
688    * height of the graph</li>
689    * <li>dragging left or right selects the columns dragged across</li>
690    * </ul>
691    * A drag on a graph annotation is treated as column selection if it starts
692    * with more horizontal than vertical movement, and as resize if it starts
693    * with more vertical than horizontal movement. Once started, the drag does
694    * not change mode.
695    * 
696    * @param evt
697    */
698   @Override
699   public void mouseDragged(MouseEvent evt)
700   {
701     /*
702      * if dragMode is Undefined:
703      * - set to Select if dx > dy
704      * - set to Resize if dy > dx
705      * - do nothing if dx == dy
706      */
707     final int x = evt.getX();
708     final int y = evt.getY();
709     if (dragMode == DragMode.Undefined)
710     {
711       int dx = Math.abs(x - mouseDragLastX);
712       int dy = Math.abs(y - mouseDragLastY);
713       if (graphStretch == -1 || dx > dy)
714       {
715         /*
716          * mostly horizontal drag, or not a graph annotation
717          */
718         dragMode = DragMode.Select;
719       }
720       else if (dy > dx)
721       {
722         /*
723          * mostly vertical drag
724          */
725         dragMode = DragMode.Resize;
726       }
727     }
728
729     if (dragMode == DragMode.Undefined)
730       {
731       /*
732        * drag is diagonal - defer deciding whether to
733        * treat as up/down or left/right
734        */
735         return;
736       }
737
738     try
739     {
740       if (dragMode == DragMode.Resize)
741       {
742         /*
743          * resize graph annotation if mouse was dragged up or down
744          */
745         int deltaY = mouseDragLastY - evt.getY();
746         if (deltaY != 0)
747         {
748           AlignmentAnnotation graphAnnotation = av.getAlignment()
749                   .getAlignmentAnnotation()[graphStretch];
750           int newHeight = Math.max(0, graphAnnotation.graphHeight + deltaY);
751           graphAnnotation.graphHeight = newHeight;
752           adjustPanelHeight();
753           setNoFastPaint();
754           ap.paintAlignment(false, false);
755         }
756       }
757       else
758       {
759         /*
760          * for mouse drag left or right, delegate to 
761          * ScalePanel to adjust the column selection
762          */
763         ap.getScalePanel().mouseDragged(evt);
764       }
765     } finally
766     {
767       mouseDragLastX = x;
768       mouseDragLastY = y;
769     }
770   }
771
772   /**
773    * Constructs the tooltip, and constructs and displays a status message, for
774    * the current mouse position
775    * 
776    * @param evt
777    */
778   @Override
779   public void mouseMoved(MouseEvent evt)
780   {
781     int yPos = evt.getY();
782     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
783
784     int row = getRowIndex(yPos, aa);
785
786     if (row == -1)
787     {
788       this.setToolTipText(null);
789       return;
790     }
791
792     int column = (evt.getX() / av.getCharWidth())
793             + av.getRanges().getStartRes();
794     column = Math.min(column, av.getRanges().getEndRes());
795
796     if (av.hasHiddenColumns())
797     {
798       column = av.getAlignment().getHiddenColumns()
799               .visibleToAbsoluteColumn(column);
800     }
801
802     AlignmentAnnotation ann = aa[row];
803     if (row > -1 && ann.annotations != null
804             && column < ann.annotations.length)
805     {
806       String toolTip = buildToolTip(ann, column, aa);
807       setToolTipText(toolTip == null ? null
808               : JvSwingUtils.wrapTooltip(true, toolTip));
809       String msg = getStatusMessage(av.getAlignment(), column, ann);
810       ap.alignFrame.setStatus(msg);
811     }
812     else
813     {
814       this.setToolTipText(null);
815       ap.alignFrame.setStatus(" ");
816     }
817   }
818
819   /**
820    * Answers the index in the annotations array of the visible annotation at the
821    * given y position. This is done by adding the heights of visible annotations
822    * until the y position has been exceeded. Answers -1 if no annotations are
823    * visible, or the y position is below all annotations.
824    * 
825    * @param yPos
826    * @param aa
827    * @return
828    */
829   static int getRowIndex(int yPos, AlignmentAnnotation[] aa)
830   {
831     if (aa == null)
832     {
833       return -1;
834     }
835     int row = -1;
836     int height = 0;
837
838     for (int i = 0; i < aa.length; i++)
839     {
840       if (aa[i].visible)
841       {
842         height += aa[i].height;
843       }
844
845       if (height > yPos)
846       {
847         row = i;
848         break;
849       }
850     }
851     return row;
852   }
853
854   /**
855    * Answers a tooltip for the annotation at the current mouse position, not
856    * wrapped in &lt;html&gt; tags (apply if wanted). Answers null if there is no
857    * tooltip to show.
858    * 
859    * @param ann
860    * @param column
861    * @param anns
862    */
863   static String buildToolTip(AlignmentAnnotation ann, int column,
864           AlignmentAnnotation[] anns)
865   {
866     String tooltip = null;
867     if (ann.graphGroup > -1)
868     {
869       StringBuilder tip = new StringBuilder(32);
870       boolean first = true;
871       for (int i = 0; i < anns.length; i++)
872       {
873         if (anns[i].graphGroup == ann.graphGroup
874                 && anns[i].annotations[column] != null)
875         {
876           if (!first)
877           {
878             tip.append("<br>");
879           }
880           first = false;
881           tip.append(anns[i].label);
882           String description = anns[i].annotations[column].description;
883           if (description != null && description.length() > 0)
884           {
885             tip.append(" ").append(description);
886           }
887         }
888       }
889       tooltip = first ? null : tip.toString();
890     }
891     else if (column < ann.annotations.length
892             && ann.annotations[column] != null)
893     {
894       tooltip = ann.annotations[column].description;
895       if ("".equals(tooltip))
896       {
897         tooltip = null;
898       }
899     }
900
901     return tooltip;
902   }
903
904   /**
905    * Constructs and returns the status bar message
906    * 
907    * @param al
908    * @param column
909    * @param ann
910    */
911   static String getStatusMessage(AlignmentI al, int column,
912           AlignmentAnnotation ann)
913   {
914     /*
915      * show alignment column and annotation description if any
916      */
917     StringBuilder text = new StringBuilder(32);
918     text.append(MessageManager.getString("label.column")).append(" ")
919             .append(column + 1);
920
921     if (column < ann.annotations.length && ann.annotations[column] != null)
922     {
923       String description = ann.annotations[column].description;
924       if (description != null && description.trim().length() > 0)
925       {
926         text.append("  ").append(description);
927       }
928     }
929
930     /*
931      * if the annotation is sequence-specific, show the sequence number
932      * in the alignment, and (if not a gap) the residue and position
933      */
934     SequenceI seqref = ann.sequenceRef;
935     if (seqref != null)
936     {
937       int seqIndex = al.findIndex(seqref);
938       if (seqIndex != -1)
939       {
940         text.append(", ").append(MessageManager.getString("label.sequence"))
941                 .append(" ").append(seqIndex + 1);
942         char residue = seqref.getCharAt(column);
943         if (!Comparison.isGap(residue))
944         {
945           text.append(" ");
946           String name;
947           if (al.isNucleotide())
948           {
949             name = ResidueProperties.nucleotideName
950                     .get(String.valueOf(residue));
951             text.append(" Nucleotide: ")
952                     .append(name != null ? name : residue);
953           }
954           else
955           {
956             name = 'X' == residue ? "X"
957                     : ('*' == residue ? "STOP"
958                             : ResidueProperties.aa2Triplet
959                                     .get(String.valueOf(residue)));
960             text.append(" Residue: ").append(name != null ? name : residue);
961           }
962           int residuePos = seqref.findPosition(column);
963           text.append(" (").append(residuePos).append(")");
964         }
965       }
966     }
967
968     return text.toString();
969   }
970
971   /**
972    * DOCUMENT ME!
973    * 
974    * @param evt
975    *          DOCUMENT ME!
976    */
977   @Override
978   public void mouseClicked(MouseEvent evt)
979   {
980     // if (activeRow != -1)
981     // {
982     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
983     // AlignmentAnnotation anot = aa[activeRow];
984     // }
985   }
986
987   // TODO mouseClicked-content and drawCursor are quite experimental!
988   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
989           int y1)
990   {
991     int pady = av.getCharHeight() / 5;
992     int charOffset = 0;
993     graphics.setColor(Color.black);
994     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
995
996     if (av.validCharWidth)
997     {
998       graphics.setColor(Color.white);
999
1000       char s = seq.getCharAt(res);
1001
1002       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
1003       graphics.drawString(String.valueOf(s), charOffset + x1,
1004               (y1 + av.getCharHeight()) - pady);
1005     }
1006
1007   }
1008
1009   private volatile boolean imageFresh = false;
1010   private Rectangle visibleRect = new Rectangle(),
1011           clipBounds = new Rectangle();
1012
1013   /**
1014    * DOCUMENT ME!
1015    * 
1016    * @param g
1017    *          DOCUMENT ME!
1018    */
1019   @Override
1020   public void paintComponent(Graphics g)
1021   {
1022     // BH: note that this method is generally recommended to
1023     // call super.paintComponent(g). Otherwise, the children of this
1024     // component will not be rendered. That is not needed here
1025     // because AnnotationPanel does not have any children. It is
1026     // just a JPanel contained in a JViewPort.
1027
1028     computeVisibleRect(visibleRect);
1029     g.setColor(Color.white);
1030     g.fillRect(0, 0, visibleRect.width, visibleRect.height);
1031
1032     ViewportRanges ranges = av.getRanges();
1033
1034     if (allowFastPaint && image != null)
1035     {
1036       // BH 2018 optimizing generation of new Rectangle().
1037       if (fastPaint
1038               || (visibleRect.width != (clipBounds = g
1039                       .getClipBounds(clipBounds)).width)
1040               || (visibleRect.height != clipBounds.height))
1041       {
1042
1043           
1044           g.drawImage(image, 0, 0, this);
1045         fastPaint = false;
1046         return;
1047       }
1048     }
1049     imgWidth = (ranges.getEndRes() - ranges.getStartRes() + 1)
1050             * av.getCharWidth();
1051     if (imgWidth < 1)
1052     {
1053       fastPaint = false;
1054       return;
1055     }
1056     Graphics2D gg;
1057     if (image == null || imgWidth != image.getWidth(this)
1058             || image.getHeight(this) != getHeight())
1059     {
1060       try
1061       {
1062         image = new BufferedImage(imgWidth,
1063                 ap.getAnnotationPanel().getHeight(),
1064                 BufferedImage.TYPE_INT_RGB);
1065       } catch (OutOfMemoryError oom)
1066       {
1067         try
1068         {
1069           System.gc();
1070         } catch (Exception x)
1071         {
1072         }
1073         ;
1074         new OOMWarning(
1075                 "Couldn't allocate memory to redraw screen. Please restart Jalview",
1076                 oom);
1077         return;
1078       }
1079       gg = (Graphics2D) image.getGraphics();
1080
1081       if (av.antiAlias)
1082       {
1083         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1084                 RenderingHints.VALUE_ANTIALIAS_ON);
1085       }
1086
1087       gg.setFont(av.getFont());
1088       fm = gg.getFontMetrics();
1089       gg.setColor(Color.white);
1090       gg.fillRect(0, 0, imgWidth, image.getHeight());
1091       imageFresh = true;
1092     }
1093     else
1094     {
1095       gg = (Graphics2D) image.getGraphics();
1096
1097     }
1098     
1099     drawComponent(gg, av.getRanges().getStartRes(),
1100             av.getRanges().getEndRes() + 1);
1101     gg.dispose();
1102     imageFresh = false;
1103     g.drawImage(image, 0, 0, this);
1104   }
1105
1106   /**
1107    * non-Thread safe repaint
1108    * 
1109    * @param horizontal
1110    *          repaint with horizontal shift in alignment
1111    */
1112   public void fastPaint(int horizontal)
1113   {
1114     if ((horizontal == 0) || image == null
1115             || av.getAlignment().getAlignmentAnnotation() == null
1116             || av.getAlignment().getAlignmentAnnotation().length < 1
1117             || av.isCalcInProgress())
1118     {
1119       repaint();
1120       return;
1121     }
1122
1123     int sr = av.getRanges().getStartRes();
1124     int er = av.getRanges().getEndRes() + 1;
1125     int transX = 0;
1126
1127     if (er == sr + 1)
1128     {
1129       fastPaint = false;
1130       return;
1131     }
1132     Graphics2D gg = (Graphics2D) image.getGraphics();
1133
1134     if (imgWidth>Math.abs(horizontal*av.getCharWidth())) {
1135       //scroll is less than imgWidth away so can re-use buffered graphics
1136       gg.copyArea(0, 0, imgWidth, getHeight(),
1137               -horizontal * av.getCharWidth(), 0);
1138       
1139       if (horizontal > 0) // scrollbar pulled right, image to the left
1140       {
1141         transX = (er - sr - horizontal) * av.getCharWidth();
1142         sr = er - horizontal;
1143       }
1144       else if (horizontal < 0)
1145       {
1146         er = sr - horizontal;
1147       }
1148     }
1149
1150     gg.translate(transX, 0);
1151
1152     drawComponent(gg, sr, er);
1153
1154     gg.translate(-transX, 0);
1155
1156     gg.dispose();
1157     fastPaint = true;
1158
1159     // Call repaint on alignment panel so that repaints from other alignment
1160     // panel components can be aggregated. Otherwise performance of the overview
1161     // window and others may be adversely affected.
1162     av.getAlignPanel().repaint();
1163   }
1164
1165   private volatile boolean lastImageGood = false;
1166
1167   /**
1168    * DOCUMENT ME!
1169    * 
1170    * @param g
1171    *          DOCUMENT ME!
1172    * @param startRes
1173    *          DOCUMENT ME!
1174    * @param endRes
1175    *          DOCUMENT ME!
1176    */
1177   public void drawComponent(Graphics g, int startRes, int endRes)
1178   {
1179     BufferedImage oldFaded = fadedImage;
1180     if (av.isCalcInProgress())
1181     {
1182       if (image == null)
1183       {
1184         lastImageGood = false;
1185         return;
1186       }
1187       // We'll keep a record of the old image,
1188       // and draw a faded image until the calculation
1189       // has completed
1190       if (lastImageGood
1191               && (fadedImage == null || fadedImage.getWidth() != imgWidth
1192                       || fadedImage.getHeight() != image.getHeight()))
1193       {
1194         // System.err.println("redraw faded image ("+(fadedImage==null ?
1195         // "null image" : "") + " lastGood="+lastImageGood+")");
1196         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1197                 BufferedImage.TYPE_INT_RGB);
1198
1199         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1200
1201         fadedG.setColor(Color.white);
1202         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1203
1204         fadedG.setComposite(
1205                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1206         fadedG.drawImage(image, 0, 0, this);
1207
1208       }
1209       // make sure we don't overwrite the last good faded image until all
1210       // calculations have finished
1211       lastImageGood = false;
1212
1213     }
1214     else
1215     {
1216       if (fadedImage != null)
1217       {
1218         oldFaded = fadedImage;
1219       }
1220       fadedImage = null;
1221     }
1222
1223     g.setColor(Color.white);
1224     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1225
1226     g.setFont(av.getFont());
1227     if (fm == null)
1228     {
1229       fm = g.getFontMetrics();
1230     }
1231
1232     if ((av.getAlignment().getAlignmentAnnotation() == null)
1233             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1234     {
1235       g.setColor(Color.white);
1236       g.fillRect(0, 0, getWidth(), getHeight());
1237       g.setColor(Color.black);
1238       if (av.validCharWidth)
1239       {
1240         g.drawString(MessageManager
1241                 .getString("label.alignment_has_no_annotations"), 20, 15);
1242       }
1243
1244       return;
1245     }
1246     lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1247             endRes);
1248     if (!lastImageGood && fadedImage == null)
1249     {
1250       fadedImage = oldFaded;
1251     }
1252   }
1253
1254   @Override
1255   public FontMetrics getFontMetrics()
1256   {
1257     return fm;
1258   }
1259
1260   @Override
1261   public Image getFadedImage()
1262   {
1263     return fadedImage;
1264   }
1265
1266   @Override
1267   public int getFadedImageWidth()
1268   {
1269     return imgWidth;
1270   }
1271
1272   private int[] bounds = new int[2];
1273
1274   private boolean allowFastPaint;
1275   @Override
1276   public int[] getVisibleVRange()
1277   {
1278     if (ap != null && ap.getAlabels() != null)
1279     {
1280       int sOffset = -ap.getAlabels().getScrollOffset();
1281       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1282       bounds[0] = sOffset;
1283       bounds[1] = visHeight;
1284       return bounds;
1285     }
1286     else
1287     {
1288       return null;
1289     }
1290   }
1291
1292   /**
1293    * Try to ensure any references held are nulled
1294    */
1295   public void dispose()
1296   {
1297     av = null;
1298     ap = null;
1299     image = null;
1300     fadedImage = null;
1301     // gg = null;
1302     _mwl = null;
1303
1304     /*
1305      * I created the renderer so I will dispose of it
1306      */
1307     if (renderer != null)
1308     {
1309       renderer.dispose();
1310     }
1311   }
1312
1313   @Override
1314   public void propertyChange(PropertyChangeEvent evt)
1315   {
1316     // Respond to viewport range changes (e.g. alignment panel was scrolled)
1317     // Both scrolling and resizing change viewport ranges: scrolling changes
1318     // both start and end points, but resize only changes end values.
1319     // Here we only want to fastpaint on a scroll, with resize using a normal
1320     // paint, so scroll events are identified as changes to the horizontal or
1321     // vertical start value.
1322     if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1323     {
1324       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1325     }
1326     else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1327     {
1328       fastPaint(((int[]) evt.getNewValue())[0]
1329               - ((int[]) evt.getOldValue())[0]);
1330     }
1331     else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
1332     {
1333       repaint();
1334     }
1335   }
1336
1337   /**
1338    * computes the visible height of the annotation panel
1339    * 
1340    * @param adjustPanelHeight
1341    *          - when false, just adjust existing height according to other
1342    *          windows
1343    * @param annotationHeight
1344    * @return height to use for the ScrollerPreferredVisibleSize
1345    */
1346   public int adjustForAlignFrame(boolean adjustPanelHeight,
1347           int annotationHeight)
1348   {
1349     /*
1350      * Estimate available height in the AlignFrame for alignment +
1351      * annotations. Deduct an estimate for title bar, menu bar, scale panel,
1352      * hscroll, status bar, insets. 
1353      */
1354     int stuff = (ap.getViewName() != null ? 30 : 0)
1355             + (Platform.isAMacAndNotJS() ? 120 : 140);
1356     int availableHeight = ap.alignFrame.getHeight() - stuff;
1357     int rowHeight = av.getCharHeight();
1358
1359     if (adjustPanelHeight)
1360     {
1361       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
1362
1363       /*
1364        * If not enough vertical space, maximize annotation height while keeping
1365        * at least two rows of alignment visible
1366        */
1367       if (annotationHeight + alignmentHeight > availableHeight)
1368       {
1369         annotationHeight = Math.min(annotationHeight,
1370                 availableHeight - 2 * rowHeight);
1371       }
1372     }
1373     else
1374     {
1375       // maintain same window layout whilst updating sliders
1376       annotationHeight = Math.min(ap.annotationScroller.getSize().height,
1377               availableHeight - 2 * rowHeight);
1378     }
1379     return annotationHeight;
1380   }
1381   
1382   /**
1383    * Clears the flag that allows a 'fast paint' on the next repaint, so
1384    * requiring a full repaint
1385    */
1386   public void setNoFastPaint()
1387   {
1388     allowFastPaint = false;
1389   }
1390 }