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