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