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