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