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