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