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