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