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