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