JAL-2388 Hidden cols separated from column selection (almost complete)
[jalview.git] / src / jalview / gui / AnnotationPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.Annotation;
25 import jalview.datamodel.ColumnSelection;
26 import jalview.datamodel.HiddenColumns;
27 import jalview.datamodel.SequenceI;
28 import jalview.renderer.AnnotationRenderer;
29 import jalview.renderer.AwtRenderPanelI;
30 import jalview.schemes.ResidueProperties;
31 import jalview.util.Comparison;
32 import jalview.util.MessageManager;
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.util.ArrayList;
54 import java.util.Collections;
55 import java.util.List;
56
57 import javax.swing.JColorChooser;
58 import javax.swing.JMenuItem;
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.getAlignment().getHiddenColumns().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 = JvOptionPane.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.getAlignment().getHiddenColumns().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.getAlignment().getHiddenColumns().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 = JvOptionPane.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.getAlignment().getHiddenColumns().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     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
445
446     /*
447      * the selection list (read-only view) is in selection order, not
448      * column order; make a copy so we can sort it
449      */
450     List<Integer> selected = new ArrayList<Integer>(viscols.getSelected());
451     Collections.sort(selected);
452     for (int index : selected)
453     {
454       // always check for current display state - just in case
455       if (!hidden.isVisible(index))
456       {
457         continue;
458       }
459       String tlabel = null;
460       if (anots[index] != null)
461       { // LML added stem code
462         if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
463                 || type.equals(LABEL))
464         {
465           tlabel = anots[index].description;
466           if (tlabel == null || tlabel.length() < 1)
467           {
468             if (type.equals(HELIX) || type.equals(SHEET)
469                     || type.equals(STEM))
470             {
471               tlabel = "" + anots[index].secondaryStructure;
472             }
473             else
474             {
475               tlabel = "" + anots[index].displayCharacter;
476             }
477           }
478         }
479         if (tlabel != null && !tlabel.equals(last))
480         {
481           if (last.length() > 0)
482           {
483             collatedInput.append(" ");
484           }
485           collatedInput.append(tlabel);
486         }
487       }
488     }
489     return collatedInput.toString();
490   }
491
492   /**
493    * DOCUMENT ME!
494    * 
495    * @param evt
496    *          DOCUMENT ME!
497    */
498   @Override
499   public void mousePressed(MouseEvent evt)
500   {
501
502     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
503     if (aa == null)
504     {
505       return;
506     }
507
508     int height = 0;
509     activeRow = -1;
510
511     final int y = evt.getY();
512     for (int i = 0; i < aa.length; i++)
513     {
514       if (aa[i].visible)
515       {
516         height += aa[i].height;
517       }
518
519       if (y < height)
520       {
521         if (aa[i].editable)
522         {
523           activeRow = i;
524         }
525         else if (aa[i].graph > 0)
526         {
527           // Stretch Graph
528           graphStretch = i;
529           graphStretchY = y;
530         }
531
532         break;
533       }
534     }
535
536     /*
537      * isPopupTrigger fires in mousePressed on Mac,
538      * not until mouseRelease on Windows
539      */
540     if (evt.isPopupTrigger() && activeRow != -1)
541     {
542       showPopupMenu(y, evt.getX());
543       return;
544     }
545
546     ap.getScalePanel().mousePressed(evt);
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     /*
611      * isPopupTrigger is set in mouseReleased on Windows
612      * (in mousePressed on Mac)
613      */
614     if (evt.isPopupTrigger() && activeRow != -1)
615     {
616       showPopupMenu(evt.getY(), evt.getX());
617     }
618
619   }
620
621   /**
622    * DOCUMENT ME!
623    * 
624    * @param evt
625    *          DOCUMENT ME!
626    */
627   @Override
628   public void mouseEntered(MouseEvent evt)
629   {
630     ap.getScalePanel().mouseEntered(evt);
631   }
632
633   /**
634    * DOCUMENT ME!
635    * 
636    * @param evt
637    *          DOCUMENT ME!
638    */
639   @Override
640   public void mouseExited(MouseEvent evt)
641   {
642     ap.getScalePanel().mouseExited(evt);
643   }
644
645   /**
646    * DOCUMENT ME!
647    * 
648    * @param evt
649    *          DOCUMENT ME!
650    */
651   @Override
652   public void mouseDragged(MouseEvent evt)
653   {
654     if (graphStretch > -1)
655     {
656       av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
657               - evt.getY();
658       if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
659       {
660         av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
661       }
662       graphStretchY = evt.getY();
663       adjustPanelHeight();
664       ap.paintAlignment(true);
665     }
666     else
667     {
668       ap.getScalePanel().mouseDragged(evt);
669     }
670   }
671
672   /**
673    * Constructs the tooltip, and constructs and displays a status message, for
674    * the current mouse position
675    * 
676    * @param evt
677    */
678   @Override
679   public void mouseMoved(MouseEvent evt)
680   {
681     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
682
683     if (aa == null)
684     {
685       this.setToolTipText(null);
686       return;
687     }
688
689     int row = -1;
690     int height = 0;
691
692     for (int i = 0; i < aa.length; i++)
693     {
694       if (aa[i].visible)
695       {
696         height += aa[i].height;
697       }
698
699       if (evt.getY() < height)
700       {
701         row = i;
702         break;
703       }
704     }
705
706     if (row == -1)
707     {
708       this.setToolTipText(null);
709       return;
710     }
711
712     int column = (evt.getX() / av.getCharWidth())
713             + av.getRanges().getStartRes();
714
715     if (av.hasHiddenColumns())
716     {
717       column = av.getAlignment().getHiddenColumns()
718               .adjustForHiddenColumns(column);
719     }
720
721     AlignmentAnnotation ann = aa[row];
722     if (row > -1 && ann.annotations != null
723             && column < ann.annotations.length)
724     {
725       buildToolTip(ann, column, aa);
726       setStatusMessage(column, ann);
727     }
728     else
729     {
730       this.setToolTipText(null);
731       ap.alignFrame.statusBar.setText(" ");
732     }
733   }
734
735   /**
736    * Builds a tooltip for the annotation at the current mouse position.
737    * 
738    * @param ann
739    * @param column
740    * @param anns
741    */
742   void buildToolTip(AlignmentAnnotation ann, int column,
743           AlignmentAnnotation[] anns)
744   {
745     if (ann.graphGroup > -1)
746     {
747       StringBuilder tip = new StringBuilder(32);
748       tip.append("<html>");
749       for (int i = 0; i < anns.length; i++)
750       {
751         if (anns[i].graphGroup == ann.graphGroup
752                 && anns[i].annotations[column] != null)
753         {
754           tip.append(anns[i].label);
755           String description = anns[i].annotations[column].description;
756           if (description != null && description.length() > 0)
757           {
758             tip.append(" ").append(description);
759           }
760           tip.append("<br>");
761         }
762       }
763       if (tip.length() != 6)
764       {
765         tip.setLength(tip.length() - 4);
766         this.setToolTipText(tip.toString() + "</html>");
767       }
768     }
769     else if (ann.annotations[column] != null)
770     {
771       String description = ann.annotations[column].description;
772       if (description != null && description.length() > 0)
773       {
774         this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
775       }
776     }
777     else
778     {
779       // clear the tooltip.
780       this.setToolTipText(null);
781     }
782   }
783
784   /**
785    * Constructs and displays the status bar message
786    * 
787    * @param column
788    * @param ann
789    */
790   void setStatusMessage(int column, AlignmentAnnotation ann)
791   {
792     /*
793      * show alignment column and annotation description if any
794      */
795     StringBuilder text = new StringBuilder(32);
796     text.append(MessageManager.getString("label.column")).append(" ")
797             .append(column + 1);
798
799     if (ann.annotations[column] != null)
800     {
801       String description = ann.annotations[column].description;
802       if (description != null && description.trim().length() > 0)
803       {
804         text.append("  ").append(description);
805       }
806     }
807
808     /*
809      * if the annotation is sequence-specific, show the sequence number
810      * in the alignment, and (if not a gap) the residue and position
811      */
812     SequenceI seqref = ann.sequenceRef;
813     if (seqref != null)
814     {
815       int seqIndex = av.getAlignment().findIndex(seqref);
816       if (seqIndex != -1)
817       {
818         text.append(", ")
819                 .append(MessageManager.getString("label.sequence"))
820                 .append(" ").append(seqIndex + 1);
821         char residue = seqref.getCharAt(column);
822         if (!Comparison.isGap(residue))
823         {
824           text.append(" ");
825           String name;
826           if (av.getAlignment().isNucleotide())
827           {
828             name = ResidueProperties.nucleotideName.get(String
829                     .valueOf(residue));
830             text.append(" Nucleotide: ").append(
831                     name != null ? name : residue);
832           }
833           else
834           {
835             name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
836                     : ResidueProperties.aa2Triplet.get(String
837                             .valueOf(residue)));
838             text.append(" Residue: ").append(name != null ? name : residue);
839           }
840           int residuePos = seqref.findPosition(column);
841           text.append(" (").append(residuePos).append(")");
842         }
843       }
844     }
845
846     ap.alignFrame.statusBar.setText(text.toString());
847   }
848
849   /**
850    * DOCUMENT ME!
851    * 
852    * @param evt
853    *          DOCUMENT ME!
854    */
855   @Override
856   public void mouseClicked(MouseEvent evt)
857   {
858     // if (activeRow != -1)
859     // {
860     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
861     // AlignmentAnnotation anot = aa[activeRow];
862     // }
863   }
864
865   // TODO mouseClicked-content and drawCursor are quite experimental!
866   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
867           int y1)
868   {
869     int pady = av.getCharHeight() / 5;
870     int charOffset = 0;
871     graphics.setColor(Color.black);
872     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
873
874     if (av.validCharWidth)
875     {
876       graphics.setColor(Color.white);
877
878       char s = seq.getCharAt(res);
879
880       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
881       graphics.drawString(String.valueOf(s), charOffset + x1,
882               (y1 + av.getCharHeight()) - pady);
883     }
884
885   }
886
887   private volatile boolean imageFresh = false;
888
889   /**
890    * DOCUMENT ME!
891    * 
892    * @param g
893    *          DOCUMENT ME!
894    */
895   @Override
896   public void paintComponent(Graphics g)
897   {
898     g.setColor(Color.white);
899     g.fillRect(0, 0, getWidth(), getHeight());
900
901     if (image != null)
902     {
903       if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
904               || (getVisibleRect().height != g.getClipBounds().height))
905       {
906         g.drawImage(image, 0, 0, this);
907         fastPaint = false;
908         return;
909       }
910     }
911     imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes() + 1)
912             * av.getCharWidth();
913     if (imgWidth < 1)
914     {
915       return;
916     }
917     if (image == null || imgWidth != image.getWidth(this)
918             || image.getHeight(this) != getHeight())
919     {
920       try
921       {
922         image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
923                 .getHeight(), BufferedImage.TYPE_INT_RGB);
924       } catch (OutOfMemoryError oom)
925       {
926         try
927         {
928           System.gc();
929         } catch (Exception x)
930         {
931         }
932         ;
933         new OOMWarning(
934                 "Couldn't allocate memory to redraw screen. Please restart Jalview",
935                 oom);
936         return;
937       }
938       gg = (Graphics2D) image.getGraphics();
939
940       if (av.antiAlias)
941       {
942         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
943                 RenderingHints.VALUE_ANTIALIAS_ON);
944       }
945
946       gg.setFont(av.getFont());
947       fm = gg.getFontMetrics();
948       gg.setColor(Color.white);
949       gg.fillRect(0, 0, imgWidth, image.getHeight());
950       imageFresh = true;
951     }
952
953     drawComponent(gg, av.getRanges().getStartRes(), av.getRanges()
954             .getEndRes() + 1);
955     imageFresh = false;
956     g.drawImage(image, 0, 0, this);
957   }
958
959   /**
960    * set true to enable redraw timing debug output on stderr
961    */
962   private final boolean debugRedraw = false;
963
964   /**
965    * non-Thread safe repaint
966    * 
967    * @param horizontal
968    *          repaint with horizontal shift in alignment
969    */
970   public void fastPaint(int horizontal)
971   {
972     if ((horizontal == 0) || gg == null
973             || av.getAlignment().getAlignmentAnnotation() == null
974             || av.getAlignment().getAlignmentAnnotation().length < 1
975             || av.isCalcInProgress())
976     {
977       repaint();
978       return;
979     }
980     long stime = System.currentTimeMillis();
981     gg.copyArea(0, 0, imgWidth, getHeight(),
982             -horizontal * av.getCharWidth(), 0);
983     long mtime = System.currentTimeMillis();
984     int sr = av.getRanges().getStartRes();
985     int er = av.getRanges().getEndRes() + 1;
986     int transX = 0;
987
988     if (horizontal > 0) // scrollbar pulled right, image to the left
989     {
990       transX = (er - sr - horizontal) * av.getCharWidth();
991       sr = er - horizontal;
992     }
993     else if (horizontal < 0)
994     {
995       er = sr - horizontal;
996     }
997
998     gg.translate(transX, 0);
999
1000     drawComponent(gg, sr, er);
1001
1002     gg.translate(-transX, 0);
1003     long dtime = System.currentTimeMillis();
1004     fastPaint = true;
1005     repaint();
1006     long rtime = System.currentTimeMillis();
1007     if (debugRedraw)
1008     {
1009       System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
1010               + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
1011               + "\tRepaint call:\t" + (rtime - dtime));
1012     }
1013
1014   }
1015
1016   private volatile boolean lastImageGood = false;
1017
1018   /**
1019    * DOCUMENT ME!
1020    * 
1021    * @param g
1022    *          DOCUMENT ME!
1023    * @param startRes
1024    *          DOCUMENT ME!
1025    * @param endRes
1026    *          DOCUMENT ME!
1027    */
1028   public void drawComponent(Graphics g, int startRes, int endRes)
1029   {
1030     BufferedImage oldFaded = fadedImage;
1031     if (av.isCalcInProgress())
1032     {
1033       if (image == null)
1034       {
1035         lastImageGood = false;
1036         return;
1037       }
1038       // We'll keep a record of the old image,
1039       // and draw a faded image until the calculation
1040       // has completed
1041       if (lastImageGood
1042               && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1043                       .getHeight() != image.getHeight()))
1044       {
1045         // System.err.println("redraw faded image ("+(fadedImage==null ?
1046         // "null image" : "") + " lastGood="+lastImageGood+")");
1047         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1048                 BufferedImage.TYPE_INT_RGB);
1049
1050         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1051
1052         fadedG.setColor(Color.white);
1053         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1054
1055         fadedG.setComposite(AlphaComposite.getInstance(
1056                 AlphaComposite.SRC_OVER, .3f));
1057         fadedG.drawImage(image, 0, 0, this);
1058
1059       }
1060       // make sure we don't overwrite the last good faded image until all
1061       // calculations have finished
1062       lastImageGood = false;
1063
1064     }
1065     else
1066     {
1067       if (fadedImage != null)
1068       {
1069         oldFaded = fadedImage;
1070       }
1071       fadedImage = null;
1072     }
1073
1074     g.setColor(Color.white);
1075     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1076
1077     g.setFont(av.getFont());
1078     if (fm == null)
1079     {
1080       fm = g.getFontMetrics();
1081     }
1082
1083     if ((av.getAlignment().getAlignmentAnnotation() == null)
1084             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1085     {
1086       g.setColor(Color.white);
1087       g.fillRect(0, 0, getWidth(), getHeight());
1088       g.setColor(Color.black);
1089       if (av.validCharWidth)
1090       {
1091         g.drawString(MessageManager
1092                 .getString("label.alignment_has_no_annotations"), 20, 15);
1093       }
1094
1095       return;
1096     }
1097     lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1098             startRes, endRes);
1099     if (!lastImageGood && fadedImage == null)
1100     {
1101       fadedImage = oldFaded;
1102     }
1103   }
1104
1105   @Override
1106   public FontMetrics getFontMetrics()
1107   {
1108     return fm;
1109   }
1110
1111   @Override
1112   public Image getFadedImage()
1113   {
1114     return fadedImage;
1115   }
1116
1117   @Override
1118   public int getFadedImageWidth()
1119   {
1120     return imgWidth;
1121   }
1122
1123   private int[] bounds = new int[2];
1124
1125   @Override
1126   public int[] getVisibleVRange()
1127   {
1128     if (ap != null && ap.getAlabels() != null)
1129     {
1130       int sOffset = -ap.getAlabels().getScrollOffset();
1131       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1132       bounds[0] = sOffset;
1133       bounds[1] = visHeight;
1134       return bounds;
1135     }
1136     else
1137     {
1138       return null;
1139     }
1140   }
1141
1142   /**
1143    * Try to ensure any references held are nulled
1144    */
1145   public void dispose()
1146   {
1147     av = null;
1148     ap = null;
1149     image = null;
1150     fadedImage = null;
1151     gg = null;
1152     _mwl = null;
1153
1154     /*
1155      * I created the renderer so I will dispose of it
1156      */
1157     if (renderer != null)
1158     {
1159       renderer.dispose();
1160     }
1161   }
1162 }