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