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