Bamboo text #35 - simpler logic; avoids impossible repaint, validation?
[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. addNotify() is a very expensive operation,
572     // requiring a full re-layout of all parents and children.
573     // Note in JComponent:
574     // This method is called by the toolkit internally and should
575     // not be called directly by programs.
576     // I note that addNotify() is called in several areas of Jalview.
577
578     int annotationHeight = getAnnotationPanel().adjustPanelHeight();
579     annotationHeight = getAnnotationPanel()
580             .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
581
582     hscroll.addNotify();
583     annotationScroller.setPreferredSize(
584             new Dimension(annotationScroller.getWidth(), annotationHeight));
585
586     Dimension e = idPanel.getSize();
587     alabels.setSize(new Dimension(e.width, annotationHeight));
588
589     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
590             annotationSpaceFillerHolder.getWidth(), annotationHeight));
591     annotationScroller.validate();
592     annotationScroller.addNotify();
593   }
594
595   /**
596    * update alignment layout for viewport settings
597    * 
598    * @param wrap
599    *          DOCUMENT ME!
600    */
601   public void updateLayout()
602   {
603     if (getTopLevelAncestor() == null)
604       return;
605     ViewportRanges ranges = av.getRanges();
606     fontChanged();
607     setAnnotationVisible(av.isShowAnnotation());
608     boolean wrap = av.getWrapAlignment();
609     ranges.setStartSeq(0);
610     scalePanelHolder.setVisible(!wrap);
611     hscroll.setVisible(!wrap);
612     idwidthAdjuster.setVisible(!wrap);
613
614     if (wrap)
615     {
616       annotationScroller.setVisible(false);
617       annotationSpaceFillerHolder.setVisible(false);
618     }
619     else if (av.isShowAnnotation())
620     {
621       annotationScroller.setVisible(true);
622       annotationSpaceFillerHolder.setVisible(true);
623       validateAnnotationDimensions(false);
624     }
625
626     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
627     if (canvasWidth > 0)
628     { // may not yet be laid out
629       if (wrap)
630       {
631         int widthInRes = getSeqPanel().seqCanvas
632                 .getWrappedCanvasWidth(canvasWidth);
633         ranges.setViewportWidth(widthInRes);
634       }
635       else
636       {
637         int widthInRes = (canvasWidth / av.getCharWidth());
638         int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
639                 / av.getCharHeight());
640
641         ranges.setViewportWidth(widthInRes);
642         ranges.setViewportHeight(heightInSeq);
643       }
644     }
645
646     idSpaceFillerPanel1.setVisible(!wrap);
647
648     
649 // BH not added to anything yet!    repaint();
650   }
651
652   /**
653    * Adjust row/column scrollers to show a visible position in the alignment.
654    * 
655    * @param x
656    *          visible column to scroll to
657    * @param y
658    *          visible row to scroll to
659    * 
660    */
661   public void setScrollValues(int x, int y)
662   {
663     
664     System.out.println("AlignmentPanel.setScrollValues " + x + "_" + y);
665
666     if (av == null || av.getAlignment() == null)
667     {
668       return;
669     }
670
671     if (av.getWrapAlignment())
672     {
673       setScrollingForWrappedPanel(x);
674     }
675     else
676     {
677       int width = av.getAlignment().getVisibleWidth();
678       int height = av.getAlignment().getHeight();
679       
680       hextent = Math.min(getSeqPanel().seqCanvas.getWidth() / av.getCharWidth(),  width);
681       vextent = Math.min(getSeqPanel().seqCanvas.getHeight() / av.getCharHeight(),  height);
682
683       if (hextent < 0)
684       System.out.println("AlignmentPanel.setScrollValues  found hext=" + hextent + " vext=" +  vextent + " width=" + width + " height=" + height 
685               );
686  
687   
688       x = Math.max(0, Math.min(x,  width - hextent));
689       y = Math.max(0, Math.min(y,  height - vextent));
690       
691
692       System.out.println("AlignmentPanel.setScrollValues resetting these to " + x + "_" + y 
693               + " based on hext=" + hextent + " vext=" +  vextent + " width=" + width + " height=" + height 
694               );
695
696       updateRanges(x, y);
697       updateScrollBars(x, y, width, height);
698     }
699   }
700
701   private void updateScrollBars(int x, int y, int width, int height) 
702   {
703     hscroll.setValues(x, hextent, 0, width);
704     vscroll.setValues(y, vextent, 0, height);
705   }
706
707   /**
708    * Respond to adjustment event when horizontal or vertical scrollbar is
709    * changed
710    * 
711    * @param evt
712    *          adjustment event encoding whether hscroll or vscroll changed
713    */
714   @Override
715   public void adjustmentValueChanged(AdjustmentEvent evt)
716   {
717     if (av.getWrapAlignment())
718     {
719       adjustScrollingWrapped(evt);
720       return;
721     }
722
723     if (evt.getSource() == hscroll)
724     {
725       if (!updateRanges(hscroll.getValue(), Integer.MIN_VALUE))
726         return;
727     }
728     else if (evt.getSource() == vscroll)
729     {
730       if (!updateRanges(Integer.MIN_VALUE, vscroll.getValue()))
731         return;
732     }
733     repaint();
734   }
735
736   private boolean updateRanges(int x, int y)
737   {
738     ViewportRanges ranges = av.getRanges();
739     boolean isChanged = false;
740     if (x != Integer.MIN_VALUE)
741     {
742       int oldX = ranges.getStartRes();
743       int oldwidth = ranges.getViewportWidth();
744       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
745
746       // if we're scrolling to the position we're already at, stop
747       // this prevents infinite recursion of events when the scroll/viewport
748       // ranges values are the same
749       if (width > 0 && (x != oldX || width != oldwidth))
750       {
751         ranges.setViewportStartAndWidth(x, width);
752         isChanged = true;
753       }
754     }
755     if (y != Integer.MIN_VALUE)
756     {
757       int oldY = ranges.getStartSeq();
758       int oldheight = ranges.getViewportHeight();
759       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
760
761       // if we're scrolling to the position we're already at, stop
762       // this prevents infinite recursion of events when the scroll/viewport
763       // ranges values are the same
764       if (height > 0 && (y != oldY || height != oldheight))
765       {
766         ranges.setViewportStartAndHeight(y, height);
767         isChanged = true;
768       }
769     }
770     return isChanged;
771   }
772
773   /**
774    * Responds to a scroll change by setting the start position of the viewport.
775    * Does
776    * 
777    * @param evt
778    */
779   protected void adjustScrollingWrapped(AdjustmentEvent evt)
780   {
781     if (evt.getSource() == hscroll)
782     {
783       return; // no horizontal scroll when wrapped
784     }
785     final ViewportRanges ranges = av.getRanges();
786
787     if (evt.getSource() == vscroll)
788     {
789       int newY = vscroll.getValue();
790
791       /*
792        * if we're scrolling to the position we're already at, stop
793        * this prevents infinite recursion of events when the scroll/viewport
794        * ranges values are the same
795        */
796       int oldX = ranges.getStartRes();
797       int oldY = ranges.getWrappedScrollPosition(oldX);
798       if (oldY == newY)
799       {
800         return;
801       }
802       if (newY > -1)
803       {
804         /*
805          * limit page up/down to one width's worth of positions
806          */
807         int rowSize = ranges.getViewportWidth();
808         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
809         ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
810       }
811     }
812     else
813     {
814       // This is only called if file loaded is a jar file that
815       // was wrapped when saved and user has wrap alignment true
816       // as preference setting
817       SwingUtilities.invokeLater(new Runnable()
818       {
819         @Override
820         public void run()
821         {
822           // When updating scrolling to use ViewportChange events, this code
823           // could not be validated and it is not clear if it is now being
824           // called. Log warning here in case it is called and unforeseen
825           // problems occur
826           Cache.log.warn(
827                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
828
829           // scroll to start of panel
830           ranges.setStartRes(0);
831           ranges.setStartSeq(0);
832         }
833       });
834     }
835     repaint();
836   }
837
838   /* (non-Javadoc)
839    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
840    */
841   @Override
842   public void paintAlignment(boolean updateOverview,
843           boolean updateStructures)
844   {
845     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
846             av.isShowAutocalculatedAbove());
847     sorter.sort(getAlignment().getAlignmentAnnotation(),
848             av.getSortAnnotationsBy());
849
850     if (updateStructures)
851     {
852       av.getStructureSelectionManager().sequenceColoursChanged(this);
853     }
854     if (updateOverview)
855     {
856       alignFrame.repaint();
857
858       if (overviewPanel != null)
859       {
860         overviewPanel.updateOverviewImage();
861       }
862     } else {
863       repaint();
864     }
865   }
866
867   @Override
868   public void paintComponent(Graphics g)
869   {
870     invalidate(); // needed so that the id width adjuster works correctly
871
872     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
873     idPanelHolder.setPreferredSize(d);
874     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
875
876     validate(); // needed so that the id width adjuster works correctly
877
878     /*
879      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
880      * though I still think this call should be elsewhere.
881      */
882     ViewportRanges ranges = av.getRanges();
883     // setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
884     super.paintComponent(g);
885   }
886
887   /**
888    * Set vertical scroll bar position, and number of increments, for wrapped
889    * panel
890    * 
891    * @param topLeftColumn
892    *          the column position at top left (0..)
893    */
894   private void setScrollingForWrappedPanel(int topLeftColumn)
895   {
896     ViewportRanges ranges = av.getRanges();
897     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
898     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
899
900     /*
901      * a scrollbar's value can be set to at most (maximum-extent)
902      * so we add extent (1) to the maxScroll value
903      */
904     vscroll.setUnitIncrement(1);
905     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
906   }
907
908   /**
909    * DOCUMENT ME!
910    * 
911    * @param pg
912    *          DOCUMENT ME!
913    * @param pf
914    *          DOCUMENT ME!
915    * @param pi
916    *          DOCUMENT ME!
917    * 
918    * @return DOCUMENT ME!
919    * 
920    * @throws PrinterException
921    *           DOCUMENT ME!
922    */
923   @Override
924   public int print(Graphics pg, PageFormat pf, int pi)
925           throws PrinterException
926   {
927     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
928
929     int pwidth = (int) pf.getImageableWidth();
930     int pheight = (int) pf.getImageableHeight();
931
932     if (av.getWrapAlignment())
933     {
934       return printWrappedAlignment(pwidth, pheight, pi, pg);
935     }
936     else
937     {
938       return printUnwrapped(pwidth, pheight, pi, pg, pg);
939     }
940   }
941
942   /**
943    * Draws the alignment image, including sequence ids, sequences, and
944    * annotation labels and annotations if shown, on either one or two Graphics
945    * contexts.
946    * 
947    * @param pageWidth
948    *          in pixels
949    * @param pageHeight
950    *          in pixels
951    * @param pageIndex
952    *          (0, 1, ...)
953    * @param idGraphics
954    *          the graphics context for sequence ids and annotation labels
955    * @param alignmentGraphics
956    *          the graphics context for sequences and annotations (may or may not
957    *          be the same context as idGraphics)
958    * @return
959    * @throws PrinterException
960    */
961   public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
962           Graphics idGraphics, Graphics alignmentGraphics)
963           throws PrinterException
964   {
965     final int idWidth = getVisibleIdWidth(false);
966
967     /*
968      * Get the horizontal offset to where we draw the sequences.
969      * This is idWidth if using a single Graphics context, else zero.
970      */
971     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
972             : idWidth;
973
974     FontMetrics fm = getFontMetrics(av.getFont());
975     final int charHeight = av.getCharHeight();
976     final int scaleHeight = charHeight + fm.getDescent();
977
978     idGraphics.setColor(Color.white);
979     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
980     idGraphics.setFont(av.getFont());
981
982     /*
983      * How many sequences and residues can we fit on a printable page?
984      */
985     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
986
987     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
988
989     final int alignmentWidth = av.getAlignment().getVisibleWidth();
990     int pagesWide = (alignmentWidth / totalRes) + 1;
991
992     final int startRes = (pageIndex % pagesWide) * totalRes;
993     final int endRes = Math.min(startRes + totalRes - 1,
994             alignmentWidth - 1);
995
996     final int startSeq = (pageIndex / pagesWide) * totalSeq;
997     final int alignmentHeight = av.getAlignment().getHeight();
998     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
999
1000     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
1001
1002     if (av.isShowAnnotation())
1003     {
1004       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
1005     }
1006
1007     pagesHigh /= pageHeight;
1008
1009     if (pageIndex >= (pagesWide * pagesHigh))
1010     {
1011       return Printable.NO_SUCH_PAGE;
1012     }
1013     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1014
1015     /*
1016      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1017      */
1018     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1019     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1020             pageWidth - idWidth, scaleHeight);
1021     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1022
1023     /*
1024      * Draw the sequence ids, offset for scale height,
1025      * then reset to top left (0, 0)
1026      */
1027     idGraphics.translate(0, scaleHeight);
1028     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1029     List<SequenceI> selection = av.getSelectionGroup() == null ? null
1030             : av.getSelectionGroup().getSequences(null);
1031     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1032             selection);
1033
1034     idGraphics.setFont(av.getFont());
1035     idGraphics.translate(0, -scaleHeight);
1036
1037     /*
1038      * draw the sequences, offset for scale height, and id width (if using a
1039      * single graphics context), then reset to (0, scale height)
1040      */
1041     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1042     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1043             startRes, endRes, startSeq, endSeq - 1);
1044     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1045
1046     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1047     {
1048       /*
1049        * draw annotation labels; drawComponent() translates by
1050        * getScrollOffset(), so compensate for that first;
1051        * then reset to (0, scale height)
1052        */
1053       int offset = getAlabels().getScrollOffset();
1054       idGraphics.translate(0, -offset);
1055       idGraphics.translate(0, alignmentDrawnHeight);
1056       getAlabels().drawComponent(idGraphics, idWidth);
1057       idGraphics.translate(0, -alignmentDrawnHeight);
1058
1059       /*
1060        * draw the annotations starting at 
1061        * (idOffset, alignmentHeight) from (0, scaleHeight)
1062        */
1063       alignmentGraphics.translate(alignmentGraphicsOffset,
1064               alignmentDrawnHeight);
1065       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1066               alignmentGraphics, -1, startRes, endRes + 1);
1067     }
1068
1069     return Printable.PAGE_EXISTS;
1070   }
1071
1072   /**
1073    * Prints one page of an alignment in wrapped mode. Returns
1074    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1075    * no page could be drawn (page number out of range).
1076    * 
1077    * @param pageWidth
1078    * @param pageHeight
1079    * @param pageNumber
1080    *          (0, 1, ...)
1081    * @param g
1082    * 
1083    * @return
1084    * 
1085    * @throws PrinterException
1086    */
1087   public int printWrappedAlignment(int pageWidth, int pageHeight,
1088           int pageNumber, Graphics g) throws PrinterException
1089   {
1090     getSeqPanel().seqCanvas.calculateWrappedGeometry();
1091     int annotationHeight = 0;
1092     if (av.isShowAnnotation())
1093     {
1094       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1095     }
1096
1097     int hgap = av.getCharHeight();
1098     if (av.getScaleAboveWrapped())
1099     {
1100       hgap += av.getCharHeight();
1101     }
1102
1103     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1104             + annotationHeight;
1105
1106     int idWidth = getVisibleIdWidth(false);
1107
1108     int maxwidth = av.getAlignment().getVisibleWidth();
1109
1110     int resWidth = getSeqPanel().seqCanvas
1111             .getWrappedCanvasWidth(pageWidth - idWidth);
1112     av.getRanges().setViewportStartAndWidth(0, resWidth);
1113
1114     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1115
1116     g.setColor(Color.white);
1117     g.fillRect(0, 0, pageWidth, pageHeight);
1118     g.setFont(av.getFont());
1119     g.setColor(Color.black);
1120
1121     /*
1122      * method: print the whole wrapped alignment, but with a clip region that
1123      * is restricted to the requested page; this supports selective print of 
1124      * single pages or ranges, (at the cost of repeated processing in the 
1125      * 'normal' case, when all pages are printed)
1126      */
1127     g.translate(0, -pageNumber * pageHeight);
1128
1129     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1130
1131     /*
1132      * draw sequence ids and annotation labels (if shown)
1133      */
1134     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1135     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1136
1137     g.translate(idWidth, 0);
1138
1139     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1140             pageWidth - idWidth, totalHeight, 0);
1141
1142     if ((pageNumber * pageHeight) < totalHeight)
1143     {
1144       return Printable.PAGE_EXISTS;
1145     }
1146     else
1147     {
1148       return Printable.NO_SUCH_PAGE;
1149     }
1150   }
1151
1152   /**
1153    * get current sequence ID panel width, or nominal value if panel were to be
1154    * displayed using default settings
1155    * 
1156    * @return
1157    */
1158   public int getVisibleIdWidth()
1159   {
1160     return getVisibleIdWidth(true);
1161   }
1162
1163   /**
1164    * get current sequence ID panel width, or nominal value if panel were to be
1165    * displayed using default settings
1166    * 
1167    * @param onscreen
1168    *          indicate if the Id width for onscreen or offscreen display should
1169    *          be returned
1170    * @return
1171    */
1172   protected int getVisibleIdWidth(boolean onscreen)
1173   {
1174     // see if rendering offscreen - check preferences and calc width accordingly
1175     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1176     {
1177       return calculateIdWidth(-1).width;
1178     }
1179     Integer idwidth = onscreen ? null
1180             : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1181     if (idwidth != null)
1182     {
1183       return idwidth.intValue() + ID_WIDTH_PADDING;
1184     }
1185
1186     int w = getIdPanel().getWidth();
1187     return (w > 0 ? w : calculateIdWidth().width);
1188   }
1189
1190   /**
1191    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1192    * writes it to the specified file
1193    * 
1194    * @param type
1195    * @param file
1196    */
1197   void makeAlignmentImage(ImageMaker.TYPE type, File file)
1198   {
1199     final int borderBottomOffset = 5;
1200
1201     AlignmentDimension aDimension = getAlignmentDimension();
1202     // todo use a lambda function in place of callback here?
1203     ImageWriterI writer = new ImageWriterI()
1204     {
1205       @Override
1206       public void exportImage(Graphics graphics) throws Exception
1207       {
1208         if (av.getWrapAlignment())
1209         {
1210           printWrappedAlignment(aDimension.getWidth(),
1211                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1212         }
1213         else
1214         {
1215           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1216                   graphics, graphics);
1217         }
1218       }
1219     };
1220
1221     String fileTitle = alignFrame.getTitle();
1222     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1223             fileTitle);
1224     int imageWidth = aDimension.getWidth();
1225     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1226     String of = MessageManager.getString("label.alignment");
1227     exporter.doExport(file, this, imageWidth, imageHeight, of);
1228   }
1229
1230   /**
1231    * Calculates and returns a suitable width and height (in pixels) for an
1232    * exported image
1233    * 
1234    * @return
1235    */
1236   public AlignmentDimension getAlignmentDimension()
1237   {
1238     int maxwidth = av.getAlignment().getVisibleWidth();
1239
1240     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1241             + getScalePanel().getHeight();
1242     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1243
1244     if (av.getWrapAlignment())
1245     {
1246       height = getWrappedHeight();
1247       if (Jalview.isHeadlessMode())
1248       {
1249         // need to obtain default alignment width and then add in any
1250         // additional allowance for id margin
1251         // this duplicates the calculation in getWrappedHeight but adjusts for
1252         // offscreen idWith
1253         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1254                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1255                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1256       }
1257       else
1258       {
1259         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1260       }
1261
1262     }
1263     else if (av.isShowAnnotation())
1264     {
1265       height += getAnnotationPanel().adjustPanelHeight() + 3;
1266     }
1267     return new AlignmentDimension(width, height);
1268
1269   }
1270
1271   public void makePNGImageMap(File imgMapFile, String imageName)
1272   {
1273     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1274     // ////////////////////////////////////////////
1275     int idWidth = getVisibleIdWidth(false);
1276     FontMetrics fm = getFontMetrics(av.getFont());
1277     int scaleHeight = av.getCharHeight() + fm.getDescent();
1278
1279     // Gen image map
1280     // ////////////////////////////////
1281     if (imgMapFile != null)
1282     {
1283       try
1284       {
1285         int sSize = av.getAlignment().getHeight();
1286         int alwidth = av.getAlignment().getWidth();
1287         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1288         out.println(HTMLOutput.getImageMapHTML());
1289         out.println("<img src=\"" + imageName
1290                 + "\" border=\"0\" usemap=\"#Map\" >"
1291                 + "<map name=\"Map\">");
1292
1293         for (int s = 0; s < sSize; s++)
1294         {
1295           int sy = s * av.getCharHeight() + scaleHeight;
1296
1297           SequenceI seq = av.getAlignment().getSequenceAt(s);
1298           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1299           for (int column = 0; column < alwidth; column++)
1300           {
1301             StringBuilder text = new StringBuilder(512);
1302             String triplet = null;
1303             if (av.getAlignment().isNucleotide())
1304             {
1305               triplet = ResidueProperties.nucleotideName
1306                       .get(seq.getCharAt(column) + "");
1307             }
1308             else
1309             {
1310               triplet = ResidueProperties.aa2Triplet
1311                       .get(seq.getCharAt(column) + "");
1312             }
1313
1314             if (triplet == null)
1315             {
1316               continue;
1317             }
1318
1319             int seqPos = seq.findPosition(column);
1320             int gSize = groups.length;
1321             for (int g = 0; g < gSize; g++)
1322             {
1323               if (text.length() < 1)
1324               {
1325                 text.append("<area shape=\"rect\" coords=\"")
1326                         .append((idWidth + column * av.getCharWidth()))
1327                         .append(",").append(sy).append(",")
1328                         .append((idWidth
1329                                 + (column + 1) * av.getCharWidth()))
1330                         .append(",").append((av.getCharHeight() + sy))
1331                         .append("\"").append(" onMouseOver=\"toolTip('")
1332                         .append(seqPos).append(" ").append(triplet);
1333               }
1334
1335               if (groups[g].getStartRes() < column
1336                       && groups[g].getEndRes() > column)
1337               {
1338                 text.append("<br><em>").append(groups[g].getName())
1339                         .append("</em>");
1340               }
1341             }
1342
1343             if (text.length() < 1)
1344             {
1345               text.append("<area shape=\"rect\" coords=\"")
1346                       .append((idWidth + column * av.getCharWidth()))
1347                       .append(",").append(sy).append(",")
1348                       .append((idWidth + (column + 1) * av.getCharWidth()))
1349                       .append(",").append((av.getCharHeight() + sy))
1350                       .append("\"").append(" onMouseOver=\"toolTip('")
1351                       .append(seqPos).append(" ").append(triplet);
1352             }
1353             if (!Comparison.isGap(seq.getCharAt(column)))
1354             {
1355               List<SequenceFeature> features = seq.findFeatures(column,
1356                       column);
1357               for (SequenceFeature sf : features)
1358               {
1359                 if (sf.isContactFeature())
1360                 {
1361                   text.append("<br>").append(sf.getType()).append(" ")
1362                           .append(sf.getBegin()).append(":")
1363                           .append(sf.getEnd());
1364                 }
1365                 else
1366                 {
1367                   text.append("<br>");
1368                   text.append(sf.getType());
1369                   String description = sf.getDescription();
1370                   if (description != null
1371                           && !sf.getType().equals(description))
1372                   {
1373                     description = description.replace("\"", "&quot;");
1374                     text.append(" ").append(description);
1375                   }
1376                 }
1377                 String status = sf.getStatus();
1378                 if (status != null && !"".equals(status))
1379                 {
1380                   text.append(" (").append(status).append(")");
1381                 }
1382               }
1383               if (text.length() > 1)
1384               {
1385                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1386                 out.println(text.toString());
1387               }
1388             }
1389           }
1390         }
1391         out.println("</map></body></html>");
1392         out.close();
1393
1394       } catch (Exception ex)
1395       {
1396         ex.printStackTrace();
1397       }
1398     } // /////////END OF IMAGE MAP
1399
1400   }
1401
1402   /**
1403    * Answers the height of the entire alignment in pixels, assuming it is in
1404    * wrapped mode
1405    * 
1406    * @return
1407    */
1408   int getWrappedHeight()
1409   {
1410     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1411
1412     if (System.getProperty("java.awt.headless") != null
1413             && System.getProperty("java.awt.headless").equals("true"))
1414     {
1415       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1416               - vscroll.getPreferredSize().width
1417               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1418     }
1419
1420     int chunkWidth = getSeqPanel().seqCanvas
1421             .getWrappedCanvasWidth(seqPanelWidth);
1422
1423     int hgap = av.getCharHeight();
1424     if (av.getScaleAboveWrapped())
1425     {
1426       hgap += av.getCharHeight();
1427     }
1428
1429     int annotationHeight = 0;
1430     if (av.isShowAnnotation())
1431     {
1432       hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1433       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1434     }
1435
1436     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1437             + annotationHeight;
1438
1439     int maxwidth = av.getAlignment().getWidth();
1440     if (av.hasHiddenColumns())
1441     {
1442       maxwidth = av.getAlignment().getHiddenColumns()
1443               .absoluteToVisibleColumn(maxwidth) - 1;
1444     }
1445
1446     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1447
1448     return height;
1449   }
1450
1451   /**
1452    * close the panel - deregisters all listeners and nulls any references to
1453    * alignment data.
1454    */
1455   public void closePanel()
1456   {
1457     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1458     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1459     PaintRefresher.RemoveComponent(this);
1460
1461     closeChildFrames();
1462
1463     /*
1464      * try to ensure references are nulled
1465      */
1466     if (annotationPanel != null)
1467     {
1468       annotationPanel.dispose();
1469       annotationPanel = null;
1470     }
1471
1472     if (av != null)
1473     {
1474       av.removePropertyChangeListener(propertyChangeListener);
1475       propertyChangeListener = null;
1476       StructureSelectionManager ssm = av.getStructureSelectionManager();
1477       ssm.removeStructureViewerListener(getSeqPanel(), null);
1478       ssm.removeSelectionListener(getSeqPanel());
1479       ssm.removeCommandListener(av);
1480       ssm.removeStructureViewerListener(getSeqPanel(), null);
1481       ssm.removeSelectionListener(getSeqPanel());
1482       av.dispose();
1483       av = null;
1484     }
1485     else
1486     {
1487       if (Cache.log.isDebugEnabled())
1488       {
1489         Cache.log.warn("Closing alignment panel which is already closed.");
1490       }
1491     }
1492   }
1493
1494   /**
1495    * Close any open dialogs that would be orphaned when this one is closed
1496    */
1497   protected void closeChildFrames()
1498   {
1499     if (overviewPanel != null)
1500     {
1501       overviewPanel.dispose();
1502       overviewPanel = null;
1503     }
1504     if (calculationDialog != null)
1505     {
1506       calculationDialog.closeFrame();
1507       calculationDialog = null;
1508     }
1509   }
1510
1511   /**
1512    * hides or shows dynamic annotation rows based on groups and av state flags
1513    */
1514   public void updateAnnotation()
1515   {
1516     updateAnnotation(false, false);
1517   }
1518
1519   public void updateAnnotation(boolean applyGlobalSettings)
1520   {
1521     updateAnnotation(applyGlobalSettings, false);
1522   }
1523
1524   public void updateAnnotation(boolean applyGlobalSettings,
1525           boolean preserveNewGroupSettings)
1526   {
1527     av.updateGroupAnnotationSettings(applyGlobalSettings,
1528             preserveNewGroupSettings);
1529     adjustAnnotationHeight();
1530   }
1531
1532   @Override
1533   public AlignmentI getAlignment()
1534   {
1535     return av == null ? null : av.getAlignment();
1536   }
1537
1538   @Override
1539   public String getViewName()
1540   {
1541     return av.getViewName();
1542   }
1543
1544   /**
1545    * Make/Unmake this alignment panel the current input focus
1546    * 
1547    * @param b
1548    */
1549   public void setSelected(boolean b)
1550   {
1551     try
1552     {
1553       if (alignFrame.getSplitViewContainer() != null)
1554       {
1555         /*
1556          * bring enclosing SplitFrame to front first if there is one
1557          */
1558         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1559       }
1560       alignFrame.setSelected(b);
1561     } catch (Exception ex)
1562     {
1563     }
1564
1565     if (b)
1566     {
1567       alignFrame.setDisplayedView(this);
1568     }
1569   }
1570
1571   @Override
1572   public StructureSelectionManager getStructureSelectionManager()
1573   {
1574     return av.getStructureSelectionManager();
1575   }
1576
1577   @Override
1578   public void raiseOOMWarning(String string, OutOfMemoryError error)
1579   {
1580     new OOMWarning(string, error, this);
1581   }
1582
1583   @Override
1584   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1585   {
1586
1587     return new FeatureRenderer(this);
1588   }
1589
1590   @Override
1591   public jalview.api.FeatureRenderer getFeatureRenderer()
1592   {
1593     return seqPanel.seqCanvas.getFeatureRenderer();
1594   }
1595
1596   public void updateFeatureRenderer(
1597           jalview.renderer.seqfeatures.FeatureRenderer fr)
1598   {
1599     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1600   }
1601
1602   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1603   {
1604     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1605     {
1606       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1607     }
1608   }
1609
1610   public ScalePanel getScalePanel()
1611   {
1612     return scalePanel;
1613   }
1614
1615   public void setScalePanel(ScalePanel scalePanel)
1616   {
1617     this.scalePanel = scalePanel;
1618   }
1619
1620   public SeqPanel getSeqPanel()
1621   {
1622     return seqPanel;
1623   }
1624
1625   public void setSeqPanel(SeqPanel seqPanel)
1626   {
1627     this.seqPanel = seqPanel;
1628   }
1629
1630   public AnnotationPanel getAnnotationPanel()
1631   {
1632     return annotationPanel;
1633   }
1634
1635   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1636   {
1637     this.annotationPanel = annotationPanel;
1638   }
1639
1640   public AnnotationLabels getAlabels()
1641   {
1642     return alabels;
1643   }
1644
1645   public void setAlabels(AnnotationLabels alabels)
1646   {
1647     this.alabels = alabels;
1648   }
1649
1650   public IdPanel getIdPanel()
1651   {
1652     return idPanel;
1653   }
1654
1655   public void setIdPanel(IdPanel idPanel)
1656   {
1657     this.idPanel = idPanel;
1658   }
1659
1660   /**
1661    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1662    * The aim is to keep the two alignments 'lined up' on their centre columns.
1663    * 
1664    * @param sr
1665    *          holds mapped region(s) of this alignment that we are scrolling
1666    *          'to'; may be modified for sequence offset by this method
1667    * @param verticalOffset
1668    *          the number of visible sequences to show above the mapped region
1669    */
1670   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1671   {
1672     scrollToPosition(sr, verticalOffset, true);
1673   }
1674
1675   /**
1676    * Set a flag to say do not scroll any (cDNA/protein) complement.
1677    * 
1678    * @param b
1679    */
1680   protected void setToScrollComplementPanel(boolean b)
1681   {
1682     this.scrollComplementaryPanel = b;
1683   }
1684
1685   /**
1686    * Get whether to scroll complement panel
1687    * 
1688    * @return true if cDNA/protein complement panels should be scrolled
1689    */
1690   protected boolean isSetToScrollComplementPanel()
1691   {
1692     return this.scrollComplementaryPanel;
1693   }
1694
1695   /**
1696    * Redraw sensibly.
1697    * 
1698    * @adjustHeight if true, try to recalculate panel height for visible
1699    *               annotations
1700    */
1701   protected void refresh(boolean adjustHeight)
1702   {
1703     validateAnnotationDimensions(adjustHeight);
1704     addNotify();
1705     if (adjustHeight)
1706     {
1707       // sort, repaint, update overview
1708       paintAlignment(true, false);
1709     }
1710     else
1711     {
1712       // lightweight repaint
1713       repaint();
1714     }
1715   }
1716
1717   @Override
1718   /**
1719    * Property change event fired when a change is made to the viewport ranges
1720    * object associated with this alignment panel's viewport
1721    */
1722   public void propertyChange(PropertyChangeEvent evt)
1723   {
1724     // update this panel's scroll values based on the new viewport ranges values
1725     updateScrollBarsFromRanges();
1726
1727     // now update any complementary alignment (its viewport ranges object
1728     // is different so does not get automatically updated)
1729     if (isSetToScrollComplementPanel())
1730     {
1731       setToScrollComplementPanel(false);
1732       av.scrollComplementaryAlignment();
1733       setToScrollComplementPanel(true);
1734     }
1735   }
1736
1737   void updateScrollBarsFromRanges()
1738   {
1739     ViewportRanges ranges = av.getRanges();
1740     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
1741   }
1742
1743   /**
1744    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1745    * reference should be nulled when the dialog is closed.
1746    * 
1747    * @param calculationChooser
1748    */
1749   public void setCalculationDialog(CalculationChooser calculationChooser)
1750   {
1751     calculationDialog = calculationChooser;
1752   }
1753
1754   /**
1755    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1756    * if none is open)
1757    */
1758   public CalculationChooser getCalculationDialog()
1759   {
1760     return calculationDialog;
1761   }
1762
1763   /**
1764    * From appletgui, for JalviewJS JavaScript interface
1765    * 
1766    * preliminary - untested
1767    * 
1768    * @param ostart
1769    * @param end
1770    * @param seqIndex
1771    * @param scrollToNearest
1772    * @param redrawOverview
1773    * @return
1774    */
1775   public boolean scrollTo(int ostart, int end, int seqIndex,
1776           boolean scrollToNearest, boolean redrawOverview)
1777   {
1778     int startv, endv, starts, ends;// , width;
1779
1780     int start = -1;
1781     if (av.hasHiddenColumns())
1782     {
1783       AlignmentI al = av.getAlignment();
1784       start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1785       end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1786       if (start == end)
1787       {
1788         if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1789         {
1790           // don't scroll - position isn't visible
1791           return false;
1792         }
1793       }
1794     }
1795     else
1796     {
1797       start = ostart;
1798     }
1799
1800     ViewportRanges ranges = av.getRanges();
1801     if (!av.getWrapAlignment())
1802     {
1803       /*
1804        * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1805        * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1806        * setScrollValues(start - 1, seqIndex); } else if ((endv =
1807        * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1808        * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1809        * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1810        * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1811        * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1812        */
1813
1814       // below is scrolling logic up to Jalview 2.8.2
1815       // if ((av.getStartRes() > end)
1816       // || (av.getEndRes() < start)
1817       // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1818       // {
1819       // if (start > av.getAlignment().getWidth() - hextent)
1820       // {
1821       // start = av.getAlignment().getWidth() - hextent;
1822       // if (start < 0)
1823       // {
1824       // start = 0;
1825       // }
1826       //
1827       // }
1828       // if (seqIndex > av.getAlignment().getHeight() - vextent)
1829       // {
1830       // seqIndex = av.getAlignment().getHeight() - vextent;
1831       // if (seqIndex < 0)
1832       // {
1833       // seqIndex = 0;
1834       // }
1835       // }
1836       // setScrollValues(start, seqIndex);
1837       // }
1838       // logic copied from jalview.gui.AlignmentPanel:
1839       if ((startv = ranges.getStartRes()) >= start)
1840       {
1841         /*
1842          * Scroll left to make start of search results visible
1843          */
1844         setScrollValues(start - 1, seqIndex);
1845       }
1846       else if ((endv = ranges.getEndRes()) <= end)
1847       {
1848         /*
1849          * Scroll right to make end of search results visible
1850          */
1851         setScrollValues(startv + 1 + end - endv, seqIndex);
1852       }
1853       else if ((starts = ranges.getStartSeq()) > seqIndex)
1854       {
1855         /*
1856          * Scroll up to make start of search results visible
1857          */
1858         setScrollValues(ranges.getStartRes(), seqIndex);
1859       }
1860       else if ((ends = ranges.getEndSeq()) <= seqIndex)
1861       {
1862         /*
1863          * Scroll down to make end of search results visible
1864          */
1865         setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1866       }
1867       /*
1868        * Else results are already visible - no need to scroll
1869        */
1870     }
1871     else
1872     {
1873       ranges.scrollToWrappedVisible(start);
1874     }
1875
1876     paintAlignment(redrawOverview, false);
1877     return true;
1878   }
1879
1880   private boolean holdRepaint = false;
1881
1882   /**
1883    * Called by IdCanvas and SeqPanel to defer painting until after JVP loading.
1884    * 
1885    * @return true if holding
1886    */
1887   public boolean getHoldRepaint()
1888   {
1889     return holdRepaint;
1890   }
1891
1892   /**
1893    * Called by Jalview2xml while loading
1894    * 
1895    * @param tf
1896    */
1897   public void setHoldRepaint(boolean tf)
1898   {
1899     if (holdRepaint == tf)
1900     {
1901       return;
1902     }
1903     holdRepaint = tf;
1904     if (!tf)
1905     {
1906       repaint();
1907     }
1908   }
1909
1910   @Override
1911   public void repaint()
1912   {
1913     if (holdRepaint)
1914     {
1915       // System.out.println("AP repaint holding");
1916       // Platform.stackTrace();
1917       return;
1918     }
1919     super.repaint();
1920   }
1921
1922   public void selectAllSequences()
1923   {
1924     selectSequences(av.getAlignment().getSequences());
1925   }
1926
1927   public void deselectAllSequences()
1928   {
1929     if (av.cursorMode)
1930     {
1931       getSeqPanel().keyboardNo1 = null;
1932       getSeqPanel().keyboardNo2 = null;
1933     }
1934     av.setSelectionGroup(null);
1935     av.getColumnSelection().clear();
1936     av.setSelectionGroup(null);
1937     getIdPanel().getIdCanvas().searchResults = null;
1938     av.sendSelection();
1939     // JAL-2034 - should delegate to
1940     // alignPanel to decide if overview needs
1941     // updating.
1942     paintAlignment(false, false);
1943     PaintRefresher.Refresh(this, av.getSequenceSetId());
1944   }
1945
1946   public void selectSequences(List<SequenceI> seqs)
1947   {
1948     SequenceGroup sg = new SequenceGroup(seqs);
1949     sg.setEndRes(av.getAlignment().getWidth() - 1);
1950     av.setSelectionGroup(sg);
1951     av.isSelectionGroupChanged(true);
1952     av.sendSelection();
1953     // JAL-2034 - should delegate to
1954     // alignPanel to decide if overview needs
1955     // updating.
1956     paintAlignment(false, false);
1957     PaintRefresher.Refresh(this, av.getSequenceSetId());
1958   }
1959
1960 }