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