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