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