JAL-2349 store/restore mappable contact matrix in project and fix up interactive...
[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 java.awt.AlphaComposite;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Graphics;
28 import java.awt.Graphics2D;
29 import java.awt.Image;
30 import java.awt.Rectangle;
31 import java.awt.RenderingHints;
32 import java.awt.event.ActionEvent;
33 import java.awt.event.ActionListener;
34 import java.awt.event.AdjustmentEvent;
35 import java.awt.event.AdjustmentListener;
36 import java.awt.event.MouseEvent;
37 import java.awt.event.MouseListener;
38 import java.awt.event.MouseMotionListener;
39 import java.awt.event.MouseWheelEvent;
40 import java.awt.event.MouseWheelListener;
41 import java.awt.image.BufferedImage;
42 import java.beans.PropertyChangeEvent;
43 import java.util.ArrayList;
44 import java.util.BitSet;
45 import java.util.Collections;
46 import java.util.List;
47
48 import javax.swing.JMenuItem;
49 import javax.swing.JPanel;
50 import javax.swing.JPopupMenu;
51 import javax.swing.Scrollable;
52 import javax.swing.ToolTipManager;
53
54 import jalview.api.AlignViewportI;
55 import jalview.datamodel.AlignmentAnnotation;
56 import jalview.datamodel.AlignmentI;
57 import jalview.datamodel.Annotation;
58 import jalview.datamodel.ColumnSelection;
59 import jalview.datamodel.ContactListI;
60 import jalview.datamodel.ContactMatrixI;
61 import jalview.datamodel.ContactRange;
62 import jalview.datamodel.GraphLine;
63 import jalview.datamodel.HiddenColumns;
64 import jalview.datamodel.SequenceI;
65 import jalview.gui.JalviewColourChooser.ColourChooserListener;
66 import jalview.renderer.AnnotationRenderer;
67 import jalview.renderer.AwtRenderPanelI;
68 import jalview.renderer.ContactGeometry;
69 import jalview.schemes.ResidueProperties;
70 import jalview.util.Comparison;
71 import jalview.util.MessageManager;
72 import jalview.util.Platform;
73 import jalview.viewmodel.ViewportListenerI;
74 import jalview.viewmodel.ViewportRanges;
75 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
76
77 /**
78  * AnnotationPanel displays visible portion of annotation rows below unwrapped
79  * alignment
80  * 
81  * @author $author$
82  * @version $Revision$
83  */
84 public class AnnotationPanel extends JPanel implements AwtRenderPanelI,
85         MouseListener, MouseWheelListener, MouseMotionListener,
86         ActionListener, AdjustmentListener, Scrollable, ViewportListenerI
87 {
88   enum DragMode
89   {
90     Select, Resize, Undefined, MatrixSelect
91   };
92
93   String HELIX = MessageManager.getString("label.helix");
94
95   String SHEET = MessageManager.getString("label.sheet");
96
97   /**
98    * For RNA secondary structure "stems" aka helices
99    */
100   String STEM = MessageManager.getString("label.rna_helix");
101
102   String LABEL = MessageManager.getString("label.label");
103
104   String REMOVE = MessageManager.getString("label.remove_annotation");
105
106   String COLOUR = MessageManager.getString("action.colour");
107
108   public final Color HELIX_COLOUR = Color.red.darker();
109
110   public final Color SHEET_COLOUR = Color.green.darker().darker();
111
112   public final Color STEM_COLOUR = Color.blue.darker();
113
114   /** DOCUMENT ME!! */
115   public AlignViewport av;
116
117   AlignmentPanel ap;
118
119   public int activeRow = -1;
120
121   public BufferedImage image;
122
123   public volatile BufferedImage fadedImage;
124
125   // private Graphics2D gg;
126
127   public FontMetrics fm;
128
129   public int imgWidth = 0;
130
131   boolean fastPaint = false;
132
133   // Used For mouse Dragging and resizing graphs
134   int graphStretch = -1;
135
136   int mouseDragLastX = -1;
137
138   int mouseDragLastY = -1;
139
140   int firstDragX = -1;
141
142   int firstDragY = -1;
143
144   DragMode dragMode = DragMode.Undefined;
145
146   boolean mouseDragging = false;
147
148   // for editing cursor
149   int cursorX = 0;
150
151   int cursorY = 0;
152
153   public final AnnotationRenderer renderer;
154
155   private MouseWheelListener[] _mwl;
156
157   private boolean notJustOne;
158
159   /**
160    * Creates a new AnnotationPanel object.
161    * 
162    * @param ap
163    *          DOCUMENT ME!
164    */
165   public AnnotationPanel(AlignmentPanel ap)
166   {
167     ToolTipManager.sharedInstance().registerComponent(this);
168     ToolTipManager.sharedInstance().setInitialDelay(0);
169     ToolTipManager.sharedInstance().setDismissDelay(10000);
170     this.ap = ap;
171     av = ap.av;
172     this.setLayout(null);
173     addMouseListener(this);
174     addMouseMotionListener(this);
175     ap.annotationScroller.getVerticalScrollBar()
176             .addAdjustmentListener(this);
177     // save any wheel listeners on the scroller, so we can propagate scroll
178     // events to them.
179     _mwl = ap.annotationScroller.getMouseWheelListeners();
180     // and then set our own listener to consume all mousewheel events
181     ap.annotationScroller.addMouseWheelListener(this);
182     renderer = new AnnotationRenderer();
183
184     av.getRanges().addPropertyChangeListener(this);
185   }
186
187   public AnnotationPanel(AlignViewport av)
188   {
189     this.av = av;
190     renderer = new AnnotationRenderer();
191   }
192
193   @Override
194   public void mouseWheelMoved(MouseWheelEvent e)
195   {
196     if (e.isShiftDown())
197     {
198       e.consume();
199       double wheelRotation = e.getPreciseWheelRotation();
200       if (wheelRotation > 0)
201       {
202         av.getRanges().scrollRight(true);
203       }
204       else if (wheelRotation < 0)
205       {
206         av.getRanges().scrollRight(false);
207       }
208     }
209     else
210     {
211       // TODO: find the correct way to let the event bubble up to
212       // ap.annotationScroller
213       for (MouseWheelListener mwl : _mwl)
214       {
215         if (mwl != null)
216         {
217           mwl.mouseWheelMoved(e);
218         }
219         if (e.isConsumed())
220         {
221           break;
222         }
223       }
224     }
225   }
226
227   @Override
228   public Dimension getPreferredScrollableViewportSize()
229   {
230     Dimension ps = getPreferredSize();
231     return new Dimension(ps.width, adjustForAlignFrame(false, ps.height));
232   }
233
234   @Override
235   public int getScrollableBlockIncrement(Rectangle visibleRect,
236           int orientation, int direction)
237   {
238     return 30;
239   }
240
241   @Override
242   public boolean getScrollableTracksViewportHeight()
243   {
244     return false;
245   }
246
247   @Override
248   public boolean getScrollableTracksViewportWidth()
249   {
250     return true;
251   }
252
253   @Override
254   public int getScrollableUnitIncrement(Rectangle visibleRect,
255           int orientation, int direction)
256   {
257     return 30;
258   }
259
260   /*
261    * (non-Javadoc)
262    * 
263    * @see
264    * java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event
265    * .AdjustmentEvent)
266    */
267   @Override
268   public void adjustmentValueChanged(AdjustmentEvent evt)
269   {
270     // update annotation label display
271     ap.getAlabels().setScrollOffset(-evt.getValue());
272   }
273
274   /**
275    * Calculates the height of the annotation displayed in the annotation panel.
276    * Callers should normally call the ap.adjustAnnotationHeight method to ensure
277    * all annotation associated components are updated correctly.
278    * 
279    */
280   public int adjustPanelHeight()
281   {
282     int height = av.calcPanelHeight();
283     this.setPreferredSize(new Dimension(1, height));
284     if (ap != null)
285     {
286       // revalidate only when the alignment panel is fully constructed
287       ap.validate();
288     }
289
290     return height;
291   }
292
293   /**
294    * DOCUMENT ME!
295    * 
296    * @param evt
297    *          DOCUMENT ME!
298    */
299   @Override
300   public void actionPerformed(ActionEvent evt)
301   {
302     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
303     if (aa == null)
304     {
305       return;
306     }
307     Annotation[] anot = aa[activeRow].annotations;
308
309     if (anot.length < av.getColumnSelection().getMax())
310     {
311       Annotation[] temp = new Annotation[av.getColumnSelection().getMax()
312               + 2];
313       System.arraycopy(anot, 0, temp, 0, anot.length);
314       anot = temp;
315       aa[activeRow].annotations = anot;
316     }
317
318     String action = evt.getActionCommand();
319     if (action.equals(REMOVE))
320     {
321       for (int index : av.getColumnSelection().getSelected())
322       {
323         if (av.getAlignment().getHiddenColumns().isVisible(index))
324         {
325           anot[index] = null;
326         }
327       }
328     }
329     else if (action.equals(LABEL))
330     {
331       String exMesg = collectAnnotVals(anot, LABEL);
332       String label = JvOptionPane.showInputDialog(
333               MessageManager.getString("label.enter_label"), exMesg);
334
335       if (label == null)
336       {
337         return;
338       }
339
340       if ((label.length() > 0) && !aa[activeRow].hasText)
341       {
342         aa[activeRow].hasText = true;
343       }
344
345       for (int index : av.getColumnSelection().getSelected())
346       {
347         if (!av.getAlignment().getHiddenColumns().isVisible(index))
348         {
349           continue;
350         }
351
352         if (anot[index] == null)
353         {
354           anot[index] = new Annotation(label, "", ' ', 0);
355         }
356         else
357         {
358           anot[index].displayCharacter = label;
359         }
360       }
361     }
362     else if (action.equals(COLOUR))
363     {
364       final Annotation[] fAnot = anot;
365       String title = MessageManager
366               .getString("label.select_foreground_colour");
367       ColourChooserListener listener = new ColourChooserListener()
368       {
369         @Override
370         public void colourSelected(Color c)
371         {
372           HiddenColumns hiddenColumns = av.getAlignment()
373                   .getHiddenColumns();
374           for (int index : av.getColumnSelection().getSelected())
375           {
376             if (hiddenColumns.isVisible(index))
377             {
378               if (fAnot[index] == null)
379               {
380                 fAnot[index] = new Annotation("", "", ' ', 0);
381               }
382               fAnot[index].colour = c;
383             }
384           }
385         };
386       };
387       JalviewColourChooser.showColourChooser(this, title, Color.black,
388               listener);
389     }
390     else
391     // HELIX, SHEET or STEM
392     {
393       char type = 0;
394       String symbol = "\u03B1"; // alpha
395
396       if (action.equals(HELIX))
397       {
398         type = 'H';
399       }
400       else if (action.equals(SHEET))
401       {
402         type = 'E';
403         symbol = "\u03B2"; // beta
404       }
405
406       // Added by LML to color stems
407       else if (action.equals(STEM))
408       {
409         type = 'S';
410         int column = av.getColumnSelection().getSelectedRanges().get(0)[0];
411         symbol = aa[activeRow].getDefaultRnaHelixSymbol(column);
412       }
413
414       if (!aa[activeRow].hasIcons)
415       {
416         aa[activeRow].hasIcons = true;
417       }
418
419       String label = JvOptionPane.showInputDialog(MessageManager
420               .getString("label.enter_label_for_the_structure"), symbol);
421
422       if (label == null)
423       {
424         return;
425       }
426
427       if ((label.length() > 0) && !aa[activeRow].hasText)
428       {
429         aa[activeRow].hasText = true;
430         if (action.equals(STEM))
431         {
432           aa[activeRow].showAllColLabels = true;
433         }
434       }
435       for (int index : av.getColumnSelection().getSelected())
436       {
437         if (!av.getAlignment().getHiddenColumns().isVisible(index))
438         {
439           continue;
440         }
441
442         if (anot[index] == null)
443         {
444           anot[index] = new Annotation(label, "", type, 0);
445         }
446
447         anot[index].secondaryStructure = type != 'S' ? type
448                 : label.length() == 0 ? ' ' : label.charAt(0);
449         anot[index].displayCharacter = label;
450
451       }
452     }
453
454     av.getAlignment().validateAnnotation(aa[activeRow]);
455     ap.alignmentChanged();
456     ap.alignFrame.setMenusForViewport();
457     adjustPanelHeight();
458     repaint();
459
460     return;
461   }
462
463   /**
464    * Returns any existing annotation concatenated as a string. For each
465    * annotation, takes the description, if any, else the secondary structure
466    * character (if type is HELIX, SHEET or STEM), else the display character (if
467    * type is LABEL).
468    * 
469    * @param anots
470    * @param type
471    * @return
472    */
473   private String collectAnnotVals(Annotation[] anots, String type)
474   {
475     // TODO is this method wanted? why? 'last' is not used
476
477     StringBuilder collatedInput = new StringBuilder(64);
478     String last = "";
479     ColumnSelection viscols = av.getColumnSelection();
480     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
481
482     /*
483      * the selection list (read-only view) is in selection order, not
484      * column order; make a copy so we can sort it
485      */
486     List<Integer> selected = new ArrayList<>(viscols.getSelected());
487     Collections.sort(selected);
488     for (int index : selected)
489     {
490       // always check for current display state - just in case
491       if (!hidden.isVisible(index))
492       {
493         continue;
494       }
495       String tlabel = null;
496       if (anots[index] != null)
497       { // LML added stem code
498         if (type.equals(HELIX) || type.equals(SHEET) || type.equals(STEM)
499                 || type.equals(LABEL))
500         {
501           tlabel = anots[index].description;
502           if (tlabel == null || tlabel.length() < 1)
503           {
504             if (type.equals(HELIX) || type.equals(SHEET)
505                     || type.equals(STEM))
506             {
507               tlabel = "" + anots[index].secondaryStructure;
508             }
509             else
510             {
511               tlabel = "" + anots[index].displayCharacter;
512             }
513           }
514         }
515         if (tlabel != null && !tlabel.equals(last))
516         {
517           if (last.length() > 0)
518           {
519             collatedInput.append(" ");
520           }
521           collatedInput.append(tlabel);
522         }
523       }
524     }
525     return collatedInput.toString();
526   }
527
528   /**
529    * Action on right mouse pressed on Mac is to show a pop-up menu for the
530    * annotation. Action on left mouse pressed is to find which annotation is
531    * pressed and mark the start of a column selection or graph resize operation.
532    * 
533    * @param evt
534    */
535   @Override
536   public void mousePressed(MouseEvent evt)
537   {
538
539     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
540     if (aa == null)
541     {
542       return;
543     }
544     mouseDragLastX = evt.getX();
545     mouseDragLastY = evt.getY();
546
547     /*
548      * add visible annotation heights until we reach the y
549      * position, to find which annotation it is in
550      */
551     int height = 0;
552     activeRow = -1;
553     int yOffset = 0;
554     // todo could reuse getRowIndexAndOffset ?
555     final int y = evt.getY();
556
557     for (int i = 0; i < aa.length; i++)
558     {
559       if (aa[i].visible)
560       {
561         height += aa[i].height;
562       }
563
564       if (y < height)
565       {
566         if (aa[i].editable)
567         {
568           activeRow = i;
569         }
570         else if (aa[i].graph != 0)
571         {
572           /*
573            * we have clicked on a resizable graph annotation
574            */
575           graphStretch = i;
576           yOffset = height - y;
577         }
578         break;
579       }
580     }
581
582     /*
583      * isPopupTrigger fires in mousePressed on Mac,
584      * not until mouseRelease on Windows
585      */
586     if (evt.isPopupTrigger() && activeRow != -1)
587     {
588       showPopupMenu(y, evt.getX());
589       return;
590     }
591
592     if (graphStretch != -1)
593     {
594
595       if (aa[graphStretch].graph == AlignmentAnnotation.CONTACT_MAP)
596       {
597         // data in row has position on y as well as x axis
598         if (evt.isAltDown() || evt.isAltGraphDown())
599         {
600           dragMode = DragMode.MatrixSelect;
601           firstDragX = mouseDragLastX;
602           firstDragY = mouseDragLastY;
603         }
604       }
605     }
606     else
607     {
608       // no row (or row that can be adjusted) was pressed. Simulate a ruler click
609       ap.getScalePanel().mousePressed(evt);
610     }
611   }
612
613   /**
614    * checks whether the annotation row under the mouse click evt's handles the
615    * event
616    * 
617    * @param evt
618    * @return false if evt was not handled
619    */
620   boolean matrix_clicked(MouseEvent evt)
621   {
622     int[] rowIndex = getRowIndexAndOffset(evt.getY(),
623             av.getAlignment().getAlignmentAnnotation());
624     if (rowIndex == null)
625     {
626       jalview.bin.Console
627               .error("IMPLEMENTATION ERROR: matrix click out of range.");
628       return false;
629     }
630     int yOffset = rowIndex[1];
631
632     AlignmentAnnotation clicked = av.getAlignment()
633             .getAlignmentAnnotation()[rowIndex[0]];
634     if (clicked.graph != AlignmentAnnotation.CONTACT_MAP)
635     {
636       return false;
637     }
638
639     // TODO - use existing threshold to select related sections of matrix
640     GraphLine thr = clicked.getThreshold();
641
642     int currentX = getColumnForXPos(evt.getX());
643     ContactListI forCurrentX = av.getContactList(clicked, currentX);
644     if (forCurrentX != null)
645     {
646       ContactGeometry cXcgeom = new ContactGeometry(forCurrentX,
647               clicked.graphHeight);
648       ContactGeometry.contactInterval cXci = cXcgeom.mapFor(yOffset,
649               yOffset);
650       /**
651        * start and end range corresponding to the row range under the mouse at
652        * column currentX
653        */
654       int fr, to;
655       fr = Math.min(cXci.cStart, cXci.cEnd);
656       to = Math.max(cXci.cStart, cXci.cEnd);
657
658       // double click selects the whole group
659       if (evt.getClickCount() == 2)
660       {
661         ContactMatrixI matrix = av.getContactMatrix(clicked);
662
663         if (matrix != null)
664         {
665           // simplest approach is to select all group containing column
666           if (matrix.hasGroups())
667           {
668             SequenceI rseq = clicked.sequenceRef;
669             BitSet grp = matrix.getGroupsFor(currentX);
670             // TODO: cXci needs to be mapped to real groups
671             for (int c = fr; c <= to; c++)
672             {
673               BitSet additionalGrp = matrix.getGroupsFor(c);
674               grp.or(additionalGrp);
675             }
676             HiddenColumns hc = av.getAlignment().getHiddenColumns();
677             for (int p = grp.nextSetBit(0); p >= 0; p = grp
678                     .nextSetBit(p + 1))
679             {
680               int offp = (rseq != null)
681                       ? rseq.findIndex(rseq.getStart() - 1 + p)
682                       : p;
683
684               if (!av.hasHiddenColumns() || hc.isVisible(offp))
685               {
686                 av.getColumnSelection().addElement(offp);
687               }
688             }
689           }
690           // possible alternative for interactive selection - threshold
691           // gives 'ceiling' for forming a cluster
692           // when a row+column is selected, farthest common ancestor less
693           // than thr is used to compute cluster
694
695         }
696       }
697       else
698       {
699         // select corresponding range in segment under mouse
700         {
701           int[] rng = forCurrentX.getMappedPositionsFor(fr, to);
702           if (rng != null)
703           {
704             av.getColumnSelection().addRangeOfElements(rng, true);
705           }
706           av.getColumnSelection().addElement(currentX);
707         }
708         // PAE SPECIFIC
709         // and also select everything lower than the max range adjacent
710         // (kind of works)
711         if (evt.isControlDown()
712                 && PAEContactMatrix.PAEMATRIX.equals(clicked.getCalcId()))
713         {
714           int c = fr - 1;
715           ContactRange cr = forCurrentX.getRangeFor(fr, to);
716           double cval;
717           // TODO: could use GraphLine instead of arbitrary picking
718           // TODO: could report mean/median/variance for partitions
719           // (contiguous selected vs unselected regions and inter-contig
720           // regions)
721           // controls feathering - what other elements in row/column
722           // should we select
723           double thresh = cr.getMean() + (cr.getMax() - cr.getMean()) * .15;
724           while (c > 0)
725           {
726             cval = forCurrentX.getContactAt(c);
727             if (// cr.getMin() <= cval &&
728             cval <= thresh)
729             {
730               int[] cols = forCurrentX.getMappedPositionsFor(c, c);
731               if (cols != null)
732               {
733                 av.getColumnSelection().addRangeOfElements(cols, true);
734               }
735               else
736               {
737                 break;
738               }
739             }
740             c--;
741           }
742             c = to;
743             while (c < forCurrentX.getContactHeight())
744             {
745               cval = forCurrentX.getContactAt(c);
746               if (// cr.getMin() <= cval &&
747               cval <= thresh)
748               {
749                 int[] cols = forCurrentX.getMappedPositionsFor(c, c);
750                 if (cols != null)
751                 {
752                   av.getColumnSelection().addRangeOfElements(cols, true);
753                 }
754               }
755               else
756               {
757                 break;
758               }
759               c++;
760
761             }
762           }
763       }
764     }
765     ap.paintAlignment(false, false);
766     PaintRefresher.Refresh(ap, av.getSequenceSetId());
767     av.sendSelection();
768     return true;
769   }
770   /**
771    * Construct and display a context menu at the right-click position
772    * 
773    * @param y
774    * @param x
775    */
776   void showPopupMenu(final int y, int x)
777   {
778     if (av.getColumnSelection() == null
779             || av.getColumnSelection().isEmpty())
780     {
781       return;
782     }
783
784     JPopupMenu pop = new JPopupMenu(
785             MessageManager.getString("label.structure_type"));
786     JMenuItem item;
787     /*
788      * Just display the needed structure options
789      */
790     if (av.getAlignment().isNucleotide())
791     {
792       item = new JMenuItem(STEM);
793       item.addActionListener(this);
794       pop.add(item);
795     }
796     else
797     {
798       item = new JMenuItem(HELIX);
799       item.addActionListener(this);
800       pop.add(item);
801       item = new JMenuItem(SHEET);
802       item.addActionListener(this);
803       pop.add(item);
804     }
805     item = new JMenuItem(LABEL);
806     item.addActionListener(this);
807     pop.add(item);
808     item = new JMenuItem(COLOUR);
809     item.addActionListener(this);
810     pop.add(item);
811     item = new JMenuItem(REMOVE);
812     item.addActionListener(this);
813     pop.add(item);
814     pop.show(this, x, y);
815   }
816
817   /**
818    * Action on mouse up is to clear mouse drag data and call mouseReleased on
819    * ScalePanel, to deal with defining the selection group (if any) defined by
820    * the mouse drag
821    * 
822    * @param evt
823    */
824   @Override
825   public void mouseReleased(MouseEvent evt)
826   {
827     if (dragMode == DragMode.MatrixSelect)
828     {
829       matrixSelectRange(evt);
830     }
831     graphStretch = -1;
832     mouseDragLastX = -1;
833     mouseDragLastY = -1;
834     firstDragX = -1;
835     firstDragY = -1;
836     mouseDragging = false;
837     if (dragMode == DragMode.Resize)
838     {
839       ap.adjustAnnotationHeight();
840     }
841     dragMode = DragMode.Undefined;
842     if (!matrix_clicked(evt))
843     {
844       ap.getScalePanel().mouseReleased(evt);
845     }
846
847     /*
848      * isPopupTrigger is set in mouseReleased on Windows
849      * (in mousePressed on Mac)
850      */
851     if (evt.isPopupTrigger() && activeRow != -1)
852     {
853       showPopupMenu(evt.getY(), evt.getX());
854     }
855
856   }
857
858   /**
859    * DOCUMENT ME!
860    * 
861    * @param evt
862    *          DOCUMENT ME!
863    */
864   @Override
865   public void mouseEntered(MouseEvent evt)
866   {
867     this.mouseDragging = false;
868     ap.getScalePanel().mouseEntered(evt);
869   }
870
871   /**
872    * On leaving the panel, calls ScalePanel.mouseExited to deal with scrolling
873    * with column selection on a mouse drag
874    * 
875    * @param evt
876    */
877   @Override
878   public void mouseExited(MouseEvent evt)
879   {
880     ap.getScalePanel().mouseExited(evt);
881   }
882
883   /**
884    * Action on starting or continuing a mouse drag. There are two possible
885    * actions:
886    * <ul>
887    * <li>drag up or down on a graphed annotation increases or decreases the
888    * height of the graph</li>
889    * <li>dragging left or right selects the columns dragged across</li>
890    * </ul>
891    * A drag on a graph annotation is treated as column selection if it starts
892    * with more horizontal than vertical movement, and as resize if it starts
893    * with more vertical than horizontal movement. Once started, the drag does
894    * not change mode.
895    * 
896    * @param evt
897    */
898   @Override
899   public void mouseDragged(MouseEvent evt)
900   {
901     /*
902      * if dragMode is Undefined:
903      * - set to Select if dx > dy
904      * - set to Resize if dy > dx
905      * - do nothing if dx == dy
906      */
907     final int x = evt.getX();
908     final int y = evt.getY();
909     if (dragMode == DragMode.Undefined)
910     {
911       int dx = Math.abs(x - mouseDragLastX);
912       int dy = Math.abs(y - mouseDragLastY);
913       if (graphStretch == -1 || dx > dy)
914       {
915         /*
916          * mostly horizontal drag, or not a graph annotation
917          */
918         dragMode = DragMode.Select;
919       }
920       else if (dy > dx)
921       {
922         /*
923          * mostly vertical drag
924          */
925         dragMode = DragMode.Resize;
926         notJustOne = evt.isShiftDown();
927
928         /*
929          * but could also be a matrix drag
930          */
931         if ((evt.isAltDown() || evt.isAltGraphDown()) && (av.getAlignment()
932                 .getAlignmentAnnotation()[graphStretch].graph == AlignmentAnnotation.CONTACT_MAP))
933         {
934           /*
935            * dragging in a matrix
936            */
937           dragMode = DragMode.MatrixSelect;
938           firstDragX = mouseDragLastX;
939           firstDragY = mouseDragLastY;
940         }
941       }
942     }
943
944     if (dragMode == DragMode.Undefined)
945
946     {
947       /*
948        * drag is diagonal - defer deciding whether to
949        * treat as up/down or left/right
950        */
951       return;
952     }
953
954     try
955     {
956       if (dragMode == DragMode.Resize)
957       {
958         /*
959          * resize graph annotation if mouse was dragged up or down
960          */
961         int deltaY = mouseDragLastY - evt.getY();
962         if (deltaY != 0)
963         {
964           AlignmentAnnotation graphAnnotation = av.getAlignment()
965                   .getAlignmentAnnotation()[graphStretch];
966           int newHeight = Math.max(0, graphAnnotation.graphHeight + deltaY);
967           if (notJustOne)
968           {
969             for (AlignmentAnnotation similar : av.getAlignment()
970                     .findAnnotations(null, graphAnnotation.getCalcId(),
971                             graphAnnotation.label))
972             {
973               similar.graphHeight = newHeight;
974             }
975
976           }
977           else
978           {
979             graphAnnotation.graphHeight = newHeight;
980           }
981           adjustPanelHeight();
982           ap.paintAlignment(false, false);
983         }
984       }
985       else if (dragMode == DragMode.MatrixSelect)
986       {
987         /*
988          * TODO draw a rubber band for range
989          */
990         mouseDragLastX = x;
991         mouseDragLastY = y;
992         ap.paintAlignment(false, false);
993       }
994       else
995       {
996         /*
997          * for mouse drag left or right, delegate to 
998          * ScalePanel to adjust the column selection
999          */
1000         ap.getScalePanel().mouseDragged(evt);
1001       }
1002     } finally
1003     {
1004       mouseDragLastX = x;
1005       mouseDragLastY = y;
1006     }
1007   }
1008
1009   public void matrixSelectRange(MouseEvent evt)
1010   {
1011     /*
1012      * get geometry of drag
1013      */
1014     int fromY = Math.min(firstDragY, evt.getY());
1015     int toY = Math.max(firstDragY, evt.getY());
1016     int fromX = Math.min(firstDragX, evt.getX());
1017     int toX = Math.max(firstDragX, evt.getX());
1018
1019     int deltaY = toY - fromY;
1020     int deltaX = toX - fromX;
1021
1022     int[] rowIndex = getRowIndexAndOffset(fromY,
1023             av.getAlignment().getAlignmentAnnotation());
1024     int[] toRowIndex = getRowIndexAndOffset(toY,
1025             av.getAlignment().getAlignmentAnnotation());
1026
1027     if (rowIndex == null || toRowIndex == null)
1028     {
1029       jalview.bin.Console.trace("Drag out of range. needs to be clipped");
1030
1031     }
1032     if (rowIndex[0] != toRowIndex[0])
1033     {
1034       jalview.bin.Console.trace("Drag went to another row. needs to be clipped");
1035     }
1036
1037     // rectangular selection on matrix style annotation
1038     AlignmentAnnotation cma = av.getAlignment()
1039             .getAlignmentAnnotation()[rowIndex[0]];
1040
1041     int lastX = getColumnForXPos(fromX);
1042     int currentX = getColumnForXPos(toX);
1043     int fromXc = Math.min(lastX, currentX);
1044     int toXc = Math.max(lastX, currentX);
1045     ContactListI forFromX = av.getContactList(cma, fromXc);
1046     ContactListI forToX = av.getContactList(cma, toXc);
1047
1048     if (forFromX != null && forToX != null)
1049     {
1050       ContactGeometry lastXcgeom = new ContactGeometry(forFromX,
1051               cma.graphHeight);
1052       ContactGeometry.contactInterval lastXci = lastXcgeom
1053               .mapFor(rowIndex[1], rowIndex[1] - deltaY);
1054
1055       ContactGeometry cXcgeom = new ContactGeometry(forToX,
1056               cma.graphHeight);
1057       ContactGeometry.contactInterval cXci = cXcgeom.mapFor(rowIndex[1],
1058               rowIndex[1] - deltaY);
1059
1060       // mark rectangular region formed by drag
1061       jalview.bin.Console.trace("Matrix Selection from last(" + fromXc
1062               + ",[" + lastXci.cStart + "," + lastXci.cEnd + "]) to cur("
1063               + toXc + ",[" + cXci.cStart + "," + cXci.cEnd + "])");
1064       int fr, to;
1065       fr = Math.min(lastXci.cStart, lastXci.cEnd);
1066       to = Math.max(lastXci.cStart, lastXci.cEnd);
1067       int[] mappedPos = forFromX.getMappedPositionsFor(fr, to);
1068       if (mappedPos != null)
1069       {
1070         jalview.bin.Console.trace("Marking " + fr + " to " + to
1071                 + " mapping to sequence positions " + mappedPos[0] + " to "
1072                 + mappedPos[1]);
1073         for (int pair = 0; pair < mappedPos.length; pair += 2)
1074         {
1075           for (int c = mappedPos[pair]; c <= mappedPos[pair + 1]; c++)
1076 //          {
1077 //            if (cma.sequenceRef != null)
1078 //            {
1079 //              int col = cma.sequenceRef.findIndex(cma.sequenceRef.getStart()+c);
1080 //              av.getColumnSelection().addElement(col);
1081 //            }
1082 //            else
1083             {
1084               av.getColumnSelection().addElement(c);
1085             }
1086         }
1087       }
1088       // and again for most recent corner of drag
1089       fr = Math.min(cXci.cStart, cXci.cEnd);
1090       to = Math.max(cXci.cStart, cXci.cEnd);
1091       mappedPos = forFromX.getMappedPositionsFor(fr, to);
1092       if (mappedPos != null)
1093       {
1094         for (int pair = 0; pair < mappedPos.length; pair += 2)
1095         {
1096           jalview.bin.Console.trace("Marking " + fr + " to " + to
1097                   + " mapping to sequence positions " + mappedPos[pair] + " to "
1098                   + mappedPos[pair+1]);
1099           for (int c = mappedPos[pair]; c <= mappedPos[pair + 1]; c++)
1100           {
1101 //            if (cma.sequenceRef != null)
1102 //            {
1103 //              int col = cma.sequenceRef.findIndex(cma.sequenceRef.getStart()+c);
1104 //              av.getColumnSelection().addElement(col);
1105 //            }
1106 //            else
1107             {
1108               av.getColumnSelection().addElement(c);
1109             }
1110           }
1111         }
1112       }
1113       fr = Math.min(lastX, currentX);
1114       to = Math.max(lastX, currentX);
1115
1116       jalview.bin.Console.trace("Marking " + fr + " to " + to);
1117       for (int c = fr; c <= to; c++)
1118       {
1119         av.getColumnSelection().addElement(c);
1120       }
1121     }
1122
1123   }
1124
1125   /**
1126    * Constructs the tooltip, and constructs and displays a status message, for
1127    * the current mouse position
1128    * 
1129    * @param evt
1130    */
1131   @Override
1132   public void mouseMoved(MouseEvent evt)
1133   {
1134     int yPos = evt.getY();
1135     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1136     int rowAndOffset[] = getRowIndexAndOffset(yPos, aa);
1137     int row = rowAndOffset[0];
1138
1139     if (row == -1)
1140     {
1141       this.setToolTipText(null);
1142       return;
1143     }
1144
1145     int column = getColumnForXPos(evt.getX());
1146
1147     AlignmentAnnotation ann = aa[row];
1148     if (row > -1 && ann.annotations != null
1149             && column < ann.annotations.length)
1150     {
1151       String toolTip = buildToolTip(ann, column, aa, rowAndOffset[1], av,
1152               ap);
1153       setToolTipText(toolTip == null ? null
1154               : JvSwingUtils.wrapTooltip(true, toolTip));
1155       String msg = getStatusMessage(av.getAlignment(), column, ann,
1156               rowAndOffset[1], av);
1157       ap.alignFrame.setStatus(msg);
1158     }
1159     else
1160     {
1161       this.setToolTipText(null);
1162       ap.alignFrame.setStatus(" ");
1163     }
1164   }
1165
1166   private int getColumnForXPos(int x)
1167   {
1168     int column = (x / av.getCharWidth()) + av.getRanges().getStartRes();
1169     column = Math.min(column, av.getRanges().getEndRes());
1170
1171     if (av.hasHiddenColumns())
1172     {
1173       column = av.getAlignment().getHiddenColumns()
1174               .visibleToAbsoluteColumn(column);
1175     }
1176     return column;
1177   }
1178
1179   /**
1180    * Answers the index in the annotations array of the visible annotation at the
1181    * given y position. This is done by adding the heights of visible annotations
1182    * until the y position has been exceeded. Answers -1 if no annotations are
1183    * visible, or the y position is below all annotations.
1184    * 
1185    * @param yPos
1186    * @param aa
1187    * @return
1188    */
1189   static int getRowIndex(int yPos, AlignmentAnnotation[] aa)
1190   {
1191     if (aa == null)
1192     {
1193       return -1;
1194     }
1195     return getRowIndexAndOffset(yPos, aa)[0];
1196   }
1197
1198   static int[] getRowIndexAndOffset(int yPos, AlignmentAnnotation[] aa)
1199   {
1200     int[] res = new int[2];
1201     res[0] = -1;
1202     res[1] = 0;
1203     if (aa == null)
1204     {
1205       return res;
1206     }
1207     int row = -1;
1208     int height = 0, lheight = 0;
1209     for (int i = 0; i < aa.length; i++)
1210     {
1211       if (aa[i].visible)
1212       {
1213         lheight = height;
1214         height += aa[i].height;
1215       }
1216
1217       if (height > yPos)
1218       {
1219         row = i;
1220         res[0] = row;
1221         res[1] = height - yPos;
1222         break;
1223       }
1224     }
1225     return res;
1226   }
1227
1228   /**
1229    * Answers a tooltip for the annotation at the current mouse position, not
1230    * wrapped in &lt;html&gt; tags (apply if wanted). Answers null if there is no
1231    * tooltip to show.
1232    * 
1233    * @param ann
1234    * @param column
1235    * @param anns
1236    * @param rowAndOffset
1237    */
1238   static String buildToolTip(AlignmentAnnotation ann, int column,
1239           AlignmentAnnotation[] anns, int rowAndOffset, AlignViewportI av,
1240           AlignmentPanel ap)
1241   {
1242     String tooltip = null;
1243     if (ann.graphGroup > -1)
1244     {
1245       StringBuilder tip = new StringBuilder(32);
1246       boolean first = true;
1247       for (int i = 0; i < anns.length; i++)
1248       {
1249         if (anns[i].graphGroup == ann.graphGroup
1250                 && anns[i].annotations[column] != null)
1251         {
1252           if (!first)
1253           {
1254             tip.append("<br>");
1255           }
1256           first = false;
1257           tip.append(anns[i].label);
1258           String description = anns[i].annotations[column].description;
1259           if (description != null && description.length() > 0)
1260           {
1261             tip.append(" ").append(description);
1262           }
1263         }
1264       }
1265       tooltip = first ? null : tip.toString();
1266     }
1267     else if (column < ann.annotations.length
1268             && ann.annotations[column] != null)
1269     {
1270       tooltip = ann.annotations[column].description;
1271     }
1272     // TODO abstract tooltip generator so different implementations can be built
1273     if (ann.graph == AlignmentAnnotation.CONTACT_MAP)
1274     {
1275       ContactListI clist = av.getContactList(ann, column);
1276       if (clist != null)
1277       {
1278         ContactGeometry cgeom = new ContactGeometry(clist, ann.graphHeight);
1279         ContactGeometry.contactInterval ci = cgeom.mapFor(rowAndOffset);
1280         ContactRange cr = clist.getRangeFor(ci.cStart, ci.cEnd);
1281         tooltip = "Contact from " + clist.getPosition() + ", [" + ci.cStart
1282                 + " - " + ci.cEnd + "]" + "<br/>Mean:" + cr.getMean();
1283         
1284         int col = ann.sequenceRef.findPosition(column);
1285         int[][] highlightPos;
1286         int[] mappedPos = clist.getMappedPositionsFor(ci.cStart, ci.cEnd);
1287         if (mappedPos != null)
1288         {
1289           highlightPos = new int[1 + mappedPos.length][2];
1290           highlightPos[0] = new int[] { col, col };
1291           for (int p = 0, h = 0; p < mappedPos.length; h++, p += 2)
1292           {
1293             highlightPos[h][0] = ann.sequenceRef
1294                     .findPosition(mappedPos[p] - 1);
1295             highlightPos[h][1] = ann.sequenceRef
1296                     .findPosition(mappedPos[p + 1] - 1);
1297           }
1298         }
1299         else
1300         {
1301           highlightPos = new int[][] { new int[] { col, col } };
1302         }
1303         ap.getStructureSelectionManager()
1304                 .highlightPositionsOn(ann.sequenceRef, highlightPos, null);
1305       }
1306     }
1307     return tooltip;
1308   }
1309
1310   /**
1311    * Constructs and returns the status bar message
1312    * 
1313    * @param al
1314    * @param column
1315    * @param ann
1316    * @param rowAndOffset
1317    */
1318   static String getStatusMessage(AlignmentI al, int column,
1319           AlignmentAnnotation ann, int rowAndOffset, AlignViewportI av)
1320   {
1321     /*
1322      * show alignment column and annotation description if any
1323      */
1324     StringBuilder text = new StringBuilder(32);
1325     text.append(MessageManager.getString("label.column")).append(" ")
1326             .append(column + 1);
1327
1328     if (column < ann.annotations.length && ann.annotations[column] != null)
1329     {
1330       String description = ann.annotations[column].description;
1331       if (description != null && description.trim().length() > 0)
1332       {
1333         text.append("  ").append(description);
1334       }
1335     }
1336
1337     /*
1338      * if the annotation is sequence-specific, show the sequence number
1339      * in the alignment, and (if not a gap) the residue and position
1340      */
1341     SequenceI seqref = ann.sequenceRef;
1342     if (seqref != null)
1343     {
1344       int seqIndex = al.findIndex(seqref);
1345       if (seqIndex != -1)
1346       {
1347         text.append(", ").append(MessageManager.getString("label.sequence"))
1348                 .append(" ").append(seqIndex + 1);
1349         char residue = seqref.getCharAt(column);
1350         if (!Comparison.isGap(residue))
1351         {
1352           text.append(" ");
1353           String name;
1354           if (al.isNucleotide())
1355           {
1356             name = ResidueProperties.nucleotideName
1357                     .get(String.valueOf(residue));
1358             text.append(" Nucleotide: ")
1359                     .append(name != null ? name : residue);
1360           }
1361           else
1362           {
1363             name = 'X' == residue ? "X"
1364                     : ('*' == residue ? "STOP"
1365                             : ResidueProperties.aa2Triplet
1366                                     .get(String.valueOf(residue)));
1367             text.append(" Residue: ").append(name != null ? name : residue);
1368           }
1369           int residuePos = seqref.findPosition(column);
1370           text.append(" (").append(residuePos).append(")");
1371         }
1372       }
1373     }
1374
1375     return text.toString();
1376   }
1377
1378   /**
1379    * DOCUMENT ME!
1380    * 
1381    * @param evt
1382    *          DOCUMENT ME!
1383    */
1384   @Override
1385   public void mouseClicked(MouseEvent evt)
1386   {
1387     // if (activeRow != -1)
1388     // {
1389     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1390     // AlignmentAnnotation anot = aa[activeRow];
1391     // }
1392   }
1393
1394   // TODO mouseClicked-content and drawCursor are quite experimental!
1395   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
1396           int y1)
1397   {
1398     int pady = av.getCharHeight() / 5;
1399     int charOffset = 0;
1400     graphics.setColor(Color.black);
1401     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
1402
1403     if (av.validCharWidth)
1404     {
1405       graphics.setColor(Color.white);
1406
1407       char s = seq.getCharAt(res);
1408
1409       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
1410       graphics.drawString(String.valueOf(s), charOffset + x1,
1411               (y1 + av.getCharHeight()) - pady);
1412     }
1413
1414   }
1415
1416   private volatile boolean imageFresh = false;
1417
1418   private Rectangle visibleRect = new Rectangle(),
1419           clipBounds = new Rectangle();
1420
1421   /**
1422    * DOCUMENT ME!
1423    * 
1424    * @param g
1425    *          DOCUMENT ME!
1426    */
1427   @Override
1428   public void paintComponent(Graphics g)
1429   {
1430
1431     // BH: note that this method is generally recommended to
1432     // call super.paintComponent(g). Otherwise, the children of this
1433     // component will not be rendered. That is not needed here
1434     // because AnnotationPanel does not have any children. It is
1435     // just a JPanel contained in a JViewPort.
1436
1437     computeVisibleRect(visibleRect);
1438
1439     g.setColor(Color.white);
1440     g.fillRect(0, 0, visibleRect.width, visibleRect.height);
1441
1442     if (image != null)
1443     {
1444       // BH 2018 optimizing generation of new Rectangle().
1445       if (fastPaint
1446               || (visibleRect.width != (clipBounds = g
1447                       .getClipBounds(clipBounds)).width)
1448               || (visibleRect.height != clipBounds.height))
1449       {
1450
1451         g.drawImage(image, 0, 0, this);
1452         fastPaint = false;
1453         return;
1454       }
1455     }
1456     imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
1457             + 1) * av.getCharWidth();
1458     if (imgWidth < 1)
1459     {
1460       return;
1461     }
1462     Graphics2D gg;
1463     if (image == null || imgWidth != image.getWidth(this)
1464             || image.getHeight(this) != getHeight())
1465     {
1466       boolean tried = false;
1467       image = null;
1468       while (image == null && !tried)
1469       {
1470         try
1471         {
1472           image = new BufferedImage(imgWidth,
1473                   ap.getAnnotationPanel().getHeight(),
1474                   BufferedImage.TYPE_INT_RGB);
1475           tried = true;
1476         } catch (IllegalArgumentException exc)
1477         {
1478           System.err.println(
1479                   "Serious issue with viewport geometry imgWidth requested was "
1480                           + imgWidth);
1481           return;
1482         } catch (OutOfMemoryError oom)
1483         {
1484           try
1485           {
1486             System.gc();
1487           } catch (Exception x)
1488           {
1489           }
1490           ;
1491           new OOMWarning(
1492                   "Couldn't allocate memory to redraw screen. Please restart Jalview",
1493                   oom);
1494           return;
1495         }
1496
1497       }
1498       gg = (Graphics2D) image.getGraphics();
1499
1500       if (av.antiAlias)
1501       {
1502         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1503                 RenderingHints.VALUE_ANTIALIAS_ON);
1504       }
1505
1506       gg.setFont(av.getFont());
1507       fm = gg.getFontMetrics();
1508       gg.setColor(Color.white);
1509       gg.fillRect(0, 0, imgWidth, image.getHeight());
1510       imageFresh = true;
1511     }
1512     else
1513     {
1514       gg = (Graphics2D) image.getGraphics();
1515
1516     }
1517
1518     drawComponent(gg, av.getRanges().getStartRes(),
1519             av.getRanges().getEndRes() + 1);
1520     gg.dispose();
1521     imageFresh = false;
1522     g.drawImage(image, 0, 0, this);
1523   }
1524
1525   /**
1526    * set true to enable redraw timing debug output on stderr
1527    */
1528   private final boolean debugRedraw = false;
1529
1530   /**
1531    * non-Thread safe repaint
1532    * 
1533    * @param horizontal
1534    *          repaint with horizontal shift in alignment
1535    */
1536   public void fastPaint(int horizontal)
1537   {
1538     if ((horizontal == 0) || image == null
1539             || av.getAlignment().getAlignmentAnnotation() == null
1540             || av.getAlignment().getAlignmentAnnotation().length < 1
1541             || av.isCalcInProgress())
1542     {
1543       repaint();
1544       return;
1545     }
1546
1547     int sr = av.getRanges().getStartRes();
1548     int er = av.getRanges().getEndRes() + 1;
1549     int transX = 0;
1550
1551     Graphics2D gg = (Graphics2D) image.getGraphics();
1552
1553     if (imgWidth > Math.abs(horizontal * av.getCharWidth()))
1554     {
1555       // scroll is less than imgWidth away so can re-use buffered graphics
1556       gg.copyArea(0, 0, imgWidth, getHeight(),
1557               -horizontal * av.getCharWidth(), 0);
1558
1559       if (horizontal > 0) // scrollbar pulled right, image to the left
1560       {
1561         transX = (er - sr - horizontal) * av.getCharWidth();
1562         sr = er - horizontal;
1563       }
1564       else if (horizontal < 0)
1565       {
1566         er = sr - horizontal;
1567       }
1568     }
1569     gg.translate(transX, 0);
1570
1571     drawComponent(gg, sr, er);
1572
1573     gg.translate(-transX, 0);
1574
1575     gg.dispose();
1576
1577     fastPaint = true;
1578
1579     // Call repaint on alignment panel so that repaints from other alignment
1580     // panel components can be aggregated. Otherwise performance of the overview
1581     // window and others may be adversely affected.
1582     av.getAlignPanel().repaint();
1583   }
1584
1585   private volatile boolean lastImageGood = false;
1586
1587   /**
1588    * DOCUMENT ME!
1589    * 
1590    * @param g
1591    *          DOCUMENT ME!
1592    * @param startRes
1593    *          DOCUMENT ME!
1594    * @param endRes
1595    *          DOCUMENT ME!
1596    */
1597   public void drawComponent(Graphics g, int startRes, int endRes)
1598   {
1599     BufferedImage oldFaded = fadedImage;
1600     if (av.isCalcInProgress())
1601     {
1602       if (image == null)
1603       {
1604         lastImageGood = false;
1605         return;
1606       }
1607       // We'll keep a record of the old image,
1608       // and draw a faded image until the calculation
1609       // has completed
1610       if (lastImageGood
1611               && (fadedImage == null || fadedImage.getWidth() != imgWidth
1612                       || fadedImage.getHeight() != image.getHeight()))
1613       {
1614         // System.err.println("redraw faded image ("+(fadedImage==null ?
1615         // "null image" : "") + " lastGood="+lastImageGood+")");
1616         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1617                 BufferedImage.TYPE_INT_RGB);
1618
1619         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1620
1621         fadedG.setColor(Color.white);
1622         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1623
1624         fadedG.setComposite(
1625                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1626         fadedG.drawImage(image, 0, 0, this);
1627
1628       }
1629       // make sure we don't overwrite the last good faded image until all
1630       // calculations have finished
1631       lastImageGood = false;
1632
1633     }
1634     else
1635     {
1636       if (fadedImage != null)
1637       {
1638         oldFaded = fadedImage;
1639       }
1640       fadedImage = null;
1641     }
1642
1643     g.setColor(Color.white);
1644     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1645
1646     g.setFont(av.getFont());
1647     if (fm == null)
1648     {
1649       fm = g.getFontMetrics();
1650     }
1651
1652     if ((av.getAlignment().getAlignmentAnnotation() == null)
1653             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1654     {
1655       g.setColor(Color.white);
1656       g.fillRect(0, 0, getWidth(), getHeight());
1657       g.setColor(Color.black);
1658       if (av.validCharWidth)
1659       {
1660         g.drawString(MessageManager
1661                 .getString("label.alignment_has_no_annotations"), 20, 15);
1662       }
1663
1664       return;
1665     }
1666     lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1667             endRes);
1668     if (!lastImageGood && fadedImage == null)
1669     {
1670       fadedImage = oldFaded;
1671     }
1672     if (dragMode == DragMode.MatrixSelect)
1673     {
1674       g.setColor(Color.yellow);
1675       g.drawRect(Math.min(firstDragX, mouseDragLastX),
1676               Math.min(firstDragY, mouseDragLastY),
1677               Math.max(firstDragX, mouseDragLastX)
1678                       - Math.min(firstDragX, mouseDragLastX),
1679               Math.max(firstDragY, mouseDragLastY)
1680                       - Math.min(firstDragY, mouseDragLastY));
1681
1682     }
1683   }
1684
1685   @Override
1686   public FontMetrics getFontMetrics()
1687   {
1688     return fm;
1689   }
1690
1691   @Override
1692   public Image getFadedImage()
1693   {
1694     return fadedImage;
1695   }
1696
1697   @Override
1698   public int getFadedImageWidth()
1699   {
1700     return imgWidth;
1701   }
1702
1703   private int[] bounds = new int[2];
1704
1705   @Override
1706   public int[] getVisibleVRange()
1707   {
1708     if (ap != null && ap.getAlabels() != null)
1709     {
1710       int sOffset = -ap.getAlabels().getScrollOffset();
1711       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1712       bounds[0] = sOffset;
1713       bounds[1] = visHeight;
1714       return bounds;
1715     }
1716     else
1717     {
1718       return null;
1719     }
1720   }
1721
1722   /**
1723    * Try to ensure any references held are nulled
1724    */
1725   public void dispose()
1726   {
1727     av = null;
1728     ap = null;
1729     image = null;
1730     fadedImage = null;
1731     // gg = null;
1732     _mwl = null;
1733
1734     /*
1735      * I created the renderer so I will dispose of it
1736      */
1737     if (renderer != null)
1738     {
1739       renderer.dispose();
1740     }
1741   }
1742
1743   @Override
1744   public void propertyChange(PropertyChangeEvent evt)
1745   {
1746     // Respond to viewport range changes (e.g. alignment panel was scrolled)
1747     // Both scrolling and resizing change viewport ranges: scrolling changes
1748     // both start and end points, but resize only changes end values.
1749     // Here we only want to fastpaint on a scroll, with resize using a normal
1750     // paint, so scroll events are identified as changes to the horizontal or
1751     // vertical start value.
1752     if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1753     {
1754       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1755     }
1756     else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1757     {
1758       fastPaint(((int[]) evt.getNewValue())[0]
1759               - ((int[]) evt.getOldValue())[0]);
1760     }
1761     else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
1762     {
1763       repaint();
1764     }
1765   }
1766
1767   /**
1768    * computes the visible height of the annotation panel
1769    * 
1770    * @param adjustPanelHeight
1771    *          - when false, just adjust existing height according to other
1772    *          windows
1773    * @param annotationHeight
1774    * @return height to use for the ScrollerPreferredVisibleSize
1775    */
1776   public int adjustForAlignFrame(boolean adjustPanelHeight,
1777           int annotationHeight)
1778   {
1779     /*
1780      * Estimate available height in the AlignFrame for alignment +
1781      * annotations. Deduct an estimate for title bar, menu bar, scale panel,
1782      * hscroll, status bar, insets. 
1783      */
1784     int stuff = (ap.getViewName() != null ? 30 : 0)
1785             + (Platform.isAMacAndNotJS() ? 120 : 140);
1786     int availableHeight = ap.alignFrame.getHeight() - stuff;
1787     int rowHeight = av.getCharHeight();
1788
1789     if (adjustPanelHeight)
1790     {
1791       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
1792
1793       /*
1794        * If not enough vertical space, maximize annotation height while keeping
1795        * at least two rows of alignment visible
1796        */
1797       if (annotationHeight + alignmentHeight > availableHeight)
1798       {
1799         annotationHeight = Math.min(annotationHeight,
1800                 availableHeight - 2 * rowHeight);
1801       }
1802     }
1803     else
1804     {
1805       // maintain same window layout whilst updating sliders
1806       annotationHeight = Math.min(ap.annotationScroller.getSize().height,
1807               availableHeight - 2 * rowHeight);
1808     }
1809     return annotationHeight;
1810   }
1811 }