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