JAL-4134 TODO: alternative way of performing interactive picking using threshold
[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         else
605         {
606           GraphLine thr = aa[graphStretch].getThreshold();
607           
608           // possible alternative for interactive selection - threshold gives 'ceiling' for forming a cluster
609           // when a row+column is selected, farthest common ancestor less than thr is used to compute cluster  
610           int currentX = getColumnForXPos(evt.getX());
611           ContactMatrixI matrix = av.getContactMatrix(aa[graphStretch]);
612           if (matrix!=null)
613           {
614             if (matrix.hasGroups())
615             {
616             SequenceI rseq = aa[graphStretch].sequenceRef;
617             BitSet grp = matrix.getGroupsFor(currentX);
618             ColumnSelection cs = av.getColumnSelection();
619             HiddenColumns hc = av.getAlignment().getHiddenColumns();
620             for (int p=grp.nextSetBit(0); p>=0; p = grp.nextSetBit(p+1))
621             {
622               int offp = (rseq!=null) ? rseq.findIndex(rseq.getStart()-1+p) : p;
623               
624               if (!av.hasHiddenColumns() || hc.isVisible(offp))
625               { 
626                 av.getColumnSelection().addElement(offp);
627               }
628             }
629           } else 
630           {
631           ContactListI forCurrentX = av.getContactList(aa[graphStretch],
632                   currentX);
633           if (forCurrentX != null)
634           {
635             ContactGeometry cXcgeom = new ContactGeometry(forCurrentX,
636                     aa[graphStretch].graphHeight);
637             ContactGeometry.contactInterval cXci = cXcgeom.mapFor(yOffset,
638                     yOffset);
639             int fr, to;
640             fr = Math.min(cXci.cStart, cXci.cEnd);
641             to = Math.max(cXci.cStart, cXci.cEnd);
642             // select corresponding range in segment under mouse
643             {
644               for (int c = fr; c <= to; c++)
645               {
646                 av.getColumnSelection().addElement(c);
647               }
648               av.getColumnSelection().addElement(currentX);
649             }
650             // PAE SPECIFIC
651             // and also select everything lower than the max range adjacent
652             // (kind of works)
653             if (PAEContactMatrix.PAEMATRIX.equals(aa[graphStretch].getCalcId()))
654             {
655               int c = fr - 1;
656               ContactRange cr = forCurrentX.getRangeFor(fr, to);
657               double cval;
658               // TODO: could use GraphLine instead of arbitrary picking
659               // TODO: could report mean/median/variance for partitions (contiguous selected vs unselected regions and inter-contig regions)
660               // controls feathering - what other elements in row/column should we select
661               double thresh=cr.getMean()+(cr.getMax()-cr.getMean())*.15;
662               while (c > 0)
663               {
664                 cval = forCurrentX.getContactAt(c);
665                 if (// cr.getMin() <= cval &&
666                 cval <= thresh)
667                 {
668                   av.getColumnSelection().addElement(c--);
669                 }
670                 else
671                 {
672                   break;
673                 }
674               }
675               c = to;
676               while (c < forCurrentX.getContactHeight())
677               {
678                 cval = forCurrentX.getContactAt(c);
679                 if (// cr.getMin() <= cval &&
680                 cval <= thresh)
681                 {
682                   av.getColumnSelection().addElement(c++);
683                 }
684                 else
685                 {
686                   break;
687                 }
688               }
689             }
690             }
691           }
692         }
693       }}
694     }
695     else
696     {
697       ap.getScalePanel().mousePressed(evt);
698     }
699   }
700
701   /**
702    * Construct and display a context menu at the right-click position
703    * 
704    * @param y
705    * @param x
706    */
707   void showPopupMenu(final int y, int x)
708   {
709     if (av.getColumnSelection() == null
710             || av.getColumnSelection().isEmpty())
711     {
712       return;
713     }
714
715     JPopupMenu pop = new JPopupMenu(
716             MessageManager.getString("label.structure_type"));
717     JMenuItem item;
718     /*
719      * Just display the needed structure options
720      */
721     if (av.getAlignment().isNucleotide())
722     {
723       item = new JMenuItem(STEM);
724       item.addActionListener(this);
725       pop.add(item);
726     }
727     else
728     {
729       item = new JMenuItem(HELIX);
730       item.addActionListener(this);
731       pop.add(item);
732       item = new JMenuItem(SHEET);
733       item.addActionListener(this);
734       pop.add(item);
735     }
736     item = new JMenuItem(LABEL);
737     item.addActionListener(this);
738     pop.add(item);
739     item = new JMenuItem(COLOUR);
740     item.addActionListener(this);
741     pop.add(item);
742     item = new JMenuItem(REMOVE);
743     item.addActionListener(this);
744     pop.add(item);
745     pop.show(this, x, y);
746   }
747
748   /**
749    * Action on mouse up is to clear mouse drag data and call mouseReleased on
750    * ScalePanel, to deal with defining the selection group (if any) defined by
751    * the mouse drag
752    * 
753    * @param evt
754    */
755   @Override
756   public void mouseReleased(MouseEvent evt)
757   {
758     if (dragMode == DragMode.MatrixSelect)
759     {
760       matrixSelectRange(evt);
761     }
762     graphStretch = -1;
763     mouseDragLastX = -1;
764     mouseDragLastY = -1;
765     firstDragX = -1;
766     firstDragY = -1;
767     mouseDragging = false;
768     if (dragMode == DragMode.Resize)
769     {
770       ap.adjustAnnotationHeight();
771     }
772     dragMode = DragMode.Undefined;
773     ap.getScalePanel().mouseReleased(evt);
774
775     /*
776      * isPopupTrigger is set in mouseReleased on Windows
777      * (in mousePressed on Mac)
778      */
779     if (evt.isPopupTrigger() && activeRow != -1)
780     {
781       showPopupMenu(evt.getY(), evt.getX());
782     }
783
784   }
785
786   /**
787    * DOCUMENT ME!
788    * 
789    * @param evt
790    *          DOCUMENT ME!
791    */
792   @Override
793   public void mouseEntered(MouseEvent evt)
794   {
795     this.mouseDragging = false;
796     ap.getScalePanel().mouseEntered(evt);
797   }
798
799   /**
800    * On leaving the panel, calls ScalePanel.mouseExited to deal with scrolling
801    * with column selection on a mouse drag
802    * 
803    * @param evt
804    */
805   @Override
806   public void mouseExited(MouseEvent evt)
807   {
808     ap.getScalePanel().mouseExited(evt);
809   }
810
811   /**
812    * Action on starting or continuing a mouse drag. There are two possible
813    * actions:
814    * <ul>
815    * <li>drag up or down on a graphed annotation increases or decreases the
816    * height of the graph</li>
817    * <li>dragging left or right selects the columns dragged across</li>
818    * </ul>
819    * A drag on a graph annotation is treated as column selection if it starts
820    * with more horizontal than vertical movement, and as resize if it starts
821    * with more vertical than horizontal movement. Once started, the drag does
822    * not change mode.
823    * 
824    * @param evt
825    */
826   @Override
827   public void mouseDragged(MouseEvent evt)
828   {
829     /*
830      * if dragMode is Undefined:
831      * - set to Select if dx > dy
832      * - set to Resize if dy > dx
833      * - do nothing if dx == dy
834      */
835     final int x = evt.getX();
836     final int y = evt.getY();
837     if (dragMode == DragMode.Undefined)
838     {
839       int dx = Math.abs(x - mouseDragLastX);
840       int dy = Math.abs(y - mouseDragLastY);
841       if (graphStretch == -1 || dx > dy)
842       {
843         /*
844          * mostly horizontal drag, or not a graph annotation
845          */
846         dragMode = DragMode.Select;
847       }
848       else if (dy > dx)
849       {
850         /*
851          * mostly vertical drag
852          */
853         dragMode = DragMode.Resize;
854         notJustOne = evt.isShiftDown();
855
856         /*
857          * but could also be a matrix drag
858          */
859         if ((evt.isAltDown() || evt.isAltGraphDown()) && (av.getAlignment()
860                 .getAlignmentAnnotation()[graphStretch].graph == AlignmentAnnotation.CONTACT_MAP))
861         {
862           /*
863            * dragging in a matrix
864            */
865           dragMode = DragMode.MatrixSelect;
866           firstDragX = mouseDragLastX;
867           firstDragY = mouseDragLastY;
868         }
869       }
870     }
871
872     if (dragMode == DragMode.Undefined)
873
874     {
875       /*
876        * drag is diagonal - defer deciding whether to
877        * treat as up/down or left/right
878        */
879       return;
880     }
881
882     try
883     {
884       if (dragMode == DragMode.Resize)
885       {
886         /*
887          * resize graph annotation if mouse was dragged up or down
888          */
889         int deltaY = mouseDragLastY - evt.getY();
890         if (deltaY != 0)
891         {
892           AlignmentAnnotation graphAnnotation = av.getAlignment()
893                   .getAlignmentAnnotation()[graphStretch];
894           int newHeight = Math.max(0, graphAnnotation.graphHeight + deltaY);
895           if (notJustOne)
896           {
897             for (AlignmentAnnotation similar : av.getAlignment()
898                     .findAnnotations(null, graphAnnotation.getCalcId(),
899                             graphAnnotation.label))
900             {
901               similar.graphHeight = newHeight;
902             }
903
904           }
905           else
906           {
907             graphAnnotation.graphHeight = newHeight;
908           }
909           adjustPanelHeight();
910           ap.paintAlignment(false, false);
911         }
912       }
913       else if (dragMode == DragMode.MatrixSelect)
914       {
915         /*
916          * TODO draw a rubber band for range
917          */
918         mouseDragLastX = x;
919         mouseDragLastY = y;
920         ap.paintAlignment(false, false);
921       }
922       else
923       {
924         /*
925          * for mouse drag left or right, delegate to 
926          * ScalePanel to adjust the column selection
927          */
928         ap.getScalePanel().mouseDragged(evt);
929       }
930     } finally
931     {
932       mouseDragLastX = x;
933       mouseDragLastY = y;
934     }
935   }
936
937   public void matrixSelectRange(MouseEvent evt)
938   {
939     /*
940      * get geometry of drag
941      */
942     int fromY = Math.min(firstDragY, evt.getY());
943     int toY = Math.max(firstDragY, evt.getY());
944     int fromX = Math.min(firstDragX, evt.getX());
945     int toX = Math.max(firstDragX, evt.getX());
946
947     int deltaY = toY - fromY;
948     int deltaX = toX - fromX;
949
950     int[] rowIndex = getRowIndexAndOffset(fromY,
951             av.getAlignment().getAlignmentAnnotation());
952     int[] toRowIndex = getRowIndexAndOffset(toY,
953             av.getAlignment().getAlignmentAnnotation());
954
955     if (rowIndex == null || toRowIndex == null)
956     {
957       System.out.println("Drag out of range. needs to be clipped");
958
959     }
960     if (rowIndex[0] != toRowIndex[0])
961     {
962       System.out.println("Drag went to another row. needs to be clipped");
963     }
964
965     // rectangular selection on matrix style annotation
966     AlignmentAnnotation cma = av.getAlignment()
967             .getAlignmentAnnotation()[rowIndex[0]];
968
969     int lastX = getColumnForXPos(fromX);
970     int currentX = getColumnForXPos(toX);
971     int fromXc = Math.min(lastX, currentX);
972     int toXc = Math.max(lastX, currentX);
973     ContactListI forFromX = av.getContactList(cma, fromXc);
974     ContactListI forToX = av.getContactList(cma, toXc);
975
976     if (forFromX != null && forToX != null)
977     {
978       ContactGeometry lastXcgeom = new ContactGeometry(forFromX,
979               cma.graphHeight);
980       ContactGeometry.contactInterval lastXci = lastXcgeom
981               .mapFor(rowIndex[1], rowIndex[1] - deltaY);
982
983       ContactGeometry cXcgeom = new ContactGeometry(forToX,
984               cma.graphHeight);
985       ContactGeometry.contactInterval cXci = cXcgeom.mapFor(rowIndex[1],
986               rowIndex[1] - deltaY);
987
988       // mark rectangular region formed by drag
989       System.err.println("Matrix Selection from last(" + fromXc + ",["
990               + lastXci.cStart + "," + lastXci.cEnd + "]) to cur(" + toXc
991               + ",[" + cXci.cStart + "," + cXci.cEnd + "])");
992       int fr, to;
993       fr = Math.min(lastXci.cStart, lastXci.cEnd);
994       to = Math.max(lastXci.cStart, lastXci.cEnd);
995       System.err.println("Marking " + fr + " to " + to);
996       for (int c = fr; c <= to; c++)
997       {
998         if (cma.sequenceRef != null)
999         {
1000           int col = cma.sequenceRef.findIndex(c);
1001           av.getColumnSelection().addElement(col);
1002         }
1003         else
1004         {
1005           av.getColumnSelection().addElement(c);
1006         }
1007       }
1008       fr = Math.min(cXci.cStart, cXci.cEnd);
1009       to = Math.max(cXci.cStart, cXci.cEnd);
1010       System.err.println("Marking " + fr + " to " + to);
1011       for (int c = fr; c <= to; c++)
1012       {
1013         if (cma.sequenceRef != null)
1014         {
1015           int col = cma.sequenceRef.findIndex(c);
1016           av.getColumnSelection().addElement(col);
1017         }
1018         else
1019         {
1020           av.getColumnSelection().addElement(c);
1021         }
1022       }
1023       fr = Math.min(lastX, currentX);
1024       to = Math.max(lastX, currentX);
1025
1026       System.err.println("Marking " + fr + " to " + to);
1027       for (int c = fr; c <= to; c++)
1028       {
1029         av.getColumnSelection().addElement(c);
1030       }
1031     }
1032
1033   }
1034
1035   /**
1036    * Constructs the tooltip, and constructs and displays a status message, for
1037    * the current mouse position
1038    * 
1039    * @param evt
1040    */
1041   @Override
1042   public void mouseMoved(MouseEvent evt)
1043   {
1044     int yPos = evt.getY();
1045     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1046     int rowAndOffset[] = getRowIndexAndOffset(yPos, aa);
1047     int row = rowAndOffset[0];
1048
1049     if (row == -1)
1050     {
1051       this.setToolTipText(null);
1052       return;
1053     }
1054
1055     int column = getColumnForXPos(evt.getX());
1056
1057     AlignmentAnnotation ann = aa[row];
1058     if (row > -1 && ann.annotations != null
1059             && column < ann.annotations.length)
1060     {
1061       String toolTip = buildToolTip(ann, column, aa, rowAndOffset[1], av,
1062               ap);
1063       setToolTipText(toolTip == null ? null
1064               : JvSwingUtils.wrapTooltip(true, toolTip));
1065       String msg = getStatusMessage(av.getAlignment(), column, ann,
1066               rowAndOffset[1], av);
1067       ap.alignFrame.setStatus(msg);
1068     }
1069     else
1070     {
1071       this.setToolTipText(null);
1072       ap.alignFrame.setStatus(" ");
1073     }
1074   }
1075
1076   private int getColumnForXPos(int x)
1077   {
1078     int column = (x / av.getCharWidth()) + av.getRanges().getStartRes();
1079     column = Math.min(column, av.getRanges().getEndRes());
1080
1081     if (av.hasHiddenColumns())
1082     {
1083       column = av.getAlignment().getHiddenColumns()
1084               .visibleToAbsoluteColumn(column);
1085     }
1086     return column;
1087   }
1088
1089   /**
1090    * Answers the index in the annotations array of the visible annotation at the
1091    * given y position. This is done by adding the heights of visible annotations
1092    * until the y position has been exceeded. Answers -1 if no annotations are
1093    * visible, or the y position is below all annotations.
1094    * 
1095    * @param yPos
1096    * @param aa
1097    * @return
1098    */
1099   static int getRowIndex(int yPos, AlignmentAnnotation[] aa)
1100   {
1101     if (aa == null)
1102     {
1103       return -1;
1104     }
1105     return getRowIndexAndOffset(yPos, aa)[0];
1106   }
1107
1108   static int[] getRowIndexAndOffset(int yPos, AlignmentAnnotation[] aa)
1109   {
1110     int[] res = new int[2];
1111     res[0] = -1;
1112     res[1] = 0;
1113     if (aa == null)
1114     {
1115       return res;
1116     }
1117     int row = -1;
1118     int height = 0, lheight = 0;
1119     for (int i = 0; i < aa.length; i++)
1120     {
1121       if (aa[i].visible)
1122       {
1123         lheight = height;
1124         height += aa[i].height;
1125       }
1126
1127       if (height > yPos)
1128       {
1129         row = i;
1130         res[0] = row;
1131         res[1] = height - yPos;
1132         break;
1133       }
1134     }
1135     return res;
1136   }
1137
1138   /**
1139    * Answers a tooltip for the annotation at the current mouse position, not
1140    * wrapped in &lt;html&gt; tags (apply if wanted). Answers null if there is no
1141    * tooltip to show.
1142    * 
1143    * @param ann
1144    * @param column
1145    * @param anns
1146    * @param rowAndOffset
1147    */
1148   static String buildToolTip(AlignmentAnnotation ann, int column,
1149           AlignmentAnnotation[] anns, int rowAndOffset, AlignViewportI av,
1150           AlignmentPanel ap)
1151   {
1152     String tooltip = null;
1153     if (ann.graphGroup > -1)
1154     {
1155       StringBuilder tip = new StringBuilder(32);
1156       boolean first = true;
1157       for (int i = 0; i < anns.length; i++)
1158       {
1159         if (anns[i].graphGroup == ann.graphGroup
1160                 && anns[i].annotations[column] != null)
1161         {
1162           if (!first)
1163           {
1164             tip.append("<br>");
1165           }
1166           first = false;
1167           tip.append(anns[i].label);
1168           String description = anns[i].annotations[column].description;
1169           if (description != null && description.length() > 0)
1170           {
1171             tip.append(" ").append(description);
1172           }
1173         }
1174       }
1175       tooltip = first ? null : tip.toString();
1176     }
1177     else if (column < ann.annotations.length
1178             && ann.annotations[column] != null)
1179     {
1180       tooltip = ann.annotations[column].description;
1181     }
1182     // TODO abstract tooltip generator so different implementations can be built
1183     if (ann.graph == AlignmentAnnotation.CONTACT_MAP)
1184     {
1185       ContactListI clist = av.getContactList(ann, column);
1186       if (clist != null)
1187       {
1188         ContactGeometry cgeom = new ContactGeometry(clist, ann.graphHeight);
1189         ContactGeometry.contactInterval ci = cgeom.mapFor(rowAndOffset);
1190         ContactRange cr = clist.getRangeFor(ci.cStart, ci.cEnd);
1191         tooltip = "Contact from " + clist.getPosition() + ", [" + ci.cStart
1192                 + " - " + ci.cEnd + "]" + "<br/>Mean:" + cr.getMean();
1193         int col = ann.sequenceRef.findPosition(column);
1194         ap.getStructureSelectionManager()
1195                 .highlightPositionsOn(ann.sequenceRef, new int[][]
1196                 { new int[] { col, col },
1197                     new int[]
1198                     { ci.cStart, ci.cEnd } }, null);
1199       }
1200     }
1201     return tooltip;
1202   }
1203
1204   /**
1205    * Constructs and returns the status bar message
1206    * 
1207    * @param al
1208    * @param column
1209    * @param ann
1210    * @param rowAndOffset
1211    */
1212   static String getStatusMessage(AlignmentI al, int column,
1213           AlignmentAnnotation ann, int rowAndOffset, AlignViewportI av)
1214   {
1215     /*
1216      * show alignment column and annotation description if any
1217      */
1218     StringBuilder text = new StringBuilder(32);
1219     text.append(MessageManager.getString("label.column")).append(" ")
1220             .append(column + 1);
1221
1222     if (column < ann.annotations.length && ann.annotations[column] != null)
1223     {
1224       String description = ann.annotations[column].description;
1225       if (description != null && description.trim().length() > 0)
1226       {
1227         text.append("  ").append(description);
1228       }
1229     }
1230
1231     /*
1232      * if the annotation is sequence-specific, show the sequence number
1233      * in the alignment, and (if not a gap) the residue and position
1234      */
1235     SequenceI seqref = ann.sequenceRef;
1236     if (seqref != null)
1237     {
1238       int seqIndex = al.findIndex(seqref);
1239       if (seqIndex != -1)
1240       {
1241         text.append(", ").append(MessageManager.getString("label.sequence"))
1242                 .append(" ").append(seqIndex + 1);
1243         char residue = seqref.getCharAt(column);
1244         if (!Comparison.isGap(residue))
1245         {
1246           text.append(" ");
1247           String name;
1248           if (al.isNucleotide())
1249           {
1250             name = ResidueProperties.nucleotideName
1251                     .get(String.valueOf(residue));
1252             text.append(" Nucleotide: ")
1253                     .append(name != null ? name : residue);
1254           }
1255           else
1256           {
1257             name = 'X' == residue ? "X"
1258                     : ('*' == residue ? "STOP"
1259                             : ResidueProperties.aa2Triplet
1260                                     .get(String.valueOf(residue)));
1261             text.append(" Residue: ").append(name != null ? name : residue);
1262           }
1263           int residuePos = seqref.findPosition(column);
1264           text.append(" (").append(residuePos).append(")");
1265         }
1266       }
1267     }
1268
1269     return text.toString();
1270   }
1271
1272   /**
1273    * DOCUMENT ME!
1274    * 
1275    * @param evt
1276    *          DOCUMENT ME!
1277    */
1278   @Override
1279   public void mouseClicked(MouseEvent evt)
1280   {
1281     // if (activeRow != -1)
1282     // {
1283     // AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1284     // AlignmentAnnotation anot = aa[activeRow];
1285     // }
1286   }
1287
1288   // TODO mouseClicked-content and drawCursor are quite experimental!
1289   public void drawCursor(Graphics graphics, SequenceI seq, int res, int x1,
1290           int y1)
1291   {
1292     int pady = av.getCharHeight() / 5;
1293     int charOffset = 0;
1294     graphics.setColor(Color.black);
1295     graphics.fillRect(x1, y1, av.getCharWidth(), av.getCharHeight());
1296
1297     if (av.validCharWidth)
1298     {
1299       graphics.setColor(Color.white);
1300
1301       char s = seq.getCharAt(res);
1302
1303       charOffset = (av.getCharWidth() - fm.charWidth(s)) / 2;
1304       graphics.drawString(String.valueOf(s), charOffset + x1,
1305               (y1 + av.getCharHeight()) - pady);
1306     }
1307
1308   }
1309
1310   private volatile boolean imageFresh = false;
1311
1312   private Rectangle visibleRect = new Rectangle(),
1313           clipBounds = new Rectangle();
1314
1315   /**
1316    * DOCUMENT ME!
1317    * 
1318    * @param g
1319    *          DOCUMENT ME!
1320    */
1321   @Override
1322   public void paintComponent(Graphics g)
1323   {
1324
1325     // BH: note that this method is generally recommended to
1326     // call super.paintComponent(g). Otherwise, the children of this
1327     // component will not be rendered. That is not needed here
1328     // because AnnotationPanel does not have any children. It is
1329     // just a JPanel contained in a JViewPort.
1330
1331     computeVisibleRect(visibleRect);
1332
1333     g.setColor(Color.white);
1334     g.fillRect(0, 0, visibleRect.width, visibleRect.height);
1335
1336     if (image != null)
1337     {
1338       // BH 2018 optimizing generation of new Rectangle().
1339       if (fastPaint
1340               || (visibleRect.width != (clipBounds = g
1341                       .getClipBounds(clipBounds)).width)
1342               || (visibleRect.height != clipBounds.height))
1343       {
1344
1345         g.drawImage(image, 0, 0, this);
1346         fastPaint = false;
1347         return;
1348       }
1349     }
1350     imgWidth = (av.getRanges().getEndRes() - av.getRanges().getStartRes()
1351             + 1) * av.getCharWidth();
1352     if (imgWidth < 1)
1353     {
1354       return;
1355     }
1356     Graphics2D gg;
1357     if (image == null || imgWidth != image.getWidth(this)
1358             || image.getHeight(this) != getHeight())
1359     {
1360       boolean tried = false;
1361       image = null;
1362       while (image == null && !tried)
1363       {
1364         try
1365         {
1366           image = new BufferedImage(imgWidth,
1367                   ap.getAnnotationPanel().getHeight(),
1368                   BufferedImage.TYPE_INT_RGB);
1369           tried = true;
1370         } catch (IllegalArgumentException exc)
1371         {
1372           System.err.println(
1373                   "Serious issue with viewport geometry imgWidth requested was "
1374                           + imgWidth);
1375           return;
1376         } catch (OutOfMemoryError oom)
1377         {
1378           try
1379           {
1380             System.gc();
1381           } catch (Exception x)
1382           {
1383           }
1384           ;
1385           new OOMWarning(
1386                   "Couldn't allocate memory to redraw screen. Please restart Jalview",
1387                   oom);
1388           return;
1389         }
1390
1391       }
1392       gg = (Graphics2D) image.getGraphics();
1393
1394       if (av.antiAlias)
1395       {
1396         gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1397                 RenderingHints.VALUE_ANTIALIAS_ON);
1398       }
1399
1400       gg.setFont(av.getFont());
1401       fm = gg.getFontMetrics();
1402       gg.setColor(Color.white);
1403       gg.fillRect(0, 0, imgWidth, image.getHeight());
1404       imageFresh = true;
1405     }
1406     else
1407     {
1408       gg = (Graphics2D) image.getGraphics();
1409
1410     }
1411
1412     drawComponent(gg, av.getRanges().getStartRes(),
1413             av.getRanges().getEndRes() + 1);
1414     gg.dispose();
1415     imageFresh = false;
1416     g.drawImage(image, 0, 0, this);
1417   }
1418
1419   /**
1420    * set true to enable redraw timing debug output on stderr
1421    */
1422   private final boolean debugRedraw = false;
1423
1424   /**
1425    * non-Thread safe repaint
1426    * 
1427    * @param horizontal
1428    *          repaint with horizontal shift in alignment
1429    */
1430   public void fastPaint(int horizontal)
1431   {
1432     if ((horizontal == 0) || image == null
1433             || av.getAlignment().getAlignmentAnnotation() == null
1434             || av.getAlignment().getAlignmentAnnotation().length < 1
1435             || av.isCalcInProgress())
1436     {
1437       repaint();
1438       return;
1439     }
1440
1441     int sr = av.getRanges().getStartRes();
1442     int er = av.getRanges().getEndRes() + 1;
1443     int transX = 0;
1444
1445     Graphics2D gg = (Graphics2D) image.getGraphics();
1446
1447     if (imgWidth > Math.abs(horizontal * av.getCharWidth()))
1448     {
1449       // scroll is less than imgWidth away so can re-use buffered graphics
1450       gg.copyArea(0, 0, imgWidth, getHeight(),
1451               -horizontal * av.getCharWidth(), 0);
1452
1453       if (horizontal > 0) // scrollbar pulled right, image to the left
1454       {
1455         transX = (er - sr - horizontal) * av.getCharWidth();
1456         sr = er - horizontal;
1457       }
1458       else if (horizontal < 0)
1459       {
1460         er = sr - horizontal;
1461       }
1462     }
1463     gg.translate(transX, 0);
1464
1465     drawComponent(gg, sr, er);
1466
1467     gg.translate(-transX, 0);
1468
1469     gg.dispose();
1470
1471     fastPaint = true;
1472
1473     // Call repaint on alignment panel so that repaints from other alignment
1474     // panel components can be aggregated. Otherwise performance of the overview
1475     // window and others may be adversely affected.
1476     av.getAlignPanel().repaint();
1477   }
1478
1479   private volatile boolean lastImageGood = false;
1480
1481   /**
1482    * DOCUMENT ME!
1483    * 
1484    * @param g
1485    *          DOCUMENT ME!
1486    * @param startRes
1487    *          DOCUMENT ME!
1488    * @param endRes
1489    *          DOCUMENT ME!
1490    */
1491   public void drawComponent(Graphics g, int startRes, int endRes)
1492   {
1493     BufferedImage oldFaded = fadedImage;
1494     if (av.isCalcInProgress())
1495     {
1496       if (image == null)
1497       {
1498         lastImageGood = false;
1499         return;
1500       }
1501       // We'll keep a record of the old image,
1502       // and draw a faded image until the calculation
1503       // has completed
1504       if (lastImageGood
1505               && (fadedImage == null || fadedImage.getWidth() != imgWidth
1506                       || fadedImage.getHeight() != image.getHeight()))
1507       {
1508         // System.err.println("redraw faded image ("+(fadedImage==null ?
1509         // "null image" : "") + " lastGood="+lastImageGood+")");
1510         fadedImage = new BufferedImage(imgWidth, image.getHeight(),
1511                 BufferedImage.TYPE_INT_RGB);
1512
1513         Graphics2D fadedG = (Graphics2D) fadedImage.getGraphics();
1514
1515         fadedG.setColor(Color.white);
1516         fadedG.fillRect(0, 0, imgWidth, image.getHeight());
1517
1518         fadedG.setComposite(
1519                 AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .3f));
1520         fadedG.drawImage(image, 0, 0, this);
1521
1522       }
1523       // make sure we don't overwrite the last good faded image until all
1524       // calculations have finished
1525       lastImageGood = false;
1526
1527     }
1528     else
1529     {
1530       if (fadedImage != null)
1531       {
1532         oldFaded = fadedImage;
1533       }
1534       fadedImage = null;
1535     }
1536
1537     g.setColor(Color.white);
1538     g.fillRect(0, 0, (endRes - startRes) * av.getCharWidth(), getHeight());
1539
1540     g.setFont(av.getFont());
1541     if (fm == null)
1542     {
1543       fm = g.getFontMetrics();
1544     }
1545
1546     if ((av.getAlignment().getAlignmentAnnotation() == null)
1547             || (av.getAlignment().getAlignmentAnnotation().length < 1))
1548     {
1549       g.setColor(Color.white);
1550       g.fillRect(0, 0, getWidth(), getHeight());
1551       g.setColor(Color.black);
1552       if (av.validCharWidth)
1553       {
1554         g.drawString(MessageManager
1555                 .getString("label.alignment_has_no_annotations"), 20, 15);
1556       }
1557
1558       return;
1559     }
1560     lastImageGood = renderer.drawComponent(this, av, g, activeRow, startRes,
1561             endRes);
1562     if (!lastImageGood && fadedImage == null)
1563     {
1564       fadedImage = oldFaded;
1565     }
1566     if (dragMode == DragMode.MatrixSelect)
1567     {
1568       g.setColor(Color.yellow);
1569       g.drawRect(Math.min(firstDragX, mouseDragLastX),
1570               Math.min(firstDragY, mouseDragLastY),
1571               Math.max(firstDragX, mouseDragLastX)
1572                       - Math.min(firstDragX, mouseDragLastX),
1573               Math.max(firstDragY, mouseDragLastY)
1574                       - Math.min(firstDragY, mouseDragLastY));
1575
1576     }
1577   }
1578
1579   @Override
1580   public FontMetrics getFontMetrics()
1581   {
1582     return fm;
1583   }
1584
1585   @Override
1586   public Image getFadedImage()
1587   {
1588     return fadedImage;
1589   }
1590
1591   @Override
1592   public int getFadedImageWidth()
1593   {
1594     return imgWidth;
1595   }
1596
1597   private int[] bounds = new int[2];
1598
1599   @Override
1600   public int[] getVisibleVRange()
1601   {
1602     if (ap != null && ap.getAlabels() != null)
1603     {
1604       int sOffset = -ap.getAlabels().getScrollOffset();
1605       int visHeight = sOffset + ap.annotationSpaceFillerHolder.getHeight();
1606       bounds[0] = sOffset;
1607       bounds[1] = visHeight;
1608       return bounds;
1609     }
1610     else
1611     {
1612       return null;
1613     }
1614   }
1615
1616   /**
1617    * Try to ensure any references held are nulled
1618    */
1619   public void dispose()
1620   {
1621     av = null;
1622     ap = null;
1623     image = null;
1624     fadedImage = null;
1625     // gg = null;
1626     _mwl = null;
1627
1628     /*
1629      * I created the renderer so I will dispose of it
1630      */
1631     if (renderer != null)
1632     {
1633       renderer.dispose();
1634     }
1635   }
1636
1637   @Override
1638   public void propertyChange(PropertyChangeEvent evt)
1639   {
1640     // Respond to viewport range changes (e.g. alignment panel was scrolled)
1641     // Both scrolling and resizing change viewport ranges: scrolling changes
1642     // both start and end points, but resize only changes end values.
1643     // Here we only want to fastpaint on a scroll, with resize using a normal
1644     // paint, so scroll events are identified as changes to the horizontal or
1645     // vertical start value.
1646     if (evt.getPropertyName().equals(ViewportRanges.STARTRES))
1647     {
1648       fastPaint((int) evt.getNewValue() - (int) evt.getOldValue());
1649     }
1650     else if (evt.getPropertyName().equals(ViewportRanges.STARTRESANDSEQ))
1651     {
1652       fastPaint(((int[]) evt.getNewValue())[0]
1653               - ((int[]) evt.getOldValue())[0]);
1654     }
1655     else if (evt.getPropertyName().equals(ViewportRanges.MOVE_VIEWPORT))
1656     {
1657       repaint();
1658     }
1659   }
1660
1661   /**
1662    * computes the visible height of the annotation panel
1663    * 
1664    * @param adjustPanelHeight
1665    *          - when false, just adjust existing height according to other
1666    *          windows
1667    * @param annotationHeight
1668    * @return height to use for the ScrollerPreferredVisibleSize
1669    */
1670   public int adjustForAlignFrame(boolean adjustPanelHeight,
1671           int annotationHeight)
1672   {
1673     /*
1674      * Estimate available height in the AlignFrame for alignment +
1675      * annotations. Deduct an estimate for title bar, menu bar, scale panel,
1676      * hscroll, status bar, insets. 
1677      */
1678     int stuff = (ap.getViewName() != null ? 30 : 0)
1679             + (Platform.isAMacAndNotJS() ? 120 : 140);
1680     int availableHeight = ap.alignFrame.getHeight() - stuff;
1681     int rowHeight = av.getCharHeight();
1682
1683     if (adjustPanelHeight)
1684     {
1685       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
1686
1687       /*
1688        * If not enough vertical space, maximize annotation height while keeping
1689        * at least two rows of alignment visible
1690        */
1691       if (annotationHeight + alignmentHeight > availableHeight)
1692       {
1693         annotationHeight = Math.min(annotationHeight,
1694                 availableHeight - 2 * rowHeight);
1695       }
1696     }
1697     else
1698     {
1699       // maintain same window layout whilst updating sliders
1700       annotationHeight = Math.min(ap.annotationScroller.getSize().height,
1701               availableHeight - 2 * rowHeight);
1702     }
1703     return annotationHeight;
1704   }
1705 }