JAL-3048 inlined 1-line methods, small refactor of ImageMaker.TYPE
[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.util.Platform;
42 import jalview.viewmodel.ViewportListenerI;
43 import jalview.viewmodel.ViewportRanges;
44
45 import java.awt.BorderLayout;
46 import java.awt.Color;
47 import java.awt.Container;
48 import java.awt.Dimension;
49 import java.awt.Font;
50 import java.awt.FontMetrics;
51 import java.awt.Graphics;
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, true, false);
338
339     boolean fastPaint = !(scrolled && av.getWrapAlignment());
340
341     getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
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    * @param redrawOverview
350    * @return
351    */
352   public boolean scrollToPosition(SearchResultsI searchResults,
353           boolean redrawOverview)
354   {
355     return scrollToPosition(searchResults, 0, redrawOverview, false);
356   }
357
358   /**
359    * Scrolls the view (if necessary) to show the position of the first
360    * highlighted region in results (if any). Answers true if the view was
361    * scrolled, or false if no matched region was found, or it is already
362    * visible.
363    * 
364    * @param results
365    * @param verticalOffset
366    *          if greater than zero, allows scrolling to a position below the
367    *          first displayed sequence
368    * @param redrawOverview
369    *          - when set, the overview will be recalculated (takes longer)
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 redrawOverview, 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(redrawOverview, 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, false);
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
551     if (adjustPanelHeight)
552     {
553       int rowHeight = av.getCharHeight();
554       int alignmentHeight = rowHeight * av.getAlignment().getHeight();
555
556       /*
557        * Estimate available height in the AlignFrame for alignment +
558        * annotations. Deduct an estimate for title bar, menu bar, scale panel,
559        * hscroll, status bar, insets. 
560        */
561       int stuff = Platform.isAMac() ? 120 : 140;
562       int availableHeight = alignFrame.getHeight() - stuff;
563
564       /*
565        * If not enough vertical space, maximize annotation height while keeping
566        * at least two rows of alignment visible
567        */
568       if (annotationHeight + alignmentHeight > availableHeight)
569       {
570         annotationHeight = Math.min(annotationHeight,
571                 availableHeight - 2 * rowHeight);
572       }
573     }
574     else
575     {
576       // maintain same window layout whilst updating sliders
577       annotationHeight = annotationScroller.getSize().height;
578     }
579     hscroll.addNotify();
580
581     annotationScroller.setPreferredSize(
582             new Dimension(annotationScroller.getWidth(), annotationHeight));
583
584     Dimension e = idPanel.getSize();
585     alabels.setSize(new Dimension(e.width, annotationHeight));
586
587     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
588             annotationSpaceFillerHolder.getWidth(), annotationHeight));
589     annotationScroller.validate();
590     annotationScroller.addNotify();
591   }
592
593   /**
594    * update alignment layout for viewport settings
595    * 
596    * @param wrap
597    *          DOCUMENT ME!
598    */
599   public void updateLayout()
600   {
601     fontChanged();
602     setAnnotationVisible(av.isShowAnnotation());
603     boolean wrap = av.getWrapAlignment();
604     ViewportRanges ranges = av.getRanges();
605     ranges.setStartSeq(0);
606     scalePanelHolder.setVisible(!wrap);
607     hscroll.setVisible(!wrap);
608     idwidthAdjuster.setVisible(!wrap);
609
610     if (wrap)
611     {
612       annotationScroller.setVisible(false);
613       annotationSpaceFillerHolder.setVisible(false);
614     }
615     else if (av.isShowAnnotation())
616     {
617       annotationScroller.setVisible(true);
618       annotationSpaceFillerHolder.setVisible(true);
619     }
620
621     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
622     if (canvasWidth > 0)
623     { // may not yet be laid out
624       if (wrap)
625       {
626         int widthInRes = getSeqPanel().seqCanvas
627                 .getWrappedCanvasWidth(canvasWidth);
628         ranges.setViewportWidth(widthInRes);
629       }
630       else
631       {
632         int widthInRes = (canvasWidth / av.getCharWidth());
633         int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
634                 / av.getCharHeight());
635
636         ranges.setViewportWidth(widthInRes);
637         ranges.setViewportHeight(heightInSeq);
638       }
639     }
640
641     idSpaceFillerPanel1.setVisible(!wrap);
642
643     repaint();
644   }
645
646   /**
647    * Adjust row/column scrollers to show a visible position in the alignment.
648    * 
649    * @param x
650    *          visible column to scroll to
651    * @param y
652    *          visible row to scroll to
653    * 
654    */
655   public void setScrollValues(int xpos, int ypos)
656   {
657     int x = xpos;
658     int y = ypos;
659
660     if (av == null || av.getAlignment() == null)
661     {
662       return;
663     }
664
665     if (av.getWrapAlignment())
666     {
667       setScrollingForWrappedPanel(x);
668     }
669     else
670     {
671       int width = av.getAlignment().getWidth();
672       int height = av.getAlignment().getHeight();
673
674       if (av.hasHiddenColumns())
675       {
676         // reset the width to exclude hidden columns
677         width = av.getAlignment().getHiddenColumns()
678                 .absoluteToVisibleColumn(width);
679       }
680
681       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
682       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
683
684       if (hextent > width)
685       {
686         hextent = width;
687       }
688
689       if (vextent > height)
690       {
691         vextent = height;
692       }
693
694       if ((hextent + x) > width)
695       {
696         x = width - hextent;
697       }
698
699       if ((vextent + y) > height)
700       {
701         y = height - vextent;
702       }
703
704       if (y < 0)
705       {
706         y = 0;
707       }
708
709       if (x < 0)
710       {
711         x = 0;
712       }
713
714       // update the scroll values
715       hscroll.setValues(x, hextent, 0, width);
716       vscroll.setValues(y, vextent, 0, height);
717     }
718   }
719
720   /**
721    * Respond to adjustment event when horizontal or vertical scrollbar is
722    * changed
723    * 
724    * @param evt
725    *          adjustment event encoding whether hscroll or vscroll changed
726    */
727   @Override
728   public void adjustmentValueChanged(AdjustmentEvent evt)
729   {
730     if (av.getWrapAlignment())
731     {
732       adjustScrollingWrapped(evt);
733       return;
734     }
735
736     ViewportRanges ranges = av.getRanges();
737
738     if (evt.getSource() == hscroll)
739     {
740       int oldX = ranges.getStartRes();
741       int oldwidth = ranges.getViewportWidth();
742       int x = hscroll.getValue();
743       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
744
745       // if we're scrolling to the position we're already at, stop
746       // this prevents infinite recursion of events when the scroll/viewport
747       // ranges values are the same
748       if ((x == oldX) && (width == oldwidth))
749       {
750         return;
751       }
752       ranges.setViewportStartAndWidth(x, width);
753     }
754     else if (evt.getSource() == vscroll)
755     {
756       int oldY = ranges.getStartSeq();
757       int oldheight = ranges.getViewportHeight();
758       int y = vscroll.getValue();
759       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
760
761       // if we're scrolling to the position we're already at, stop
762       // this prevents infinite recursion of events when the scroll/viewport
763       // ranges values are the same
764       if ((y == oldY) && (height == oldheight))
765       {
766         return;
767       }
768       ranges.setViewportStartAndHeight(y, height);
769     }
770     repaint();
771   }
772
773   /**
774    * Responds to a scroll change by setting the start position of the viewport.
775    * Does
776    * 
777    * @param evt
778    */
779   protected void adjustScrollingWrapped(AdjustmentEvent evt)
780   {
781     if (evt.getSource() == hscroll)
782     {
783       return; // no horizontal scroll when wrapped
784     }
785     final ViewportRanges ranges = av.getRanges();
786
787     if (evt.getSource() == vscroll)
788     {
789       int newY = vscroll.getValue();
790
791       /*
792        * if we're scrolling to the position we're already at, stop
793        * this prevents infinite recursion of events when the scroll/viewport
794        * ranges values are the same
795        */
796       int oldX = ranges.getStartRes();
797       int oldY = ranges.getWrappedScrollPosition(oldX);
798       if (oldY == newY)
799       {
800         return;
801       }
802       if (newY > -1)
803       {
804         /*
805          * limit page up/down to one width's worth of positions
806          */
807         int rowSize = ranges.getViewportWidth();
808         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
809         ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
810       }
811     }
812     else
813     {
814       // This is only called if file loaded is a jar file that
815       // was wrapped when saved and user has wrap alignment true
816       // as preference setting
817       SwingUtilities.invokeLater(new Runnable()
818       {
819         @Override
820         public void run()
821         {
822           // When updating scrolling to use ViewportChange events, this code
823           // could not be validated and it is not clear if it is now being
824           // called. Log warning here in case it is called and unforeseen
825           // problems occur
826           Cache.log.warn(
827                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
828
829           // scroll to start of panel
830           ranges.setStartRes(0);
831           ranges.setStartSeq(0);
832         }
833       });
834     }
835     repaint();
836   }
837
838   /* (non-Javadoc)
839    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
840    */
841   @Override
842   public void paintAlignment(boolean updateOverview,
843           boolean updateStructures)
844   {
845     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
846             av.isShowAutocalculatedAbove());
847     sorter.sort(getAlignment().getAlignmentAnnotation(),
848             av.getSortAnnotationsBy());
849     repaint();
850
851     if (updateStructures)
852     {
853       av.getStructureSelectionManager().sequenceColoursChanged(this);
854     }
855     if (updateOverview)
856     {
857
858       if (overviewPanel != null)
859       {
860         overviewPanel.updateOverviewImage();
861       }
862     }
863   }
864
865   /**
866    * DOCUMENT ME!
867    * 
868    * @param g
869    *          DOCUMENT ME!
870    */
871   @Override
872   public void paintComponent(Graphics g)
873   {
874     invalidate(); // needed so that the id width adjuster works correctly
875
876     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
877     idPanelHolder.setPreferredSize(d);
878     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
879
880     validate(); // needed so that the id width adjuster works correctly
881
882     /*
883      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
884      * though I still think this call should be elsewhere.
885      */
886     ViewportRanges ranges = av.getRanges();
887     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
888   }
889
890   /**
891    * Set vertical scroll bar position, and number of increments, for wrapped
892    * panel
893    * 
894    * @param topLeftColumn
895    *          the column position at top left (0..)
896    */
897   private void setScrollingForWrappedPanel(int topLeftColumn)
898   {
899     ViewportRanges ranges = av.getRanges();
900     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
901     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
902
903     /*
904      * a scrollbar's value can be set to at most (maximum-extent)
905      * so we add extent (1) to the maxScroll value
906      */
907     vscroll.setUnitIncrement(1);
908     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
909   }
910
911   /**
912    * DOCUMENT ME!
913    * 
914    * @param pg
915    *          DOCUMENT ME!
916    * @param pf
917    *          DOCUMENT ME!
918    * @param pi
919    *          DOCUMENT ME!
920    * 
921    * @return DOCUMENT ME!
922    * 
923    * @throws PrinterException
924    *           DOCUMENT ME!
925    */
926   @Override
927   public int print(Graphics pg, PageFormat pf, int pi)
928           throws PrinterException
929   {
930     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
931
932     int pwidth = (int) pf.getImageableWidth();
933     int pheight = (int) pf.getImageableHeight();
934
935     if (av.getWrapAlignment())
936     {
937       return printWrappedAlignment(pwidth, pheight, pi, pg);
938     }
939     else
940     {
941       return printUnwrapped(pwidth, pheight, pi, pg, pg);
942     }
943   }
944
945   /**
946    * DOCUMENT ME!
947    * 
948    * @param pg
949    *          DOCUMENT ME!
950    * @param pwidth
951    *          DOCUMENT ME!
952    * @param pheight
953    *          DOCUMENT ME!
954    * @param pi
955    *          DOCUMENT ME!
956    * 
957    * @return DOCUMENT ME!
958    * 
959    * @throws PrinterException
960    *           DOCUMENT ME!
961    */
962   /**
963    * Draws the alignment image, including sequence ids, sequences, and
964    * annotation labels and annotations if shown, on either one or two Graphics
965    * context.
966    * 
967    * @param pageWidth
968    * @param pageHeight
969    * @param pi
970    * @param idGraphics
971    *          the graphics context for sequence ids and annotation labels
972    * @param alignmentGraphics
973    *          the graphics context for sequences and annotations (may or may not
974    *          be the same context as idGraphics)
975    * @return
976    * @throws PrinterException
977    */
978   public int printUnwrapped(int pageWidth, int pageHeight, int pi,
979           Graphics idGraphics, Graphics alignmentGraphics)
980           throws PrinterException
981   {
982     final int idWidth = getVisibleIdWidth(false);
983
984     /*
985      * Get the horizontal offset to where we draw the sequences.
986      * This is idWidth if using a single Graphics context, else zero.
987      */
988     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
989             : idWidth;
990
991     FontMetrics fm = getFontMetrics(av.getFont());
992     int charHeight = av.getCharHeight();
993     int scaleHeight = charHeight + fm.getDescent();
994
995     idGraphics.setColor(Color.white);
996     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
997     idGraphics.setFont(av.getFont());
998
999     /*
1000      * How many sequences and residues can we fit on a printable page?
1001      */
1002     int totalRes = (pageWidth - idWidth) / av.getCharWidth();
1003
1004     int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
1005
1006     int alignmentWidth = av.getAlignment().getWidth();
1007     int pagesWide = (alignmentWidth / totalRes) + 1;
1008
1009     final int startRes = (pi % pagesWide) * totalRes;
1010     int endRes = (startRes + totalRes) - 1;
1011
1012     if (endRes > (alignmentWidth - 1))
1013     {
1014       endRes = alignmentWidth - 1;
1015     }
1016
1017     final int startSeq = (pi / pagesWide) * totalSeq;
1018     int endSeq = startSeq + totalSeq;
1019
1020     int alignmentHeight = av.getAlignment().getHeight();
1021     if (endSeq > alignmentHeight)
1022     {
1023       endSeq = alignmentHeight;
1024     }
1025
1026     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1027
1028     if (av.isShowAnnotation())
1029     {
1030       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1031     }
1032
1033     pagesHigh /= pageHeight;
1034
1035     if (pi >= (pagesWide * pagesHigh))
1036     {
1037       return Printable.NO_SUCH_PAGE;
1038     }
1039     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1040
1041     /*
1042      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1043      */
1044     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1045     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1046             pageWidth - idWidth, scaleHeight);
1047     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1048
1049     /*
1050      * Draw the sequence ids, offset for scale height,
1051      * then reset to top left (0, 0)
1052      */
1053     idGraphics.translate(0, scaleHeight);
1054     idGraphics.setFont(getIdPanel().getIdCanvas().getIdfont());
1055     Color currentColor = null;
1056     Color currentTextColor = null;
1057
1058     SequenceI seq;
1059     for (int i = startSeq; i < endSeq; i++)
1060     {
1061       seq = av.getAlignment().getSequenceAt(i);
1062       if ((av.getSelectionGroup() != null)
1063               && av.getSelectionGroup().getSequences(null).contains(seq))
1064       {
1065         /*
1066          * gray out ids of sequences in selection group (if any)
1067          */
1068         currentColor = Color.gray;
1069         currentTextColor = Color.black;
1070       }
1071       else
1072       {
1073         currentColor = av.getSequenceColour(seq);
1074         currentTextColor = Color.black;
1075       }
1076
1077       idGraphics.setColor(currentColor);
1078       idGraphics.fillRect(0, (i - startSeq) * charHeight, idWidth,
1079               charHeight);
1080
1081       idGraphics.setColor(currentTextColor);
1082
1083       int xPos = 0;
1084       String displayId = seq.getDisplayId(av.getShowJVSuffix());
1085       if (av.isRightAlignIds())
1086       {
1087         fm = idGraphics.getFontMetrics();
1088         xPos = idWidth - fm.stringWidth(displayId) - 4;
1089       }
1090
1091       idGraphics.drawString(displayId, xPos,
1092               (((i - startSeq) * charHeight) + charHeight)
1093                       - (charHeight / 5));
1094     }
1095     idGraphics.setFont(av.getFont());
1096     idGraphics.translate(0, -scaleHeight);
1097
1098     /*
1099      * draw the sequences, offset for scale height, and id width (if using a
1100      * single graphics context), then reset to (0, scale height)
1101      */
1102     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1103     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1104             endRes, startSeq, endSeq);
1105     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1106
1107     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1108     {
1109       /*
1110        * draw annotation labels; drawComponent() translates by
1111        * getScrollOffset(), so compensate for that first;
1112        * then reset to (0, scale height)
1113        */
1114       int offset = getAlabels().getScrollOffset();
1115       idGraphics.translate(0, -offset);
1116       idGraphics.translate(0, alignmentDrawnHeight);
1117       getAlabels().drawComponent(idGraphics, idWidth);
1118       idGraphics.translate(0, -alignmentDrawnHeight);
1119
1120       /*
1121        * draw the annotations starting at 
1122        * (idOffset, alignmentHeight) from (0, scaleHeight)
1123        */
1124       alignmentGraphics.translate(alignmentGraphicsOffset,
1125               alignmentDrawnHeight);
1126       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1127               alignmentGraphics, -1, startRes, endRes + 1);
1128     }
1129
1130     return Printable.PAGE_EXISTS;
1131   }
1132
1133   /**
1134    * DOCUMENT ME!
1135    * 
1136    * @param pg
1137    *          DOCUMENT ME!
1138    * @param pwidth
1139    *          DOCUMENT ME!
1140    * @param pheight
1141    *          DOCUMENT ME!
1142    * @param pi
1143    *          DOCUMENT ME!
1144    * 
1145    * @return DOCUMENT ME!
1146    * 
1147    * @throws PrinterException
1148    *           DOCUMENT ME!
1149    */
1150   public int printWrappedAlignment(int pwidth, int pheight, int pi,
1151           Graphics pg) throws PrinterException
1152   {
1153     int annotationHeight = 0;
1154     AnnotationLabels labels = null;
1155     if (av.isShowAnnotation())
1156     {
1157       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1158       labels = new AnnotationLabels(av);
1159     }
1160
1161     int hgap = av.getCharHeight();
1162     if (av.getScaleAboveWrapped())
1163     {
1164       hgap += av.getCharHeight();
1165     }
1166
1167     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1168             + annotationHeight;
1169
1170     int idWidth = getVisibleIdWidth(false);
1171
1172     int maxwidth = av.getAlignment().getWidth();
1173     if (av.hasHiddenColumns())
1174     {
1175       maxwidth = av.getAlignment().getHiddenColumns()
1176               .absoluteToVisibleColumn(maxwidth) - 1;
1177     }
1178
1179     int resWidth = getSeqPanel().seqCanvas
1180             .getWrappedCanvasWidth(pwidth - idWidth);
1181
1182     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1183
1184     pg.setColor(Color.white);
1185     pg.fillRect(0, 0, pwidth, pheight);
1186     pg.setFont(av.getFont());
1187
1188     // //////////////
1189     // Draw the ids
1190     pg.setColor(Color.black);
1191
1192     pg.translate(0, -pi * pheight);
1193
1194     pg.setClip(0, pi * pheight, pwidth, pheight);
1195
1196     int ypos = hgap;
1197
1198     do
1199     {
1200       for (int i = 0; i < av.getAlignment().getHeight(); i++)
1201       {
1202         pg.setFont(getIdPanel().getIdCanvas().getIdfont());
1203         SequenceI s = av.getAlignment().getSequenceAt(i);
1204         String string = s.getDisplayId(av.getShowJVSuffix());
1205         int xPos = 0;
1206         if (av.isRightAlignIds())
1207         {
1208           FontMetrics fm = pg.getFontMetrics();
1209           xPos = idWidth - fm.stringWidth(string) - 4;
1210         }
1211         pg.drawString(string, xPos,
1212                 ((i * av.getCharHeight()) + ypos + av.getCharHeight())
1213                         - (av.getCharHeight() / 5));
1214       }
1215       if (labels != null)
1216       {
1217         pg.translate(-3, ypos
1218                 + (av.getAlignment().getHeight() * av.getCharHeight()));
1219
1220         pg.setFont(av.getFont());
1221         labels.drawComponent(pg, idWidth);
1222         pg.translate(+3, -ypos
1223                 - (av.getAlignment().getHeight() * av.getCharHeight()));
1224       }
1225
1226       ypos += cHeight;
1227     } while (ypos < totalHeight);
1228
1229     pg.translate(idWidth, 0);
1230
1231     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(pg, pwidth - idWidth,
1232             totalHeight, 0);
1233
1234     if ((pi * pheight) < totalHeight)
1235     {
1236       return Printable.PAGE_EXISTS;
1237
1238     }
1239     else
1240     {
1241       return Printable.NO_SUCH_PAGE;
1242     }
1243   }
1244
1245   /**
1246    * get current sequence ID panel width, or nominal value if panel were to be
1247    * displayed using default settings
1248    * 
1249    * @return
1250    */
1251   public int getVisibleIdWidth()
1252   {
1253     return getVisibleIdWidth(true);
1254   }
1255
1256   /**
1257    * get current sequence ID panel width, or nominal value if panel were to be
1258    * displayed using default settings
1259    * 
1260    * @param onscreen
1261    *          indicate if the Id width for onscreen or offscreen display should
1262    *          be returned
1263    * @return
1264    */
1265   public int getVisibleIdWidth(boolean onscreen)
1266   {
1267     // see if rendering offscreen - check preferences and calc width accordingly
1268     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1269     {
1270       return calculateIdWidth(-1).width + 4;
1271     }
1272     Integer idwidth = null;
1273     if (onscreen || (idwidth = Cache
1274             .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1275     {
1276       int w = getIdPanel().getWidth();
1277       return (w > 0 ? w : calculateIdWidth().width + 4);
1278     }
1279     return idwidth.intValue() + 4;
1280   }
1281
1282   void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1283   {
1284     int boarderBottomOffset = 5;
1285     long pSessionId = System.currentTimeMillis();
1286     headless = (System.getProperty("java.awt.headless") != null
1287             && System.getProperty("java.awt.headless").equals("true"));
1288     if (alignFrame != null && !headless)
1289     {
1290       if (file != null)
1291       {
1292         alignFrame.setProgressBar(MessageManager
1293                 .formatMessage("status.saving_file", new Object[]
1294                 { type.getLabel() }), pSessionId);
1295       }
1296     }
1297     try
1298     {
1299       AlignmentDimension aDimension = getAlignmentDimension();
1300       try
1301       {
1302         ImageMaker im;
1303         final String imageAction, imageTitle;
1304         if (type == ImageMaker.TYPE.PNG)
1305         {
1306           imageAction = "Create PNG image from alignment";
1307           imageTitle = null;
1308         }
1309         else if (type == ImageMaker.TYPE.EPS)
1310         {
1311           imageAction = "Create EPS file from alignment";
1312           imageTitle = alignFrame.getTitle();
1313         }
1314         else
1315         {
1316           imageAction = "Create SVG file from alignment";
1317           imageTitle = alignFrame.getTitle();
1318         }
1319
1320         im = new ImageMaker(this, type, imageAction, aDimension.getWidth(),
1321                 aDimension.getHeight() + boarderBottomOffset, file,
1322                 imageTitle, alignFrame, pSessionId, headless);
1323         Graphics graphics = im.getGraphics();
1324         if (av.getWrapAlignment())
1325         {
1326           if (graphics != null)
1327           {
1328             printWrappedAlignment(aDimension.getWidth(),
1329                     aDimension.getHeight() + boarderBottomOffset, 0,
1330                     graphics);
1331             im.writeImage();
1332           }
1333         }
1334         else
1335         {
1336           if (graphics != null)
1337           {
1338             printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1339                     graphics, graphics);
1340             im.writeImage();
1341           }
1342         }
1343
1344       } catch (OutOfMemoryError err)
1345       {
1346         // Be noisy here.
1347         System.out.println("########################\n" + "OUT OF MEMORY "
1348                 + file + "\n" + "########################");
1349         new OOMWarning("Creating Image for " + file, err);
1350         // System.out.println("Create IMAGE: " + err);
1351       } catch (Exception ex)
1352       {
1353         ex.printStackTrace();
1354       }
1355     } finally
1356     {
1357
1358     }
1359   }
1360
1361   public AlignmentDimension getAlignmentDimension()
1362   {
1363     int maxwidth = av.getAlignment().getWidth();
1364     if (av.hasHiddenColumns())
1365     {
1366       maxwidth = av.getAlignment().getHiddenColumns()
1367               .absoluteToVisibleColumn(maxwidth);
1368     }
1369
1370     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1371             + getScalePanel().getHeight();
1372     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1373
1374     if (av.getWrapAlignment())
1375     {
1376       height = getWrappedHeight();
1377       if (headless)
1378       {
1379         // need to obtain default alignment width and then add in any
1380         // additional allowance for id margin
1381         // this duplicates the calculation in getWrappedHeight but adjusts for
1382         // offscreen idWith
1383         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1384                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1385                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1386       }
1387       else
1388       {
1389         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1390       }
1391
1392     }
1393     else if (av.isShowAnnotation())
1394     {
1395       height += getAnnotationPanel().adjustPanelHeight() + 3;
1396     }
1397     return new AlignmentDimension(width, height);
1398
1399   }
1400
1401   public void makePNGImageMap(File imgMapFile, String imageName)
1402   {
1403     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1404     // ////////////////////////////////////////////
1405     int idWidth = getVisibleIdWidth(false);
1406     FontMetrics fm = getFontMetrics(av.getFont());
1407     int scaleHeight = av.getCharHeight() + fm.getDescent();
1408
1409     // Gen image map
1410     // ////////////////////////////////
1411     if (imgMapFile != null)
1412     {
1413       try
1414       {
1415         int sSize = av.getAlignment().getHeight();
1416         int alwidth = av.getAlignment().getWidth();
1417         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1418         out.println(HTMLOutput.getImageMapHTML());
1419         out.println("<img src=\"" + imageName
1420                 + "\" border=\"0\" usemap=\"#Map\" >"
1421                 + "<map name=\"Map\">");
1422
1423         for (int s = 0; s < sSize; s++)
1424         {
1425           int sy = s * av.getCharHeight() + scaleHeight;
1426
1427           SequenceI seq = av.getAlignment().getSequenceAt(s);
1428           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1429           for (int column = 0; column < alwidth; column++)
1430           {
1431             StringBuilder text = new StringBuilder(512);
1432             String triplet = null;
1433             if (av.getAlignment().isNucleotide())
1434             {
1435               triplet = ResidueProperties.nucleotideName.get(seq
1436                       .getCharAt(column) + "");
1437             }
1438             else
1439             {
1440               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1441                       + "");
1442             }
1443
1444             if (triplet == null)
1445             {
1446               continue;
1447             }
1448
1449             int seqPos = seq.findPosition(column);
1450             int gSize = groups.length;
1451             for (int g = 0; g < gSize; g++)
1452             {
1453               if (text.length() < 1)
1454               {
1455                 text.append("<area shape=\"rect\" coords=\"")
1456                         .append((idWidth + column * av.getCharWidth()))
1457                         .append(",").append(sy).append(",")
1458                         .append((idWidth + (column + 1) * av.getCharWidth()))
1459                         .append(",").append((av.getCharHeight() + sy))
1460                         .append("\"").append(" onMouseOver=\"toolTip('")
1461                         .append(seqPos).append(" ").append(triplet);
1462               }
1463
1464               if (groups[g].getStartRes() < column
1465                       && groups[g].getEndRes() > column)
1466               {
1467                 text.append("<br><em>").append(groups[g].getName())
1468                         .append("</em>");
1469               }
1470             }
1471
1472             if (text.length() < 1)
1473             {
1474               text.append("<area shape=\"rect\" coords=\"")
1475                       .append((idWidth + column * av.getCharWidth()))
1476                       .append(",").append(sy).append(",")
1477                       .append((idWidth + (column + 1) * av.getCharWidth()))
1478                       .append(",").append((av.getCharHeight() + sy))
1479                       .append("\"").append(" onMouseOver=\"toolTip('")
1480                       .append(seqPos).append(" ").append(triplet);
1481             }
1482             if (!Comparison.isGap(seq.getCharAt(column)))
1483             {
1484               List<SequenceFeature> features = seq.findFeatures(column, column);
1485               for (SequenceFeature sf : features)
1486               {
1487                 if (sf.isContactFeature())
1488                 {
1489                   text.append("<br>").append(sf.getType()).append(" ")
1490                           .append(sf.getBegin()).append(":")
1491                           .append(sf.getEnd());
1492                 }
1493                 else
1494                 {
1495                   text.append("<br>");
1496                   text.append(sf.getType());
1497                   String description = sf.getDescription();
1498                   if (description != null
1499                           && !sf.getType().equals(description))
1500                   {
1501                     description = description.replace("\"", "&quot;");
1502                     text.append(" ").append(description);
1503                   }
1504                 }
1505                 String status = sf.getStatus();
1506                 if (status != null && !"".equals(status))
1507                 {
1508                   text.append(" (").append(status).append(")");
1509                 }
1510               }
1511               if (text.length() > 1)
1512               {
1513                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1514                 out.println(text.toString());
1515               }
1516             }
1517           }
1518         }
1519         out.println("</map></body></html>");
1520         out.close();
1521
1522       } catch (Exception ex)
1523       {
1524         ex.printStackTrace();
1525       }
1526     } // /////////END OF IMAGE MAP
1527
1528   }
1529
1530   int getWrappedHeight()
1531   {
1532     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1533
1534     if (System.getProperty("java.awt.headless") != null
1535             && System.getProperty("java.awt.headless").equals("true"))
1536     {
1537       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1538               - vscroll.getPreferredSize().width
1539               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1540     }
1541
1542     int chunkWidth = getSeqPanel().seqCanvas
1543             .getWrappedCanvasWidth(seqPanelWidth);
1544
1545     int hgap = av.getCharHeight();
1546     if (av.getScaleAboveWrapped())
1547     {
1548       hgap += av.getCharHeight();
1549     }
1550
1551     int annotationHeight = 0;
1552     if (av.isShowAnnotation())
1553     {
1554       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1555     }
1556
1557     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1558             + annotationHeight;
1559
1560     int maxwidth = av.getAlignment().getWidth();
1561     if (av.hasHiddenColumns())
1562     {
1563       maxwidth = av.getAlignment().getHiddenColumns()
1564               .absoluteToVisibleColumn(maxwidth) - 1;
1565     }
1566
1567     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1568
1569     return height;
1570   }
1571
1572   /**
1573    * close the panel - deregisters all listeners and nulls any references to
1574    * alignment data.
1575    */
1576   public void closePanel()
1577   {
1578     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1579     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1580     PaintRefresher.RemoveComponent(this);
1581
1582     closeChildFrames();
1583
1584     /*
1585      * try to ensure references are nulled
1586      */
1587     if (annotationPanel != null)
1588     {
1589       annotationPanel.dispose();
1590       annotationPanel = null;
1591     }
1592
1593     if (av != null)
1594     {
1595       av.removePropertyChangeListener(propertyChangeListener);
1596       propertyChangeListener = null;
1597       StructureSelectionManager ssm = av.getStructureSelectionManager();
1598       ssm.removeStructureViewerListener(getSeqPanel(), null);
1599       ssm.removeSelectionListener(getSeqPanel());
1600       ssm.removeCommandListener(av);
1601       ssm.removeStructureViewerListener(getSeqPanel(), null);
1602       ssm.removeSelectionListener(getSeqPanel());
1603       av.dispose();
1604       av = null;
1605     }
1606     else
1607     {
1608       if (Cache.log.isDebugEnabled())
1609       {
1610         Cache.log.warn("Closing alignment panel which is already closed.");
1611       }
1612     }
1613   }
1614
1615   /**
1616    * Close any open dialogs that would be orphaned when this one is closed
1617    */
1618   protected void closeChildFrames()
1619   {
1620     if (overviewPanel != null)
1621     {
1622       overviewPanel.dispose();
1623       overviewPanel = null;
1624     }
1625     if (calculationDialog != null)
1626     {
1627       calculationDialog.closeFrame();
1628       calculationDialog = null;
1629     }
1630   }
1631
1632   /**
1633    * hides or shows dynamic annotation rows based on groups and av state flags
1634    */
1635   public void updateAnnotation()
1636   {
1637     updateAnnotation(false, false);
1638   }
1639
1640   public void updateAnnotation(boolean applyGlobalSettings)
1641   {
1642     updateAnnotation(applyGlobalSettings, false);
1643   }
1644
1645   public void updateAnnotation(boolean applyGlobalSettings,
1646           boolean preserveNewGroupSettings)
1647   {
1648     av.updateGroupAnnotationSettings(applyGlobalSettings,
1649             preserveNewGroupSettings);
1650     adjustAnnotationHeight();
1651   }
1652
1653   @Override
1654   public AlignmentI getAlignment()
1655   {
1656     return av == null ? null : av.getAlignment();
1657   }
1658
1659   @Override
1660   public String getViewName()
1661   {
1662     return av.viewName;
1663   }
1664
1665   /**
1666    * Make/Unmake this alignment panel the current input focus
1667    * 
1668    * @param b
1669    */
1670   public void setSelected(boolean b)
1671   {
1672     try
1673     {
1674       if (alignFrame.getSplitViewContainer() != null)
1675       {
1676         /*
1677          * bring enclosing SplitFrame to front first if there is one
1678          */
1679         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1680       }
1681       alignFrame.setSelected(b);
1682     } catch (Exception ex)
1683     {
1684     }
1685
1686     if (b)
1687     {
1688       alignFrame.setDisplayedView(this);
1689     }
1690   }
1691
1692   @Override
1693   public StructureSelectionManager getStructureSelectionManager()
1694   {
1695     return av.getStructureSelectionManager();
1696   }
1697
1698   @Override
1699   public void raiseOOMWarning(String string, OutOfMemoryError error)
1700   {
1701     new OOMWarning(string, error, this);
1702   }
1703
1704   @Override
1705   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1706   {
1707
1708     return new FeatureRenderer(this);
1709   }
1710
1711   @Override
1712   public jalview.api.FeatureRenderer getFeatureRenderer()
1713   {
1714     return seqPanel.seqCanvas.getFeatureRenderer();
1715   }
1716
1717   public void updateFeatureRenderer(
1718           jalview.renderer.seqfeatures.FeatureRenderer fr)
1719   {
1720     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1721   }
1722
1723   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1724   {
1725     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1726     {
1727       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1728     }
1729   }
1730
1731   public ScalePanel getScalePanel()
1732   {
1733     return scalePanel;
1734   }
1735
1736   public void setScalePanel(ScalePanel scalePanel)
1737   {
1738     this.scalePanel = scalePanel;
1739   }
1740
1741   public SeqPanel getSeqPanel()
1742   {
1743     return seqPanel;
1744   }
1745
1746   public void setSeqPanel(SeqPanel seqPanel)
1747   {
1748     this.seqPanel = seqPanel;
1749   }
1750
1751   public AnnotationPanel getAnnotationPanel()
1752   {
1753     return annotationPanel;
1754   }
1755
1756   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1757   {
1758     this.annotationPanel = annotationPanel;
1759   }
1760
1761   public AnnotationLabels getAlabels()
1762   {
1763     return alabels;
1764   }
1765
1766   public void setAlabels(AnnotationLabels alabels)
1767   {
1768     this.alabels = alabels;
1769   }
1770
1771   public IdPanel getIdPanel()
1772   {
1773     return idPanel;
1774   }
1775
1776   public void setIdPanel(IdPanel idPanel)
1777   {
1778     this.idPanel = idPanel;
1779   }
1780
1781   /**
1782    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1783    * The aim is to keep the two alignments 'lined up' on their centre columns.
1784    * 
1785    * @param sr
1786    *          holds mapped region(s) of this alignment that we are scrolling
1787    *          'to'; may be modified for sequence offset by this method
1788    * @param verticalOffset
1789    *          the number of visible sequences to show above the mapped region
1790    */
1791   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1792   {
1793     scrollToPosition(sr, verticalOffset, true, true);
1794   }
1795
1796   /**
1797    * Set a flag to say do not scroll any (cDNA/protein) complement.
1798    * 
1799    * @param b
1800    */
1801   protected void setToScrollComplementPanel(boolean b)
1802   {
1803     this.scrollComplementaryPanel = b;
1804   }
1805
1806   /**
1807    * Get whether to scroll complement panel
1808    * 
1809    * @return true if cDNA/protein complement panels should be scrolled
1810    */
1811   protected boolean isSetToScrollComplementPanel()
1812   {
1813     return this.scrollComplementaryPanel;
1814   }
1815
1816   /**
1817    * Redraw sensibly.
1818    * 
1819    * @adjustHeight if true, try to recalculate panel height for visible
1820    *               annotations
1821    */
1822   protected void refresh(boolean adjustHeight)
1823   {
1824     validateAnnotationDimensions(adjustHeight);
1825     addNotify();
1826     if (adjustHeight)
1827     {
1828       // sort, repaint, update overview
1829       paintAlignment(true, false);
1830     }
1831     else
1832     {
1833       // lightweight repaint
1834       repaint();
1835     }
1836   }
1837
1838   @Override
1839   /**
1840    * Property change event fired when a change is made to the viewport ranges
1841    * object associated with this alignment panel's viewport
1842    */
1843   public void propertyChange(PropertyChangeEvent evt)
1844   {
1845     // update this panel's scroll values based on the new viewport ranges values
1846     ViewportRanges ranges = av.getRanges();
1847     int x = ranges.getStartRes();
1848     int y = ranges.getStartSeq();
1849     setScrollValues(x, y);
1850
1851     // now update any complementary alignment (its viewport ranges object
1852     // is different so does not get automatically updated)
1853     if (isSetToScrollComplementPanel())
1854     {
1855       setToScrollComplementPanel(false);
1856       av.scrollComplementaryAlignment();
1857       setToScrollComplementPanel(true);
1858     }
1859   }
1860
1861   /**
1862    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1863    * reference should be nulled when the dialog is closed.
1864    * 
1865    * @param calculationChooser
1866    */
1867   public void setCalculationDialog(CalculationChooser calculationChooser)
1868   {
1869     calculationDialog = calculationChooser;
1870   }
1871
1872   /**
1873    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1874    * if none is open)
1875    */
1876   public CalculationChooser getCalculationDialog()
1877   {
1878     return calculationDialog;
1879   }
1880 }