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