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