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