removes unnecessary clearFastPaint
[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     // BH 2018.04.18 comment: addNotify() is not appropriate here. We
547     // are not changing ancestors, and keyboard action listeners do
548     // not need to be reset. addNotify() is a very expensive operation,
549     // requiring a full re-layout of all parents and children.
550     // Note in JComponent:
551     // This method is called by the toolkit internally and should
552     // not be called directly by programs.
553
554     int annotationHeight = getAnnotationPanel().adjustPanelHeight();
555     annotationHeight = getAnnotationPanel()
556             .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
557
558     hscroll.addNotify();
559     annotationScroller.setPreferredSize(
560             new Dimension(annotationScroller.getWidth(), annotationHeight));
561
562     Dimension e = idPanel.getSize();
563     alabels.setSize(new Dimension(e.width, annotationHeight));
564
565
566     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
567             annotationSpaceFillerHolder.getWidth(), annotationHeight));
568     annotationScroller.validate();
569     annotationScroller.addNotify();
570   }
571
572   /**
573    * update alignment layout for viewport settings
574    * 
575    * @param wrap
576    *          DOCUMENT ME!
577    */
578   public void updateLayout()
579   {
580     fontChanged();
581     setAnnotationVisible(av.isShowAnnotation());
582     boolean wrap = av.getWrapAlignment();
583     ViewportRanges ranges = av.getRanges();
584     ranges.setStartSeq(0);
585     scalePanelHolder.setVisible(!wrap);
586     hscroll.setVisible(!wrap);
587     idwidthAdjuster.setVisible(!wrap);
588
589     if (wrap)
590     {
591       annotationScroller.setVisible(false);
592       annotationSpaceFillerHolder.setVisible(false);
593     }
594     else if (av.isShowAnnotation())
595     {
596       annotationScroller.setVisible(true);
597       annotationSpaceFillerHolder.setVisible(true);
598       validateAnnotationDimensions(false);
599     }
600
601     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
602     if (canvasWidth > 0)
603     { // may not yet be laid out
604       if (wrap)
605       {
606         int widthInRes = getSeqPanel().seqCanvas
607                 .getWrappedCanvasWidth(canvasWidth);
608         ranges.setViewportWidth(widthInRes);
609       }
610       else
611       {
612         int widthInRes = (canvasWidth / av.getCharWidth());
613         int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
614                 / av.getCharHeight());
615
616         ranges.setViewportWidth(widthInRes);
617         ranges.setViewportHeight(heightInSeq);
618       }
619     }
620
621     idSpaceFillerPanel1.setVisible(!wrap);
622
623     repaint();
624   }
625
626   /**
627    * Adjust row/column scrollers to show a visible position in the alignment.
628    * 
629    * @param x
630    *          visible column to scroll to
631    * @param y
632    *          visible row to scroll to
633    * 
634    */
635   public void setScrollValues(int xpos, int ypos)
636   {
637     int x = xpos;
638     int y = ypos;
639
640     if (av == null || av.getAlignment() == null)
641     {
642       return;
643     }
644
645     if (av.getWrapAlignment())
646     {
647       setScrollingForWrappedPanel(x);
648     }
649     else
650     {
651       int width = av.getAlignment().getVisibleWidth();
652       int height = av.getAlignment().getHeight();
653
654       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
655       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
656
657       if (hextent > width)
658       {
659         hextent = width;
660       }
661
662       if (vextent > height)
663       {
664         vextent = height;
665       }
666
667       if ((hextent + x) > width)
668       {
669         x = width - hextent;
670       }
671
672       if ((vextent + y) > height)
673       {
674         y = height - vextent;
675       }
676
677       if (y < 0)
678       {
679         y = 0;
680       }
681
682       if (x < 0)
683       {
684         x = 0;
685       }
686
687       // update the scroll values
688       hscroll.setValues(x, hextent, 0, width);
689       vscroll.setValues(y, vextent, 0, height);
690     }
691   }
692
693   /**
694    * Respond to adjustment event when horizontal or vertical scrollbar is
695    * changed
696    * 
697    * @param evt
698    *          adjustment event encoding whether hscroll or vscroll changed
699    */
700   @Override
701   public void adjustmentValueChanged(AdjustmentEvent evt)
702   {
703     if (av.getWrapAlignment())
704     {
705       adjustScrollingWrapped(evt);
706       return;
707     }
708
709     ViewportRanges ranges = av.getRanges();
710
711     if (evt.getSource() == hscroll)
712     {
713       int oldX = ranges.getStartRes();
714       int oldwidth = ranges.getViewportWidth();
715       int x = hscroll.getValue();
716       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
717
718       // if we're scrolling to the position we're already at, stop
719       // this prevents infinite recursion of events when the scroll/viewport
720       // ranges values are the same
721       if ((x == oldX) && (width == oldwidth))
722       {
723         return;
724       }
725       ranges.setViewportStartAndWidth(x, width);
726     }
727     else if (evt.getSource() == vscroll)
728     {
729       int oldY = ranges.getStartSeq();
730       int oldheight = ranges.getViewportHeight();
731       int y = vscroll.getValue();
732       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
733
734       // if we're scrolling to the position we're already at, stop
735       // this prevents infinite recursion of events when the scroll/viewport
736       // ranges values are the same
737       if ((y == oldY) && (height == oldheight))
738       {
739         return;
740       }
741       ranges.setViewportStartAndHeight(y, height);
742     }
743     repaint();
744   }
745
746   /**
747    * Responds to a scroll change by setting the start position of the viewport.
748    * Does
749    * 
750    * @param evt
751    */
752   protected void adjustScrollingWrapped(AdjustmentEvent evt)
753   {
754     if (evt.getSource() == hscroll)
755     {
756       return; // no horizontal scroll when wrapped
757     }
758     final ViewportRanges ranges = av.getRanges();
759
760     if (evt.getSource() == vscroll)
761     {
762       int newY = vscroll.getValue();
763
764       /*
765        * if we're scrolling to the position we're already at, stop
766        * this prevents infinite recursion of events when the scroll/viewport
767        * ranges values are the same
768        */
769       int oldX = ranges.getStartRes();
770       int oldY = ranges.getWrappedScrollPosition(oldX);
771       if (oldY == newY)
772       {
773         return;
774       }
775       if (newY > -1)
776       {
777         /*
778          * limit page up/down to one width's worth of positions
779          */
780         int rowSize = ranges.getViewportWidth();
781         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
782         ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
783       }
784     }
785     else
786     {
787       // This is only called if file loaded is a jar file that
788       // was wrapped when saved and user has wrap alignment true
789       // as preference setting
790       SwingUtilities.invokeLater(new Runnable()
791       {
792         @Override
793         public void run()
794         {
795           // When updating scrolling to use ViewportChange events, this code
796           // could not be validated and it is not clear if it is now being
797           // called. Log warning here in case it is called and unforeseen
798           // problems occur
799           Cache.log.warn(
800                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
801
802           // scroll to start of panel
803           ranges.setStartRes(0);
804           ranges.setStartSeq(0);
805         }
806       });
807     }
808     repaint();
809   }
810
811   /* (non-Javadoc)
812    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
813    */
814   @Override
815   public void paintAlignment(boolean updateOverview,
816           boolean updateStructures)
817   {
818     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
819             av.isShowAutocalculatedAbove());
820     sorter.sort(getAlignment().getAlignmentAnnotation(),
821             av.getSortAnnotationsBy());
822     repaint();
823
824     if (updateStructures)
825     {
826       av.getStructureSelectionManager().sequenceColoursChanged(this);
827     }
828     if (updateOverview)
829     {
830
831       if (overviewPanel != null)
832       {
833         overviewPanel.updateOverviewImage();
834       }
835     }
836   }
837
838   /**
839    * DOCUMENT ME!
840    * 
841    * @param g
842    *          DOCUMENT ME!
843    */
844   @Override
845   public void paintComponent(Graphics g)
846   {
847     invalidate(); // needed so that the id width adjuster works correctly
848
849     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
850     idPanelHolder.setPreferredSize(d);
851     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
852
853     validate(); // needed so that the id width adjuster works correctly
854
855     /*
856      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
857      * though I still think this call should be elsewhere.
858      */
859     ViewportRanges ranges = av.getRanges();
860     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
861     super.paintComponent(g);
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().getVisibleWidth();
967     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().getVisibleWidth();
1085
1086     int resWidth = getSeqPanel().seqCanvas
1087             .getWrappedCanvasWidth(pageWidth - idWidth);
1088
1089     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1090
1091     g.setColor(Color.white);
1092     g.fillRect(0, 0, pageWidth, pageHeight);
1093     g.setFont(av.getFont());
1094     g.setColor(Color.black);
1095
1096     /*
1097      * method: print the whole wrapped alignment, but with a clip region that
1098      * is restricted to the requested page; this supports selective print of 
1099      * single  pages or ranges, (at the cost of some repeated processing in 
1100      * the 'normal' case, when all pages are printed)
1101      */
1102     g.translate(0, -pageNumber * pageHeight);
1103
1104     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1105
1106     /*
1107      * draw sequence ids and annotation labels (if shown)
1108      */
1109     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1110     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1111
1112     g.translate(idWidth, 0);
1113
1114     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1115             totalHeight, 0);
1116
1117     if ((pageNumber * pageHeight) < totalHeight)
1118     {
1119       return Printable.PAGE_EXISTS;
1120     }
1121     else
1122     {
1123       return Printable.NO_SUCH_PAGE;
1124     }
1125   }
1126
1127   /**
1128    * get current sequence ID panel width, or nominal value if panel were to be
1129    * displayed using default settings
1130    * 
1131    * @return
1132    */
1133   public int getVisibleIdWidth()
1134   {
1135     return getVisibleIdWidth(true);
1136   }
1137
1138   /**
1139    * get current sequence ID panel width, or nominal value if panel were to be
1140    * displayed using default settings
1141    * 
1142    * @param onscreen
1143    *          indicate if the Id width for onscreen or offscreen display should
1144    *          be returned
1145    * @return
1146    */
1147   public int getVisibleIdWidth(boolean onscreen)
1148   {
1149     // see if rendering offscreen - check preferences and calc width accordingly
1150     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1151     {
1152       return calculateIdWidth(-1).width + 4;
1153     }
1154     Integer idwidth = null;
1155     if (onscreen || (idwidth = Cache
1156             .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1157     {
1158       int w = getIdPanel().getWidth();
1159       return (w > 0 ? w : calculateIdWidth().width + 4);
1160     }
1161     return idwidth.intValue() + 4;
1162   }
1163
1164   /**
1165    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1166    * writes it to the specified file
1167    * 
1168    * @param type
1169    * @param file
1170    */
1171   void makeAlignmentImage(ImageMaker.TYPE type, File file)
1172   {
1173     final int borderBottomOffset = 5;
1174
1175     AlignmentDimension aDimension = getAlignmentDimension();
1176     // todo use a lambda function in place of callback here?
1177     ImageWriterI writer = new ImageWriterI()
1178     {
1179       @Override
1180       public void exportImage(Graphics graphics) throws Exception
1181       {
1182         if (av.getWrapAlignment())
1183         {
1184           printWrappedAlignment(aDimension.getWidth(),
1185                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1186         }
1187         else
1188         {
1189           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1190                   graphics, graphics);
1191         }
1192       }
1193     };
1194
1195     String fileTitle = alignFrame.getTitle();
1196     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1197             fileTitle);
1198     int imageWidth = aDimension.getWidth();
1199     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1200     String of = MessageManager.getString("label.alignment");
1201     exporter.doExport(file, this, imageWidth, imageHeight, of);
1202   }
1203
1204   /**
1205    * Calculates and returns a suitable width and height (in pixels) for an
1206    * exported image
1207    * 
1208    * @return
1209    */
1210   public AlignmentDimension getAlignmentDimension()
1211   {
1212     int maxwidth = av.getAlignment().getVisibleWidth();
1213
1214     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1215             + getScalePanel().getHeight();
1216     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1217
1218     if (av.getWrapAlignment())
1219     {
1220       height = getWrappedHeight();
1221       if (Jalview.isHeadlessMode())
1222       {
1223         // need to obtain default alignment width and then add in any
1224         // additional allowance for id margin
1225         // this duplicates the calculation in getWrappedHeight but adjusts for
1226         // offscreen idWith
1227         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1228                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1229                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1230       }
1231       else
1232       {
1233         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1234       }
1235
1236     }
1237     else if (av.isShowAnnotation())
1238     {
1239       height += getAnnotationPanel().adjustPanelHeight() + 3;
1240     }
1241     return new AlignmentDimension(width, height);
1242
1243   }
1244
1245   public void makePNGImageMap(File imgMapFile, String imageName)
1246   {
1247     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1248     // ////////////////////////////////////////////
1249     int idWidth = getVisibleIdWidth(false);
1250     FontMetrics fm = getFontMetrics(av.getFont());
1251     int scaleHeight = av.getCharHeight() + fm.getDescent();
1252
1253     // Gen image map
1254     // ////////////////////////////////
1255     if (imgMapFile != null)
1256     {
1257       try
1258       {
1259         int sSize = av.getAlignment().getHeight();
1260         int alwidth = av.getAlignment().getWidth();
1261         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1262         out.println(HTMLOutput.getImageMapHTML());
1263         out.println("<img src=\"" + imageName
1264                 + "\" border=\"0\" usemap=\"#Map\" >"
1265                 + "<map name=\"Map\">");
1266
1267         for (int s = 0; s < sSize; s++)
1268         {
1269           int sy = s * av.getCharHeight() + scaleHeight;
1270
1271           SequenceI seq = av.getAlignment().getSequenceAt(s);
1272           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1273           for (int column = 0; column < alwidth; column++)
1274           {
1275             StringBuilder text = new StringBuilder(512);
1276             String triplet = null;
1277             if (av.getAlignment().isNucleotide())
1278             {
1279               triplet = ResidueProperties.nucleotideName.get(seq
1280                       .getCharAt(column) + "");
1281             }
1282             else
1283             {
1284               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1285                       + "");
1286             }
1287
1288             if (triplet == null)
1289             {
1290               continue;
1291             }
1292
1293             int seqPos = seq.findPosition(column);
1294             int gSize = groups.length;
1295             for (int g = 0; g < gSize; g++)
1296             {
1297               if (text.length() < 1)
1298               {
1299                 text.append("<area shape=\"rect\" coords=\"")
1300                         .append((idWidth + column * av.getCharWidth()))
1301                         .append(",").append(sy).append(",")
1302                         .append((idWidth + (column + 1) * av.getCharWidth()))
1303                         .append(",").append((av.getCharHeight() + sy))
1304                         .append("\"").append(" onMouseOver=\"toolTip('")
1305                         .append(seqPos).append(" ").append(triplet);
1306               }
1307
1308               if (groups[g].getStartRes() < column
1309                       && groups[g].getEndRes() > column)
1310               {
1311                 text.append("<br><em>").append(groups[g].getName())
1312                         .append("</em>");
1313               }
1314             }
1315
1316             if (text.length() < 1)
1317             {
1318               text.append("<area shape=\"rect\" coords=\"")
1319                       .append((idWidth + column * av.getCharWidth()))
1320                       .append(",").append(sy).append(",")
1321                       .append((idWidth + (column + 1) * av.getCharWidth()))
1322                       .append(",").append((av.getCharHeight() + sy))
1323                       .append("\"").append(" onMouseOver=\"toolTip('")
1324                       .append(seqPos).append(" ").append(triplet);
1325             }
1326             if (!Comparison.isGap(seq.getCharAt(column)))
1327             {
1328               List<SequenceFeature> features = seq.findFeatures(column, column);
1329               for (SequenceFeature sf : features)
1330               {
1331                 if (sf.isContactFeature())
1332                 {
1333                   text.append("<br>").append(sf.getType()).append(" ")
1334                           .append(sf.getBegin()).append(":")
1335                           .append(sf.getEnd());
1336                 }
1337                 else
1338                 {
1339                   text.append("<br>");
1340                   text.append(sf.getType());
1341                   String description = sf.getDescription();
1342                   if (description != null
1343                           && !sf.getType().equals(description))
1344                   {
1345                     description = description.replace("\"", "&quot;");
1346                     text.append(" ").append(description);
1347                   }
1348                 }
1349                 String status = sf.getStatus();
1350                 if (status != null && !"".equals(status))
1351                 {
1352                   text.append(" (").append(status).append(")");
1353                 }
1354               }
1355               if (text.length() > 1)
1356               {
1357                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1358                 out.println(text.toString());
1359               }
1360             }
1361           }
1362         }
1363         out.println("</map></body></html>");
1364         out.close();
1365
1366       } catch (Exception ex)
1367       {
1368         ex.printStackTrace();
1369       }
1370     } // /////////END OF IMAGE MAP
1371
1372   }
1373
1374   int getWrappedHeight()
1375   {
1376     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1377
1378     if (System.getProperty("java.awt.headless") != null
1379             && System.getProperty("java.awt.headless").equals("true"))
1380     {
1381       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1382               - vscroll.getPreferredSize().width
1383               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1384     }
1385
1386     int chunkWidth = getSeqPanel().seqCanvas
1387             .getWrappedCanvasWidth(seqPanelWidth);
1388
1389     int hgap = av.getCharHeight();
1390     if (av.getScaleAboveWrapped())
1391     {
1392       hgap += av.getCharHeight();
1393     }
1394
1395     int annotationHeight = 0;
1396     if (av.isShowAnnotation())
1397     {
1398       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1399     }
1400
1401     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1402             + annotationHeight;
1403
1404     int maxwidth = av.getAlignment().getWidth();
1405     if (av.hasHiddenColumns())
1406     {
1407       maxwidth = av.getAlignment().getHiddenColumns()
1408               .absoluteToVisibleColumn(maxwidth) - 1;
1409     }
1410
1411     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1412
1413     return height;
1414   }
1415
1416   /**
1417    * close the panel - deregisters all listeners and nulls any references to
1418    * alignment data.
1419    */
1420   public void closePanel()
1421   {
1422     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1423     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1424     PaintRefresher.RemoveComponent(this);
1425
1426     closeChildFrames();
1427
1428     /*
1429      * try to ensure references are nulled
1430      */
1431     if (annotationPanel != null)
1432     {
1433       annotationPanel.dispose();
1434       annotationPanel = null;
1435     }
1436
1437     if (av != null)
1438     {
1439       av.removePropertyChangeListener(propertyChangeListener);
1440       propertyChangeListener = null;
1441       StructureSelectionManager ssm = av.getStructureSelectionManager();
1442       ssm.removeStructureViewerListener(getSeqPanel(), null);
1443       ssm.removeSelectionListener(getSeqPanel());
1444       ssm.removeCommandListener(av);
1445       ssm.removeStructureViewerListener(getSeqPanel(), null);
1446       ssm.removeSelectionListener(getSeqPanel());
1447       av.dispose();
1448       av = null;
1449     }
1450     else
1451     {
1452       if (Cache.log.isDebugEnabled())
1453       {
1454         Cache.log.warn("Closing alignment panel which is already closed.");
1455       }
1456     }
1457   }
1458
1459   /**
1460    * Close any open dialogs that would be orphaned when this one is closed
1461    */
1462   protected void closeChildFrames()
1463   {
1464     if (overviewPanel != null)
1465     {
1466       overviewPanel.dispose();
1467       overviewPanel = null;
1468     }
1469     if (calculationDialog != null)
1470     {
1471       calculationDialog.closeFrame();
1472       calculationDialog = null;
1473     }
1474   }
1475
1476   /**
1477    * hides or shows dynamic annotation rows based on groups and av state flags
1478    */
1479   public void updateAnnotation()
1480   {
1481     updateAnnotation(false, false);
1482   }
1483
1484   public void updateAnnotation(boolean applyGlobalSettings)
1485   {
1486     updateAnnotation(applyGlobalSettings, false);
1487   }
1488
1489   public void updateAnnotation(boolean applyGlobalSettings,
1490           boolean preserveNewGroupSettings)
1491   {
1492     av.updateGroupAnnotationSettings(applyGlobalSettings,
1493             preserveNewGroupSettings);
1494     adjustAnnotationHeight();
1495   }
1496
1497   @Override
1498   public AlignmentI getAlignment()
1499   {
1500     return av == null ? null : av.getAlignment();
1501   }
1502
1503   @Override
1504   public String getViewName()
1505   {
1506     return av.getViewName();
1507   }
1508
1509   /**
1510    * Make/Unmake this alignment panel the current input focus
1511    * 
1512    * @param b
1513    */
1514   public void setSelected(boolean b)
1515   {
1516     try
1517     {
1518       if (alignFrame.getSplitViewContainer() != null)
1519       {
1520         /*
1521          * bring enclosing SplitFrame to front first if there is one
1522          */
1523         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1524       }
1525       alignFrame.setSelected(b);
1526     } catch (Exception ex)
1527     {
1528     }
1529
1530     if (b)
1531     {
1532       alignFrame.setDisplayedView(this);
1533     }
1534   }
1535
1536   @Override
1537   public StructureSelectionManager getStructureSelectionManager()
1538   {
1539     return av.getStructureSelectionManager();
1540   }
1541
1542   @Override
1543   public void raiseOOMWarning(String string, OutOfMemoryError error)
1544   {
1545     new OOMWarning(string, error, this);
1546   }
1547
1548   @Override
1549   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1550   {
1551
1552     return new FeatureRenderer(this);
1553   }
1554
1555   @Override
1556   public jalview.api.FeatureRenderer getFeatureRenderer()
1557   {
1558     return seqPanel.seqCanvas.getFeatureRenderer();
1559   }
1560
1561   public void updateFeatureRenderer(
1562           jalview.renderer.seqfeatures.FeatureRenderer fr)
1563   {
1564     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1565   }
1566
1567   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1568   {
1569     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1570     {
1571       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1572     }
1573   }
1574
1575   public ScalePanel getScalePanel()
1576   {
1577     return scalePanel;
1578   }
1579
1580   public void setScalePanel(ScalePanel scalePanel)
1581   {
1582     this.scalePanel = scalePanel;
1583   }
1584
1585   public SeqPanel getSeqPanel()
1586   {
1587     return seqPanel;
1588   }
1589
1590   public void setSeqPanel(SeqPanel seqPanel)
1591   {
1592     this.seqPanel = seqPanel;
1593   }
1594
1595   public AnnotationPanel getAnnotationPanel()
1596   {
1597     return annotationPanel;
1598   }
1599
1600   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1601   {
1602     this.annotationPanel = annotationPanel;
1603   }
1604
1605   public AnnotationLabels getAlabels()
1606   {
1607     return alabels;
1608   }
1609
1610   public void setAlabels(AnnotationLabels alabels)
1611   {
1612     this.alabels = alabels;
1613   }
1614
1615   public IdPanel getIdPanel()
1616   {
1617     return idPanel;
1618   }
1619
1620   public void setIdPanel(IdPanel idPanel)
1621   {
1622     this.idPanel = idPanel;
1623   }
1624
1625   /**
1626    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1627    * The aim is to keep the two alignments 'lined up' on their centre columns.
1628    * 
1629    * @param sr
1630    *          holds mapped region(s) of this alignment that we are scrolling
1631    *          'to'; may be modified for sequence offset by this method
1632    * @param verticalOffset
1633    *          the number of visible sequences to show above the mapped region
1634    */
1635   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1636   {
1637     scrollToPosition(sr, verticalOffset, true);
1638   }
1639
1640   /**
1641    * Set a flag to say do not scroll any (cDNA/protein) complement.
1642    * 
1643    * @param b
1644    */
1645   protected void setToScrollComplementPanel(boolean b)
1646   {
1647     this.scrollComplementaryPanel = b;
1648   }
1649
1650   /**
1651    * Get whether to scroll complement panel
1652    * 
1653    * @return true if cDNA/protein complement panels should be scrolled
1654    */
1655   protected boolean isSetToScrollComplementPanel()
1656   {
1657     return this.scrollComplementaryPanel;
1658   }
1659
1660   /**
1661    * Redraw sensibly.
1662    * 
1663    * @adjustHeight if true, try to recalculate panel height for visible
1664    *               annotations
1665    */
1666   protected void refresh(boolean adjustHeight)
1667   {
1668     validateAnnotationDimensions(adjustHeight);
1669     addNotify();
1670     if (adjustHeight)
1671     {
1672       // sort, repaint, update overview
1673       paintAlignment(true, false);
1674     }
1675     else
1676     {
1677       // lightweight repaint
1678       repaint();
1679     }
1680   }
1681
1682   @Override
1683   /**
1684    * Property change event fired when a change is made to the viewport ranges
1685    * object associated with this alignment panel's viewport
1686    */
1687   public void propertyChange(PropertyChangeEvent evt)
1688   {
1689     // update this panel's scroll values based on the new viewport ranges values
1690     ViewportRanges ranges = av.getRanges();
1691     int x = ranges.getStartRes();
1692     int y = ranges.getStartSeq();
1693     setScrollValues(x, y);
1694
1695     // now update any complementary alignment (its viewport ranges object
1696     // is different so does not get automatically updated)
1697     if (isSetToScrollComplementPanel())
1698     {
1699       setToScrollComplementPanel(false);
1700       av.scrollComplementaryAlignment();
1701       setToScrollComplementPanel(true);
1702     }
1703   }
1704
1705   /**
1706    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1707    * reference should be nulled when the dialog is closed.
1708    * 
1709    * @param calculationChooser
1710    */
1711   public void setCalculationDialog(CalculationChooser calculationChooser)
1712   {
1713     calculationDialog = calculationChooser;
1714   }
1715
1716   /**
1717    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1718    * if none is open)
1719    */
1720   public CalculationChooser getCalculationDialog()
1721   {
1722     return calculationDialog;
1723   }
1724
1725 }