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