spike branch updated from latest features/JAL-2446
[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,
76         ViewportListenerI
77 {
78   public AlignViewport av;
79
80   ViewportRanges vpRanges;
81
82   OverviewPanel overviewPanel;
83
84   private SeqPanel seqPanel;
85
86   private IdPanel idPanel;
87
88   private boolean headless;
89
90   IdwidthAdjuster idwidthAdjuster;
91
92   /** DOCUMENT ME!! */
93   public AlignFrame alignFrame;
94
95   private ScalePanel scalePanel;
96
97   private AnnotationPanel annotationPanel;
98
99   private AnnotationLabels alabels;
100
101   // this value is set false when selection area being dragged
102   boolean fastPaint = true;
103
104   private int hextent = 0;
105
106   private int vextent = 0;
107
108   /*
109    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
110    * false, suppresses invoking the same method recursively.
111    */
112   private boolean scrollComplementaryPanel = true;
113
114   private PropertyChangeListener propertyChangeListener;
115
116   private CalculationChooser calculationDialog;
117
118   /**
119    * Creates a new AlignmentPanel object.
120    * 
121    * @param af
122    * @param av
123    */
124   public AlignmentPanel(AlignFrame af, final AlignViewport av)
125   {
126     alignFrame = af;
127     this.av = av;
128     vpRanges = av.getRanges();
129     setSeqPanel(new SeqPanel(av, this));
130     setIdPanel(new IdPanel(av, this));
131
132     setScalePanel(new ScalePanel(av, this));
133
134     idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
135     idwidthAdjuster = new IdwidthAdjuster(this);
136     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
137
138     setAnnotationPanel(new AnnotationPanel(this));
139     setAlabels(new AnnotationLabels(this));
140
141     annotationScroller.setViewportView(getAnnotationPanel());
142     annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
143
144     scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
145     seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
146
147     setScrollValues(0, 0);
148
149     hscroll.addAdjustmentListener(this);
150     vscroll.addAdjustmentListener(this);
151
152     addComponentListener(new ComponentAdapter()
153     {
154       @Override
155       public void componentResized(ComponentEvent evt)
156       {
157         // reset the viewport ranges when the alignment panel is resized
158         // in particular, this initialises the end residue value when Jalview
159         // is initialised
160         if (av.getWrapAlignment())
161         {
162           int widthInRes = getSeqPanel().seqCanvas
163                   .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
164           vpRanges.setViewportWidth(widthInRes);
165         }
166         else
167         {
168           int widthInRes = getSeqPanel().seqCanvas.getWidth()
169                   / av.getCharWidth();
170           int heightInSeq = getSeqPanel().seqCanvas.getHeight()
171                   / av.getCharHeight();
172           
173           vpRanges.setViewportWidth(widthInRes);
174           vpRanges.setViewportHeight(heightInSeq);
175         }
176       }
177
178     });
179
180     final AlignmentPanel ap = this;
181     propertyChangeListener = new PropertyChangeListener()
182     {
183       @Override
184       public void propertyChange(PropertyChangeEvent evt)
185       {
186         if (evt.getPropertyName().equals("alignment"))
187         {
188           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
189           alignmentChanged();
190         }
191       }
192     };
193     av.addPropertyChangeListener(propertyChangeListener);
194
195     av.getRanges().addPropertyChangeListener(this);
196     fontChanged();
197     adjustAnnotationHeight();
198     updateLayout();
199   }
200
201   @Override
202   public AlignViewportI getAlignViewport()
203   {
204     return av;
205   }
206
207   public void alignmentChanged()
208   {
209     av.alignmentChanged(this);
210
211     if (getCalculationDialog() != null)
212     {
213       getCalculationDialog().validateCalcTypes();
214     }
215
216     alignFrame.updateEditMenuBar();
217
218     paintAlignment(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(new Dimension(10, av.getCharHeight()
232             + fm.getDescent()));
233     idSpaceFillerPanel1.setPreferredSize(new Dimension(10, av
234             .getCharHeight() + fm.getDescent()));
235
236     getIdPanel().getIdCanvas().gg = null;
237     getSeqPanel().seqCanvas.img = null;
238     getAnnotationPanel().adjustPanelHeight();
239
240     Dimension d = calculateIdWidth();
241
242     d.setSize(d.width + 4, d.height);
243     getIdPanel().getIdCanvas().setPreferredSize(d);
244     hscrollFillerPanel.setPreferredSize(d);
245
246     if (this.alignFrame.getSplitViewContainer() != null)
247     {
248       ((SplitFrame) this.alignFrame.getSplitViewContainer()).adjustLayout();
249     }
250
251     repaint();
252   }
253
254   /**
255    * Calculate the width of the alignment labels based on the displayed names
256    * and any bounds on label width set in preferences.
257    * 
258    * @return Dimension giving the maximum width of the alignment label panel
259    *         that should be used.
260    */
261   public Dimension calculateIdWidth()
262   {
263     // calculate sensible default width when no preference is available
264     Dimension r = null;
265     if (av.getIdWidth() < 0)
266     {
267       int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
268       int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
269       r = calculateIdWidth(maxwidth);
270       av.setIdWidth(r.width);
271     }
272     else
273     {
274       r = new Dimension();
275       r.width = av.getIdWidth();
276       r.height = 0;
277     }
278     return r;
279   }
280
281   /**
282    * Calculate the width of the alignment labels based on the displayed names
283    * and any bounds on label width set in preferences.
284    * 
285    * @param maxwidth
286    *          -1 or maximum width allowed for IdWidth
287    * @return Dimension giving the maximum width of the alignment label panel
288    *         that should be used.
289    */
290   public Dimension calculateIdWidth(int maxwidth)
291   {
292     Container c = new Container();
293
294     FontMetrics fm = c.getFontMetrics(new Font(av.font.getName(),
295             Font.ITALIC, av.font.getSize()));
296
297     AlignmentI al = av.getAlignment();
298     int i = 0;
299     int idWidth = 0;
300     String id;
301
302     while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
303     {
304       SequenceI s = al.getSequenceAt(i);
305
306       id = s.getDisplayId(av.getShowJVSuffix());
307
308       if (fm.stringWidth(id) > idWidth)
309       {
310         idWidth = fm.stringWidth(id);
311       }
312
313       i++;
314     }
315
316     // Also check annotation label widths
317     i = 0;
318
319     if (al.getAlignmentAnnotation() != null)
320     {
321       fm = c.getFontMetrics(getAlabels().getFont());
322
323       while (i < al.getAlignmentAnnotation().length)
324       {
325         String label = al.getAlignmentAnnotation()[i].label;
326
327         if (fm.stringWidth(label) > idWidth)
328         {
329           idWidth = fm.stringWidth(label);
330         }
331
332         i++;
333       }
334     }
335
336     return new Dimension(maxwidth < 0 ? idWidth : Math.min(maxwidth,
337             idWidth), 12);
338   }
339
340   /**
341    * Highlight the given results on the alignment.
342    * 
343    */
344   public void highlightSearchResults(SearchResultsI results)
345   {
346     boolean scrolled = scrollToPosition(results, 0, true, false);
347
348     boolean noFastPaint = scrolled && av.getWrapAlignment();
349
350     getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
351   }
352
353   /**
354    * Scroll the view to show the position of the highlighted region in results
355    * (if any)
356    * 
357    * @param searchResults
358    * @param redrawOverview
359    * @return
360    */
361   public boolean scrollToPosition(SearchResultsI searchResults,
362           boolean redrawOverview)
363   {
364     return scrollToPosition(searchResults, 0, redrawOverview, false);
365   }
366
367   /**
368    * Scrolls the view (if necessary) to show the position of the first
369    * highlighted region in results (if any). Answers true if the view was
370    * scrolled, or false if no matched region was found, or it is already
371    * visible.
372    * 
373    * @param results
374    * @param verticalOffset
375    *          if greater than zero, allows scrolling to a position below the
376    *          first displayed sequence
377    * @param redrawOverview
378    *          - when set, the overview will be recalculated (takes longer)
379    * @param centre
380    *          if true, try to centre the search results horizontally in the view
381    * @return
382    */
383   protected boolean scrollToPosition(SearchResultsI results,
384           int verticalOffset, boolean redrawOverview, boolean centre)
385   {
386     int startv, endv, starts, ends;
387
388     if (results == null || results.isEmpty() || av == null
389             || av.getAlignment() == null)
390     {
391       return false;
392     }
393     int seqIndex = av.getAlignment().findIndex(results);
394     if (seqIndex == -1)
395     {
396       return false;
397     }
398     SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
399
400     int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
401     if (r == null)
402     {
403       return false;
404     }
405     int start = r[0];
406     int end = r[1];
407
408     /*
409      * To centre results, scroll to positions half the visible width
410      * left/right of the start/end positions
411      */
412     if (centre)
413     {
414       int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
415       start = Math.max(start - offset, 0);
416       end = end + offset - 1;
417     }
418     if (start < 0)
419     {
420       return false;
421     }
422     if (end == seq.getEnd())
423     {
424       return false;
425     }
426
427     if (av.hasHiddenColumns())
428     {
429       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
430       start = hidden.findColumnPosition(start);
431       end = hidden.findColumnPosition(end);
432       if (start == end)
433       {
434         if (!hidden.isVisible(r[0]))
435         {
436           // don't scroll - position isn't visible
437           return false;
438         }
439       }
440     }
441
442     /*
443      * allow for offset of target sequence (actually scroll to one above it)
444      */
445     seqIndex = Math.max(0, seqIndex - verticalOffset);
446     boolean scrollNeeded = true;
447
448     if (!av.getWrapAlignment())
449     {
450       if ((startv = vpRanges.getStartRes()) >= start)
451       {
452         /*
453          * Scroll left to make start of search results visible
454          */
455         setScrollValues(start, seqIndex);
456       }
457       else if ((endv = vpRanges.getEndRes()) <= end)
458       {
459         /*
460          * Scroll right to make end of search results visible
461          */
462         setScrollValues(startv + end - endv, seqIndex);
463       }
464       else if ((starts = vpRanges.getStartSeq()) > seqIndex)
465       {
466         /*
467          * Scroll up to make start of search results visible
468          */
469         setScrollValues(vpRanges.getStartRes(), seqIndex);
470       }
471       else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
472       {
473         /*
474          * Scroll down to make end of search results visible
475          */
476         setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
477                 + 1);
478       }
479       /*
480        * Else results are already visible - no need to scroll
481        */
482       scrollNeeded = false;
483     }
484     else
485     {
486       scrollNeeded = vpRanges.scrollToWrappedVisible(start);
487     }
488
489     paintAlignment(redrawOverview);
490
491     return scrollNeeded;
492   }
493
494   /**
495    * DOCUMENT ME!
496    * 
497    * @return DOCUMENT ME!
498    */
499   public OverviewPanel getOverviewPanel()
500   {
501     return overviewPanel;
502   }
503
504   /**
505    * DOCUMENT ME!
506    * 
507    * @param op
508    *          DOCUMENT ME!
509    */
510   public void setOverviewPanel(OverviewPanel op)
511   {
512     overviewPanel = op;
513   }
514
515   /**
516    * 
517    * @param b
518    *          Hide or show annotation panel
519    * 
520    */
521   public void setAnnotationVisible(boolean b)
522   {
523     if (!av.getWrapAlignment())
524     {
525       annotationSpaceFillerHolder.setVisible(b);
526       annotationScroller.setVisible(b);
527     }
528     repaint();
529   }
530
531   /**
532    * automatically adjust annotation panel height for new annotation whilst
533    * ensuring the alignment is still visible.
534    */
535   @Override
536   public void adjustAnnotationHeight()
537   {
538     // TODO: display vertical annotation scrollbar if necessary
539     // this is called after loading new annotation onto alignment
540     if (alignFrame.getHeight() == 0)
541     {
542       System.out.println("NEEDS FIXING");
543     }
544     validateAnnotationDimensions(true);
545     addNotify();
546     paintAlignment(true);
547   }
548
549   /**
550    * calculate the annotation dimensions and refresh slider values accordingly.
551    * need to do repaints/notifys afterwards.
552    */
553   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
554   {
555     int annotationHeight = getAnnotationPanel().adjustPanelHeight();
556
557     if (adjustPanelHeight)
558     {
559       int rowHeight = av.getCharHeight();
560       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
561
562       /*
563        * Estimate available height in the AlignFrame for alignment +
564        * annotations. Deduct an estimate for title bar, menu bar, scale panel,
565        * hscroll, status bar (as these are not laid out we can't inspect their
566        * actual heights). Insets gives frame borders.
567        */
568       int stuff = Platform.isAMac() ? 80 : 100;
569       Insets insets = alignFrame.getInsets();
570       int availableHeight = alignFrame.getHeight() - stuff - insets.top
571               - insets.bottom;
572
573       /*
574        * If not enough vertical space, maximize annotation height while keeping
575        * at least two rows of alignment visible
576        */
577       if (annotationHeight + alignmentHeight > availableHeight)
578       {
579         annotationHeight = Math.min(annotationHeight, availableHeight - 2
580                 * rowHeight);
581       }
582     }
583     else
584     {
585       // maintain same window layout whilst updating sliders
586       annotationHeight = annotationScroller.getSize().height;
587     }
588     hscroll.addNotify();
589
590     annotationScroller.setPreferredSize(new Dimension(annotationScroller
591             .getWidth(), annotationHeight));
592
593     Dimension e = idPanel.getSize();
594     alabels.setSize(new Dimension(e.width, annotationHeight));
595
596     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
597             annotationSpaceFillerHolder.getWidth(), annotationHeight));
598     annotationScroller.validate();
599     annotationScroller.addNotify();
600   }
601
602   /**
603    * update alignment layout for viewport settings
604    * 
605    * @param wrap
606    *          DOCUMENT ME!
607    */
608   public void updateLayout()
609   {
610     fontChanged();
611     setAnnotationVisible(av.isShowAnnotation());
612     boolean wrap = av.getWrapAlignment();
613     vpRanges.setStartSeq(0);
614     scalePanelHolder.setVisible(!wrap);
615     hscroll.setVisible(!wrap);
616     idwidthAdjuster.setVisible(!wrap);
617
618     if (wrap)
619     {
620       annotationScroller.setVisible(false);
621       annotationSpaceFillerHolder.setVisible(false);
622     }
623     else if (av.isShowAnnotation())
624     {
625       annotationScroller.setVisible(true);
626       annotationSpaceFillerHolder.setVisible(true);
627     }
628
629     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
630     if (canvasWidth > 0)
631     { // may not yet be laid out
632       if (wrap)
633       {
634         int widthInRes = getSeqPanel().seqCanvas
635                 .getWrappedCanvasWidth(canvasWidth);
636         vpRanges.setViewportWidth(widthInRes);
637       }
638       else
639       {
640         int widthInRes = (canvasWidth / av.getCharWidth()) - 1;
641         int heightInSeq = (getSeqPanel().seqCanvas.getHeight() / av
642                 .getCharHeight()) - 1;
643
644         vpRanges.setViewportWidth(widthInRes);
645         vpRanges.setViewportHeight(heightInSeq);
646       }
647     }
648
649     idSpaceFillerPanel1.setVisible(!wrap);
650
651     repaint();
652   }
653
654
655   /**
656    * Adjust row/column scrollers to show a visible position in the alignment.
657    * 
658    * @param x
659    *          visible column to scroll to
660    * @param y
661    *          visible row to scroll to
662    * 
663    */
664   public void setScrollValues(int xpos, int ypos)
665   {
666     int x = xpos;
667     int y = ypos;
668
669     if (av == null || av.getAlignment() == null)
670     {
671       return;
672     }
673
674     if (av.getWrapAlignment())
675     {
676       setScrollingForWrappedPanel(x);
677     }
678     else
679     {
680       int width = av.getAlignment().getWidth();
681       int height = av.getAlignment().getHeight();
682
683       if (av.hasHiddenColumns())
684       {
685         // reset the width to exclude hidden columns
686         width = av.getAlignment().getHiddenColumns().findColumnPosition(width);
687       }
688
689       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
690       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
691
692       if (hextent > width)
693       {
694         hextent = width;
695       }
696
697       if (vextent > height)
698       {
699         vextent = height;
700       }
701
702       if ((hextent + x) > width)
703       {
704         x = width - hextent;
705       }
706
707       if ((vextent + y) > height)
708       {
709         y = height - vextent;
710       }
711
712       if (y < 0)
713       {
714         y = 0;
715       }
716
717       if (x < 0)
718       {
719         x = 0;
720       }
721
722       // update the scroll values
723       hscroll.setValues(x, hextent, 0, width);
724       vscroll.setValues(y, vextent, 0, height);
725     }
726   }
727
728   /**
729    * Respond to adjustment event when horizontal or vertical scrollbar is
730    * changed
731    * 
732    * @param evt
733    *          adjustment event encoding whether hscroll or vscroll changed
734    */
735   @Override
736   public void adjustmentValueChanged(AdjustmentEvent evt)
737   {
738     if (av.getWrapAlignment())
739     {
740       adjustScrollingWrapped(evt);
741       return;
742     }
743
744     if (evt.getSource() == hscroll)
745     {
746       int oldX = vpRanges.getStartRes();
747       int oldwidth = vpRanges.getViewportWidth();
748       int x = hscroll.getValue();
749       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
750
751       // if we're scrolling to the position we're already at, stop
752       // this prevents infinite recursion of events when the scroll/viewport
753       // ranges values are the same
754       if ((x == oldX) && (width == oldwidth))
755       {
756         return;
757       }
758       vpRanges.setViewportStartAndWidth(x, width);
759     }
760     else if (evt.getSource() == vscroll)
761     {
762       int oldY = vpRanges.getStartSeq();
763       int oldheight = vpRanges.getViewportHeight();
764       int y = vscroll.getValue();
765       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
766
767       // if we're scrolling to the position we're already at, stop
768       // this prevents infinite recursion of events when the scroll/viewport
769       // ranges values are the same
770       if ((y == oldY) && (height == oldheight))
771       {
772         return;
773       }
774       vpRanges.setViewportStartAndHeight(y, height);
775     }
776     if (!fastPaint)
777     {
778       repaint();
779     }
780   }
781
782   /**
783    * Responds to a scroll change by setting the start position of the viewport.
784    * Does
785    * 
786    * @param evt
787    */
788   protected void adjustScrollingWrapped(AdjustmentEvent evt)
789   {
790     if (evt.getSource() == hscroll)
791     {
792       return; // no horizontal scroll when wrapped
793     }
794     if (evt.getSource() == vscroll)
795     {
796       int newY = vscroll.getValue();
797
798       /*
799        * if we're scrolling to the position we're already at, stop
800        * this prevents infinite recursion of events when the scroll/viewport
801        * ranges values are the same
802        */
803       int oldX = vpRanges.getStartRes();
804       int oldY = vpRanges.getWrappedScrollPosition(oldX);
805       if (oldY == newY)
806       {
807         return;
808       }
809       if (newY > -1)
810       {
811         /*
812          * limit page up/down to one width's worth of positions
813          */
814         int rowSize = vpRanges.getViewportWidth();
815         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
816         vpRanges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
817       }
818     }
819     else
820     {
821       // This is only called if file loaded is a jar file that
822       // was wrapped when saved and user has wrap alignment true
823       // as preference setting
824       SwingUtilities.invokeLater(new Runnable()
825       {
826         @Override
827         public void run()
828       {
829           // When updating scrolling to use ViewportChange events, this code
830           // could not be validated and it is not clear if it is now being
831           // called. Log warning here in case it is called and unforeseen
832           // problems occur
833           Cache.log
834                   .warn("Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
835
836           // scroll to start of panel
837           vpRanges.setStartRes(0);
838           vpRanges.setStartSeq(0);
839         }
840       });
841     }
842     repaint();
843   }
844
845   /**
846    * Repaint the alignment including the annotations and overview panels (if
847    * shown).
848    */
849   @Override
850   public void paintAlignment(boolean updateOverview)
851   {
852     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
853             av.isShowAutocalculatedAbove());
854     sorter.sort(getAlignment().getAlignmentAnnotation(),
855             av.getSortAnnotationsBy());
856     repaint();
857
858     if (updateOverview)
859     {
860       // TODO: determine if this paintAlignment changed structure colours
861       av.getStructureSelectionManager().sequenceColoursChanged(this);
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 : 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 sSize = av.getAlignment().getHeight();
1445         int alwidth = av.getAlignment().getWidth();
1446         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1447         out.println(HTMLOutput.getImageMapHTML());
1448         out.println("<img src=\"" + imageName
1449                 + "\" border=\"0\" usemap=\"#Map\" >"
1450                 + "<map name=\"Map\">");
1451
1452         for (int s = 0; s < sSize; s++)
1453         {
1454           int sy = s * av.getCharHeight() + scaleHeight;
1455
1456           SequenceI seq = av.getAlignment().getSequenceAt(s);
1457           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1458           for (int column = 0; column < alwidth; column++)
1459           {
1460             StringBuilder text = new StringBuilder(512);
1461             String triplet = null;
1462             if (av.getAlignment().isNucleotide())
1463             {
1464               triplet = ResidueProperties.nucleotideName.get(seq
1465                       .getCharAt(column) + "");
1466             }
1467             else
1468             {
1469               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1470                       + "");
1471             }
1472
1473             if (triplet == null)
1474             {
1475               continue;
1476             }
1477
1478             int seqPos = seq.findPosition(column);
1479             int gSize = groups.length;
1480             for (int g = 0; g < gSize; g++)
1481             {
1482               if (text.length() < 1)
1483               {
1484                 text.append("<area shape=\"rect\" coords=\"")
1485                         .append((idWidth + column * av.getCharWidth()))
1486                         .append(",").append(sy).append(",")
1487                         .append((idWidth + (column + 1) * av.getCharWidth()))
1488                         .append(",").append((av.getCharHeight() + sy))
1489                         .append("\"").append(" onMouseOver=\"toolTip('")
1490                         .append(seqPos).append(" ").append(triplet);
1491               }
1492
1493               if (groups[g].getStartRes() < column
1494                       && groups[g].getEndRes() > column)
1495               {
1496                 text.append("<br><em>").append(groups[g].getName())
1497                         .append("</em>");
1498               }
1499             }
1500
1501             if (text.length() < 1)
1502             {
1503               text.append("<area shape=\"rect\" coords=\"")
1504                       .append((idWidth + column * av.getCharWidth()))
1505                       .append(",").append(sy).append(",")
1506                       .append((idWidth + (column + 1) * av.getCharWidth()))
1507                       .append(",").append((av.getCharHeight() + sy))
1508                       .append("\"").append(" onMouseOver=\"toolTip('")
1509                       .append(seqPos).append(" ").append(triplet);
1510             }
1511             if (!Comparison.isGap(seq.getCharAt(column)))
1512             {
1513               List<SequenceFeature> features = seq.findFeatures(column, column);
1514               for (SequenceFeature sf : features)
1515               {
1516                 if (sf.isContactFeature())
1517                 {
1518                   text.append("<br>").append(sf.getType()).append(" ")
1519                           .append(sf.getBegin()).append(":")
1520                           .append(sf.getEnd());
1521                 }
1522                 else
1523                 {
1524                   text.append("<br>");
1525                   text.append(sf.getType());
1526                   String description = sf.getDescription();
1527                   if (description != null
1528                           && !sf.getType().equals(description))
1529                   {
1530                     description = description.replace("\"", "&quot;");
1531                     text.append(" ").append(description);
1532                   }
1533                 }
1534                 String status = sf.getStatus();
1535                 if (status != null && !"".equals(status))
1536                 {
1537                   text.append(" (").append(status).append(")");
1538                 }
1539               }
1540               if (text.length() > 1)
1541               {
1542                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1543                 out.println(text.toString());
1544               }
1545             }
1546           }
1547         }
1548         out.println("</map></body></html>");
1549         out.close();
1550
1551       } catch (Exception ex)
1552       {
1553         ex.printStackTrace();
1554       }
1555     } // /////////END OF IMAGE MAP
1556
1557   }
1558
1559   int getWrappedHeight()
1560   {
1561     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1562
1563     if (System.getProperty("java.awt.headless") != null
1564             && System.getProperty("java.awt.headless").equals("true"))
1565     {
1566       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1567               - vscroll.getPreferredSize().width
1568               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1569     }
1570
1571     int chunkWidth = getSeqPanel().seqCanvas
1572             .getWrappedCanvasWidth(seqPanelWidth);
1573
1574     int hgap = av.getCharHeight();
1575     if (av.getScaleAboveWrapped())
1576     {
1577       hgap += av.getCharHeight();
1578     }
1579
1580     int annotationHeight = 0;
1581     if (av.isShowAnnotation())
1582     {
1583       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1584     }
1585
1586     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1587             + annotationHeight;
1588
1589     int maxwidth = av.getAlignment().getWidth();
1590     if (av.hasHiddenColumns())
1591     {
1592       maxwidth = av.getAlignment().getHiddenColumns()
1593               .findColumnPosition(maxwidth) - 1;
1594     }
1595
1596     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1597
1598     return height;
1599   }
1600
1601   /**
1602    * close the panel - deregisters all listeners and nulls any references to
1603    * alignment data.
1604    */
1605   public void closePanel()
1606   {
1607     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1608     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1609     PaintRefresher.RemoveComponent(this);
1610
1611     closeChildFrames();
1612
1613     /*
1614      * try to ensure references are nulled
1615      */
1616     if (annotationPanel != null)
1617     {
1618       annotationPanel.dispose();
1619     }
1620
1621     if (av != null)
1622     {
1623       av.removePropertyChangeListener(propertyChangeListener);
1624       jalview.structure.StructureSelectionManager ssm = av
1625               .getStructureSelectionManager();
1626       ssm.removeStructureViewerListener(getSeqPanel(), null);
1627       ssm.removeSelectionListener(getSeqPanel());
1628       ssm.removeCommandListener(av);
1629       ssm.removeStructureViewerListener(getSeqPanel(), null);
1630       ssm.removeSelectionListener(getSeqPanel());
1631       av.dispose();
1632       av = null;
1633     }
1634     else
1635     {
1636       if (Cache.log.isDebugEnabled())
1637       {
1638         Cache.log.warn("Closing alignment panel which is already closed.");
1639       }
1640     }
1641   }
1642
1643   /**
1644    * Close any open dialogs that would be orphaned when this one is closed
1645    */
1646   protected void closeChildFrames()
1647   {
1648     if (calculationDialog != null)
1649     {
1650       calculationDialog.closeFrame();
1651     }
1652   }
1653
1654   /**
1655    * hides or shows dynamic annotation rows based on groups and av state flags
1656    */
1657   public void updateAnnotation()
1658   {
1659     updateAnnotation(false, false);
1660   }
1661
1662   public void updateAnnotation(boolean applyGlobalSettings)
1663   {
1664     updateAnnotation(applyGlobalSettings, false);
1665   }
1666
1667   public void updateAnnotation(boolean applyGlobalSettings,
1668           boolean preserveNewGroupSettings)
1669   {
1670     av.updateGroupAnnotationSettings(applyGlobalSettings,
1671             preserveNewGroupSettings);
1672     adjustAnnotationHeight();
1673   }
1674
1675   @Override
1676   public AlignmentI getAlignment()
1677   {
1678     return av == null ? null : av.getAlignment();
1679   }
1680
1681   @Override
1682   public String getViewName()
1683   {
1684     return av.viewName;
1685   }
1686
1687   /**
1688    * Make/Unmake this alignment panel the current input focus
1689    * 
1690    * @param b
1691    */
1692   public void setSelected(boolean b)
1693   {
1694     try
1695     {
1696       if (alignFrame.getSplitViewContainer() != null)
1697       {
1698         /*
1699          * bring enclosing SplitFrame to front first if there is one
1700          */
1701         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1702       }
1703       alignFrame.setSelected(b);
1704     } catch (Exception ex)
1705     {
1706     }
1707
1708     if (b)
1709     {
1710       alignFrame.setDisplayedView(this);
1711     }
1712   }
1713
1714   @Override
1715   public StructureSelectionManager getStructureSelectionManager()
1716   {
1717     return av.getStructureSelectionManager();
1718   }
1719
1720   @Override
1721   public void raiseOOMWarning(String string, OutOfMemoryError error)
1722   {
1723     new OOMWarning(string, error, this);
1724   }
1725
1726   @Override
1727   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1728   {
1729
1730     return new FeatureRenderer(this);
1731   }
1732
1733   @Override
1734   public jalview.api.FeatureRenderer getFeatureRenderer()
1735   {
1736     return seqPanel.seqCanvas.getFeatureRenderer();
1737   }
1738
1739   public void updateFeatureRenderer(
1740           jalview.renderer.seqfeatures.FeatureRenderer fr)
1741   {
1742     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1743   }
1744
1745   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1746   {
1747     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1748     {
1749       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1750     }
1751   }
1752
1753   public ScalePanel getScalePanel()
1754   {
1755     return scalePanel;
1756   }
1757
1758   public void setScalePanel(ScalePanel scalePanel)
1759   {
1760     this.scalePanel = scalePanel;
1761   }
1762
1763   public SeqPanel getSeqPanel()
1764   {
1765     return seqPanel;
1766   }
1767
1768   public void setSeqPanel(SeqPanel seqPanel)
1769   {
1770     this.seqPanel = seqPanel;
1771   }
1772
1773   public AnnotationPanel getAnnotationPanel()
1774   {
1775     return annotationPanel;
1776   }
1777
1778   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1779   {
1780     this.annotationPanel = annotationPanel;
1781   }
1782
1783   public AnnotationLabels getAlabels()
1784   {
1785     return alabels;
1786   }
1787
1788   public void setAlabels(AnnotationLabels alabels)
1789   {
1790     this.alabels = alabels;
1791   }
1792
1793   public IdPanel getIdPanel()
1794   {
1795     return idPanel;
1796   }
1797
1798   public void setIdPanel(IdPanel idPanel)
1799   {
1800     this.idPanel = idPanel;
1801   }
1802
1803   /**
1804    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1805    * The aim is to keep the two alignments 'lined up' on their centre columns.
1806    * 
1807    * @param sr
1808    *          holds mapped region(s) of this alignment that we are scrolling
1809    *          'to'; may be modified for sequence offset by this method
1810    * @param verticalOffset
1811    *          the number of visible sequences to show above the mapped region
1812    */
1813   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1814   {
1815     /*
1816      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1817      * mapped), we can make the scroll-to location a sequence above the one
1818      * actually mapped.
1819      */
1820     SequenceI mappedTo = sr.getResults().get(0).getSequence();
1821     List<SequenceI> seqs = av.getAlignment().getSequences();
1822
1823     /*
1824      * This is like AlignmentI.findIndex(seq) but here we are matching the
1825      * dataset sequence not the aligned sequence
1826      */
1827     boolean matched = false;
1828     for (SequenceI seq : seqs)
1829     {
1830       if (mappedTo == seq.getDatasetSequence())
1831       {
1832         matched = true;
1833         break;
1834       }
1835     }
1836     if (!matched)
1837     {
1838       return; // failsafe, shouldn't happen
1839     }
1840
1841     /*
1842      * Scroll to position but centring the target residue.
1843      */
1844     scrollToPosition(sr, verticalOffset, true, true);
1845   }
1846
1847   /**
1848    * Set a flag to say do not scroll any (cDNA/protein) complement.
1849    * 
1850    * @param b
1851    */
1852   protected void setToScrollComplementPanel(boolean b)
1853   {
1854     this.scrollComplementaryPanel = b;
1855   }
1856
1857   /**
1858    * Get whether to scroll complement panel
1859    * 
1860    * @return true if cDNA/protein complement panels should be scrolled
1861    */
1862   protected boolean isSetToScrollComplementPanel()
1863   {
1864     return this.scrollComplementaryPanel;
1865   }
1866
1867   /**
1868    * Redraw sensibly.
1869    * 
1870    * @adjustHeight if true, try to recalculate panel height for visible
1871    *               annotations
1872    */
1873   protected void refresh(boolean adjustHeight)
1874   {
1875     validateAnnotationDimensions(adjustHeight);
1876     addNotify();
1877     if (adjustHeight)
1878     {
1879       // sort, repaint, update overview
1880       paintAlignment(true);
1881     }
1882     else
1883     {
1884       // lightweight repaint
1885       repaint();
1886     }
1887   }
1888
1889   @Override
1890   /**
1891    * Property change event fired when a change is made to the viewport ranges 
1892    * object associated with this alignment panel's viewport
1893    */
1894   public void propertyChange(PropertyChangeEvent evt)
1895   {
1896     // update this panel's scroll values based on the new viewport ranges values
1897     int x = vpRanges.getStartRes();
1898     int y = vpRanges.getStartSeq();
1899     setScrollValues(x, y);
1900
1901     // now update any complementary alignment (its viewport ranges object
1902     // is different so does not get automatically updated)
1903     if (isSetToScrollComplementPanel())
1904     {
1905       setToScrollComplementPanel(false);
1906       av.scrollComplementaryAlignment();
1907       setToScrollComplementPanel(true);
1908     }
1909   }
1910
1911   /**
1912    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1913    * reference should be nulled when the dialog is closed.
1914    * 
1915    * @param calculationChooser
1916    */
1917   public void setCalculationDialog(CalculationChooser calculationChooser)
1918   {
1919     calculationDialog = calculationChooser;
1920   }
1921
1922   /**
1923    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1924    * if none is open)
1925    */
1926   public CalculationChooser getCalculationDialog()
1927   {
1928     return calculationDialog;
1929   }
1930 }