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