JAL-4274 Use Cache BITMAP_* if no other image restrictions given
[jalview.git] / src / jalview / gui / AlignmentPanel.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.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
27 import java.awt.Font;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
40 import java.io.File;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
44
45 import javax.swing.SwingUtilities;
46
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentAnnotation;
54 import jalview.datamodel.AlignmentI;
55 import jalview.datamodel.HiddenColumns;
56 import jalview.datamodel.SearchResultsI;
57 import jalview.datamodel.SequenceFeature;
58 import jalview.datamodel.SequenceGroup;
59 import jalview.datamodel.SequenceI;
60 import jalview.gui.ImageExporter.ImageWriterI;
61 import jalview.io.HTMLOutput;
62 import jalview.io.exceptions.ImageOutputException;
63 import jalview.jbgui.GAlignmentPanel;
64 import jalview.math.AlignmentDimension;
65 import jalview.schemes.ResidueProperties;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.ImageMaker;
69 import jalview.util.MessageManager;
70 import jalview.util.imagemaker.BitmapImageSizing;
71 import jalview.viewmodel.ViewportListenerI;
72 import jalview.viewmodel.ViewportRanges;
73
74 /**
75  * DOCUMENT ME!
76  * 
77  * @author $author$
78  * @version $Revision: 1.161 $
79  */
80 @SuppressWarnings("serial")
81 public class AlignmentPanel extends GAlignmentPanel implements
82         AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
83 {
84   /*
85    * spare space in pixels between sequence id and alignment panel
86    */
87   private static final int ID_WIDTH_PADDING = 4;
88
89   public AlignViewport av;
90
91   OverviewPanel overviewPanel;
92
93   private SeqPanel seqPanel;
94
95   private IdPanel idPanel;
96
97   IdwidthAdjuster idwidthAdjuster;
98
99   public AlignFrame alignFrame;
100
101   private ScalePanel scalePanel;
102
103   private AnnotationPanel annotationPanel;
104
105   private AnnotationLabels alabels;
106
107   private int hextent = 0;
108
109   private int vextent = 0;
110
111   /*
112    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
113    * false, suppresses invoking the same method recursively.
114    */
115   private boolean scrollComplementaryPanel = true;
116
117   private PropertyChangeListener propertyChangeListener;
118
119   private CalculationChooser calculationDialog;
120
121   /**
122    * Creates a new AlignmentPanel object.
123    * 
124    * @param af
125    * @param av
126    */
127   public AlignmentPanel(AlignFrame af, final AlignViewport av)
128   {
129     // setBackground(Color.white); // BH 2019
130     alignFrame = af;
131     this.av = av;
132     setSeqPanel(new SeqPanel(av, this));
133     setIdPanel(new IdPanel(av, this));
134
135     setScalePanel(new ScalePanel(av, this));
136
137     idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
138     idwidthAdjuster = new IdwidthAdjuster(this);
139     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
140
141     setAnnotationPanel(new AnnotationPanel(this));
142     setAlabels(new AnnotationLabels(this));
143
144     annotationScroller.setViewportView(getAnnotationPanel());
145     annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
146
147     scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
148     seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
149
150     setScrollValues(0, 0);
151
152     hscroll.addAdjustmentListener(this);
153     vscroll.addAdjustmentListener(this);
154
155     addComponentListener(new ComponentAdapter()
156     {
157       @Override
158       public void componentResized(ComponentEvent evt)
159       {
160         // reset the viewport ranges when the alignment panel is resized
161         // in particular, this initialises the end residue value when Jalview
162         // is initialised
163         ViewportRanges ranges = av.getRanges();
164         if (av.getWrapAlignment())
165         {
166           int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
167                   getSeqPanel().seqCanvas.getWidth());
168           ranges.setViewportWidth(widthInRes);
169         }
170         else
171         {
172           int widthInRes = getSeqPanel().seqCanvas.getWidth()
173                   / av.getCharWidth();
174           int heightInSeq = getSeqPanel().seqCanvas.getHeight()
175                   / av.getCharHeight();
176
177           ranges.setViewportWidth(widthInRes);
178           ranges.setViewportHeight(heightInSeq);
179         }
180       }
181
182     });
183
184     final AlignmentPanel ap = this;
185     propertyChangeListener = new PropertyChangeListener()
186     {
187       @Override
188       public void propertyChange(PropertyChangeEvent evt)
189       {
190         if (evt.getPropertyName().equals("alignment"))
191         {
192           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
193           alignmentChanged();
194         }
195       }
196     };
197     av.addPropertyChangeListener(propertyChangeListener);
198
199     av.getRanges().addPropertyChangeListener(this);
200     fontChanged();
201     adjustAnnotationHeight();
202     updateLayout();
203   }
204
205   @Override
206   public AlignViewportI getAlignViewport()
207   {
208     return av;
209   }
210
211   public void alignmentChanged()
212   {
213     av.alignmentChanged(this);
214
215     if (getCalculationDialog() != null)
216     {
217       getCalculationDialog().validateCalcTypes();
218     }
219
220     alignFrame.updateEditMenuBar();
221
222     // no idea if we need to update structure
223     paintAlignment(true, true);
224
225   }
226
227   /**
228    * DOCUMENT ME!
229    */
230   public void fontChanged()
231   {
232     // set idCanvas bufferedImage to null
233     // to prevent drawing old image
234     FontMetrics fm = getFontMetrics(av.getFont());
235
236     // update the flag controlling whether the grid is too small to render the
237     // font
238     av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
239
240     scalePanelHolder.setPreferredSize(
241             new Dimension(10, av.getCharHeight() + fm.getDescent()));
242     idSpaceFillerPanel1.setPreferredSize(
243             new Dimension(10, av.getCharHeight() + fm.getDescent()));
244     idwidthAdjuster.invalidate();
245     scalePanelHolder.invalidate();
246     // BH 2018 getIdPanel().getIdCanvas().gg = null;
247     getSeqPanel().seqCanvas.img = null;
248     getAnnotationPanel().adjustPanelHeight();
249
250     Dimension d = calculateIdWidth();
251     getIdPanel().getIdCanvas().setPreferredSize(d);
252     hscrollFillerPanel.setPreferredSize(d);
253
254     repaint();
255   }
256
257   /**
258    * Calculates the width of the alignment labels based on the displayed names
259    * and any bounds on label width set in preferences. The calculated width is
260    * also set as a property of the viewport.
261    * 
262    * @return Dimension giving the maximum width of the alignment label panel
263    *         that should be used.
264    */
265   public Dimension calculateIdWidth()
266   {
267     int oldWidth = av.getIdWidth();
268
269     // calculate sensible default width when no preference is available
270     Dimension r = null;
271     if (av.getIdWidth() < 0)
272     {
273       r = calculateDefaultAlignmentIdWidth();
274       av.setIdWidth(r.width);
275     }
276     else
277     {
278       r = new Dimension();
279       r.width = av.getIdWidth();
280       r.height = 0;
281     }
282
283     /*
284      * fudge: if desired width has changed, update layout
285      * (see also paintComponent - updates layout on a repaint)
286      */
287     if (r.width != oldWidth)
288     {
289       idPanelHolder.setPreferredSize(r);
290       validate();
291     }
292     return r;
293   }
294
295   public Dimension calculateDefaultAlignmentIdWidth()
296   {
297     int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
298     int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
299     int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
300     return calculateIdWidth(-1, false, false);
301   }
302
303   /**
304    * Calculate the width of the alignment labels based on the displayed names
305    * and any bounds on label width set in preferences.
306    * 
307    * @param maxwidth
308    *          -1 or maximum width allowed for IdWidth
309    * @return Dimension giving the maximum width of the alignment label panel
310    *         that should be used.
311    */
312   protected Dimension calculateIdWidth(int maxwidth)
313   {
314     return calculateIdWidth(maxwidth, true, false);
315   }
316
317   public Dimension calculateIdWidth(int maxwidth,
318           boolean includeAnnotations, boolean visibleOnly)
319   {
320     Container c = new Container();
321
322     FontMetrics fm = c.getFontMetrics(
323             new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
324
325     AlignmentI al = av.getAlignment();
326     int i = 0;
327     int idWidth = 0;
328
329     while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
330     {
331       SequenceI s = al.getSequenceAt(i);
332       String id = s.getDisplayId(av.getShowJVSuffix());
333       int stringWidth = fm.stringWidth(id);
334       idWidth = Math.max(idWidth, stringWidth);
335       i++;
336     }
337
338     // Also check annotation label widths
339     if (includeAnnotations && al.getAlignmentAnnotation() != null)
340     {
341       if (Jalview.isHeadlessMode())
342       {
343         AnnotationLabels aal = getAlabels();
344         int stringWidth = aal.drawLabels(null, false, idWidth, false, false,
345                 fm);
346         idWidth = Math.max(idWidth, stringWidth);
347       }
348       else
349       {
350         fm = c.getFontMetrics(getAlabels().getFont());
351
352         for (i = 0; i < al.getAlignmentAnnotation().length; i++)
353         {
354           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
355           if (visibleOnly && !aa.visible)
356           {
357             continue;
358           }
359           String label = aa.label;
360           int stringWidth = fm.stringWidth(label);
361           idWidth = Math.max(idWidth, stringWidth);
362         }
363       }
364     }
365
366     int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
367     w += ID_WIDTH_PADDING;
368
369     return new Dimension(w, 12);
370   }
371
372   /**
373    * Highlight the given results on the alignment
374    * 
375    */
376   public void highlightSearchResults(SearchResultsI results)
377   {
378     boolean scrolled = scrollToPosition(results, 0, false);
379
380     boolean fastPaint = !(scrolled && av.getWrapAlignment());
381
382     getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
383   }
384
385   /**
386    * Scroll the view to show the position of the highlighted region in results
387    * (if any)
388    * 
389    * @param searchResults
390    * @return
391    */
392   public boolean scrollToPosition(SearchResultsI searchResults)
393   {
394     return scrollToPosition(searchResults, 0, false);
395   }
396
397   /**
398    * Scrolls the view (if necessary) to show the position of the first
399    * highlighted region in results (if any). Answers true if the view was
400    * scrolled, or false if no matched region was found, or it is already
401    * visible.
402    * 
403    * @param results
404    * @param verticalOffset
405    *          if greater than zero, allows scrolling to a position below the
406    *          first displayed sequence
407    * @param centre
408    *          if true, try to centre the search results horizontally in the view
409    * @return
410    */
411   protected boolean scrollToPosition(SearchResultsI results,
412           int verticalOffset, boolean centre)
413   {
414     int startv, endv, starts, ends;
415     ViewportRanges ranges = av.getRanges();
416
417     if (results == null || results.isEmpty() || av == null
418             || av.getAlignment() == null)
419     {
420       return false;
421     }
422     int seqIndex = av.getAlignment().findIndex(results);
423     if (seqIndex == -1)
424     {
425       return false;
426     }
427     SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
428
429     int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
430     if (r == null)
431     {
432       return false;
433     }
434     int start = r[0];
435     int end = r[1];
436
437     /*
438      * To centre results, scroll to positions half the visible width
439      * left/right of the start/end positions
440      */
441     if (centre)
442     {
443       int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
444       start = Math.max(start - offset, 0);
445       end = end + offset - 1;
446     }
447     if (start < 0)
448     {
449       return false;
450     }
451     if (end == seq.getEnd())
452     {
453       return false;
454     }
455
456     if (av.hasHiddenColumns())
457     {
458       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
459       start = hidden.absoluteToVisibleColumn(start);
460       end = hidden.absoluteToVisibleColumn(end);
461       if (start == end)
462       {
463         if (!hidden.isVisible(r[0]))
464         {
465           // don't scroll - position isn't visible
466           return false;
467         }
468       }
469     }
470
471     /*
472      * allow for offset of target sequence (actually scroll to one above it)
473      */
474     seqIndex = Math.max(0, seqIndex - verticalOffset);
475     boolean scrollNeeded = true;
476
477     if (!av.getWrapAlignment())
478     {
479       if ((startv = ranges.getStartRes()) >= start)
480       {
481         /*
482          * Scroll left to make start of search results visible
483          */
484         setScrollValues(start, seqIndex);
485       }
486       else if ((endv = ranges.getEndRes()) <= end)
487       {
488         /*
489          * Scroll right to make end of search results visible
490          */
491         setScrollValues(startv + end - endv, seqIndex);
492       }
493       else if ((starts = ranges.getStartSeq()) > seqIndex)
494       {
495         /*
496          * Scroll up to make start of search results visible
497          */
498         setScrollValues(ranges.getStartRes(), seqIndex);
499       }
500       else if ((ends = ranges.getEndSeq()) <= seqIndex)
501       {
502         /*
503          * Scroll down to make end of search results visible
504          */
505         setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
506       }
507       /*
508        * Else results are already visible - no need to scroll
509        */
510       scrollNeeded = false;
511     }
512     else
513     {
514       scrollNeeded = ranges.scrollToWrappedVisible(start);
515     }
516
517     paintAlignment(false, false);
518
519     return scrollNeeded;
520   }
521
522   /**
523    * DOCUMENT ME!
524    * 
525    * @return DOCUMENT ME!
526    */
527   public OverviewPanel getOverviewPanel()
528   {
529     return overviewPanel;
530   }
531
532   /**
533    * DOCUMENT ME!
534    * 
535    * @param op
536    *          DOCUMENT ME!
537    */
538   public void setOverviewPanel(OverviewPanel op)
539   {
540     overviewPanel = op;
541   }
542
543   /**
544    * 
545    * @param b
546    *          Hide or show annotation panel
547    * 
548    */
549   public void setAnnotationVisible(boolean b)
550   {
551     if (!av.getWrapAlignment())
552     {
553       annotationSpaceFillerHolder.setVisible(b);
554       annotationScroller.setVisible(b);
555     }
556     repaint();
557   }
558
559   /**
560    * automatically adjust annotation panel height for new annotation whilst
561    * ensuring the alignment is still visible.
562    */
563   @Override
564   public void adjustAnnotationHeight()
565   {
566     // TODO: display vertical annotation scrollbar if necessary
567     // this is called after loading new annotation onto alignment
568     if (alignFrame.getHeight() == 0)
569     {
570       jalview.bin.Console.outPrintln("NEEDS FIXING");
571     }
572     validateAnnotationDimensions(true);
573     addNotify();
574     // TODO: many places call this method and also paintAlignment with various
575     // different settings. this means multiple redraws are triggered...
576     paintAlignment(true, av.needToUpdateStructureViews());
577   }
578
579   /**
580    * calculate the annotation dimensions and refresh slider values accordingly.
581    * need to do repaints/notifys afterwards.
582    */
583   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
584   {
585     // BH 2018.04.18 comment: addNotify() is not appropriate here. We
586     // are not changing ancestors, and keyboard action listeners do
587     // not need to be reset. addNotify() is a very expensive operation,
588     // requiring a full re-layout of all parents and children.
589     // Note in JComponent:
590     // This method is called by the toolkit internally and should
591     // not be called directly by programs.
592     // I note that addNotify() is called in several areas of Jalview.
593
594     AnnotationPanel ap = getAnnotationPanel();
595     int annotationHeight = ap.adjustPanelHeight();
596     annotationHeight = ap.adjustForAlignFrame(adjustPanelHeight,
597             annotationHeight);
598
599     hscroll.addNotify();
600     Dimension e = idPanel.getSize();
601     int idWidth = e.width;
602     boolean manuallyAdjusted = this.getIdPanel().getIdCanvas()
603             .manuallyAdjusted();
604     annotationScroller.setPreferredSize(new Dimension(
605             manuallyAdjusted ? idWidth : annotationScroller.getWidth(),
606             annotationHeight));
607
608     alabels.setPreferredSize(new Dimension(idWidth, annotationHeight));
609
610     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
611             manuallyAdjusted ? idWidth
612                     : annotationSpaceFillerHolder.getWidth(),
613             annotationHeight));
614     annotationScroller.validate();
615     annotationScroller.addNotify();
616     ap.validate();
617   }
618
619   /**
620    * update alignment layout for viewport settings
621    * 
622    * @param wrap
623    *          DOCUMENT ME!
624    */
625   public void updateLayout()
626   {
627     fontChanged();
628     setAnnotationVisible(av.isShowAnnotation());
629     boolean wrap = av.getWrapAlignment();
630     ViewportRanges ranges = av.getRanges();
631     ranges.setStartSeq(0);
632     // scalePanelHolder.setVisible(!wrap);
633     hscroll.setVisible(!wrap);
634     // Allow idPanel width adjustment in wrap mode
635     idwidthAdjuster.setVisible(true);
636
637     if (wrap)
638     {
639       annotationScroller.setVisible(false);
640       annotationSpaceFillerHolder.setVisible(false);
641     }
642     else if (av.isShowAnnotation())
643     {
644       annotationScroller.setVisible(true);
645       annotationSpaceFillerHolder.setVisible(true);
646       validateAnnotationDimensions(false);
647     }
648
649     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
650     if (canvasWidth > 0)
651     { // may not yet be laid out
652       if (wrap)
653       {
654         int widthInRes = getSeqPanel().seqCanvas
655                 .getWrappedCanvasWidth(canvasWidth);
656         ranges.setViewportWidth(widthInRes);
657       }
658       else
659       {
660         int widthInRes = (canvasWidth / av.getCharWidth());
661         int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
662                 / av.getCharHeight());
663
664         ranges.setViewportWidth(widthInRes);
665         ranges.setViewportHeight(heightInSeq);
666       }
667     }
668
669     // idSpaceFillerPanel1.setVisible(!wrap);
670
671     repaint();
672   }
673
674   /**
675    * Adjust row/column scrollers to show a visible position in the alignment.
676    * 
677    * @param x
678    *          visible column to scroll to
679    * @param y
680    *          visible row to scroll to
681    * 
682    */
683   public void setScrollValues(int xpos, int ypos)
684   {
685     int x = xpos;
686     int y = ypos;
687
688     if (av == null || av.getAlignment() == null)
689     {
690       return;
691     }
692
693     if (av.getWrapAlignment())
694     {
695       setScrollingForWrappedPanel(x);
696     }
697     else
698     {
699       int width = av.getAlignment().getVisibleWidth();
700       int height = av.getAlignment().getHeight();
701
702       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
703       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
704
705       if (hextent > width)
706       {
707         hextent = width;
708       }
709
710       if (vextent > height)
711       {
712         vextent = height;
713       }
714
715       if ((hextent + x) > width)
716       {
717         x = width - hextent;
718       }
719
720       if ((vextent + y) > height)
721       {
722         y = height - vextent;
723       }
724
725       if (y < 0)
726       {
727         y = 0;
728       }
729
730       if (x < 0)
731       {
732         x = 0;
733       }
734
735       // update the scroll values
736       hscroll.setValues(x, hextent, 0, width);
737       vscroll.setValues(y, vextent, 0, height);
738     }
739   }
740
741   /**
742    * Respond to adjustment event when horizontal or vertical scrollbar is
743    * changed
744    * 
745    * @param evt
746    *          adjustment event encoding whether hscroll or vscroll changed
747    */
748   @Override
749   public void adjustmentValueChanged(AdjustmentEvent evt)
750   {
751     if (av.getWrapAlignment())
752     {
753       adjustScrollingWrapped(evt);
754       return;
755     }
756
757     ViewportRanges ranges = av.getRanges();
758
759     if (evt.getSource() == hscroll)
760     {
761       int oldX = ranges.getStartRes();
762       int oldwidth = ranges.getViewportWidth();
763       int x = hscroll.getValue();
764       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
765
766       // if we're scrolling to the position we're already at, stop
767       // this prevents infinite recursion of events when the scroll/viewport
768       // ranges values are the same
769       if ((x == oldX) && (width == oldwidth))
770       {
771         return;
772       }
773       ranges.setViewportStartAndWidth(x, width);
774     }
775     else if (evt.getSource() == vscroll)
776     {
777       int oldY = ranges.getStartSeq();
778       int oldheight = ranges.getViewportHeight();
779       int y = vscroll.getValue();
780       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
781
782       // if we're scrolling to the position we're already at, stop
783       // this prevents infinite recursion of events when the scroll/viewport
784       // ranges values are the same
785       if ((y == oldY) && (height == oldheight))
786       {
787         return;
788       }
789       ranges.setViewportStartAndHeight(y, height);
790     }
791     repaint();
792   }
793
794   /**
795    * Responds to a scroll change by setting the start position of the viewport.
796    * Does
797    * 
798    * @param evt
799    */
800   protected void adjustScrollingWrapped(AdjustmentEvent evt)
801   {
802     if (evt.getSource() == hscroll)
803     {
804       return; // no horizontal scroll when wrapped
805     }
806     final ViewportRanges ranges = av.getRanges();
807
808     if (evt.getSource() == vscroll)
809     {
810       int newY = vscroll.getValue();
811
812       /*
813        * if we're scrolling to the position we're already at, stop
814        * this prevents infinite recursion of events when the scroll/viewport
815        * ranges values are the same
816        */
817       int oldX = ranges.getStartRes();
818       int oldY = ranges.getWrappedScrollPosition(oldX);
819       if (oldY == newY)
820       {
821         return;
822       }
823       if (newY > -1)
824       {
825         /*
826          * limit page up/down to one width's worth of positions
827          */
828         int rowSize = ranges.getViewportWidth();
829         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
830         ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
831       }
832     }
833     else
834     {
835       // This is only called if file loaded is a jar file that
836       // was wrapped when saved and user has wrap alignment true
837       // as preference setting
838       SwingUtilities.invokeLater(new Runnable()
839       {
840         @Override
841         public void run()
842         {
843           // When updating scrolling to use ViewportChange events, this code
844           // could not be validated and it is not clear if it is now being
845           // called. Log warning here in case it is called and unforeseen
846           // problems occur
847           Console.warn(
848                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
849
850           // scroll to start of panel
851           ranges.setStartRes(0);
852           ranges.setStartSeq(0);
853         }
854       });
855     }
856     repaint();
857   }
858
859   /* (non-Javadoc)
860    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
861    */
862   @Override
863   public void paintAlignment(boolean updateOverview,
864           boolean updateStructures)
865   {
866     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
867             av.isShowAutocalculatedAbove());
868     sorter.sort(getAlignment().getAlignmentAnnotation(),
869             av.getSortAnnotationsBy());
870     repaint();
871
872     if (updateStructures)
873     {
874       av.getStructureSelectionManager().sequenceColoursChanged(this);
875     }
876     if (updateOverview)
877     {
878
879       if (overviewPanel != null)
880       {
881         overviewPanel.updateOverviewImage();
882       }
883     }
884   }
885
886   @Override
887   public void paintComponent(Graphics g)
888   {
889     invalidate(); // needed so that the id width adjuster works correctly
890     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
891     int idWidth = d.width;
892
893     // check wrapped alignment as at least 1 residue width
894     if (av.getWrapAlignment())
895     {
896       SeqCanvas sc = this.getSeqPanel().seqCanvas;
897       if (sc != null && sc.getWidth() < sc.getMinimumWrappedCanvasWidth())
898       {
899         // need to make some adjustments
900         idWidth -= (sc.getMinimumWrappedCanvasWidth() - sc.getWidth());
901         av.setIdWidth(idWidth);
902         av.getAlignPanel().getIdPanel().getIdCanvas()
903                 .setManuallyAdjusted(true);
904
905         validateAnnotationDimensions(false);
906       }
907     }
908
909     idPanelHolder.setPreferredSize(new Dimension(idWidth, d.height));
910     hscrollFillerPanel.setPreferredSize(new Dimension(idWidth, 12));
911
912     validate(); // needed so that the id width adjuster works correctly
913
914     /*
915      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
916      * though I still think this call should be elsewhere.
917      */
918     ViewportRanges ranges = av.getRanges();
919     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
920     super.paintComponent(g);
921   }
922
923   /**
924    * Set vertical scroll bar position, and number of increments, for wrapped
925    * panel
926    * 
927    * @param topLeftColumn
928    *          the column position at top left (0..)
929    */
930   private void setScrollingForWrappedPanel(int topLeftColumn)
931   {
932     ViewportRanges ranges = av.getRanges();
933     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
934     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
935
936     /*
937      * a scrollbar's value can be set to at most (maximum-extent)
938      * so we add extent (1) to the maxScroll value
939      */
940     vscroll.setUnitIncrement(1);
941     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
942   }
943
944   /**
945    * DOCUMENT ME!
946    * 
947    * @param pg
948    *          DOCUMENT ME!
949    * @param pf
950    *          DOCUMENT ME!
951    * @param pi
952    *          DOCUMENT ME!
953    * 
954    * @return DOCUMENT ME!
955    * 
956    * @throws PrinterException
957    *           DOCUMENT ME!
958    */
959   @Override
960   public int print(Graphics pg, PageFormat pf, int pi)
961           throws PrinterException
962   {
963     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
964
965     int pwidth = (int) pf.getImageableWidth();
966     int pheight = (int) pf.getImageableHeight();
967
968     if (av.getWrapAlignment())
969     {
970       return printWrappedAlignment(pwidth, pheight, pi, pg);
971     }
972     else
973     {
974       return printUnwrapped(pwidth, pheight, pi, pg, pg);
975     }
976   }
977
978   /**
979    * Draws the alignment image, including sequence ids, sequences, and
980    * annotation labels and annotations if shown, on either one or two Graphics
981    * contexts.
982    * 
983    * @param pageWidth
984    *          in pixels
985    * @param pageHeight
986    *          in pixels
987    * @param pageIndex
988    *          (0, 1, ...)
989    * @param idGraphics
990    *          the graphics context for sequence ids and annotation labels
991    * @param alignmentGraphics
992    *          the graphics context for sequences and annotations (may or may not
993    *          be the same context as idGraphics)
994    * @return
995    * @throws PrinterException
996    */
997   public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
998           Graphics idGraphics, Graphics alignmentGraphics)
999           throws PrinterException
1000   {
1001     final int idWidth = getVisibleIdWidth(false);
1002
1003     /*
1004      * Get the horizontal offset to where we draw the sequences.
1005      * This is idWidth if using a single Graphics context, else zero.
1006      */
1007     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
1008             : idWidth;
1009
1010     FontMetrics fm = getFontMetrics(av.getFont());
1011     final int charHeight = av.getCharHeight();
1012     final int scaleHeight = charHeight + fm.getDescent();
1013
1014     idGraphics.setColor(Color.white);
1015     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
1016     idGraphics.setFont(av.getFont());
1017
1018     /*
1019      * How many sequences and residues can we fit on a printable page?
1020      */
1021     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1022
1023     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1024
1025     final int alignmentWidth = av.getAlignment().getVisibleWidth();
1026     int pagesWide = (alignmentWidth / totalRes) + 1;
1027
1028     final int startRes = (pageIndex % pagesWide) * totalRes;
1029     final int endRes = Math.min(startRes + totalRes - 1,
1030             alignmentWidth - 1);
1031
1032     final int startSeq = (pageIndex / pagesWide) * totalSeq;
1033     final int alignmentHeight = av.getAlignment().getHeight();
1034     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
1035
1036     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1037
1038     if (av.isShowAnnotation())
1039     {
1040       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1041     }
1042
1043     pagesHigh /= pageHeight;
1044
1045     if (pageIndex >= (pagesWide * pagesHigh))
1046     {
1047       return Printable.NO_SUCH_PAGE;
1048     }
1049     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1050
1051     /*
1052      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1053      */
1054     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1055     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1056             pageWidth - idWidth, scaleHeight);
1057     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1058
1059     /*
1060      * Draw the sequence ids, offset for scale height,
1061      * then reset to top left (0, 0)
1062      */
1063     idGraphics.translate(0, scaleHeight);
1064     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1065     List<SequenceI> selection = av.getSelectionGroup() == null ? null
1066             : av.getSelectionGroup().getSequences(null);
1067     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1068             selection, false);
1069
1070     idGraphics.setFont(av.getFont());
1071     idGraphics.translate(0, -scaleHeight);
1072
1073     /*
1074      * draw the sequences, offset for scale height, and id width (if using a
1075      * single graphics context), then reset to (0, scale height)
1076      */
1077     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1078     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1079             startRes, endRes, startSeq, endSeq - 1);
1080     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1081
1082     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1083     {
1084       /*
1085        * draw annotation labels; drawComponent() translates by
1086        * getScrollOffset(), so compensate for that first;
1087        * then reset to (0, scale height)
1088        */
1089       int offset = getAlabels().getScrollOffset();
1090       idGraphics.translate(0, -offset);
1091       idGraphics.translate(0, alignmentDrawnHeight);
1092       getAlabels().drawComponentNotGUI(idGraphics, idWidth);
1093       idGraphics.translate(0, -alignmentDrawnHeight);
1094
1095       /*
1096        * draw the annotations starting at 
1097        * (idOffset, alignmentHeight) from (0, scaleHeight)
1098        */
1099       alignmentGraphics.translate(alignmentGraphicsOffset,
1100               alignmentDrawnHeight);
1101       updateLayout();
1102       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1103               alignmentGraphics, -1, startRes, endRes + 1);
1104     }
1105
1106     return Printable.PAGE_EXISTS;
1107   }
1108
1109   /**
1110    * Prints one page of an alignment in wrapped mode. Returns
1111    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1112    * no page could be drawn (page number out of range).
1113    * 
1114    * @param pageWidth
1115    * @param pageHeight
1116    * @param pageNumber
1117    *          (0, 1, ...)
1118    * @param g
1119    * 
1120    * @return
1121    * 
1122    * @throws PrinterException
1123    */
1124   public int printWrappedAlignment(int pageWidth, int pageHeight,
1125           int pageNumber, Graphics g) throws PrinterException
1126   {
1127     getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1128             getHeight());
1129     int annotationHeight = 0;
1130     if (av.isShowAnnotation())
1131     {
1132       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1133     }
1134
1135     int hgap = av.getCharHeight();
1136     if (av.getScaleAboveWrapped())
1137     {
1138       hgap += av.getCharHeight();
1139     }
1140
1141     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1142             + annotationHeight;
1143
1144     int idWidth = getVisibleIdWidth(false);
1145
1146     int maxwidth = av.getAlignment().getVisibleWidth();
1147
1148     int resWidth = getSeqPanel().seqCanvas
1149             .getWrappedCanvasWidth(pageWidth - idWidth);
1150     av.getRanges().setViewportStartAndWidth(0, resWidth);
1151
1152     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1153
1154     g.setColor(Color.white);
1155     g.fillRect(0, 0, pageWidth, pageHeight);
1156     g.setFont(av.getFont());
1157     g.setColor(Color.black);
1158
1159     /*
1160      * method: print the whole wrapped alignment, but with a clip region that
1161      * is restricted to the requested page; this supports selective print of 
1162      * single pages or ranges, (at the cost of repeated processing in the 
1163      * 'normal' case, when all pages are printed)
1164      */
1165     g.translate(0, -pageNumber * pageHeight);
1166
1167     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1168
1169     /*
1170      * draw sequence ids and annotation labels (if shown)
1171      */
1172     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1173     idCanvas.drawIdsWrappedNoGUI((Graphics2D) g, av, 0, totalHeight);
1174
1175     g.translate(idWidth, 0);
1176
1177     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1178             pageWidth - idWidth, totalHeight, 0);
1179
1180     if ((pageNumber * pageHeight) < totalHeight)
1181     {
1182       return Printable.PAGE_EXISTS;
1183     }
1184     else
1185     {
1186       return Printable.NO_SUCH_PAGE;
1187     }
1188   }
1189
1190   /**
1191    * get current sequence ID panel width, or nominal value if panel were to be
1192    * displayed using default settings
1193    * 
1194    * @return
1195    */
1196   public int getVisibleIdWidth()
1197   {
1198     return getVisibleIdWidth(true);
1199   }
1200
1201   /**
1202    * get current sequence ID panel width, or nominal value if panel were to be
1203    * displayed using default settings
1204    * 
1205    * @param onscreen
1206    *          indicate if the Id width for onscreen or offscreen display should
1207    *          be returned
1208    * @return
1209    */
1210   protected int getVisibleIdWidth(boolean onscreen)
1211   {
1212     // see if rendering offscreen - check preferences and calc width accordingly
1213     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1214     {
1215       return calculateIdWidth(-1).width;
1216     }
1217     Integer idwidth = onscreen ? null
1218             : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1219     if (idwidth != null)
1220     {
1221       return idwidth.intValue() + ID_WIDTH_PADDING;
1222     }
1223
1224     int w = getIdPanel().getWidth();
1225     w = this.calculateIdWidth(-1, true, true).width;
1226     return (w > 0 ? w : calculateIdWidth().width);
1227   }
1228
1229   void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1230           throws ImageOutputException
1231   {
1232     makeAlignmentImage(type, file, renderer,
1233             BitmapImageSizing.defaultBitmapImageSizing());
1234   }
1235
1236   /**
1237    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1238    * writes it to the specified file
1239    * 
1240    * @param type
1241    * @param file
1242    * @param textrenderer
1243    * @param bitmapscale
1244    */
1245   void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1246           BitmapImageSizing userBis) throws ImageOutputException
1247   {
1248     final int borderBottomOffset = 5;
1249
1250     AlignmentDimension aDimension = getAlignmentDimension();
1251
1252     // todo use a lambda function in place of callback here?
1253     ImageWriterI writer = new ImageWriterI()
1254     {
1255       @Override
1256       public void exportImage(Graphics graphics) throws Exception
1257       {
1258         if (av.getWrapAlignment())
1259         {
1260           printWrappedAlignment(aDimension.getWidth(),
1261                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1262         }
1263         else
1264         {
1265           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1266                   graphics, graphics);
1267         }
1268       }
1269     };
1270
1271     String fileTitle = alignFrame.getTitle();
1272     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1273             fileTitle);
1274     int imageWidth = aDimension.getWidth();
1275     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1276     String of = MessageManager.getString("label.alignment");
1277     exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1278             userBis);
1279   }
1280
1281   /**
1282    * Calculates and returns a suitable width and height (in pixels) for an
1283    * exported image
1284    * 
1285    * @return
1286    */
1287   public AlignmentDimension getAlignmentDimension()
1288   {
1289     int maxwidth = av.getAlignment().getVisibleWidth();
1290
1291     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1292             + getScalePanel().getHeight();
1293     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1294
1295     if (av.getWrapAlignment())
1296     {
1297       height = getWrappedHeight();
1298       if (Jalview.isHeadlessMode())
1299       {
1300         // need to obtain default alignment width and then add in any
1301         // additional allowance for id margin
1302         // this duplicates the calculation in getWrappedHeight but adjusts for
1303         // offscreen idWith
1304         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1305                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1306                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1307       }
1308       else
1309       {
1310         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1311       }
1312
1313     }
1314     else if (av.isShowAnnotation())
1315     {
1316       height += getAnnotationPanel().adjustPanelHeight() + 3;
1317     }
1318     return new AlignmentDimension(width, height);
1319
1320   }
1321
1322   public void makePNGImageMap(File imgMapFile, String imageName)
1323           throws ImageOutputException
1324   {
1325     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1326     // ////////////////////////////////////////////
1327     int idWidth = getVisibleIdWidth(false);
1328     FontMetrics fm = getFontMetrics(av.getFont());
1329     int scaleHeight = av.getCharHeight() + fm.getDescent();
1330
1331     // Gen image map
1332     // ////////////////////////////////
1333     if (imgMapFile != null)
1334     {
1335       try
1336       {
1337         int sSize = av.getAlignment().getHeight();
1338         int alwidth = av.getAlignment().getWidth();
1339         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1340         out.println(HTMLOutput.getImageMapHTML());
1341         out.println("<img src=\"" + imageName
1342                 + "\" border=\"0\" usemap=\"#Map\" >"
1343                 + "<map name=\"Map\">");
1344
1345         for (int s = 0; s < sSize; s++)
1346         {
1347           int sy = s * av.getCharHeight() + scaleHeight;
1348
1349           SequenceI seq = av.getAlignment().getSequenceAt(s);
1350           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1351           for (int column = 0; column < alwidth; column++)
1352           {
1353             StringBuilder text = new StringBuilder(512);
1354             String triplet = null;
1355             if (av.getAlignment().isNucleotide())
1356             {
1357               triplet = ResidueProperties.nucleotideName
1358                       .get(seq.getCharAt(column) + "");
1359             }
1360             else
1361             {
1362               triplet = ResidueProperties.aa2Triplet
1363                       .get(seq.getCharAt(column) + "");
1364             }
1365
1366             if (triplet == null)
1367             {
1368               continue;
1369             }
1370
1371             int seqPos = seq.findPosition(column);
1372             int gSize = groups.length;
1373             for (int g = 0; g < gSize; g++)
1374             {
1375               if (text.length() < 1)
1376               {
1377                 text.append("<area shape=\"rect\" coords=\"")
1378                         .append((idWidth + column * av.getCharWidth()))
1379                         .append(",").append(sy).append(",")
1380                         .append((idWidth
1381                                 + (column + 1) * av.getCharWidth()))
1382                         .append(",").append((av.getCharHeight() + sy))
1383                         .append("\"").append(" onMouseOver=\"toolTip('")
1384                         .append(seqPos).append(" ").append(triplet);
1385               }
1386
1387               if (groups[g].getStartRes() < column
1388                       && groups[g].getEndRes() > column)
1389               {
1390                 text.append("<br><em>").append(groups[g].getName())
1391                         .append("</em>");
1392               }
1393             }
1394
1395             if (text.length() < 1)
1396             {
1397               text.append("<area shape=\"rect\" coords=\"")
1398                       .append((idWidth + column * av.getCharWidth()))
1399                       .append(",").append(sy).append(",")
1400                       .append((idWidth + (column + 1) * av.getCharWidth()))
1401                       .append(",").append((av.getCharHeight() + sy))
1402                       .append("\"").append(" onMouseOver=\"toolTip('")
1403                       .append(seqPos).append(" ").append(triplet);
1404             }
1405             if (!Comparison.isGap(seq.getCharAt(column)))
1406             {
1407               List<SequenceFeature> features = seq.findFeatures(column,
1408                       column);
1409               for (SequenceFeature sf : features)
1410               {
1411                 if (sf.isContactFeature())
1412                 {
1413                   text.append("<br>").append(sf.getType()).append(" ")
1414                           .append(sf.getBegin()).append(":")
1415                           .append(sf.getEnd());
1416                 }
1417                 else
1418                 {
1419                   text.append("<br>");
1420                   text.append(sf.getType());
1421                   String description = sf.getDescription();
1422                   if (description != null
1423                           && !sf.getType().equals(description))
1424                   {
1425                     description = description.replace("\"", "&quot;");
1426                     text.append(" ").append(description);
1427                   }
1428                 }
1429                 String status = sf.getStatus();
1430                 if (status != null && !"".equals(status))
1431                 {
1432                   text.append(" (").append(status).append(")");
1433                 }
1434               }
1435               if (text.length() > 1)
1436               {
1437                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1438                 out.println(text.toString());
1439               }
1440             }
1441           }
1442         }
1443         out.println("</map></body></html>");
1444         out.close();
1445
1446       } catch (Exception ex)
1447       {
1448         throw new ImageOutputException(
1449                 "couldn't write ImageMap due to unexpected error", ex);
1450       }
1451     } // /////////END OF IMAGE MAP
1452
1453   }
1454
1455   /**
1456    * Answers the height of the entire alignment in pixels, assuming it is in
1457    * wrapped mode
1458    * 
1459    * @return
1460    */
1461   int getWrappedHeight()
1462   {
1463     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1464
1465     if (Jalview.isHeadlessMode())
1466     {
1467       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1468               - vscroll.getPreferredSize().width
1469               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1470     }
1471
1472     int chunkWidth = getSeqPanel().seqCanvas
1473             .getWrappedCanvasWidth(seqPanelWidth);
1474
1475     int hgap = av.getCharHeight();
1476     if (av.getScaleAboveWrapped())
1477     {
1478       hgap += av.getCharHeight();
1479     }
1480
1481     int annotationHeight = 0;
1482     if (av.isShowAnnotation())
1483     {
1484       hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1485       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1486     }
1487
1488     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1489             + annotationHeight;
1490
1491     int maxwidth = av.getAlignment().getWidth();
1492     if (av.hasHiddenColumns())
1493     {
1494       maxwidth = av.getAlignment().getHiddenColumns()
1495               .absoluteToVisibleColumn(maxwidth) - 1;
1496     }
1497
1498     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1499
1500     return height;
1501   }
1502
1503   /**
1504    * close the panel - deregisters all listeners and nulls any references to
1505    * alignment data.
1506    */
1507   public void closePanel()
1508   {
1509     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1510     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1511     PaintRefresher.RemoveComponent(this);
1512
1513     closeChildFrames();
1514
1515     /*
1516      * try to ensure references are nulled
1517      */
1518     if (annotationPanel != null)
1519     {
1520       annotationPanel.dispose();
1521       annotationPanel = null;
1522     }
1523
1524     if (av != null)
1525     {
1526       av.removePropertyChangeListener(propertyChangeListener);
1527       propertyChangeListener = null;
1528       StructureSelectionManager ssm = av.getStructureSelectionManager();
1529       ssm.removeStructureViewerListener(getSeqPanel(), null);
1530       ssm.removeSelectionListener(getSeqPanel());
1531       ssm.removeCommandListener(av);
1532       ssm.removeStructureViewerListener(getSeqPanel(), null);
1533       ssm.removeSelectionListener(getSeqPanel());
1534       av.dispose();
1535       av = null;
1536     }
1537     else
1538     {
1539       if (Console.isDebugEnabled())
1540       {
1541         Console.warn("Closing alignment panel which is already closed.");
1542       }
1543     }
1544   }
1545
1546   /**
1547    * Close any open dialogs that would be orphaned when this one is closed
1548    */
1549   protected void closeChildFrames()
1550   {
1551     if (overviewPanel != null)
1552     {
1553       overviewPanel.dispose();
1554       overviewPanel = null;
1555     }
1556     if (calculationDialog != null)
1557     {
1558       calculationDialog.closeFrame();
1559       calculationDialog = null;
1560     }
1561   }
1562
1563   /**
1564    * hides or shows dynamic annotation rows based on groups and av state flags
1565    */
1566   public void updateAnnotation()
1567   {
1568     updateAnnotation(false, false);
1569   }
1570
1571   public void updateAnnotation(boolean applyGlobalSettings)
1572   {
1573     updateAnnotation(applyGlobalSettings, false);
1574   }
1575
1576   public void updateAnnotation(boolean applyGlobalSettings,
1577           boolean preserveNewGroupSettings)
1578   {
1579     av.updateGroupAnnotationSettings(applyGlobalSettings,
1580             preserveNewGroupSettings);
1581     adjustAnnotationHeight();
1582   }
1583
1584   @Override
1585   public AlignmentI getAlignment()
1586   {
1587     return av == null ? null : av.getAlignment();
1588   }
1589
1590   @Override
1591   public String getViewName()
1592   {
1593     return av.getViewName();
1594   }
1595
1596   /**
1597    * Make/Unmake this alignment panel the current input focus
1598    * 
1599    * @param b
1600    */
1601   public void setSelected(boolean b)
1602   {
1603     try
1604     {
1605       if (alignFrame.getSplitViewContainer() != null)
1606       {
1607         /*
1608          * bring enclosing SplitFrame to front first if there is one
1609          */
1610         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1611       }
1612       alignFrame.setSelected(b);
1613     } catch (Exception ex)
1614     {
1615     }
1616     if (b)
1617     {
1618       setAlignFrameView();
1619     }
1620   }
1621
1622   public void setAlignFrameView()
1623   {
1624     alignFrame.setDisplayedView(this);
1625   }
1626
1627   @Override
1628   public StructureSelectionManager getStructureSelectionManager()
1629   {
1630     return av.getStructureSelectionManager();
1631   }
1632
1633   @Override
1634   public void raiseOOMWarning(String string, OutOfMemoryError error)
1635   {
1636     new OOMWarning(string, error, this);
1637   }
1638
1639   @Override
1640   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1641   {
1642
1643     return new FeatureRenderer(this);
1644   }
1645
1646   @Override
1647   public jalview.api.FeatureRenderer getFeatureRenderer()
1648   {
1649     return seqPanel.seqCanvas.getFeatureRenderer();
1650   }
1651
1652   public void updateFeatureRenderer(
1653           jalview.renderer.seqfeatures.FeatureRenderer fr)
1654   {
1655     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1656   }
1657
1658   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1659   {
1660     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1661     {
1662       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1663     }
1664   }
1665
1666   public ScalePanel getScalePanel()
1667   {
1668     return scalePanel;
1669   }
1670
1671   public void setScalePanel(ScalePanel scalePanel)
1672   {
1673     this.scalePanel = scalePanel;
1674   }
1675
1676   public SeqPanel getSeqPanel()
1677   {
1678     return seqPanel;
1679   }
1680
1681   public void setSeqPanel(SeqPanel seqPanel)
1682   {
1683     this.seqPanel = seqPanel;
1684   }
1685
1686   public AnnotationPanel getAnnotationPanel()
1687   {
1688     return annotationPanel;
1689   }
1690
1691   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1692   {
1693     this.annotationPanel = annotationPanel;
1694   }
1695
1696   public AnnotationLabels getAlabels()
1697   {
1698     return alabels;
1699   }
1700
1701   public void setAlabels(AnnotationLabels alabels)
1702   {
1703     this.alabels = alabels;
1704   }
1705
1706   public IdPanel getIdPanel()
1707   {
1708     return idPanel;
1709   }
1710
1711   public void setIdPanel(IdPanel idPanel)
1712   {
1713     this.idPanel = idPanel;
1714   }
1715
1716   /**
1717    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1718    * The aim is to keep the two alignments 'lined up' on their centre columns.
1719    * 
1720    * @param sr
1721    *          holds mapped region(s) of this alignment that we are scrolling
1722    *          'to'; may be modified for sequence offset by this method
1723    * @param verticalOffset
1724    *          the number of visible sequences to show above the mapped region
1725    */
1726   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1727   {
1728     scrollToPosition(sr, verticalOffset, true);
1729   }
1730
1731   /**
1732    * Set a flag to say do not scroll any (cDNA/protein) complement.
1733    * 
1734    * @param b
1735    */
1736   protected void setToScrollComplementPanel(boolean b)
1737   {
1738     this.scrollComplementaryPanel = b;
1739   }
1740
1741   /**
1742    * Get whether to scroll complement panel
1743    * 
1744    * @return true if cDNA/protein complement panels should be scrolled
1745    */
1746   protected boolean isSetToScrollComplementPanel()
1747   {
1748     return this.scrollComplementaryPanel;
1749   }
1750
1751   /**
1752    * Redraw sensibly.
1753    * 
1754    * @adjustHeight if true, try to recalculate panel height for visible
1755    *               annotations
1756    */
1757   protected void refresh(boolean adjustHeight)
1758   {
1759     validateAnnotationDimensions(adjustHeight);
1760     addNotify();
1761     if (adjustHeight)
1762     {
1763       // sort, repaint, update overview
1764       paintAlignment(true, false);
1765     }
1766     else
1767     {
1768       // lightweight repaint
1769       repaint();
1770     }
1771   }
1772
1773   @Override
1774   /**
1775    * Property change event fired when a change is made to the viewport ranges
1776    * object associated with this alignment panel's viewport
1777    */
1778   public void propertyChange(PropertyChangeEvent evt)
1779   {
1780     // update this panel's scroll values based on the new viewport ranges values
1781     ViewportRanges ranges = av.getRanges();
1782     int x = ranges.getStartRes();
1783     int y = ranges.getStartSeq();
1784     setScrollValues(x, y);
1785
1786     // now update any complementary alignment (its viewport ranges object
1787     // is different so does not get automatically updated)
1788     if (isSetToScrollComplementPanel())
1789     {
1790       setToScrollComplementPanel(false);
1791       av.scrollComplementaryAlignment();
1792       setToScrollComplementPanel(true);
1793     }
1794   }
1795
1796   /**
1797    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1798    * reference should be nulled when the dialog is closed.
1799    * 
1800    * @param calculationChooser
1801    */
1802   public void setCalculationDialog(CalculationChooser calculationChooser)
1803   {
1804     calculationDialog = calculationChooser;
1805   }
1806
1807   /**
1808    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1809    * if none is open)
1810    */
1811   public CalculationChooser getCalculationDialog()
1812   {
1813     return calculationDialog;
1814   }
1815
1816   /**
1817    * Constructs and sets the title for the Overview window (if there is one),
1818    * including the align frame's title, and view name (if applicable). Returns
1819    * the title, or null if this panel has no Overview window open.
1820    * 
1821    * @param alignFrame
1822    * @return
1823    */
1824   public String setOverviewTitle(AlignFrame alignFrame)
1825   {
1826     if (this.overviewPanel == null)
1827     {
1828       return null;
1829     }
1830     String overviewTitle = MessageManager
1831             .formatMessage("label.overview_params", new Object[]
1832             { alignFrame.getTitle() });
1833     String viewName = getViewName();
1834     if (viewName != null)
1835     {
1836       overviewTitle += (" " + viewName);
1837     }
1838     overviewPanel.setTitle(overviewTitle);
1839     return overviewTitle;
1840   }
1841
1842   /**
1843    * If this alignment panel has an Overview panel open, closes it
1844    */
1845   public void closeOverviewPanel()
1846   {
1847     if (overviewPanel != null)
1848     {
1849       overviewPanel.close();
1850       overviewPanel = null;
1851     }
1852   }
1853
1854 }