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