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