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