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