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