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