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