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