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