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