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