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