JAL-2146 status message now with formatted residue name / code
[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     if (evt.getActionCommand().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 (evt.getActionCommand().equals(LABEL))
304     {
305       String exMesg = collectAnnotVals(anot, LABEL);
306       String label = JOptionPane.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); // TODO: verify that
329           // null exceptions
330           // aren't raised
331           // elsewhere.
332         }
333         else
334         {
335           anot[index].displayCharacter = label;
336         }
337       }
338     }
339     else if (evt.getActionCommand().equals(COLOUR))
340     {
341       Color col = JColorChooser.showDialog(this,
342               MessageManager.getString("label.select_foreground_colour"),
343               Color.black);
344
345       for (int index : av.getColumnSelection().getSelected())
346       {
347         if (!av.getColumnSelection().isVisible(index))
348         {
349           continue;
350         }
351
352         if (anot[index] == null)
353         {
354           anot[index] = new Annotation("", "", ' ', 0);
355         }
356
357         anot[index].colour = col;
358       }
359     }
360     else
361     // HELIX, SHEET or STEM
362     {
363       char type = 0;
364       String symbol = "\u03B1";
365
366       if (evt.getActionCommand().equals(HELIX))
367       {
368         type = 'H';
369       }
370       else if (evt.getActionCommand().equals(SHEET))
371       {
372         type = 'E';
373         symbol = "\u03B2";
374       }
375
376       // Added by LML to color stems
377       else if (evt.getActionCommand().equals(STEM))
378       {
379         type = 'S';
380         symbol = "\u03C3";
381       }
382
383       if (!aa[activeRow].hasIcons)
384       {
385         aa[activeRow].hasIcons = true;
386       }
387
388       String label = JOptionPane.showInputDialog(MessageManager
389               .getString("label.enter_label_for_the_structure"), symbol);
390
391       if (label == null)
392       {
393         return;
394       }
395
396       if ((label.length() > 0) && !aa[activeRow].hasText)
397       {
398         aa[activeRow].hasText = true;
399         if (evt.getActionCommand().equals(STEM))
400         {
401           aa[activeRow].showAllColLabels = true;
402         }
403       }
404       for (int index : av.getColumnSelection().getSelected())
405       {
406         if (!av.getColumnSelection().isVisible(index))
407         {
408           continue;
409         }
410
411         if (anot[index] == null)
412         {
413           anot[index] = new Annotation(label, "", type, 0);
414         }
415
416         anot[index].secondaryStructure = type != 'S' ? type : label
417                 .length() == 0 ? ' ' : label.charAt(0);
418         anot[index].displayCharacter = label;
419
420       }
421     }
422
423     av.getAlignment().validateAnnotation(aa[activeRow]);
424     ap.alignmentChanged();
425     ap.alignFrame.setMenusForViewport();
426     adjustPanelHeight();
427     repaint();
428
429     return;
430   }
431
432   /**
433    * Returns any existing annotation concatenated as a string. For each
434    * annotation, takes the description, if any, else the secondary structure
435    * character (if type is HELIX, SHEET or STEM), else the display character (if
436    * type is LABEL).
437    * 
438    * @param anots
439    * @param type
440    * @return
441    */
442   private String collectAnnotVals(Annotation[] anots, String type)
443   {
444     // TODO is this method wanted? why? 'last' is not used
445
446     StringBuilder collatedInput = new StringBuilder(64);
447     String last = "";
448     ColumnSelection viscols = av.getColumnSelection();
449     // TODO: refactor and save av.getColumnSelection for efficiency
450     List<Integer> selected = viscols.getSelected();
451     Collections.sort(selected);
452     for (int index : selected)
453     {
454       // always check for current display state - just in case
455       if (!viscols.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)
463                 || type.equals(STEM) || 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     for (int i = 0; i < aa.length; i++)
512     {
513       if (aa[i].visible)
514       {
515         height += aa[i].height;
516       }
517
518       if (evt.getY() < 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 = evt.getY();
529         }
530
531         break;
532       }
533     }
534
535     if (evt.isPopupTrigger() && activeRow != -1)
536     {
537       if (av.getColumnSelection() == null)
538       {
539         return;
540       }
541
542       JPopupMenu pop = new JPopupMenu(
543               MessageManager.getString("label.structure_type"));
544       JMenuItem item;
545       /*
546        * Just display the needed structure options
547        */
548       if (av.getAlignment().isNucleotide() == true)
549       {
550         item = new JMenuItem(STEM);
551         item.addActionListener(this);
552         pop.add(item);
553       }
554       else
555       {
556         item = new JMenuItem(HELIX);
557         item.addActionListener(this);
558         pop.add(item);
559         item = new JMenuItem(SHEET);
560         item.addActionListener(this);
561         pop.add(item);
562       }
563       item = new JMenuItem(LABEL);
564       item.addActionListener(this);
565       pop.add(item);
566       item = new JMenuItem(COLOUR);
567       item.addActionListener(this);
568       pop.add(item);
569       item = new JMenuItem(REMOVE);
570       item.addActionListener(this);
571       pop.add(item);
572       pop.show(this, evt.getX(), evt.getY());
573
574       return;
575     }
576
577     if (aa == null)
578     {
579       return;
580     }
581
582     ap.getScalePanel().mousePressed(evt);
583
584   }
585
586   /**
587    * DOCUMENT ME!
588    * 
589    * @param evt
590    *          DOCUMENT ME!
591    */
592   @Override
593   public void mouseReleased(MouseEvent evt)
594   {
595     graphStretch = -1;
596     graphStretchY = -1;
597     mouseDragging = false;
598     ap.getScalePanel().mouseReleased(evt);
599   }
600
601   /**
602    * DOCUMENT ME!
603    * 
604    * @param evt
605    *          DOCUMENT ME!
606    */
607   @Override
608   public void mouseEntered(MouseEvent evt)
609   {
610     ap.getScalePanel().mouseEntered(evt);
611   }
612
613   /**
614    * DOCUMENT ME!
615    * 
616    * @param evt
617    *          DOCUMENT ME!
618    */
619   @Override
620   public void mouseExited(MouseEvent evt)
621   {
622     ap.getScalePanel().mouseExited(evt);
623   }
624
625   /**
626    * DOCUMENT ME!
627    * 
628    * @param evt
629    *          DOCUMENT ME!
630    */
631   @Override
632   public void mouseDragged(MouseEvent evt)
633   {
634     if (graphStretch > -1)
635     {
636       av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight += graphStretchY
637               - evt.getY();
638       if (av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight < 0)
639       {
640         av.getAlignment().getAlignmentAnnotation()[graphStretch].graphHeight = 0;
641       }
642       graphStretchY = evt.getY();
643       adjustPanelHeight();
644       ap.paintAlignment(true);
645     }
646     else
647     {
648       ap.getScalePanel().mouseDragged(evt);
649     }
650   }
651
652   /**
653    * Constructs the tooltip, and constructs and displays a status message, for
654    * the current mouse position
655    * 
656    * @param evt
657    */
658   @Override
659   public void mouseMoved(MouseEvent evt)
660   {
661     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
662
663     if (aa == null)
664     {
665       this.setToolTipText(null);
666       return;
667     }
668
669     int row = -1;
670     int height = 0;
671
672     for (int i = 0; i < aa.length; i++)
673     {
674       if (aa[i].visible)
675       {
676         height += aa[i].height;
677       }
678
679       if (evt.getY() < height)
680       {
681         row = i;
682         break;
683       }
684     }
685
686     if (row == -1)
687     {
688       this.setToolTipText(null);
689       return;
690     }
691
692     int column = (evt.getX() / av.getCharWidth()) + av.getStartRes();
693
694     if (av.hasHiddenColumns())
695     {
696       column = av.getColumnSelection().adjustForHiddenColumns(column);
697     }
698
699     AlignmentAnnotation ann = aa[row];
700     if (row > -1 && ann.annotations != null
701             && column < ann.annotations.length)
702     {
703       buildToolTip(ann, column, aa);
704       setStatusMessage(column, ann);
705     }
706     else
707     {
708       this.setToolTipText(null);
709       ap.alignFrame.statusBar.setText(" ");
710     }
711   }
712
713   /**
714    * Builds a tooltip for the annotation at the current mouse position.
715    * 
716    * @param ann
717    * @param column
718    * @param anns
719    */
720   void buildToolTip(AlignmentAnnotation ann, int column,
721           AlignmentAnnotation[] anns)
722   {
723     if (ann.graphGroup > -1)
724     {
725       StringBuilder tip = new StringBuilder(32);
726       tip.append("<html>");
727       for (int i = 0; i < anns.length; i++)
728       {
729         if (anns[i].graphGroup == ann.graphGroup
730                 && anns[i].annotations[column] != null)
731         {
732           tip.append(anns[i].label);
733           String description = anns[i].annotations[column].description;
734           if (description != null && description.length() > 0)
735           {
736             tip.append(" ").append(description);
737           }
738           tip.append("<br>");
739         }
740       }
741       if (tip.length() != 6)
742       {
743         tip.setLength(tip.length() - 4);
744         this.setToolTipText(tip.toString() + "</html>");
745       }
746     }
747     else if (ann.annotations[column] != null)
748     {
749       String description = ann.annotations[column].description;
750       if (description != null && description.length() > 0)
751       {
752         this.setToolTipText(JvSwingUtils.wrapTooltip(true, description));
753       }
754     }
755     else
756     {
757       // clear the tooltip.
758       this.setToolTipText(null);
759     }
760   }
761
762   /**
763    * Constructs and displays the status bar message
764    * 
765    * @param column
766    * @param ann
767    */
768   void setStatusMessage(int column, AlignmentAnnotation ann)
769   {
770     /*
771      * show alignment column and annotation description if any
772      */
773     StringBuilder text = new StringBuilder(32);
774     text.append(MessageManager.getString("label.column")).append(" ")
775             .append(column + 1);
776
777     if (ann.annotations[column] != null)
778     {
779       String description = ann.annotations[column].description;
780       if (description != null && description.trim().length() > 0)
781       {
782         text.append("  ").append(description);
783       }
784     }
785
786     /*
787      * if the annotation is sequence-specific, show the sequence number
788      * in the alignment, and (if not a gap) the residue and position
789      */
790     SequenceI seqref = ann.sequenceRef;
791     if (seqref != null)
792     {
793       int seqIndex = av.getAlignment().findIndex(seqref);
794       if (seqIndex != -1)
795       {
796         text.append(", ")
797                 .append(MessageManager.getString("label.sequence"))
798                 .append(" ")
799                 .append(seqIndex + 1);
800         char residue = seqref.getCharAt(column);
801         if (!Comparison.isGap(residue))
802         {
803           text.append(" ");
804           String name;
805           if (av.getAlignment().isNucleotide())
806           {
807             name = ResidueProperties.nucleotideName.get(String
808                     .valueOf(residue));
809             text.append(" Nucleotide: ").append(
810                     name != null ? name : residue);
811           }
812           else
813           {
814             name = 'X' == residue ? "X" : ('*' == residue ? "STOP"
815                     : ResidueProperties.aa2Triplet.get(String
816                             .valueOf(residue)));
817             text.append(" Residue: ").append(name != null ? name : residue);
818           }
819           int residuePos = seqref.findPosition(column);
820           text.append(" (").append(residuePos).append(")");
821         }
822       }
823     }
824
825     ap.alignFrame.statusBar.setText(text.toString());
826   }
827
828   /**
829    * DOCUMENT ME!
830    * 
831    * @param evt
832    *          DOCUMENT ME!
833    */
834   @Override
835   public void mouseClicked(MouseEvent evt)
836   {
837     // if (activeRow != -1)
838     // {
839     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
840     // AlignmentAnnotation anot = aa[activeRow];
841     // }
842   }
843
844   // TODO mouseClicked-content and drawCursor are quite experimental!
845   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
846           int y1)
847   {
848     int pady = av.getCharHeight() / 5;
849     int charOffset = 0;
850     graphics.setColor(Color.black);
851     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
852
853     if (av.validCharWidth)
854     {
855       graphics.setColor(Color.white);
856
857       char s = seq.getCharAt(res);
858
859       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
860       graphics.drawString(String.valueOf(s), charOffset + x1,
861               (y1 + av.getCharHeight()) - pady);
862     }
863
864   }
865
866   private volatile boolean imageFresh = false;
867
868   /**
869    * DOCUMENT ME!
870    * 
871    * @param g
872    *          DOCUMENT ME!
873    */
874   @Override
875   public void paintComponent(Graphics g)
876   {
877     g.setColor(Color.white);
878     g.fillRect(0, 0, getWidth(), getHeight());
879
880     if (image != null)
881     {
882       if (fastPaint || (getVisibleRect().width != g.getClipBounds().width)
883               || (getVisibleRect().height != g.getClipBounds().height))
884       {
885         g.drawImage(image, 0, 0, this);
886         fastPaint = false;
887         return;
888       }
889     }
890     imgWidth = (av.endRes - av.startRes + 1) * av.getCharWidth();
891     if (imgWidth < 1)
892     {
893       return;
894     }
895     if (image == null || imgWidth != image.getWidth(this)
896             || image.getHeight(this) != getHeight())
897     {
898       try
899       {
900         image = new BufferedImage(imgWidth, ap.getAnnotationPanel()
901                 .getHeight(), BufferedImage.TYPE_INT_RGB);
902       } catch (OutOfMemoryError oom)
903       {
904         try
905         {
906           System.gc();
907         } catch (Exception x)
908         {
909         }
910         ;
911         new OOMWarning(
912                 "Couldn't allocate memory to redraw screen. Please restart Jalview",
913                 oom);
914         return;
915       }
916       gg = (Graphics2D) image.getGraphics();
917
918       if (av.antiAlias)
919       {
920         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
921                 RenderingHints.VALUE_ANTIALIAS_ON);
922       }
923
924       gg.setFont(av.getFont());
925       fm = gg.getFontMetrics();
926       gg.setColor(Color.white);
927       gg.fillRect(0, 0, imgWidth, image.getHeight());
928       imageFresh = true;
929     }
930
931     drawComponent(gg, av.startRes, av.endRes + 1);
932     imageFresh = false;
933     g.drawImage(image, 0, 0, this);
934   }
935
936   /**
937    * set true to enable redraw timing debug output on stderr
938    */
939   private final boolean debugRedraw = false;
940
941   /**
942    * non-Thread safe repaint
943    * 
944    * @param horizontal
945    *          repaint with horizontal shift in alignment
946    */
947   public void fastPaint(int horizontal)
948   {
949     if ((horizontal == 0) || gg == null
950             || av.getAlignment().getAlignmentAnnotation() == null
951             || av.getAlignment().getAlignmentAnnotation().length < 1
952             || av.isCalcInProgress())
953     {
954       repaint();
955       return;
956     }
957     long stime = System.currentTimeMillis();
958     gg.copyArea(0, 0, imgWidth, getHeight(),
959             -horizontal * av.getCharWidth(), 0);
960     long mtime = System.currentTimeMillis();
961     int sr = av.startRes;
962     int er = av.endRes + 1;
963     int transX = 0;
964
965     if (horizontal > 0) // scrollbar pulled right, image to the left
966     {
967       transX = (er - sr - horizontal) * av.getCharWidth();
968       sr = er - horizontal;
969     }
970     else if (horizontal < 0)
971     {
972       er = sr - horizontal;
973     }
974
975     gg.translate(transX, 0);
976
977     drawComponent(gg, sr, er);
978
979     gg.translate(-transX, 0);
980     long dtime = System.currentTimeMillis();
981     fastPaint = true;
982     repaint();
983     long rtime = System.currentTimeMillis();
984     if (debugRedraw)
985     {
986       System.err.println("Scroll:\t" + horizontal + "\tCopyArea:\t"
987               + (mtime - stime) + "\tDraw component:\t" + (dtime - mtime)
988               + "\tRepaint call:\t" + (rtime - dtime));
989     }
990
991   }
992
993   private volatile boolean lastImageGood = false;
994
995   /**
996    * DOCUMENT ME!
997    * 
998    * @param g
999    *          DOCUMENT ME!
1000    * @param startRes
1001    *          DOCUMENT ME!
1002    * @param endRes
1003    *          DOCUMENT ME!
1004    */
1005   public void drawComponent(Graphics g, int startRes, int endRes)
1006   {
1007     BufferedImage oldFaded = fadedImage;
1008     if (av.isCalcInProgress())
1009     {
1010       if (image == null)
1011       {
1012         lastImageGood = false;
1013         return;
1014       }
1015       // We'll keep a record of the old image,
1016       // and draw a faded image until the calculation
1017       // has completed
1018       if (lastImageGood
1019               && (fadedImage == null || fadedImage.getWidth() != imgWidth || fadedImage
1020                       .getHeight() != image.getHeight()))
1021       {
1022         // System.err.println("redraw faded image ("+(fadedImage==null ?
1023         // "null image" : "") + " lastGood="+lastImageGood+")");
1024         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1025                 BufferedImage.TYPE_INT_RGB);
1026
1027         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1028
1029         fadedG.setColor(Color.white);
1030         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1031
1032         fadedG.setComposite(AlphaComposite.getInstance(
1033                 AlphaComposite.SRC_OVER, .3f));
1034         fadedG.drawImage(image, 0, 0, this);
1035
1036       }
1037       // make sure we don't overwrite the last good faded image until all
1038       // calculations have finished
1039       lastImageGood = false;
1040
1041     }
1042     else
1043     {
1044       if (fadedImage != null)
1045       {
1046         oldFaded = fadedImage;
1047       }
1048       fadedImage = null;
1049     }
1050
1051     g.setColor(Color.white);
1052     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1053
1054     g.setFont(av.getFont());
1055     if (fm == null)
1056     {
1057       fm = g.getFontMetrics();
1058     }
1059
1060     if ((av.getAlignment().getAlignmentAnnotation() == null)
1061             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1062     {
1063       g.setColor(Color.white);
1064       g.fillRect(0, 0, getWidth(), getHeight());
1065       g.setColor(Color.black);
1066       if (av.validCharWidth)
1067       {
1068         g.drawString(MessageManager
1069                 .getString("label.alignment_has_no_annotations"), 20, 15);
1070       }
1071
1072       return;
1073     }
1074     lastImageGood = renderer.drawComponent(this, av, g, activeRow,
1075             startRes, endRes);
1076     if (!lastImageGood && fadedImage == null)
1077     {
1078       fadedImage = oldFaded;
1079     }
1080   }
1081
1082   @Override
1083   public FontMetrics getFontMetrics()
1084   {
1085     return fm;
1086   }
1087
1088   @Override
1089   public Image getFadedImage()
1090   {
1091     return fadedImage;
1092   }
1093
1094   @Override
1095   public int getFadedImageWidth()
1096   {
1097     return imgWidth;
1098   }
1099
1100   private int[] bounds = new int[2];
1101
1102   @Override
1103   public int[] getVisibleVRange()
1104   {
1105     if (ap != null && ap.getAlabels() != null)
1106     {
1107       int sOffset = -ap.getAlabels().getScrollOffset();
1108       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1109       bounds[0] = sOffset;
1110       bounds[1] = visHeight;
1111       return bounds;
1112     }
1113     else
1114     {
1115       return null;
1116     }
1117   }
1118 }