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