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