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