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