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