JAL-2216 explicitly null AnnotationPanel and AnnotationRenderer fields
[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.SequenceI;
27 import jalview.renderer.AnnotationRenderer;
28 import jalview.renderer.AwtRenderPanelI;
29 import jalview.schemes.ResidueProperties;
30 import jalview.util.Comparison;
31 import jalview.util.MessageManager;
32
33 import java.awt.AlphaComposite;
34 import java.awt.Color;
35 import java.awt.Dimension;
36 import java.awt.FontMetrics;
37 import java.awt.Graphics;
38 import java.awt.Graphics2D;
39 import java.awt.Image;
40 import java.awt.Rectangle;
41 import java.awt.RenderingHints;
42 import java.awt.event.ActionEvent;
43 import java.awt.event.ActionListener;
44 import java.awt.event.AdjustmentEvent;
45 import java.awt.event.AdjustmentListener;
46 import java.awt.event.MouseEvent;
47 import java.awt.event.MouseListener;
48 import java.awt.event.MouseMotionListener;
49 import java.awt.event.MouseWheelEvent;
50 import java.awt.event.MouseWheelListener;
51 import java.awt.image.BufferedImage;
52 import java.util.ArrayList;
53 import java.util.Collections;
54 import java.util.List;
55
56 import javax.swing.JColorChooser;
57 import javax.swing.JMenuItem;
58 import javax.swing.JOptionPane;
59 import javax.swing.JPanel;
60 import javax.swing.JPopupMenu;
61 import javax.swing.Scrollable;
62 import javax.swing.ToolTipManager;
63
64 /**
65  * AnnotationPanel displays visible portion of annotation rows below unwrapped
66  * alignment
67  * 
68  * @author $author$
69  * @version $Revision$
70  */
71 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
72         MouseListener, MouseWheelListener, MouseMotionListener,
73         ActionListener, AdjustmentListener, Scrollable
74 {
75   String HELIX = MessageManager.getString("label.helix");
76
77   String SHEET = MessageManager.getString("label.sheet");
78
79   /**
80    * For RNA secondary structure "stems" aka helices
81    */
82   String STEM = MessageManager.getString("label.rna_helix");
83
84   String LABEL = MessageManager.getString("label.label");
85
86   String REMOVE = MessageManager.getString("label.remove_annotation");
87
88   String COLOUR = MessageManager.getString("action.colour");
89
90   public final Color HELIX_COLOUR = Color.red.darker();
91
92   public final Color SHEET_COLOUR = Color.green.darker().darker();
93
94   public final Color STEM_COLOUR = Color.blue.darker();
95
96   /** DOCUMENT ME!! */
97   public AlignViewport av;
98
99   AlignmentPanel ap;
100
101   public int activeRow = -1;
102
103   public BufferedImage image;
104
105   public volatile BufferedImage fadedImage;
106
107   Graphics2D gg;
108
109   public FontMetrics fm;
110
111   public int imgWidth = 0;
112
113   boolean fastPaint = false;
114
115   // Used For mouse Dragging and resizing graphs
116   int graphStretch = -1;
117
118   int graphStretchY = -1;
119
120   int min; // used by mouseDragged to see if user
121
122   int max; // used by mouseDragged to see if user
123
124   boolean mouseDragging = false;
125
126   // for editing cursor
127   int cursorX = 0;
128
129   int cursorY = 0;
130
131   public final AnnotationRenderer renderer;
132
133   private MouseWheelListener[] _mwl;
134
135   /**
136    * Creates a new AnnotationPanel object.
137    * 
138    * @param ap
139    *          DOCUMENT ME!
140    */
141   public AnnotationPanel(AlignmentPanel ap)
142   {
143     ToolTipManager.sharedInstance().registerComponent(this);
144     ToolTipManager.sharedInstance().setInitialDelay(0);
145     ToolTipManager.sharedInstance().setDismissDelay(10000);
146     this.ap = ap;
147     av = ap.av;
148     this.setLayout(null);
149     addMouseListener(this);
150     addMouseMotionListener(this);
151     ap.annotationScroller.getVerticalScrollBar()
152             .addAdjustmentListener(this);
153     // save any wheel listeners on the scroller, so we can propagate scroll
154     // events to them.
155     _mwl = ap.annotationScroller.getMouseWheelListeners();
156     // and then set our own listener to consume all mousewheel events
157     ap.annotationScroller.addMouseWheelListener(this);
158     renderer = new AnnotationRenderer();
159   }
160
161   public AnnotationPanel(AlignViewport av)
162   {
163     this.av = av;
164     renderer = new AnnotationRenderer();
165   }
166
167   @Override
168   public void mouseWheelMoved(MouseWheelEvent e)
169   {
170     if (e.isShiftDown())
171     {
172       e.consume();
173       if (e.getWheelRotation() > 0)
174       {
175         ap.scrollRight(true);
176       }
177       else
178       {
179         ap.scrollRight(false);
180       }
181     }
182     else
183     {
184       // TODO: find the correct way to let the event bubble up to
185       // ap.annotationScroller
186       for (MouseWheelListener mwl : _mwl)
187       {
188         if (mwl != null)
189         {
190           mwl.mouseWheelMoved(e);
191         }
192         if (e.isConsumed())
193         {
194           break;
195         }
196       }
197     }
198   }
199
200   @Override
201   public Dimension getPreferredScrollableViewportSize()
202   {
203     return getPreferredSize();
204   }
205
206   @Override
207   public int getScrollableBlockIncrement(Rectangle visibleRect,
208           int orientation, int direction)
209   {
210     return 30;
211   }
212
213   @Override
214   public boolean getScrollableTracksViewportHeight()
215   {
216     return false;
217   }
218
219   @Override
220   public boolean getScrollableTracksViewportWidth()
221   {
222     return true;
223   }
224
225   @Override
226   public int getScrollableUnitIncrement(Rectangle visibleRect,
227           int orientation, int direction)
228   {
229     return 30;
230   }
231
232   /*
233    * (non-Javadoc)
234    * 
235    * @see
236    * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
237    * .AdjustmentEvent)
238    */
239   @Override
240   public void adjustmentValueChanged(AdjustmentEvent evt)
241   {
242     // update annotation label display
243     ap.getAlabels().setScrollOffset(-evt.getValue());
244   }
245
246   /**
247    * Calculates the height of the annotation displayed in the annotation panel.
248    * Callers should normally call the ap.adjustAnnotationHeight method to ensure
249    * all annotation associated components are updated correctly.
250    * 
251    */
252   public int adjustPanelHeight()
253   {
254     int height = av.calcPanelHeight();
255     this.setPreferredSize(new Dimension(1, height));
256     if (ap != null)
257     {
258       // revalidate only when the alignment panel is fully constructed
259       ap.validate();
260     }
261
262     return height;
263   }
264
265   /**
266    * DOCUMENT ME!
267    * 
268    * @param evt
269    *          DOCUMENT ME!
270    */
271   @Override
272   public void actionPerformed(ActionEvent evt)
273   {
274     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
275     if (aa == null)
276     {
277       return;
278     }
279     Annotation[] anot = aa[activeRow].annotations;
280
281     if (anot.length < av.getColumnSelection().getMax())
282     {
283       Annotation[] temp = new Annotation[av.getColumnSelection().getMax() + 2];
284       System.arraycopy(anot, 0, temp, 0, anot.length);
285       anot = temp;
286       aa[activeRow].annotations = anot;
287     }
288
289     String action = evt.getActionCommand();
290     if (action.equals(REMOVE))
291     {
292       for (int index : av.getColumnSelection().getSelected())
293       {
294         if (av.getColumnSelection().isVisible(index))
295         {
296           anot[index] = null;
297         }
298       }
299     }
300     else if (action.equals(LABEL))
301     {
302       String exMesg = collectAnnotVals(anot, LABEL);
303       String label = JOptionPane.showInputDialog(this,
304               MessageManager.getString("label.enter_label"), exMesg);
305
306       if (label == null)
307       {
308         return;
309       }
310
311       if ((label.length() > 0) && !aa[activeRow].hasText)
312       {
313         aa[activeRow].hasText = true;
314       }
315
316       for (int index : av.getColumnSelection().getSelected())
317       {
318         if (!av.getColumnSelection().isVisible(index))
319         {
320           continue;
321         }
322
323         if (anot[index] == null)
324         {
325           anot[index] = new Annotation(label, "", ' ', 0);
326         }
327         else
328         {
329           anot[index].displayCharacter = label;
330         }
331       }
332     }
333     else if (action.equals(COLOUR))
334     {
335       Color col = JColorChooser.showDialog(this,
336               MessageManager.getString("label.select_foreground_colour"),
337               Color.black);
338
339       for (int index : av.getColumnSelection().getSelected())
340       {
341         if (!av.getColumnSelection().isVisible(index))
342         {
343           continue;
344         }
345
346         if (anot[index] == null)
347         {
348           anot[index] = new Annotation("", "", ' ', 0);
349         }
350
351         anot[index].colour = col;
352       }
353     }
354     else
355     // HELIX, SHEET or STEM
356     {
357       char type = 0;
358       String symbol = "\u03B1"; // alpha
359
360       if (action.equals(HELIX))
361       {
362         type = 'H';
363       }
364       else if (action.equals(SHEET))
365       {
366         type = 'E';
367         symbol = "\u03B2"; // beta
368       }
369
370       // Added by LML to color stems
371       else if (action.equals(STEM))
372       {
373         type = 'S';
374         int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
375         symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
376       }
377
378       if (!aa[activeRow].hasIcons)
379       {
380         aa[activeRow].hasIcons = true;
381       }
382
383       String label = JOptionPane.showInputDialog(MessageManager
384               .getString("label.enter_label_for_the_structure"), symbol);
385
386       if (label == null)
387       {
388         return;
389       }
390
391       if ((label.length() > 0) && !aa[activeRow].hasText)
392       {
393         aa[activeRow].hasText = true;
394         if (action.equals(STEM))
395         {
396           aa[activeRow].showAllColLabels = true;
397         }
398       }
399       for (int index : av.getColumnSelection().getSelected())
400       {
401         if (!av.getColumnSelection().isVisible(index))
402         {
403           continue;
404         }
405
406         if (anot[index] == null)
407         {
408           anot[index] = new Annotation(label, "", type, 0);
409         }
410
411         anot[index].secondaryStructure = type != 'S' ? type : label
412                 .length() == 0 ? ' ' : label.charAt(0);
413         anot[index].displayCharacter = label;
414
415       }
416     }
417
418     av.getAlignment().validateAnnotation(aa[activeRow]);
419     ap.alignmentChanged();
420     ap.alignFrame.setMenusForViewport();
421     adjustPanelHeight();
422     repaint();
423
424     return;
425   }
426
427   /**
428    * Returns any existing annotation concatenated as a string. For each
429    * annotation, takes the description, if any, else the secondary structure
430    * character (if type is HELIX, SHEET or STEM), else the display character (if
431    * type is LABEL).
432    * 
433    * @param anots
434    * @param type
435    * @return
436    */
437   private String collectAnnotVals(Annotation[] anots, String type)
438   {
439     // TODO is this method wanted? why? 'last' is not used
440
441     StringBuilder collatedInput = new StringBuilder(64);
442     String last = "";
443     ColumnSelection viscols = av.getColumnSelection();
444
445     /*
446      * the selection list (read-only view) is in selection order, not
447      * column order; make a copy so we can sort it
448      */
449     List<Integer> selected = new ArrayList<Integer>(viscols.getSelected());
450     Collections.sort(selected);
451     for (int index : selected)
452     {
453       // always check for current display state - just in case
454       if (!viscols.isVisible(index))
455       {
456         continue;
457       }
458       String tlabel = null;
459       if (anots[index] != null)
460       { // LML added stem code
461         if (type.equals(HELIX) || type.equals(SHEET)
462                 || type.equals(STEM) || type.equals(LABEL))
463         {
464           tlabel = anots[index].description;
465           if (tlabel == null || tlabel.length() < 1)
466           {
467             if (type.equals(HELIX) || type.equals(SHEET)
468                     || type.equals(STEM))
469             {
470               tlabel = "" + anots[index].secondaryStructure;
471             }
472             else
473             {
474               tlabel = "" + anots[index].displayCharacter;
475             }
476           }
477         }
478         if (tlabel != null && !tlabel.equals(last))
479         {
480           if (last.length() > 0)
481           {
482             collatedInput.append(" ");
483           }
484           collatedInput.append(tlabel);
485         }
486       }
487     }
488     return collatedInput.toString();
489   }
490
491   /**
492    * DOCUMENT ME!
493    * 
494    * @param evt
495    *          DOCUMENT ME!
496    */
497   @Override
498   public void mousePressed(MouseEvent evt)
499   {
500
501     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
502     if (aa == null)
503     {
504       return;
505     }
506
507     int height = 0;
508     activeRow = -1;
509
510     final int y = evt.getY();
511     for (int i = 0; i < aa.length; i++)
512     {
513       if (aa[i].visible)
514       {
515         height += aa[i].height;
516       }
517
518       if (y < height)
519       {
520         if (aa[i].editable)
521         {
522           activeRow = i;
523         }
524         else if (aa[i].graph > 0)
525         {
526           // Stretch Graph
527           graphStretch = i;
528           graphStretchY = y;
529         }
530
531         break;
532       }
533     }
534
535     /*
536      * isPopupTrigger fires in mousePressed on Mac,
537      * not until mouseRelease on Windows
538      */
539     if (evt.isPopupTrigger() && activeRow != -1)
540     {
541       showPopupMenu(y, evt.getX());
542       return;
543     }
544
545     ap.getScalePanel().mousePressed(evt);
546   }
547
548   /**
549    * Construct and display a context menu at the right-click position
550    * 
551    * @param y
552    * @param x
553    */
554   void showPopupMenu(final int y, int x)
555   {
556     if (av.getColumnSelection() == null
557             || av.getColumnSelection().isEmpty())
558     {
559       return;
560     }
561
562     JPopupMenu pop = new JPopupMenu(
563             MessageManager.getString("label.structure_type"));
564     JMenuItem item;
565     /*
566      * Just display the needed structure options
567      */
568     if (av.getAlignment().isNucleotide())
569     {
570       item = new JMenuItem(STEM);
571       item.addActionListener(this);
572       pop.add(item);
573     }
574     else
575     {
576       item = new JMenuItem(HELIX);
577       item.addActionListener(this);
578       pop.add(item);
579       item = new JMenuItem(SHEET);
580       item.addActionListener(this);
581       pop.add(item);
582     }
583     item = new JMenuItem(LABEL);
584     item.addActionListener(this);
585     pop.add(item);
586     item = new JMenuItem(COLOUR);
587     item.addActionListener(this);
588     pop.add(item);
589     item = new JMenuItem(REMOVE);
590     item.addActionListener(this);
591     pop.add(item);
592     pop.show(this, x, y);
593   }
594
595   /**
596    * DOCUMENT ME!
597    * 
598    * @param evt
599    *          DOCUMENT ME!
600    */
601   @Override
602   public void mouseReleased(MouseEvent evt)
603   {
604     graphStretch = -1;
605     graphStretchY = -1;
606     mouseDragging = false;
607     ap.getScalePanel().mouseReleased(evt);
608
609     /*
610      * isPopupTrigger is set in mouseReleased on Windows
611      * (in mousePressed on Mac)
612      */
613     if (evt.isPopupTrigger() && activeRow != -1)
614     {
615       showPopupMenu(evt.getY(), evt.getX());
616     }
617
618   }
619
620   /**
621    * DOCUMENT ME!
622    * 
623    * @param evt
624    *          DOCUMENT ME!
625    */
626   @Override
627   public void mouseEntered(MouseEvent evt)
628   {
629     ap.getScalePanel().mouseEntered(evt);
630   }
631
632   /**
633    * DOCUMENT ME!
634    * 
635    * @param evt
636    *          DOCUMENT ME!
637    */
638   @Override
639   public void mouseExited(MouseEvent evt)
640   {
641     ap.getScalePanel().mouseExited(evt);
642   }
643
644   /**
645    * DOCUMENT ME!
646    * 
647    * @param evt
648    *          DOCUMENT ME!
649    */
650   @Override
651   public void mouseDragged(MouseEvent evt)
652   {
653     if (graphStretch > -1)
654     {
655       av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
656               - evt.getY();
657       if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
658       {
659         av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
660       }
661       graphStretchY = evt.getY();
662       adjustPanelHeight();
663       ap.paintAlignment(true);
664     }
665     else
666     {
667       ap.getScalePanel().mouseDragged(evt);
668     }
669   }
670
671   /**
672    * Constructs the tooltip, and constructs and displays a status message, for
673    * the current mouse position
674    * 
675    * @param evt
676    */
677   @Override
678   public void mouseMoved(MouseEvent evt)
679   {
680     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
681
682     if (aa == null)
683     {
684       this.setToolTipText(null);
685       return;
686     }
687
688     int row = -1;
689     int height = 0;
690
691     for (int i = 0; i < aa.length; i++)
692     {
693       if (aa[i].visible)
694       {
695         height += aa[i].height;
696       }
697
698       if (evt.getY() < height)
699       {
700         row = i;
701         break;
702       }
703     }
704
705     if (row == -1)
706     {
707       this.setToolTipText(null);
708       return;
709     }
710
711     int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
712
713     if (av.hasHiddenColumns())
714     {
715       column = av.getColumnSelection().adjustForHiddenColumns(column);
716     }
717
718     AlignmentAnnotation ann = aa[row];
719     if (row > -1 && ann.annotations != null
720             && column < ann.annotations.length)
721     {
722       buildToolTip(ann, column, aa);
723       setStatusMessage(column, ann);
724     }
725     else
726     {
727       this.setToolTipText(null);
728       ap.alignFrame.statusBar.setText(" ");
729     }
730   }
731
732   /**
733    * Builds a tooltip for the annotation at the current mouse position.
734    * 
735    * @param ann
736    * @param column
737    * @param anns
738    */
739   void buildToolTip(AlignmentAnnotation ann, int column,
740           AlignmentAnnotation[] anns)
741   {
742     if (ann.graphGroup > -1)
743     {
744       StringBuilder tip = new StringBuilder(32);
745       tip.append("<html>");
746       for (int i = 0; i < anns.length; i++)
747       {
748         if (anns[i].graphGroup == ann.graphGroup
749                 && anns[i].annotations[column] != null)
750         {
751           tip.append(anns[i].label);
752           String description = anns[i].annotations[column].description;
753           if (description != null && description.length() > 0)
754           {
755             tip.append(" ").append(description);
756           }
757           tip.append("<br>");
758         }
759       }
760       if (tip.length() != 6)
761       {
762         tip.setLength(tip.length() - 4);
763         this.setToolTipText(tip.toString() + "</html>");
764       }
765     }
766     else if (ann.annotations[column] != null)
767     {
768       String description = ann.annotations[column].description;
769       if (description != null && description.length() > 0)
770       {
771         this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
772       }
773     }
774     else
775     {
776       // clear the tooltip.
777       this.setToolTipText(null);
778     }
779   }
780
781   /**
782    * Constructs and displays the status bar message
783    * 
784    * @param column
785    * @param ann
786    */
787   void setStatusMessage(int column, AlignmentAnnotation ann)
788   {
789     /*
790      * show alignment column and annotation description if any
791      */
792     StringBuilder text = new StringBuilder(32);
793     text.append(MessageManager.getString("label.column")).append(" ")
794             .append(column + 1);
795
796     if (ann.annotations[column] != null)
797     {
798       String description = ann.annotations[column].description;
799       if (description != null && description.trim().length() > 0)
800       {
801         text.append("  ").append(description);
802       }
803     }
804
805     /*
806      * if the annotation is sequence-specific, show the sequence number
807      * in the alignment, and (if not a gap) the residue and position
808      */
809     SequenceI seqref = ann.sequenceRef;
810     if (seqref != null)
811     {
812       int seqIndex = av.getAlignment().findIndex(seqref);
813       if (seqIndex != -1)
814       {
815         text.append(", ")
816                 .append(MessageManager.getString("label.sequence"))
817                 .append(" ")
818                 .append(seqIndex + 1);
819         char residue = seqref.getCharAt(column);
820         if (!Comparison.isGap(residue))
821         {
822           text.append(" ");
823           String name;
824           if (av.getAlignment().isNucleotide())
825           {
826             name = ResidueProperties.nucleotideName.get(String
827                     .valueOf(residue));
828             text.append(" Nucleotide: ").append(
829                     name != null ? name : residue);
830           }
831           else
832           {
833             name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
834                     : ResidueProperties.aa2Triplet.get(String
835                             .valueOf(residue)));
836             text.append(" Residue: ").append(name != null ? name : residue);
837           }
838           int residuePos = seqref.findPosition(column);
839           text.append(" (").append(residuePos).append(")");
840         }
841       }
842     }
843
844     ap.alignFrame.statusBar.setText(text.toString());
845   }
846
847   /**
848    * DOCUMENT ME!
849    * 
850    * @param evt
851    *          DOCUMENT ME!
852    */
853   @Override
854   public void mouseClicked(MouseEvent evt)
855   {
856     // if (activeRow != -1)
857     // {
858     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
859     // AlignmentAnnotation anot = aa[activeRow];
860     // }
861   }
862
863   // TODO mouseClicked-content and drawCursor are quite experimental!
864   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
865           int y1)
866   {
867     int pady = av.getCharHeight() / 5;
868     int charOffset = 0;
869     graphics.setColor(Color.black);
870     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
871
872     if (av.validCharWidth)
873     {
874       graphics.setColor(Color.white);
875
876       char s = seq.getCharAt(res);
877
878       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
879       graphics.drawString(String.valueOf(s), charOffset + x1,
880               (y1 + av.getCharHeight()) - pady);
881     }
882
883   }
884
885   private volatile boolean imageFresh = false;
886
887   /**
888    * DOCUMENT ME!
889    * 
890    * @param g
891    *          DOCUMENT ME!
892    */
893   @Override
894   public void paintComponent(Graphics g)
895   {
896     g.setColor(Color.white);
897     g.fillRect(0, 0, getWidth(), getHeight());
898
899     if (image != null)
900     {
901       if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
902               || (getVisibleRect().height != g.getClipBounds().height))
903       {
904         g.drawImage(image, 0, 0, this);
905         fastPaint = false;
906         return;
907       }
908     }
909     imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
910     if (imgWidth < 1)
911     {
912       return;
913     }
914     if (image == null || imgWidth != image.getWidth(this)
915             || image.getHeight(this) != getHeight())
916     {
917       try
918       {
919         image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
920                 .getHeight(), BufferedImage.TYPE_INT_RGB);
921       } catch (OutOfMemoryError oom)
922       {
923         try
924         {
925           System.gc();
926         } catch (Exception x)
927         {
928         }
929         ;
930         new OOMWarning(
931                 "Couldn't allocate memory to redraw screen. Please restart Jalview",
932                 oom);
933         return;
934       }
935       gg = (Graphics2D) image.getGraphics();
936
937       if (av.antiAlias)
938       {
939         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
940                 RenderingHints.VALUE_ANTIALIAS_ON);
941       }
942
943       gg.setFont(av.getFont());
944       fm = gg.getFontMetrics();
945       gg.setColor(Color.white);
946       gg.fillRect(0, 0, imgWidth, image.getHeight());
947       imageFresh = true;
948     }
949
950     drawComponent(gg, av.startRes, av.endRes + 1);
951     imageFresh = false;
952     g.drawImage(image, 0, 0, this);
953   }
954
955   /**
956    * set true to enable redraw timing debug output on stderr
957    */
958   private final boolean debugRedraw = false;
959
960   /**
961    * non-Thread safe repaint
962    * 
963    * @param horizontal
964    *          repaint with horizontal shift in alignment
965    */
966   public void fastPaint(int horizontal)
967   {
968     if ((horizontal == 0) || gg == null
969             || av.getAlignment().getAlignmentAnnotation() == null
970             || av.getAlignment().getAlignmentAnnotation().length < 1
971             || av.isCalcInProgress())
972     {
973       repaint();
974       return;
975     }
976     long stime = System.currentTimeMillis();
977     gg.copyArea(0, 0, imgWidth, getHeight(),
978             -horizontal * av.getCharWidth(), 0);
979     long mtime = System.currentTimeMillis();
980     int sr = av.startRes;
981     int er = av.endRes + 1;
982     int transX = 0;
983
984     if (horizontal > 0) // scrollbar pulled right, image to the left
985     {
986       transX = (er - sr - horizontal) * av.getCharWidth();
987       sr = er - horizontal;
988     }
989     else if (horizontal < 0)
990     {
991       er = sr - horizontal;
992     }
993
994     gg.translate(transX, 0);
995
996     drawComponent(gg, sr, er);
997
998     gg.translate(-transX, 0);
999     long dtime = System.currentTimeMillis();
1000     fastPaint = true;
1001     repaint();
1002     long rtime = System.currentTimeMillis();
1003     if (debugRedraw)
1004     {
1005       System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
1006               + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1007               + "\tRepaint call:\t" + (rtime - dtime));
1008     }
1009
1010   }
1011
1012   private volatile boolean lastImageGood = false;
1013
1014   /**
1015    * DOCUMENT ME!
1016    * 
1017    * @param g
1018    *          DOCUMENT ME!
1019    * @param startRes
1020    *          DOCUMENT ME!
1021    * @param endRes
1022    *          DOCUMENT ME!
1023    */
1024   public void drawComponent(Graphics g, int startRes, int endRes)
1025   {
1026     BufferedImage oldFaded = fadedImage;
1027     if (av.isCalcInProgress())
1028     {
1029       if (image == null)
1030       {
1031         lastImageGood = false;
1032         return;
1033       }
1034       // We'll keep a record of the old image,
1035       // and draw a faded image until the calculation
1036       // has completed
1037       if (lastImageGood
1038               && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1039                       .getHeight() != image.getHeight()))
1040       {
1041         // System.err.println("redraw faded image ("+(fadedImage==null ?
1042         // "null image" : "") + " lastGood="+lastImageGood+")");
1043         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1044                 BufferedImage.TYPE_INT_RGB);
1045
1046         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1047
1048         fadedG.setColor(Color.white);
1049         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1050
1051         fadedG.setComposite(AlphaComposite.getInstance(
1052                 AlphaComposite.SRC_OVER, .3f));
1053         fadedG.drawImage(image, 0, 0, this);
1054
1055       }
1056       // make sure we don't overwrite the last good faded image until all
1057       // calculations have finished
1058       lastImageGood = false;
1059
1060     }
1061     else
1062     {
1063       if (fadedImage != null)
1064       {
1065         oldFaded = fadedImage;
1066       }
1067       fadedImage = null;
1068     }
1069
1070     g.setColor(Color.white);
1071     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1072
1073     g.setFont(av.getFont());
1074     if (fm == null)
1075     {
1076       fm = g.getFontMetrics();
1077     }
1078
1079     if ((av.getAlignment().getAlignmentAnnotation() == null)
1080             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1081     {
1082       g.setColor(Color.white);
1083       g.fillRect(0, 0, getWidth(), getHeight());
1084       g.setColor(Color.black);
1085       if (av.validCharWidth)
1086       {
1087         g.drawString(MessageManager
1088                 .getString("label.alignment_has_no_annotations"), 20, 15);
1089       }
1090
1091       return;
1092     }
1093     lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1094             startRes, endRes);
1095     if (!lastImageGood && fadedImage == null)
1096     {
1097       fadedImage = oldFaded;
1098     }
1099   }
1100
1101   @Override
1102   public FontMetrics getFontMetrics()
1103   {
1104     return fm;
1105   }
1106
1107   @Override
1108   public Image getFadedImage()
1109   {
1110     return fadedImage;
1111   }
1112
1113   @Override
1114   public int getFadedImageWidth()
1115   {
1116     return imgWidth;
1117   }
1118
1119   private int[] bounds = new int[2];
1120
1121   @Override
1122   public int[] getVisibleVRange()
1123   {
1124     if (ap != null && ap.getAlabels() != null)
1125     {
1126       int sOffset = -ap.getAlabels().getScrollOffset();
1127       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1128       bounds[0] = sOffset;
1129       bounds[1] = visHeight;
1130       return bounds;
1131     }
1132     else
1133     {
1134       return null;
1135     }
1136   }
1137
1138   /**
1139    * Try to ensure any references held are nulled
1140    */
1141   public void dispose()
1142   {
1143     av = null;
1144     ap = null;
1145     image = null;
1146     fadedImage = null;
1147     gg = null;
1148     _mwl = null;
1149
1150     /*
1151      * I created the renderer so I will dispose of it
1152      */
1153     if (renderer != null)
1154     {
1155       renderer.dispose();
1156     }
1157   }
1158 }