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