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