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