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