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