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