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