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