JAL-2094 new classes ColorI, Colour added
[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     long pSessionId = System.currentTimeMillis();
1274     headless = (System.getProperty("java.awt.headless") != null && System
1275             .getProperty("java.awt.headless").equals("true"));
1276     if (alignFrame != null && !headless)
1277     {
1278       if (file != null)
1279       {
1280         alignFrame.setProgressBar(MessageManager.formatMessage(
1281               "status.saving_file", new Object[] { type.getLabel() }),
1282                 pSessionId);
1283       }
1284     }
1285     try
1286     {
1287       AlignmentDimension aDimension = getAlignmentDimension();
1288       try
1289       {
1290         jalview.util.ImageMaker im;
1291         final String imageAction, imageTitle;
1292         if (type == jalview.util.ImageMaker.TYPE.PNG)
1293         {
1294           imageAction = "Create PNG image from alignment";
1295           imageTitle = null;
1296         }
1297         else if (type == jalview.util.ImageMaker.TYPE.EPS)
1298         {
1299           imageAction = "Create EPS file from alignment";
1300           imageTitle = alignFrame.getTitle();
1301         }
1302         else
1303         {
1304           imageAction = "Create SVG file from alignment";
1305           imageTitle = alignFrame.getTitle();
1306         }
1307
1308         im = new jalview.util.ImageMaker(this, type, imageAction,
1309                 aDimension.getWidth(), aDimension.getHeight(), file,
1310                 imageTitle, alignFrame, pSessionId, headless);
1311         if (av.getWrapAlignment())
1312         {
1313           if (im.getGraphics() != null)
1314           {
1315             printWrappedAlignment(im.getGraphics(), aDimension.getWidth(),
1316                     aDimension.getHeight(), 0);
1317             im.writeImage();
1318           }
1319         }
1320         else
1321         {
1322           if (im.getGraphics() != null)
1323           {
1324             printUnwrapped(im.getGraphics(), aDimension.getWidth(),
1325                     aDimension.getHeight(), 0);
1326             im.writeImage();
1327           }
1328         }
1329
1330       } catch (OutOfMemoryError err)
1331       {
1332         // Be noisy here.
1333         System.out.println("########################\n" + "OUT OF MEMORY "
1334                 + file + "\n" + "########################");
1335         new OOMWarning("Creating Image for " + file, err);
1336         // System.out.println("Create IMAGE: " + err);
1337       } catch (Exception ex)
1338       {
1339         ex.printStackTrace();
1340       }
1341     } finally
1342     {
1343
1344     }
1345   }
1346
1347   public AlignmentDimension getAlignmentDimension()
1348   {
1349     int maxwidth = av.getAlignment().getWidth();
1350     if (av.hasHiddenColumns())
1351     {
1352       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth);
1353     }
1354
1355     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1356             + getScalePanel().getHeight();
1357     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1358
1359     if (av.getWrapAlignment())
1360     {
1361       height = getWrappedHeight();
1362       if (headless)
1363       {
1364         // need to obtain default alignment width and then add in any
1365         // additional allowance for id margin
1366         // this duplicates the calculation in getWrappedHeight but adjusts for
1367         // offscreen idWith
1368         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1369                 - alignFrame.getInsets().left
1370                 - alignFrame.getInsets().right - getVisibleIdWidth()
1371                 + getVisibleIdWidth(false);
1372       }
1373       else
1374       {
1375         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1376       }
1377
1378     }
1379     else if (av.isShowAnnotation())
1380     {
1381       height += getAnnotationPanel().adjustPanelHeight() + 3;
1382     }
1383     return new AlignmentDimension(width, height);
1384
1385   }
1386
1387   /**
1388    * DOCUMENT ME!
1389    */
1390   public void makeEPS(File epsFile)
1391   {
1392     makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1393   }
1394
1395   /**
1396    * DOCUMENT ME!
1397    */
1398   public void makePNG(File pngFile)
1399   {
1400     makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1401   }
1402
1403   public void makeSVG(File svgFile)
1404   {
1405     makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1406   }
1407
1408   public void makePNGImageMap(File imgMapFile, String imageName)
1409   {
1410     // /////ONLY WORKS WITH NONE WRAPPED ALIGNMENTS
1411     // ////////////////////////////////////////////
1412     int idWidth = getVisibleIdWidth(false);
1413     FontMetrics fm = getFontMetrics(av.getFont());
1414     int scaleHeight = av.getCharHeight() + fm.getDescent();
1415
1416     // Gen image map
1417     // ////////////////////////////////
1418     if (imgMapFile != null)
1419     {
1420       try
1421       {
1422         int s, sSize = av.getAlignment().getHeight(), res, alwidth = av
1423                 .getAlignment().getWidth(), g, gSize, f, fSize, sy;
1424         StringBuffer text = new StringBuffer();
1425         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1426         out.println(jalview.io.HTMLOutput.getImageMapHTML());
1427         out.println("<img src=\"" + imageName
1428                 + "\" border=\"0\" usemap=\"#Map\" >"
1429                 + "<map name=\"Map\">");
1430
1431         for (s = 0; s < sSize; s++)
1432         {
1433           sy = s * av.getCharHeight() + scaleHeight;
1434
1435           SequenceI seq = av.getAlignment().getSequenceAt(s);
1436           SequenceFeature[] features = seq.getSequenceFeatures();
1437           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1438           for (res = 0; res < alwidth; res++)
1439           {
1440             text = new StringBuffer();
1441             String triplet = null;
1442             if (av.getAlignment().isNucleotide())
1443             {
1444               triplet = ResidueProperties.nucleotideName.get(seq
1445                       .getCharAt(res) + "");
1446             }
1447             else
1448             {
1449               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(res)
1450                       + "");
1451             }
1452
1453             if (triplet == null)
1454             {
1455               continue;
1456             }
1457
1458             int alIndex = seq.findPosition(res);
1459             gSize = groups.length;
1460             for (g = 0; g < gSize; g++)
1461             {
1462               if (text.length() < 1)
1463               {
1464                 text.append("<area shape=\"rect\" coords=\""
1465                         + (idWidth + res * av.getCharWidth()) + "," + sy
1466                         + "," + (idWidth + (res + 1) * av.getCharWidth())
1467                         + "," + (av.getCharHeight() + sy) + "\""
1468                         + " onMouseOver=\"toolTip('" + alIndex + " "
1469                         + triplet);
1470               }
1471
1472               if (groups[g].getStartRes() < res
1473                       && groups[g].getEndRes() > res)
1474               {
1475                 text.append("<br><em>" + groups[g].getName() + "</em>");
1476               }
1477             }
1478
1479             if (features != null)
1480             {
1481               if (text.length() < 1)
1482               {
1483                 text.append("<area shape=\"rect\" coords=\""
1484                         + (idWidth + res * av.getCharWidth()) + "," + sy
1485                         + "," + (idWidth + (res + 1) * av.getCharWidth())
1486                         + "," + (av.getCharHeight() + sy) + "\""
1487                         + " onMouseOver=\"toolTip('" + alIndex + " "
1488                         + triplet);
1489               }
1490               fSize = features.length;
1491               for (f = 0; f < fSize; f++)
1492               {
1493
1494                 if ((features[f].getBegin() <= seq.findPosition(res))
1495                         && (features[f].getEnd() >= seq.findPosition(res)))
1496                 {
1497                   if (features[f].getType().equals("disulfide bond"))
1498                   {
1499                     if (features[f].getBegin() == seq.findPosition(res)
1500                             || features[f].getEnd() == seq
1501                                     .findPosition(res))
1502                     {
1503                       text.append("<br>disulfide bond "
1504                               + features[f].getBegin() + ":"
1505                               + features[f].getEnd());
1506                     }
1507                   }
1508                   else
1509                   {
1510                     text.append("<br>");
1511                     text.append(features[f].getType());
1512                     if (features[f].getDescription() != null
1513                             && !features[f].getType().equals(
1514                                     features[f].getDescription()))
1515                     {
1516                       text.append(" " + features[f].getDescription());
1517                     }
1518
1519                     if (features[f].getValue("status") != null)
1520                     {
1521                       text.append(" (" + features[f].getValue("status")
1522                               + ")");
1523                     }
1524                   }
1525                 }
1526
1527               }
1528             }
1529             if (text.length() > 1)
1530             {
1531               text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1532               out.println(text.toString());
1533             }
1534           }
1535         }
1536         out.println("</map></body></html>");
1537         out.close();
1538
1539       } catch (Exception ex)
1540       {
1541         ex.printStackTrace();
1542       }
1543     } // /////////END OF IMAGE MAP
1544
1545   }
1546
1547   int getWrappedHeight()
1548   {
1549     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1550
1551     if (System.getProperty("java.awt.headless") != null
1552             && System.getProperty("java.awt.headless").equals("true"))
1553     {
1554       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1555               - vscroll.getPreferredSize().width
1556               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1557     }
1558
1559     int chunkWidth = getSeqPanel().seqCanvas
1560             .getWrappedCanvasWidth(seqPanelWidth);
1561
1562     int hgap = av.getCharHeight();
1563     if (av.getScaleAboveWrapped())
1564     {
1565       hgap += av.getCharHeight();
1566     }
1567
1568     int annotationHeight = 0;
1569     if (av.isShowAnnotation())
1570     {
1571       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1572     }
1573
1574     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1575             + annotationHeight;
1576
1577     int maxwidth = av.getAlignment().getWidth();
1578     if (av.hasHiddenColumns())
1579     {
1580       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
1581     }
1582
1583     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1584
1585     return height;
1586   }
1587
1588   /**
1589    * close the panel - deregisters all listeners and nulls any references to
1590    * alignment data.
1591    */
1592   public void closePanel()
1593   {
1594     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1595     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1596     PaintRefresher.RemoveComponent(this);
1597     if (av != null)
1598     {
1599       jalview.structure.StructureSelectionManager ssm = av
1600               .getStructureSelectionManager();
1601       ssm.removeStructureViewerListener(getSeqPanel(), null);
1602       ssm.removeSelectionListener(getSeqPanel());
1603       ssm.removeCommandListener(av);
1604       ssm.removeStructureViewerListener(getSeqPanel(), null);
1605       ssm.removeSelectionListener(getSeqPanel());
1606       av.setAlignment(null);
1607       av = null;
1608     }
1609     else
1610     {
1611       if (Cache.log.isDebugEnabled())
1612       {
1613         Cache.log.warn("Closing alignment panel which is already closed.");
1614       }
1615     }
1616   }
1617
1618   /**
1619    * hides or shows dynamic annotation rows based on groups and av state flags
1620    */
1621   public void updateAnnotation()
1622   {
1623     updateAnnotation(false, false);
1624   }
1625
1626   public void updateAnnotation(boolean applyGlobalSettings)
1627   {
1628     updateAnnotation(applyGlobalSettings, false);
1629   }
1630
1631   public void updateAnnotation(boolean applyGlobalSettings,
1632           boolean preserveNewGroupSettings)
1633   {
1634     av.updateGroupAnnotationSettings(applyGlobalSettings,
1635             preserveNewGroupSettings);
1636     adjustAnnotationHeight();
1637   }
1638
1639   @Override
1640   public AlignmentI getAlignment()
1641   {
1642     return av == null ? null : av.getAlignment();
1643   }
1644
1645   @Override
1646   public String getViewName()
1647   {
1648     return av.viewName;
1649   }
1650
1651   /**
1652    * Make/Unmake this alignment panel the current input focus
1653    * 
1654    * @param b
1655    */
1656   public void setSelected(boolean b)
1657   {
1658     try
1659     {
1660       if (alignFrame.getSplitViewContainer() != null)
1661       {
1662         /*
1663          * bring enclosing SplitFrame to front first if there is one
1664          */
1665         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1666       }
1667       alignFrame.setSelected(b);
1668     } catch (Exception ex)
1669     {
1670     }
1671
1672     if (b)
1673     {
1674       alignFrame.setDisplayedView(this);
1675     }
1676   }
1677
1678   @Override
1679   public StructureSelectionManager getStructureSelectionManager()
1680   {
1681     return av.getStructureSelectionManager();
1682   }
1683
1684   @Override
1685   public void raiseOOMWarning(String string, OutOfMemoryError error)
1686   {
1687     new OOMWarning(string, error, this);
1688   }
1689
1690   @Override
1691   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1692   {
1693
1694     return new FeatureRenderer(this);
1695   }
1696
1697   @Override
1698   public jalview.api.FeatureRenderer getFeatureRenderer()
1699   {
1700     return seqPanel.seqCanvas.getFeatureRenderer();
1701   }
1702
1703   public void updateFeatureRenderer(
1704           jalview.renderer.seqfeatures.FeatureRenderer fr)
1705   {
1706     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1707   }
1708
1709   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1710   {
1711     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1712     {
1713       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1714     }
1715   }
1716
1717   public ScalePanel getScalePanel()
1718   {
1719     return scalePanel;
1720   }
1721
1722   public void setScalePanel(ScalePanel scalePanel)
1723   {
1724     this.scalePanel = scalePanel;
1725   }
1726
1727   public SeqPanel getSeqPanel()
1728   {
1729     return seqPanel;
1730   }
1731
1732   public void setSeqPanel(SeqPanel seqPanel)
1733   {
1734     this.seqPanel = seqPanel;
1735   }
1736
1737   public AnnotationPanel getAnnotationPanel()
1738   {
1739     return annotationPanel;
1740   }
1741
1742   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1743   {
1744     this.annotationPanel = annotationPanel;
1745   }
1746
1747   public AnnotationLabels getAlabels()
1748   {
1749     return alabels;
1750   }
1751
1752   public void setAlabels(AnnotationLabels alabels)
1753   {
1754     this.alabels = alabels;
1755   }
1756
1757   public IdPanel getIdPanel()
1758   {
1759     return idPanel;
1760   }
1761
1762   public void setIdPanel(IdPanel idPanel)
1763   {
1764     this.idPanel = idPanel;
1765   }
1766
1767   /**
1768    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1769    * The aim is to keep the two alignments 'lined up' on their centre columns.
1770    * 
1771    * @param sr
1772    *          holds mapped region(s) of this alignment that we are scrolling
1773    *          'to'; may be modified for sequence offset by this method
1774    * @param verticalOffset
1775    *          the number of visible sequences to show above the mapped region
1776    */
1777   public void scrollToCentre(SearchResults sr, int verticalOffset)
1778   {
1779     /*
1780      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
1781      * mapped), we can make the scroll-to location a sequence above the one
1782      * actually mapped.
1783      */
1784     SequenceI mappedTo = sr.getResultSequence(0);
1785     List<SequenceI> seqs = av.getAlignment().getSequences();
1786
1787     /*
1788      * This is like AlignmentI.findIndex(seq) but here we are matching the
1789      * dataset sequence not the aligned sequence
1790      */
1791     boolean matched = false;
1792     for (SequenceI seq : seqs)
1793     {
1794       if (mappedTo == seq.getDatasetSequence())
1795       {
1796         matched = true;
1797         break;
1798       }
1799     }
1800     if (!matched)
1801     {
1802       return; // failsafe, shouldn't happen
1803     }
1804
1805     /*
1806      * Scroll to position but centring the target residue.
1807      */
1808     scrollToPosition(sr, verticalOffset, true, true);
1809   }
1810
1811   /**
1812    * Set a flag to say do not scroll any (cDNA/protein) complement.
1813    * 
1814    * @param b
1815    */
1816   protected void setDontScrollComplement(boolean b)
1817   {
1818     this.dontScrollComplement = b;
1819   }
1820
1821   protected boolean isDontScrollComplement()
1822   {
1823     return this.dontScrollComplement;
1824   }
1825 }