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