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