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