removal of AlignmentFrame lines
[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 jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.HiddenColumns;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.JalviewColourChooser.ColourChooserListener;
29 import jalview.renderer.AnnotationRenderer;
30 import jalview.renderer.AwtRenderPanelI;
31 import jalview.schemes.ResidueProperties;
32 import jalview.util.Comparison;
33 import jalview.util.MessageManager;
34 import jalview.util.Platform;
35 import jalview.viewmodel.ViewportListenerI;
36 import jalview.viewmodel.ViewportRanges;
37
38 import java.awt.AlphaComposite;
39 import java.awt.Color;
40 import java.awt.Dimension;
41 import java.awt.FontMetrics;
42 import java.awt.Graphics;
43 import java.awt.Graphics2D;
44 import java.awt.Image;
45 import java.awt.Rectangle;
46 import java.awt.RenderingHints;
47 import java.awt.event.ActionEvent;
48 import java.awt.event.ActionListener;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.MouseEvent;
52 import java.awt.event.MouseListener;
53 import java.awt.event.MouseMotionListener;
54 import java.awt.event.MouseWheelEvent;
55 import java.awt.event.MouseWheelListener;
56 import java.awt.image.BufferedImage;
57 import java.beans.PropertyChangeEvent;
58 import java.util.ArrayList;
59 import java.util.Collections;
60 import java.util.List;
61
62 import javax.swing.JMenuItem;
63 import javax.swing.JPanel;
64 import javax.swing.JPopupMenu;
65 import javax.swing.Scrollable;
66 import javax.swing.ToolTipManager;
67
68 /**
69  * AnnotationPanel displays visible portion of annotation rows below unwrapped
70  * alignment
71  * 
72  * @author $author$
73  * @version $Revision$
74  */
75 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
76         MouseListener, MouseWheelListener, MouseMotionListener,
77         ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
78 {
79   enum DragMode
80   {
81     Select, Resize, Undefined
82   };
83
84   String HELIX = MessageManager.getString("label.helix");
85
86   String SHEET = MessageManager.getString("label.sheet");
87
88   /**
89    * For RNA secondary structure "stems" aka helices
90    */
91   String STEM = MessageManager.getString("label.rna_helix");
92
93   String LABEL = MessageManager.getString("label.label");
94
95   String REMOVE = MessageManager.getString("label.remove_annotation");
96
97   String COLOUR = MessageManager.getString("action.colour");
98
99   public final Color HELIX_COLOUR = Color.red.darker();
100
101   public final Color SHEET_COLOUR = Color.green.darker().darker();
102
103   public final Color STEM_COLOUR = Color.blue.darker();
104
105   /** DOCUMENT ME!! */
106   public AlignViewport av;
107
108   AlignmentPanel ap;
109
110   public int activeRow = -1;
111
112   public BufferedImage image;
113
114   public volatile BufferedImage fadedImage;
115
116   // private Graphics2D gg;
117
118   public FontMetrics fm;
119
120   public int imgWidth = 0;
121
122   boolean fastPaint = false;
123
124   // Used For mouse Dragging and resizing graphs
125   int graphStretch = -1;
126
127   int mouseDragLastX = -1;
128
129   int mouseDragLastY = -1;
130
131   DragMode dragMode = DragMode.Undefined;
132
133   boolean mouseDragging = false;
134
135   // for editing cursor
136   int cursorX = 0;
137
138   int cursorY = 0;
139
140   public final AnnotationRenderer renderer;
141
142   private MouseWheelListener[] _mwl;
143
144   /**
145    * Creates a new AnnotationPanel object.
146    * 
147    * @param ap
148    *          DOCUMENT ME!
149    */
150   public AnnotationPanel(AlignmentPanel ap)
151   {
152             setBackground(Color.white);  // BH 2019
153
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().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       JalviewColourChooser.showColourChooser(this,
373               title, Color.black, listener);
374     }
375     else
376     // HELIX, SHEET or STEM
377     {
378       char type = 0;
379       String symbol = "\u03B1"; // alpha
380
381       if (action.equals(HELIX))
382       {
383         type = 'H';
384       }
385       else if (action.equals(SHEET))
386       {
387         type = 'E';
388         symbol = "\u03B2"; // beta
389       }
390
391       // Added by LML to color stems
392       else if (action.equals(STEM))
393       {
394         type = 'S';
395         int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
396         symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
397       }
398
399       if (!aa[activeRow].hasIcons)
400       {
401         aa[activeRow].hasIcons = true;
402       }
403
404       String label = JvOptionPane.showInputDialog(MessageManager
405               .getString("label.enter_label_for_the_structure"), symbol);
406
407       if (label == null)
408       {
409         return;
410       }
411
412       if ((label.length() > 0) && !aa[activeRow].hasText)
413       {
414         aa[activeRow].hasText = true;
415         if (action.equals(STEM))
416         {
417           aa[activeRow].showAllColLabels = true;
418         }
419       }
420       for (int index : av.getColumnSelection().getSelected())
421       {
422         if (!av.getAlignment().getHiddenColumns().isVisible(index))
423         {
424           continue;
425         }
426
427         if (anot[index] == null)
428         {
429           anot[index] = new Annotation(label, "", type, 0);
430         }
431
432         anot[index].secondaryStructure = type != 'S' ? type
433                 : label.length() == 0 ? ' ' : label.charAt(0);
434         anot[index].displayCharacter = label;
435
436       }
437     }
438
439     av.getAlignment().validateAnnotation(aa[activeRow]);
440     ap.alignmentChanged();
441     ap.alignFrame.setMenusForViewport();
442     adjustPanelHeight();
443     repaint();
444
445     return;
446   }
447
448   /**
449    * Returns any existing annotation concatenated as a string. For each
450    * annotation, takes the description, if any, else the secondary structure
451    * character (if type is HELIX, SHEET or STEM), else the display character (if
452    * type is LABEL).
453    * 
454    * @param anots
455    * @param type
456    * @return
457    */
458   private String collectAnnotVals(Annotation[] anots, String type)
459   {
460     // TODO is this method wanted? why? 'last' is not used
461
462     StringBuilder collatedInput = new StringBuilder(64);
463     String last = "";
464     ColumnSelection viscols = av.getColumnSelection();
465     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
466
467     /*
468      * the selection list (read-only view) is in selection order, not
469      * column order; make a copy so we can sort it
470      */
471     List<Integer> selected = new ArrayList<>(viscols.getSelected());
472     Collections.sort(selected);
473     for (int index : selected)
474     {
475       // always check for current display state - just in case
476       if (!hidden.isVisible(index))
477       {
478         continue;
479       }
480       String tlabel = null;
481       if (anots[index] != null)
482       { // LML added stem code
483         if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
484                 || type.equals(LABEL))
485         {
486           tlabel = anots[index].description;
487           if (tlabel == null || tlabel.length() < 1)
488           {
489             if (type.equals(HELIX) || type.equals(SHEET)
490                     || type.equals(STEM))
491             {
492               tlabel = "" + anots[index].secondaryStructure;
493             }
494             else
495             {
496               tlabel = "" + anots[index].displayCharacter;
497             }
498           }
499         }
500         if (tlabel != null && !tlabel.equals(last))
501         {
502           if (last.length() > 0)
503           {
504             collatedInput.append(" ");
505           }
506           collatedInput.append(tlabel);
507         }
508       }
509     }
510     return collatedInput.toString();
511   }
512
513   /**
514    * Action on right mouse pressed on Mac is to show a pop-up menu for the
515    * annotation. Action on left mouse pressed is to find which annotation is
516    * pressed and mark the start of a column selection or graph resize operation.
517    * 
518    * @param evt
519    */
520   @Override
521   public void mousePressed(MouseEvent evt)
522   {
523
524     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
525     if (aa == null)
526     {
527       return;
528     }
529     mouseDragLastX = evt.getX();
530     mouseDragLastY = evt.getY();
531
532     /*
533      * add visible annotation heights until we reach the y
534      * position, to find which annotation it is in
535      */
536     int height = 0;
537     activeRow = -1;
538
539     final int y = evt.getY();
540     for (int i = 0; i < aa.length; i++)
541     {
542       if (aa[i].visible)
543       {
544         height += aa[i].height;
545       }
546
547       if (y < height)
548       {
549         if (aa[i].editable)
550         {
551           activeRow = i;
552         }
553         else if (aa[i].graph > 0)
554         {
555           /*
556            * we have clicked on a resizable graph annotation
557            */
558           graphStretch = i;
559         }
560         break;
561       }
562     }
563
564     /*
565      * isPopupTrigger fires in mousePressed on Mac,
566      * not until mouseRelease on Windows
567      */
568     if (evt.isPopupTrigger() && activeRow != -1)
569     {
570       showPopupMenu(y, evt.getX());
571       return;
572     }
573
574     ap.getScalePanel().mousePressed(evt);
575   }
576
577   /**
578    * Construct and display a context menu at the right-click position
579    * 
580    * @param y
581    * @param x
582    */
583   void showPopupMenu(final int y, int x)
584   {
585     if (av.getColumnSelection() == null
586             || av.getColumnSelection().isEmpty())
587     {
588       return;
589     }
590
591     JPopupMenu pop = new JPopupMenu(
592             MessageManager.getString("label.structure_type"));
593     JMenuItem item;
594     /*
595      * Just display the needed structure options
596      */
597     if (av.getAlignment().isNucleotide())
598     {
599       item = new JMenuItem(STEM);
600       item.addActionListener(this);
601       pop.add(item);
602     }
603     else
604     {
605       item = new JMenuItem(HELIX);
606       item.addActionListener(this);
607       pop.add(item);
608       item = new JMenuItem(SHEET);
609       item.addActionListener(this);
610       pop.add(item);
611     }
612     item = new JMenuItem(LABEL);
613     item.addActionListener(this);
614     pop.add(item);
615     item = new JMenuItem(COLOUR);
616     item.addActionListener(this);
617     pop.add(item);
618     item = new JMenuItem(REMOVE);
619     item.addActionListener(this);
620     pop.add(item);
621     pop.show(this, x, y);
622   }
623
624   /**
625    * Action on mouse up is to clear mouse drag data and call mouseReleased on
626    * ScalePanel, to deal with defining the selection group (if any) defined by
627    * the mouse drag
628    * 
629    * @param evt
630    */
631   @Override
632   public void mouseReleased(MouseEvent evt)
633   {
634     graphStretch = -1;
635     mouseDragLastX = -1;
636     mouseDragLastY = -1;
637     mouseDragging = false;
638     dragMode = DragMode.Undefined;
639     ap.getScalePanel().mouseReleased(evt);
640
641     /*
642      * isPopupTrigger is set in mouseReleased on Windows
643      * (in mousePressed on Mac)
644      */
645     if (evt.isPopupTrigger() && activeRow != -1)
646     {
647       showPopupMenu(evt.getY(), evt.getX());
648     }
649
650   }
651
652   /**
653    * DOCUMENT ME!
654    * 
655    * @param evt
656    *          DOCUMENT ME!
657    */
658   @Override
659   public void mouseEntered(MouseEvent evt)
660   {
661     this.mouseDragging = false;
662     ap.getScalePanel().mouseEntered(evt);
663   }
664
665   /**
666    * On leaving the panel, calls ScalePanel.mouseExited to deal with scrolling
667    * with column selection on a mouse drag
668    * 
669    * @param evt
670    */
671   @Override
672   public void mouseExited(MouseEvent evt)
673   {
674     ap.getScalePanel().mouseExited(evt);
675   }
676
677   /**
678    * DOCUMENT ME!
679    * 
680    * @param evt
681    *          DOCUMENT ME!
682    */
683   @Override
684   public void mouseDragged(MouseEvent evt)
685   {
686     /*
687      * todo: if dragMode is Undefined:
688      * - set to Select if dx > dy
689      * - set to Resize if dy > dx
690      * - do nothing if dx == dy
691      */
692     final int x = evt.getX();
693     final int y = evt.getY();
694     if (dragMode == DragMode.Undefined)
695     {
696       int dx = Math.abs(x - mouseDragLastX);
697       int dy = Math.abs(y - mouseDragLastY);
698       if (graphStretch == -1 || dx > dy)
699       {
700         /*
701          * mostly horizontal drag, or not a graph annotation
702          */
703         dragMode = DragMode.Select;
704       }
705       else if (dy > dx)
706       {
707         /*
708          * mostly vertical drag
709          */
710         dragMode = DragMode.Resize;
711       }
712     }
713
714     if (dragMode == DragMode.Undefined)
715     {
716       /*
717        * drag is diagonal - defer deciding whether to
718        * treat as up/down or left/right
719        */
720       return;
721     }
722
723     try
724     {
725       if (dragMode == DragMode.Resize)
726       {
727         /*
728          * resize graph annotation if mouse was dragged up or down
729          */
730         int deltaY = mouseDragLastY - evt.getY();
731         if (deltaY != 0)
732         {
733           AlignmentAnnotation graphAnnotation = av.getAlignment()
734                   .getAlignmentAnnotation()[graphStretch];
735           int newHeight = Math.max(0, graphAnnotation.graphHeight + deltaY);
736           graphAnnotation.graphHeight = newHeight;
737           adjustPanelHeight();
738           ap.paintAlignment(false, false);
739         }
740       }
741       else
742       {
743         /*
744          * for mouse drag left or right, delegate to 
745          * ScalePanel to adjust the column selection
746          */
747         ap.getScalePanel().mouseDragged(evt);
748       }
749     } finally
750     {
751       mouseDragLastX = x;
752       mouseDragLastY = y;
753     }
754   }
755
756   /**
757    * Constructs the tooltip, and constructs and displays a status message, for
758    * the current mouse position
759    * 
760    * @param evt
761    */
762   @Override
763   public void mouseMoved(MouseEvent evt)
764   {
765     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
766
767     if (aa == null)
768     {
769       this.setToolTipText(null);
770       return;
771     }
772
773     int row = -1;
774     int height = 0;
775
776     for (int i = 0; i < aa.length; i++)
777     {
778       if (aa[i].visible)
779       {
780         height += aa[i].height;
781       }
782
783       if (evt.getY() < height)
784       {
785         row = i;
786         break;
787       }
788     }
789
790     if (row == -1)
791     {
792       this.setToolTipText(null);
793       return;
794     }
795
796     int column = (evt.getX() / av.getCharWidth())
797             + av.getRanges().getStartRes();
798
799     if (av.hasHiddenColumns())
800     {
801       column = av.getAlignment().getHiddenColumns()
802               .visibleToAbsoluteColumn(column);
803     }
804
805     AlignmentAnnotation ann = aa[row];
806     if (row > -1 && ann.annotations != null
807             && column < ann.annotations.length)
808     {
809       buildToolTip(ann, column, aa);
810       setStatusMessage(column, ann);
811     }
812     else
813     {
814       this.setToolTipText(null);
815       ap.alignFrame.setStatus(" ");
816     }
817   }
818
819   /**
820    * Builds a tooltip for the annotation at the current mouse position.
821    * 
822    * @param ann
823    * @param column
824    * @param anns
825    */
826   void buildToolTip(AlignmentAnnotation ann, int column,
827           AlignmentAnnotation[] anns)
828   {
829     if (ann.graphGroup > -1)
830     {
831       StringBuilder tip = new StringBuilder(32);
832       tip.append("<html>");
833       for (int i = 0; i < anns.length; i++)
834       {
835         if (anns[i].graphGroup == ann.graphGroup
836                 && anns[i].annotations[column] != null)
837         {
838           tip.append(anns[i].label);
839           String description = anns[i].annotations[column].description;
840           if (description != null && description.length() > 0)
841           {
842             tip.append(" ").append(description);
843           }
844           tip.append("<br>");
845         }
846       }
847       if (tip.length() != 6)
848       {
849         tip.setLength(tip.length() - 4);
850         this.setToolTipText(tip.toString() + "</html>");
851       }
852     }
853     else if (ann.annotations[column] != null)
854     {
855       String description = ann.annotations[column].description;
856       if (description != null && description.length() > 0)
857       {
858         this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
859       }
860       else
861       {
862         this.setToolTipText(null); // no tooltip if null or empty description
863       }
864     }
865     else
866     {
867       // clear the tooltip.
868       this.setToolTipText(null);
869     }
870   }
871
872   /**
873    * Constructs and displays the status bar message
874    * 
875    * @param column
876    * @param ann
877    */
878   void setStatusMessage(int column, AlignmentAnnotation ann)
879   {
880     /*
881      * show alignment column and annotation description if any
882      */
883     StringBuilder text = new StringBuilder(32);
884     text.append(MessageManager.getString("label.column")).append(" ")
885             .append(column + 1);
886
887     if (ann.annotations[column] != null)
888     {
889       String description = ann.annotations[column].description;
890       if (description != null && description.trim().length() > 0)
891       {
892         text.append("  ").append(description);
893       }
894     }
895
896     /*
897      * if the annotation is sequence-specific, show the sequence number
898      * in the alignment, and (if not a gap) the residue and position
899      */
900     SequenceI seqref = ann.sequenceRef;
901     if (seqref != null)
902     {
903       int seqIndex = av.getAlignment().findIndex(seqref);
904       if (seqIndex != -1)
905       {
906         text.append(", ").append(MessageManager.getString("label.sequence"))
907                 .append(" ").append(seqIndex + 1);
908         char residue = seqref.getCharAt(column);
909         if (!Comparison.isGap(residue))
910         {
911           text.append(" ");
912           String name;
913           if (av.getAlignment().isNucleotide())
914           {
915             name = ResidueProperties.nucleotideName
916                     .get(String.valueOf(residue));
917             text.append(" Nucleotide: ")
918                     .append(name != null ? name : residue);
919           }
920           else
921           {
922             name = 'X' == residue ? "X"
923                     : ('*' == residue ? "STOP"
924                             : ResidueProperties.aa2Triplet
925                                     .get(String.valueOf(residue)));
926             text.append(" Residue: ").append(name != null ? name : residue);
927           }
928           int residuePos = seqref.findPosition(column);
929           text.append(" (").append(residuePos).append(")");
930         }
931       }
932     }
933
934     ap.alignFrame.setStatus(text.toString());
935   }
936
937   /**
938    * DOCUMENT ME!
939    * 
940    * @param evt
941    *          DOCUMENT ME!
942    */
943   @Override
944   public void mouseClicked(MouseEvent evt)
945   {
946     // if (activeRow != -1)
947     // {
948     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
949     // AlignmentAnnotation anot = aa[activeRow];
950     // }
951   }
952
953   // TODO mouseClicked-content and drawCursor are quite experimental!
954   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
955           int y1)
956   {
957     int pady = av.getCharHeight() / 5;
958     int charOffset = 0;
959     graphics.setColor(Color.black);
960     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
961
962     if (av.validCharWidth)
963     {
964       graphics.setColor(Color.white);
965
966       char s = seq.getCharAt(res);
967
968       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
969       graphics.drawString(String.valueOf(s), charOffset + x1,
970               (y1 + av.getCharHeight()) - pady);
971     }
972
973   }
974
975   private volatile boolean imageFresh = false;
976   private Rectangle visibleRect = new Rectangle(), clipBounds = new Rectangle();
977
978   /**
979    * DOCUMENT ME!
980    * 
981    * @param g
982    *          DOCUMENT ME!
983    */
984   @Override
985   public void paintComponent(Graphics g)
986   {
987           
988           // BH: note that this method is generally recommended to 
989           // call super.paintComponent(g). Otherwise, the children of this
990           // component will not be rendered. That is not needed here 
991           // because AnnotationPanel does not have any children. It is
992           // just a JPanel contained in a JViewPort. 
993
994     computeVisibleRect(visibleRect);
995     
996     g.setColor(Color.white);
997     g.fillRect(0, 0, visibleRect.width, visibleRect.height);
998
999     if (image != null)
1000     {
1001         // BH 2018 optimizing generation of new Rectangle().
1002       if (fastPaint || (visibleRect.width != (clipBounds = g.getClipBounds(clipBounds)).width)
1003             || (visibleRect.height != clipBounds.height))
1004       {
1005
1006           
1007           g.drawImage(image, 0, 0, this);
1008         fastPaint = false;
1009         return;
1010       }
1011     }
1012     imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
1013             + 1) * av.getCharWidth();
1014     if (imgWidth < 1)
1015     {
1016       return;
1017     }
1018     Graphics2D gg;
1019     if (image == null || imgWidth != image.getWidth(this)
1020             || image.getHeight(this) != getHeight())
1021     {
1022       try
1023       {
1024         image = new BufferedImage(imgWidth,
1025                 ap.getAnnotationPanel().getHeight(),
1026                 BufferedImage.TYPE_INT_RGB);
1027       } catch (OutOfMemoryError oom)
1028       {
1029         try
1030         {
1031           System.gc();
1032         } catch (Exception x)
1033         {
1034         }
1035         ;
1036         new OOMWarning(
1037                 "Couldn't allocate memory to redraw screen. Please restart Jalview",
1038                 oom);
1039         return;
1040       }
1041       gg = (Graphics2D) image.getGraphics();
1042
1043       if (av.antiAlias)
1044       {
1045         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1046                 RenderingHints.VALUE_ANTIALIAS_ON);
1047       }
1048
1049       gg.setFont(av.getFont());
1050       fm = gg.getFontMetrics();
1051       gg.setColor(Color.white);
1052       gg.fillRect(0, 0, imgWidth, image.getHeight());
1053       imageFresh = true;
1054     } else {
1055         gg = (Graphics2D) image.getGraphics();
1056
1057     }
1058     
1059     drawComponent(gg, av.getRanges().getStartRes(),
1060             av.getRanges().getEndRes() + 1);
1061     gg.dispose();
1062     imageFresh = false;
1063     g.drawImage(image, 0, 0, this);
1064   }
1065
1066   /**
1067    * set true to enable redraw timing debug output on stderr
1068    */
1069   private final boolean debugRedraw = false;
1070
1071   /**
1072    * non-Thread safe repaint
1073    * 
1074    * @param horizontal
1075    *          repaint with horizontal shift in alignment
1076    */
1077   public void fastPaint(int horizontal)
1078   {
1079     if ((horizontal == 0) || image == null
1080             || av.getAlignment().getAlignmentAnnotation() == null
1081             || av.getAlignment().getAlignmentAnnotation().length < 1
1082             || av.isCalcInProgress())
1083     {
1084       repaint();
1085       return;
1086     }
1087
1088     int sr = av.getRanges().getStartRes();
1089     int er = av.getRanges().getEndRes() + 1;
1090     int transX = 0;
1091
1092     Graphics2D gg = (Graphics2D) image.getGraphics();
1093
1094     gg.copyArea(0, 0, imgWidth, getHeight(),
1095             -horizontal * av.getCharWidth(), 0);
1096
1097     if (horizontal > 0) // scrollbar pulled right, image to the left
1098     {
1099       transX = (er - sr - horizontal) * av.getCharWidth();
1100       sr = er - horizontal;
1101     }
1102     else if (horizontal < 0)
1103     {
1104       er = sr - horizontal;
1105     }
1106
1107     gg.translate(transX, 0);
1108
1109     drawComponent(gg, sr, er);
1110
1111     gg.translate(-transX, 0);
1112
1113     gg.dispose();
1114     
1115     fastPaint = true;
1116
1117     // Call repaint on alignment panel so that repaints from other alignment
1118     // panel components can be aggregated. Otherwise performance of the overview
1119     // window and others may be adversely affected.
1120     av.getAlignPanel().repaint();
1121   }
1122
1123   private volatile boolean lastImageGood = false;
1124
1125   /**
1126    * DOCUMENT ME!
1127    * 
1128    * @param g
1129    *          DOCUMENT ME!
1130    * @param startRes
1131    *          DOCUMENT ME!
1132    * @param endRes
1133    *          DOCUMENT ME!
1134    */
1135   public void drawComponent(Graphics g, int startRes, int endRes)
1136   {
1137     BufferedImage oldFaded = fadedImage;
1138     if (av.isCalcInProgress())
1139     {
1140       if (image == null)
1141       {
1142         lastImageGood = false;
1143         return;
1144       }
1145       // We'll keep a record of the old image,
1146       // and draw a faded image until the calculation
1147       // has completed
1148       if (lastImageGood
1149               && (fadedImage == null || fadedImage.getWidth() != imgWidth
1150                       || fadedImage.getHeight() != image.getHeight()))
1151       {
1152         // System.err.println("redraw faded image ("+(fadedImage==null ?
1153         // "null image" : "") + " lastGood="+lastImageGood+")");
1154         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1155                 BufferedImage.TYPE_INT_RGB);
1156
1157         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1158
1159         fadedG.setColor(Color.white);
1160         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1161
1162         fadedG.setComposite(
1163                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1164         fadedG.drawImage(image, 0, 0, this);
1165
1166       }
1167       // make sure we don't overwrite the last good faded image until all
1168       // calculations have finished
1169       lastImageGood = false;
1170
1171     }
1172     else
1173     {
1174       if (fadedImage != null)
1175       {
1176         oldFaded = fadedImage;
1177       }
1178       fadedImage = null;
1179     }
1180
1181     g.setColor(Color.white);
1182     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1183
1184     g.setFont(av.getFont());
1185     if (fm == null)
1186     {
1187       fm = g.getFontMetrics();
1188     }
1189
1190     if ((av.getAlignment().getAlignmentAnnotation() == null)
1191             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1192     {
1193       g.setColor(Color.white);
1194       g.fillRect(0, 0, getWidth(), getHeight());
1195       g.setColor(Color.black);
1196       if (av.validCharWidth)
1197       {
1198         g.drawString(MessageManager
1199                 .getString("label.alignment_has_no_annotations"), 20, 15);
1200       }
1201
1202       return;
1203     }
1204     lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1205             endRes);
1206     if (!lastImageGood && fadedImage == null)
1207     {
1208       fadedImage = oldFaded;
1209     }
1210   }
1211
1212   @Override
1213   public FontMetrics getFontMetrics()
1214   {
1215     return fm;
1216   }
1217
1218   @Override
1219   public Image getFadedImage()
1220   {
1221     return fadedImage;
1222   }
1223
1224   @Override
1225   public int getFadedImageWidth()
1226   {
1227     return imgWidth;
1228   }
1229
1230   private int[] bounds = new int[2];
1231
1232   @Override
1233   public int[] getVisibleVRange()
1234   {
1235     if (ap != null && ap.getAlabels() != null)
1236     {
1237       int sOffset = -ap.getAlabels().getScrollOffset();
1238       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1239       bounds[0] = sOffset;
1240       bounds[1] = visHeight;
1241       return bounds;
1242     }
1243     else
1244     {
1245       return null;
1246     }
1247   }
1248
1249   /**
1250    * Try to ensure any references held are nulled
1251    */
1252   public void dispose()
1253   {
1254     av = null;
1255     ap = null;
1256     image = null;
1257     fadedImage = null;
1258 //    gg = null;
1259     _mwl = null;
1260
1261     /*
1262      * I created the renderer so I will dispose of it
1263      */
1264     if (renderer != null)
1265     {
1266       renderer.dispose();
1267     }
1268   }
1269
1270   @Override
1271   public void propertyChange(PropertyChangeEvent evt)
1272   {
1273     // Respond to viewport range changes (e.g. alignment panel was scrolled)
1274     // Both scrolling and resizing change viewport ranges: scrolling changes
1275     // both start and end points, but resize only changes end values.
1276     // Here we only want to fastpaint on a scroll, with resize using a normal
1277     // paint, so scroll events are identified as changes to the horizontal or
1278     // vertical start value.
1279     if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1280     {
1281       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1282     }
1283     else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1284     {
1285       fastPaint(((int[]) evt.getNewValue())[0]
1286               - ((int[]) evt.getOldValue())[0]);
1287     }
1288     else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
1289     {
1290       repaint();
1291     }
1292   }
1293
1294   /**
1295    * computes the visible height of the annotation panel
1296    * 
1297    * @param adjustPanelHeight
1298    *          - when false, just adjust existing height according to other
1299    *          windows
1300    * @param annotationHeight
1301    * @return height to use for the ScrollerPreferredVisibleSize
1302    */
1303   public int adjustForAlignFrame(boolean adjustPanelHeight,
1304           int annotationHeight)
1305   {
1306     /*
1307      * Estimate available height in the AlignFrame for alignment +
1308      * annotations. Deduct an estimate for title bar, menu bar, scale panel,
1309      * hscroll, status bar, insets. 
1310      */
1311     int stuff = (ap.getViewName() != null ? 30 : 0)
1312             + (Platform.isAMac() ? 120 : 140);
1313     int availableHeight = ap.alignFrame.getHeight() - stuff;
1314     int rowHeight = av.getCharHeight();
1315
1316     if (adjustPanelHeight)
1317     {
1318       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
1319
1320       /*
1321        * If not enough vertical space, maximize annotation height while keeping
1322        * at least two rows of alignment visible
1323        */
1324       if (annotationHeight + alignmentHeight > availableHeight)
1325       {
1326         annotationHeight = Math.min(annotationHeight,
1327                 availableHeight - 2 * rowHeight);
1328       }
1329     }
1330     else
1331     {
1332       // maintain same window layout whilst updating sliders
1333       annotationHeight = Math.min(ap.annotationScroller.getSize().height,
1334               availableHeight - 2 * rowHeight);
1335     }
1336     return annotationHeight;
1337   }
1338 }