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