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