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