JAL-2491 Tweaks for applet
[jalview.git] / src / jalview / gui / AlignmentPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.Cache;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.jbgui.GAlignmentPanel;
33 import jalview.math.AlignmentDimension;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.StructureSelectionManager;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.ViewportListenerI;
39 import jalview.viewmodel.ViewportRanges;
40
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Container;
44 import java.awt.Dimension;
45 import java.awt.Font;
46 import java.awt.FontMetrics;
47 import java.awt.Graphics;
48 import java.awt.Insets;
49 import java.awt.event.AdjustmentEvent;
50 import java.awt.event.AdjustmentListener;
51 import java.awt.event.ComponentAdapter;
52 import java.awt.event.ComponentEvent;
53 import java.awt.print.PageFormat;
54 import java.awt.print.Printable;
55 import java.awt.print.PrinterException;
56 import java.beans.PropertyChangeEvent;
57 import java.beans.PropertyChangeListener;
58 import java.io.File;
59 import java.io.FileWriter;
60 import java.io.PrintWriter;
61 import java.util.List;
62
63 import javax.swing.SwingUtilities;
64
65 /**
66  * DOCUMENT ME!
67  * 
68  * @author $author$
69  * @version $Revision: 1.161 $
70  */
71 public class AlignmentPanel extends GAlignmentPanel implements
72         AdjustmentListener, Printable, AlignmentViewPanel,
73         ViewportListenerI
74 {
75   public AlignViewport av;
76
77   ViewportRanges vpRanges;
78
79   OverviewPanel overviewPanel;
80
81   private SeqPanel seqPanel;
82
83   private IdPanel idPanel;
84
85   private boolean headless;
86
87   IdwidthAdjuster idwidthAdjuster;
88
89   /** DOCUMENT ME!! */
90   public AlignFrame alignFrame;
91
92   private ScalePanel scalePanel;
93
94   private AnnotationPanel annotationPanel;
95
96   private AnnotationLabels alabels;
97
98   // this value is set false when selection area being dragged
99   boolean fastPaint = true;
100
101   private int hextent = 0;
102
103   private int vextent = 0;
104
105   /*
106    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
107    * true, suppresses invoking the same method recursively.
108    */
109   private boolean dontScrollComplement = false;
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             setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
773           }
774         });
775       }
776       repaint();
777     }
778     else
779     {
780       // horizontal scroll
781       if (evt.getSource() == hscroll)
782       {
783         int x = hscroll.getValue();
784         int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
785
786         // if we're scrolling to the position we're already at, stop
787         // this prevents infinite recursion of events when the scroll/viewport
788         // ranges values are the same
789         if ((x == oldX) && (width == oldwidth))
790         {
791           return;
792         }
793         vpRanges.setViewportStartAndWidth(x, width);
794       }
795       else if (evt.getSource() == vscroll)
796       {
797         int y = vscroll.getValue();
798         int height = getSeqPanel().seqCanvas.getHeight()
799                 / av.getCharHeight();
800
801         // if we're scrolling to the position we're already at, stop
802         // this prevents infinite recursion of events when the scroll/viewport
803         // ranges values are the same
804         if ((y == oldY) && (height == oldheight))
805         {
806           return;
807         }
808         vpRanges.setViewportStartAndHeight(y, height);
809       }
810       if (!fastPaint)
811       {
812         repaint();
813       }
814     }
815   }
816
817   /**
818    * Repaint the alignment including the annotations and overview panels (if
819    * shown).
820    */
821   @Override
822   public void paintAlignment(boolean updateOverview)
823   {
824     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
825             av.isShowAutocalculatedAbove());
826     sorter.sort(getAlignment().getAlignmentAnnotation(),
827             av.getSortAnnotationsBy());
828     repaint();
829
830     if (updateOverview)
831     {
832       // TODO: determine if this paintAlignment changed structure colours
833       av.getStructureSelectionManager().sequenceColoursChanged(this);
834
835       if (overviewPanel != null)
836       {
837         overviewPanel.updateOverviewImage();
838       }
839     }
840   }
841
842   /**
843    * DOCUMENT ME!
844    * 
845    * @param g
846    *          DOCUMENT ME!
847    */
848   @Override
849   public void paintComponent(Graphics g)
850   {
851     invalidate();
852
853     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
854     idPanelHolder.setPreferredSize(d);
855     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
856     validate();
857
858     /*
859      * set scroll bar positions
860      */
861     setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
862   }
863
864   /*
865    * Set vertical scroll bar parameters for wrapped panel
866    * @param res 
867    *    the residue to scroll to
868    */
869   private void setScrollingForWrappedPanel(int res)
870   {
871     // get the width of the alignment in residues
872     int maxwidth = av.getAlignment().getWidth();
873     if (av.hasHiddenColumns())
874     {
875       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
876     }
877
878     // get the width of the canvas in residues
879     int canvasWidth = getSeqPanel().seqCanvas
880             .getWrappedCanvasWidth(getSeqPanel().seqCanvas.getWidth());
881     if (canvasWidth > 0)
882     {
883       // position we want to scroll to is number of canvasWidth's to get there
884       int current = res / canvasWidth;
885
886       // max scroll position: add one because extent is 1 and scrollbar value
887       // can only be set to at most max - extent
888       int max = maxwidth / canvasWidth + 1;
889       vscroll.setUnitIncrement(1);
890       vscroll.setValues(current, 1, 0, max);
891     }
892   }
893
894   /**
895    * DOCUMENT ME!
896    * 
897    * @param pg
898    *          DOCUMENT ME!
899    * @param pf
900    *          DOCUMENT ME!
901    * @param pi
902    *          DOCUMENT ME!
903    * 
904    * @return DOCUMENT ME!
905    * 
906    * @throws PrinterException
907    *           DOCUMENT ME!
908    */
909   @Override
910   public int print(Graphics pg, PageFormat pf, int pi)
911           throws PrinterException
912   {
913     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
914
915     int pwidth = (int) pf.getImageableWidth();
916     int pheight = (int) pf.getImageableHeight();
917
918     if (av.getWrapAlignment())
919     {
920       return printWrappedAlignment(pwidth, pheight, pi, pg);
921     }
922     else
923     {
924       return printUnwrapped(pwidth, pheight, pi, pg, pg);
925     }
926   }
927
928   /**
929    * DOCUMENT ME!
930    * 
931    * @param pg
932    *          DOCUMENT ME!
933    * @param pwidth
934    *          DOCUMENT ME!
935    * @param pheight
936    *          DOCUMENT ME!
937    * @param pi
938    *          DOCUMENT ME!
939    * 
940    * @return DOCUMENT ME!
941    * 
942    * @throws PrinterException
943    *           DOCUMENT ME!
944    */
945   /**
946    * Draws the alignment image, including sequence ids, sequences, and
947    * annotation labels and annotations if shown, on either one or two Graphics
948    * context.
949    * 
950    * @param pageWidth
951    * @param pageHeight
952    * @param pi
953    * @param idGraphics
954    *          the graphics context for sequence ids and annotation labels
955    * @param alignmentGraphics
956    *          the graphics context for sequences and annotations (may or may not
957    *          be the same context as idGraphics)
958    * @return
959    * @throws PrinterException
960    */
961   public int printUnwrapped(int pageWidth, int pageHeight, int pi,
962           Graphics idGraphics, Graphics alignmentGraphics)
963           throws PrinterException
964   {
965     final int idWidth = getVisibleIdWidth(false);
966
967     /*
968      * Get the horizontal offset to where we draw the sequences.
969      * This is idWidth if using a single Graphics context, else zero.
970      */
971     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0 : idWidth;
972
973     FontMetrics fm = getFontMetrics(av.getFont());
974     int charHeight = av.getCharHeight();
975     int scaleHeight = charHeight + fm.getDescent();
976
977     idGraphics.setColor(Color.white);
978     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
979     idGraphics.setFont(av.getFont());
980
981     /*
982      * How many sequences and residues can we fit on a printable page?
983      */
984     int totalRes = (pageWidth - idWidth) / av.getCharWidth();
985
986     int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
987
988     int alignmentWidth = av.getAlignment().getWidth();
989     int pagesWide = (alignmentWidth / totalRes) + 1;
990
991     final int startRes = (pi % pagesWide) * totalRes;
992     int endRes = (startRes + totalRes) - 1;
993
994     if (endRes > (alignmentWidth - 1))
995     {
996       endRes = alignmentWidth - 1;
997     }
998
999     final int startSeq = (pi / pagesWide) * totalSeq;
1000     int endSeq = startSeq + totalSeq;
1001
1002     int alignmentHeight = av.getAlignment().getHeight();
1003     if (endSeq > alignmentHeight)
1004     {
1005       endSeq = alignmentHeight;
1006     }
1007
1008     int pagesHigh = ((alignmentHeight / totalSeq) + 1)
1009             * pageHeight;
1010
1011     if (av.isShowAnnotation())
1012     {
1013       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1014     }
1015
1016     pagesHigh /= pageHeight;
1017
1018     if (pi >= (pagesWide * pagesHigh))
1019     {
1020       return Printable.NO_SUCH_PAGE;
1021     }
1022     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight
1023             + 3;
1024
1025     /*
1026      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1027      */
1028     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1029     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1030             pageWidth - idWidth, scaleHeight);
1031     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1032
1033     /*
1034      * Draw the sequence ids, offset for scale height,
1035      * then reset to top left (0, 0)
1036      */
1037     idGraphics.translate(0, scaleHeight);
1038     idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1039     Color currentColor = null;
1040     Color currentTextColor = null;
1041
1042     SequenceI seq;
1043     for (int i = startSeq; i < endSeq; i++)
1044     {
1045       seq = av.getAlignment().getSequenceAt(i);
1046       if ((av.getSelectionGroup() != null)
1047               && av.getSelectionGroup().getSequences(null).contains(seq))
1048       {
1049         /*
1050          * gray out ids of sequences in selection group (if any)
1051          */
1052         currentColor = Color.gray;
1053         currentTextColor = Color.black;
1054       }
1055       else
1056       {
1057         currentColor = av.getSequenceColour(seq);
1058         currentTextColor = Color.black;
1059       }
1060
1061       idGraphics.setColor(currentColor);
1062       idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1063               charHeight);
1064
1065       idGraphics.setColor(currentTextColor);
1066
1067       int xPos = 0;
1068       String displayId = seq.getDisplayId(av.getShowJVSuffix());
1069       if (av.isRightAlignIds())
1070       {
1071         fm = idGraphics.getFontMetrics();
1072         xPos = idWidth
1073                 - fm.stringWidth(displayId)
1074                 - 4;
1075       }
1076
1077       idGraphics.drawString(displayId, xPos,
1078               (((i - startSeq) * charHeight) + charHeight)
1079                       - (charHeight / 5));
1080     }
1081     idGraphics.setFont(av.getFont());
1082     idGraphics.translate(0, -scaleHeight);
1083
1084     /*
1085      * draw the sequences, offset for scale height, and id width (if using a
1086      * single graphics context), then reset to (0, scale height)
1087      */
1088     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1089     getSeqPanel().seqCanvas.drawPanel(alignmentGraphics, startRes, endRes,
1090             startSeq, endSeq, 0);
1091     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1092
1093     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1094     {
1095       /*
1096        * draw annotation labels; drawComponent() translates by
1097        * getScrollOffset(), so compensate for that first;
1098        * then reset to (0, scale height)
1099        */
1100       int offset = getAlabels().getScrollOffset();
1101       idGraphics.translate(0, -offset);
1102       idGraphics.translate(0, alignmentDrawnHeight);
1103       getAlabels().drawComponent(idGraphics, idWidth);
1104       idGraphics.translate(0, -alignmentDrawnHeight);
1105
1106       /*
1107        * draw the annotations starting at 
1108        * (idOffset, alignmentHeight) from (0, scaleHeight)
1109        */
1110       alignmentGraphics.translate(alignmentGraphicsOffset, alignmentDrawnHeight);
1111       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1112               alignmentGraphics, -1, startRes, endRes + 1);
1113     }
1114
1115     return Printable.PAGE_EXISTS;
1116   }
1117
1118   /**
1119    * DOCUMENT ME!
1120    * 
1121    * @param pg
1122    *          DOCUMENT ME!
1123    * @param pwidth
1124    *          DOCUMENT ME!
1125    * @param pheight
1126    *          DOCUMENT ME!
1127    * @param pi
1128    *          DOCUMENT ME!
1129    * 
1130    * @return DOCUMENT ME!
1131    * 
1132    * @throws PrinterException
1133    *           DOCUMENT ME!
1134    */
1135   public int printWrappedAlignment(int pwidth, int pheight, int pi,
1136           Graphics pg) throws PrinterException
1137   {
1138     int annotationHeight = 0;
1139     AnnotationLabels labels = null;
1140     if (av.isShowAnnotation())
1141     {
1142       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1143       labels = new AnnotationLabels(av);
1144     }
1145
1146     int hgap = av.getCharHeight();
1147     if (av.getScaleAboveWrapped())
1148     {
1149       hgap += av.getCharHeight();
1150     }
1151
1152     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1153             + annotationHeight;
1154
1155     int idWidth = getVisibleIdWidth(false);
1156
1157     int maxwidth = av.getAlignment().getWidth();
1158     if (av.hasHiddenColumns())
1159     {
1160       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1161     }
1162
1163     int resWidth = getSeqPanel().seqCanvas.getWrappedCanvasWidth(pwidth
1164             - idWidth);
1165
1166     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1167
1168     pg.setColor(Color.white);
1169     pg.fillRect(0, 0, pwidth, pheight);
1170     pg.setFont(av.getFont());
1171
1172     // //////////////
1173     // Draw the ids
1174     pg.setColor(Color.black);
1175
1176     pg.translate(0, -pi * pheight);
1177
1178     pg.setClip(0, pi * pheight, pwidth, pheight);
1179
1180     int ypos = hgap;
1181
1182     do
1183     {
1184       for (int i = 0; i < av.getAlignment().getHeight(); i++)
1185       {
1186         pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1187         SequenceI s = av.getAlignment().getSequenceAt(i);
1188         String string = s.getDisplayId(av.getShowJVSuffix());
1189         int xPos = 0;
1190         if (av.isRightAlignIds())
1191         {
1192           FontMetrics fm = pg.getFontMetrics();
1193           xPos = idWidth - fm.stringWidth(string) - 4;
1194         }
1195         pg.drawString(string, xPos,
1196                 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1197                         - (av.getCharHeight() / 5));
1198       }
1199       if (labels != null)
1200       {
1201         pg.translate(-3,
1202                 ypos + (av.getAlignment().getHeight() * av.getCharHeight()));
1203
1204         pg.setFont(av.getFont());
1205         labels.drawComponent(pg, idWidth);
1206         pg.translate(
1207                 +3,
1208                 -ypos
1209                         - (av.getAlignment().getHeight() * av
1210                                 .getCharHeight()));
1211       }
1212
1213       ypos += cHeight;
1214     } while (ypos < totalHeight);
1215
1216     pg.translate(idWidth, 0);
1217
1218     getSeqPanel().seqCanvas.drawWrappedPanel(pg, pwidth - idWidth,
1219             totalHeight, 0);
1220
1221     if ((pi * pheight) < totalHeight)
1222     {
1223       return Printable.PAGE_EXISTS;
1224
1225     }
1226     else
1227     {
1228       return Printable.NO_SUCH_PAGE;
1229     }
1230   }
1231
1232   /**
1233    * get current sequence ID panel width, or nominal value if panel were to be
1234    * displayed using default settings
1235    * 
1236    * @return
1237    */
1238   public int getVisibleIdWidth()
1239   {
1240     return getVisibleIdWidth(true);
1241   }
1242
1243   /**
1244    * get current sequence ID panel width, or nominal value if panel were to be
1245    * displayed using default settings
1246    * 
1247    * @param onscreen
1248    *          indicate if the Id width for onscreen or offscreen display should
1249    *          be returned
1250    * @return
1251    */
1252   public int getVisibleIdWidth(boolean onscreen)
1253   {
1254     // see if rendering offscreen - check preferences and calc width accordingly
1255     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1256     {
1257       return calculateIdWidth(-1).width + 4;
1258     }
1259     Integer idwidth = null;
1260     if (onscreen
1261             || (idwidth = Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1262     {
1263       int w = getIdPanel().getWidth();
1264       return (w > 0 ? w : calculateIdWidth().width + 4);
1265     }
1266     return idwidth.intValue() + 4;
1267   }
1268
1269   void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1270   {
1271     int boarderBottomOffset = 5;
1272     long pSessionId = System.currentTimeMillis();
1273     headless = (System.getProperty("java.awt.headless") != null && System
1274             .getProperty("java.awt.headless").equals("true"));
1275     if (alignFrame != null && !headless)
1276     {
1277       if (file != null)
1278       {
1279         alignFrame.setProgressBar(MessageManager.formatMessage(
1280                 "status.saving_file", new Object[] { type.getLabel() }),
1281                 pSessionId);
1282       }
1283     }
1284     try
1285     {
1286       AlignmentDimension aDimension = getAlignmentDimension();
1287       try
1288       {
1289         jalview.util.ImageMaker im;
1290         final String imageAction, imageTitle;
1291         if (type == jalview.util.ImageMaker.TYPE.PNG)
1292         {
1293           imageAction = "Create PNG image from alignment";
1294           imageTitle = null;
1295         }
1296         else if (type == jalview.util.ImageMaker.TYPE.EPS)
1297         {
1298           imageAction = "Create EPS file from alignment";
1299           imageTitle = alignFrame.getTitle();
1300         }
1301         else
1302         {
1303           imageAction = "Create SVG file from alignment";
1304           imageTitle = alignFrame.getTitle();
1305         }
1306
1307         im = new jalview.util.ImageMaker(this, type, imageAction,
1308                 aDimension.getWidth(), aDimension.getHeight()
1309                         + boarderBottomOffset, file, imageTitle,
1310                 alignFrame, pSessionId, headless);
1311         Graphics graphics = im.getGraphics();
1312         if (av.getWrapAlignment())
1313         {
1314           if (graphics != null)
1315           {
1316             printWrappedAlignment(aDimension.getWidth(),
1317                     aDimension.getHeight() + boarderBottomOffset, 0,
1318                     graphics);
1319             im.writeImage();
1320           }
1321         }
1322         else
1323         {
1324           if (graphics != null)
1325           {
1326             printUnwrapped(aDimension.getWidth(), aDimension.getHeight(),
1327                     0, graphics, graphics);
1328             im.writeImage();
1329           }
1330         }
1331
1332       } catch (OutOfMemoryError err)
1333       {
1334         // Be noisy here.
1335         System.out.println("########################\n" + "OUT OF MEMORY "
1336                 + file + "\n" + "########################");
1337         new OOMWarning("Creating Image for " + file, err);
1338         // System.out.println("Create IMAGE: " + err);
1339       } catch (Exception ex)
1340       {
1341         ex.printStackTrace();
1342       }
1343     } finally
1344     {
1345
1346     }
1347   }
1348
1349   public AlignmentDimension getAlignmentDimension()
1350   {
1351     int maxwidth = av.getAlignment().getWidth();
1352     if (av.hasHiddenColumns())
1353     {
1354       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1355     }
1356
1357     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1358             + getScalePanel().getHeight();
1359     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1360
1361     if (av.getWrapAlignment())
1362     {
1363       height = getWrappedHeight();
1364       if (headless)
1365       {
1366         // need to obtain default alignment width and then add in any
1367         // additional allowance for id margin
1368         // this duplicates the calculation in getWrappedHeight but adjusts for
1369         // offscreen idWith
1370         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1371                 - alignFrame.getInsets().left
1372                 - alignFrame.getInsets().right - getVisibleIdWidth()
1373                 + getVisibleIdWidth(false);
1374       }
1375       else
1376       {
1377         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1378       }
1379
1380     }
1381     else if (av.isShowAnnotation())
1382     {
1383       height += getAnnotationPanel().adjustPanelHeight() + 3;
1384     }
1385     return new AlignmentDimension(width, height);
1386
1387   }
1388
1389   /**
1390    * DOCUMENT ME!
1391    */
1392   public void makeEPS(File epsFile)
1393   {
1394     makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1395   }
1396
1397   /**
1398    * DOCUMENT ME!
1399    */
1400   public void makePNG(File pngFile)
1401   {
1402     makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1403   }
1404
1405   public void makeSVG(File svgFile)
1406   {
1407     makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1408   }
1409
1410   public void makePNGImageMap(File imgMapFile, String imageName)
1411   {
1412     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1413     // ////////////////////////////////////////////
1414     int idWidth = getVisibleIdWidth(false);
1415     FontMetrics fm = getFontMetrics(av.getFont());
1416     int scaleHeight = av.getCharHeight() + fm.getDescent();
1417
1418     // Gen image map
1419     // ////////////////////////////////
1420     if (imgMapFile != null)
1421     {
1422       try
1423       {
1424         int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1425                 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1426         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1427         out.println(jalview.io.HTMLOutput.getImageMapHTML());
1428         out.println("<img src=\"" + imageName
1429                 + "\" border=\"0\" usemap=\"#Map\" >"
1430                 + "<map name=\"Map\">");
1431
1432         for (s = 0; s < sSize; s++)
1433         {
1434           sy = s * av.getCharHeight() + scaleHeight;
1435
1436           SequenceI seq = av.getAlignment().getSequenceAt(s);
1437           SequenceFeature[] features = seq.getSequenceFeatures();
1438           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1439           for (res = 0; res < alwidth; res++)
1440           {
1441             StringBuilder text = new StringBuilder();
1442             String triplet = null;
1443             if (av.getAlignment().isNucleotide())
1444             {
1445               triplet = ResidueProperties.nucleotideName.get(seq
1446                       .getCharAt(res) + "");
1447             }
1448             else
1449             {
1450               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1451                       + "");
1452             }
1453
1454             if (triplet == null)
1455             {
1456               continue;
1457             }
1458
1459             int alIndex = seq.findPosition(res);
1460             gSize = groups.length;
1461             for (g = 0; g < gSize; g++)
1462             {
1463               if (text.length() < 1)
1464               {
1465                 text.append("<area shape=\"rect\" coords=\"")
1466                         .append((idWidth + res * av.getCharWidth()))
1467                         .append(",").append(sy).append(",")
1468                         .append((idWidth + (res + 1) * av.getCharWidth()))
1469                         .append(",").append((av.getCharHeight() + sy))
1470                         .append("\"").append(" onMouseOver=\"toolTip('")
1471                         .append(alIndex).append(" ").append(triplet);
1472               }
1473
1474               if (groups[g].getStartRes() < res
1475                       && groups[g].getEndRes() > res)
1476               {
1477                 text.append("<br><em>").append(groups[g].getName())
1478                         .append("</em>");
1479               }
1480             }
1481
1482             if (features != null)
1483             {
1484               if (text.length() < 1)
1485               {
1486                 text.append("<area shape=\"rect\" coords=\"")
1487                         .append((idWidth + res * av.getCharWidth()))
1488                         .append(",").append(sy).append(",")
1489                         .append((idWidth + (res + 1) * av.getCharWidth()))
1490                         .append(",").append((av.getCharHeight() + sy))
1491                         .append("\"").append(" onMouseOver=\"toolTip('")
1492                         .append(alIndex).append(" ").append(triplet);
1493               }
1494               fSize = features.length;
1495               for (f = 0; f < fSize; f++)
1496               {
1497
1498                 if ((features[f].getBegin() <= seq.findPosition(res))
1499                         && (features[f].getEnd() >= seq.findPosition(res)))
1500                 {
1501                   if (features[f].isContactFeature())
1502                   {
1503                     if (features[f].getBegin() == seq.findPosition(res)
1504                             || features[f].getEnd() == seq
1505                                     .findPosition(res))
1506                     {
1507                       text.append("<br>").append(features[f].getType())
1508                               .append(" ").append(features[f].getBegin())
1509                               .append(":").append(features[f].getEnd());
1510                     }
1511                   }
1512                   else
1513                   {
1514                     text.append("<br>");
1515                     text.append(features[f].getType());
1516                     if (features[f].getDescription() != null
1517                             && !features[f].getType().equals(
1518                                     features[f].getDescription()))
1519                     {
1520                       text.append(" ").append(features[f].getDescription());
1521                     }
1522
1523                     if (features[f].getValue("status") != null)
1524                     {
1525                       text.append(" (").append(features[f].getValue("status"))
1526                               .append(")");
1527                     }
1528                   }
1529                 }
1530
1531               }
1532             }
1533             if (text.length() > 1)
1534             {
1535               text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1536               out.println(text.toString());
1537             }
1538           }
1539         }
1540         out.println("</map></body></html>");
1541         out.close();
1542
1543       } catch (Exception ex)
1544       {
1545         ex.printStackTrace();
1546       }
1547     } // /////////END OF IMAGE MAP
1548
1549   }
1550
1551   int getWrappedHeight()
1552   {
1553     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1554
1555     if (System.getProperty("java.awt.headless") != null
1556             && System.getProperty("java.awt.headless").equals("true"))
1557     {
1558       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1559               - vscroll.getPreferredSize().width
1560               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1561     }
1562
1563     int chunkWidth = getSeqPanel().seqCanvas
1564             .getWrappedCanvasWidth(seqPanelWidth);
1565
1566     int hgap = av.getCharHeight();
1567     if (av.getScaleAboveWrapped())
1568     {
1569       hgap += av.getCharHeight();
1570     }
1571
1572     int annotationHeight = 0;
1573     if (av.isShowAnnotation())
1574     {
1575       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1576     }
1577
1578     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1579             + annotationHeight;
1580
1581     int maxwidth = av.getAlignment().getWidth();
1582     if (av.hasHiddenColumns())
1583     {
1584       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1585     }
1586
1587     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1588
1589     return height;
1590   }
1591
1592   /**
1593    * close the panel - deregisters all listeners and nulls any references to
1594    * alignment data.
1595    */
1596   public void closePanel()
1597   {
1598     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1599     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1600     PaintRefresher.RemoveComponent(this);
1601
1602     /*
1603      * try to ensure references are nulled
1604      */
1605     if (annotationPanel != null)
1606     {
1607       annotationPanel.dispose();
1608     }
1609
1610     if (av != null)
1611     {
1612       av.removePropertyChangeListener(propertyChangeListener);
1613       jalview.structure.StructureSelectionManager ssm = av
1614               .getStructureSelectionManager();
1615       ssm.removeStructureViewerListener(getSeqPanel(), null);
1616       ssm.removeSelectionListener(getSeqPanel());
1617       ssm.removeCommandListener(av);
1618       ssm.removeStructureViewerListener(getSeqPanel(), null);
1619       ssm.removeSelectionListener(getSeqPanel());
1620       av.dispose();
1621       av = null;
1622     }
1623     else
1624     {
1625       if (Cache.log.isDebugEnabled())
1626       {
1627         Cache.log.warn("Closing alignment panel which is already closed.");
1628       }
1629     }
1630   }
1631
1632   /**
1633    * hides or shows dynamic annotation rows based on groups and av state flags
1634    */
1635   public void updateAnnotation()
1636   {
1637     updateAnnotation(false, false);
1638   }
1639
1640   public void updateAnnotation(boolean applyGlobalSettings)
1641   {
1642     updateAnnotation(applyGlobalSettings, false);
1643   }
1644
1645   public void updateAnnotation(boolean applyGlobalSettings,
1646           boolean preserveNewGroupSettings)
1647   {
1648     av.updateGroupAnnotationSettings(applyGlobalSettings,
1649             preserveNewGroupSettings);
1650     adjustAnnotationHeight();
1651   }
1652
1653   @Override
1654   public AlignmentI getAlignment()
1655   {
1656     return av == null ? null : av.getAlignment();
1657   }
1658
1659   @Override
1660   public String getViewName()
1661   {
1662     return av.viewName;
1663   }
1664
1665   /**
1666    * Make/Unmake this alignment panel the current input focus
1667    * 
1668    * @param b
1669    */
1670   public void setSelected(boolean b)
1671   {
1672     try
1673     {
1674       if (alignFrame.getSplitViewContainer() != null)
1675       {
1676         /*
1677          * bring enclosing SplitFrame to front first if there is one
1678          */
1679         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1680       }
1681       alignFrame.setSelected(b);
1682     } catch (Exception ex)
1683     {
1684     }
1685
1686     if (b)
1687     {
1688       alignFrame.setDisplayedView(this);
1689     }
1690   }
1691
1692   @Override
1693   public StructureSelectionManager getStructureSelectionManager()
1694   {
1695     return av.getStructureSelectionManager();
1696   }
1697
1698   @Override
1699   public void raiseOOMWarning(String string, OutOfMemoryError error)
1700   {
1701     new OOMWarning(string, error, this);
1702   }
1703
1704   @Override
1705   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1706   {
1707
1708     return new FeatureRenderer(this);
1709   }
1710
1711   @Override
1712   public jalview.api.FeatureRenderer getFeatureRenderer()
1713   {
1714     return seqPanel.seqCanvas.getFeatureRenderer();
1715   }
1716
1717   public void updateFeatureRenderer(
1718           jalview.renderer.seqfeatures.FeatureRenderer fr)
1719   {
1720     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1721   }
1722
1723   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1724   {
1725     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1726     {
1727       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1728     }
1729   }
1730
1731   public ScalePanel getScalePanel()
1732   {
1733     return scalePanel;
1734   }
1735
1736   public void setScalePanel(ScalePanel scalePanel)
1737   {
1738     this.scalePanel = scalePanel;
1739   }
1740
1741   public SeqPanel getSeqPanel()
1742   {
1743     return seqPanel;
1744   }
1745
1746   public void setSeqPanel(SeqPanel seqPanel)
1747   {
1748     this.seqPanel = seqPanel;
1749   }
1750
1751   public AnnotationPanel getAnnotationPanel()
1752   {
1753     return annotationPanel;
1754   }
1755
1756   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1757   {
1758     this.annotationPanel = annotationPanel;
1759   }
1760
1761   public AnnotationLabels getAlabels()
1762   {
1763     return alabels;
1764   }
1765
1766   public void setAlabels(AnnotationLabels alabels)
1767   {
1768     this.alabels = alabels;
1769   }
1770
1771   public IdPanel getIdPanel()
1772   {
1773     return idPanel;
1774   }
1775
1776   public void setIdPanel(IdPanel idPanel)
1777   {
1778     this.idPanel = idPanel;
1779   }
1780
1781   /**
1782    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1783    * The aim is to keep the two alignments 'lined up' on their centre columns.
1784    * 
1785    * @param sr
1786    *          holds mapped region(s) of this alignment that we are scrolling
1787    *          'to'; may be modified for sequence offset by this method
1788    * @param verticalOffset
1789    *          the number of visible sequences to show above the mapped region
1790    */
1791   public void scrollToCentre(SearchResultsI sr, int verticalOffset)
1792   {
1793     /*
1794      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1795      * mapped), we can make the scroll-to location a sequence above the one
1796      * actually mapped.
1797      */
1798     SequenceI mappedTo = sr.getResults().get(0).getSequence();
1799     List<SequenceI> seqs = av.getAlignment().getSequences();
1800
1801     /*
1802      * This is like AlignmentI.findIndex(seq) but here we are matching the
1803      * dataset sequence not the aligned sequence
1804      */
1805     boolean matched = false;
1806     for (SequenceI seq : seqs)
1807     {
1808       if (mappedTo == seq.getDatasetSequence())
1809       {
1810         matched = true;
1811         break;
1812       }
1813     }
1814     if (!matched)
1815     {
1816       return; // failsafe, shouldn't happen
1817     }
1818
1819     /*
1820      * Scroll to position but centring the target residue.
1821      */
1822     scrollToPosition(sr, verticalOffset, true, true);
1823   }
1824
1825   /**
1826    * Set a flag to say do not scroll any (cDNA/protein) complement.
1827    * 
1828    * @param b
1829    */
1830   protected void setDontScrollComplement(boolean b)
1831   {
1832     this.dontScrollComplement = b;
1833   }
1834
1835   protected boolean isDontScrollComplement()
1836   {
1837     return this.dontScrollComplement;
1838   }
1839
1840   /**
1841    * Redraw sensibly.
1842    * 
1843    * @adjustHeight if true, try to recalculate panel height for visible
1844    *               annotations
1845    */
1846   protected void refresh(boolean adjustHeight)
1847   {
1848     validateAnnotationDimensions(adjustHeight);
1849     addNotify();
1850     if (adjustHeight)
1851     {
1852       // sort, repaint, update overview
1853       paintAlignment(true);
1854     }
1855     else
1856     {
1857       // lightweight repaint
1858       repaint();
1859     }
1860   }
1861
1862   @Override
1863   /**
1864    * Property change event fired when a change is made to the viewport ranges 
1865    * object associated with this alignment panel's viewport
1866    */
1867   public void propertyChange(PropertyChangeEvent evt)
1868   {
1869     // update this panel's scroll values based on the new viewport ranges values
1870     int x = vpRanges.getStartRes();
1871     int y = vpRanges.getStartSeq();
1872     setScrollValues(x, y);
1873
1874     // now update any complementary alignment (its viewport ranges object
1875     // is different so does not get automatically updated)
1876     if (!isDontScrollComplement())
1877     {
1878       setDontScrollComplement(true);
1879       av.scrollComplementaryAlignment();
1880       setDontScrollComplement(false);
1881     }
1882   }
1883 }