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