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