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