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