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