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