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