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