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