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