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