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