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