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