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