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