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