72a074d5213fc476ff00aa5b8c8369f3f7c46c4f
[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       if (overviewPanel != null)
846       {
847         overviewPanel.updateOverviewImage();
848       }
849     }
850   }
851
852   /**
853    * DOCUMENT ME!
854    * 
855    * @param g
856    *          DOCUMENT ME!
857    */
858   @Override
859   public void paintComponent(Graphics g)
860   {
861
862     invalidate(); // needed so that the id width adjuster works correctly
863
864     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
865     idPanelHolder.setPreferredSize(d);
866     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
867
868     validate(); // needed so that the id width adjuster works correctly
869
870     /*
871      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
872      * though I still think this call should be elsewhere.
873      */
874     ViewportRanges ranges = av.getRanges();
875     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
876     super.paintComponent(g);
877   }
878
879   /**
880    * Set vertical scroll bar position, and number of increments, for wrapped
881    * panel
882    * 
883    * @param topLeftColumn
884    *          the column position at top left (0..)
885    */
886   private void setScrollingForWrappedPanel(int topLeftColumn)
887   {
888     ViewportRanges ranges = av.getRanges();
889     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
890     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
891
892     /*
893      * a scrollbar's value can be set to at most (maximum-extent)
894      * so we add extent (1) to the maxScroll value
895      */
896     vscroll.setUnitIncrement(1);
897     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
898   }
899
900   /**
901    * DOCUMENT ME!
902    * 
903    * @param pg
904    *          DOCUMENT ME!
905    * @param pf
906    *          DOCUMENT ME!
907    * @param pi
908    *          DOCUMENT ME!
909    * 
910    * @return DOCUMENT ME!
911    * 
912    * @throws PrinterException
913    *           DOCUMENT ME!
914    */
915   @Override
916   public int print(Graphics pg, PageFormat pf, int pi)
917           throws PrinterException
918   {
919     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
920
921     int pwidth = (int) pf.getImageableWidth();
922     int pheight = (int) pf.getImageableHeight();
923
924     if (av.getWrapAlignment())
925     {
926       return printWrappedAlignment(pwidth, pheight, pi, pg);
927     }
928     else
929     {
930       return printUnwrapped(pwidth, pheight, pi, pg, pg);
931     }
932   }
933
934   /**
935    * Draws the alignment image, including sequence ids, sequences, and
936    * annotation labels and annotations if shown, on either one or two Graphics
937    * contexts.
938    * 
939    * @param pageWidth
940    *          in pixels
941    * @param pageHeight
942    *          in pixels
943    * @param pageIndex
944    *          (0, 1, ...)
945    * @param idGraphics
946    *          the graphics context for sequence ids and annotation labels
947    * @param alignmentGraphics
948    *          the graphics context for sequences and annotations (may or may not
949    *          be the same context as idGraphics)
950    * @return
951    * @throws PrinterException
952    */
953   public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
954           Graphics idGraphics, Graphics alignmentGraphics)
955           throws PrinterException
956   {
957     final int idWidth = getVisibleIdWidth(false);
958
959     /*
960      * Get the horizontal offset to where we draw the sequences.
961      * This is idWidth if using a single Graphics context, else zero.
962      */
963     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
964             : idWidth;
965
966     FontMetrics fm = getFontMetrics(av.getFont());
967     final int charHeight = av.getCharHeight();
968     final int scaleHeight = charHeight + fm.getDescent();
969
970     idGraphics.setColor(Color.white);
971     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
972     idGraphics.setFont(av.getFont());
973
974     /*
975      * How many sequences and residues can we fit on a printable page?
976      */
977     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
978
979     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
980
981     final int alignmentWidth = av.getAlignment().getVisibleWidth();
982     int pagesWide = (alignmentWidth / totalRes) + 1;
983
984     final int startRes = (pageIndex % pagesWide) * totalRes;
985     final int endRes = Math.min(startRes + totalRes - 1,
986             alignmentWidth - 1);
987
988     final int startSeq = (pageIndex / pagesWide) * totalSeq;
989     final int alignmentHeight = av.getAlignment().getHeight();
990     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
991
992     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
993
994     if (av.isShowAnnotation())
995     {
996       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
997     }
998
999     pagesHigh /= pageHeight;
1000
1001     if (pageIndex >= (pagesWide * pagesHigh))
1002     {
1003       return Printable.NO_SUCH_PAGE;
1004     }
1005     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1006
1007     /*
1008      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1009      */
1010     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1011     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1012             pageWidth - idWidth, scaleHeight);
1013     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1014
1015     /*
1016      * Draw the sequence ids, offset for scale height,
1017      * then reset to top left (0, 0)
1018      */
1019     idGraphics.translate(0, scaleHeight);
1020     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1021     List<SequenceI> selection = av.getSelectionGroup() == null ? null
1022             : av.getSelectionGroup().getSequences(null);
1023     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1024             selection);
1025
1026     idGraphics.setFont(av.getFont());
1027     idGraphics.translate(0, -scaleHeight);
1028
1029     /*
1030      * draw the sequences, offset for scale height, and id width (if using a
1031      * single graphics context), then reset to (0, scale height)
1032      */
1033     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1034     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1035             endRes, startSeq, endSeq - 1);
1036     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1037
1038     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1039     {
1040       /*
1041        * draw annotation labels; drawComponent() translates by
1042        * getScrollOffset(), so compensate for that first;
1043        * then reset to (0, scale height)
1044        */
1045       int offset = getAlabels().getScrollOffset();
1046       idGraphics.translate(0, -offset);
1047       idGraphics.translate(0, alignmentDrawnHeight);
1048       getAlabels().drawComponent(idGraphics, idWidth);
1049       idGraphics.translate(0, -alignmentDrawnHeight);
1050
1051       /*
1052        * draw the annotations starting at 
1053        * (idOffset, alignmentHeight) from (0, scaleHeight)
1054        */
1055       alignmentGraphics.translate(alignmentGraphicsOffset,
1056               alignmentDrawnHeight);
1057       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1058               alignmentGraphics, -1, startRes, endRes + 1);
1059     }
1060
1061     return Printable.PAGE_EXISTS;
1062   }
1063
1064   /**
1065    * Prints one page of an alignment in wrapped mode. Returns
1066    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1067    * no page could be drawn (page number out of range).
1068    * 
1069    * @param pageWidth
1070    * @param pageHeight
1071    * @param pageNumber
1072    *          (0, 1, ...)
1073    * @param g
1074    * 
1075    * @return
1076    * 
1077    * @throws PrinterException
1078    */
1079   public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1080           Graphics g) throws PrinterException
1081   {
1082     int annotationHeight = 0;
1083     if (av.isShowAnnotation())
1084     {
1085       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1086     }
1087
1088     int hgap = av.getCharHeight();
1089     if (av.getScaleAboveWrapped())
1090     {
1091       hgap += av.getCharHeight();
1092     }
1093
1094     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1095             + annotationHeight;
1096
1097     int idWidth = getVisibleIdWidth(false);
1098
1099     int maxwidth = av.getAlignment().getVisibleWidth();
1100
1101     int resWidth = getSeqPanel().seqCanvas
1102             .getWrappedCanvasWidth(pageWidth - idWidth);
1103
1104     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1105
1106     g.setColor(Color.white);
1107     g.fillRect(0, 0, pageWidth, pageHeight);
1108     g.setFont(av.getFont());
1109     g.setColor(Color.black);
1110
1111     /*
1112      * method: print the whole wrapped alignment, but with a clip region that
1113      * is restricted to the requested page; this supports selective print of 
1114      * single  pages or ranges, (at the cost of some repeated processing in 
1115      * the 'normal' case, when all pages are printed)
1116      */
1117     g.translate(0, -pageNumber * pageHeight);
1118
1119     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1120
1121     /*
1122      * draw sequence ids and annotation labels (if shown)
1123      */
1124     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1125     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1126
1127     g.translate(idWidth, 0);
1128
1129     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1130             totalHeight, 0);
1131
1132     if ((pageNumber * pageHeight) < totalHeight)
1133     {
1134       return Printable.PAGE_EXISTS;
1135     }
1136     else
1137     {
1138       return Printable.NO_SUCH_PAGE;
1139     }
1140   }
1141
1142   /**
1143    * get current sequence ID panel width, or nominal value if panel were to be
1144    * displayed using default settings
1145    * 
1146    * @return
1147    */
1148   public int getVisibleIdWidth()
1149   {
1150     return getVisibleIdWidth(true);
1151   }
1152
1153   /**
1154    * get current sequence ID panel width, or nominal value if panel were to be
1155    * displayed using default settings
1156    * 
1157    * @param onscreen
1158    *          indicate if the Id width for onscreen or offscreen display should
1159    *          be returned
1160    * @return
1161    */
1162   public int getVisibleIdWidth(boolean onscreen)
1163   {
1164     // see if rendering offscreen - check preferences and calc width accordingly
1165     if (!onscreen && Cache.getDefault(Preferences.FIGURE_AUTOIDWIDTH, false))
1166     {
1167       return calculateIdWidth(-1).width + 4;
1168     }
1169     Integer idwidth = null;
1170     if (onscreen || (idwidth = Cache
1171             .getIntegerProperty(Preferences.FIGURE_FIXEDIDWIDTH)) == null)
1172     {
1173       int w = getIdPanel().getWidth();
1174       return (w > 0 ? w : calculateIdWidth().width + 4);
1175     }
1176     return idwidth.intValue() + 4;
1177   }
1178
1179   /**
1180    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1181    * writes it to the specified file
1182    * 
1183    * @param type
1184    * @param file
1185    */
1186   void makeAlignmentImage(ImageMaker.TYPE type, File file)
1187   {
1188     final int borderBottomOffset = 5;
1189
1190     AlignmentDimension aDimension = getAlignmentDimension();
1191     // todo use a lambda function in place of callback here?
1192     ImageWriterI writer = new ImageWriterI()
1193     {
1194       @Override
1195       public void exportImage(Graphics graphics) throws Exception
1196       {
1197         if (av.getWrapAlignment())
1198         {
1199           printWrappedAlignment(aDimension.getWidth(),
1200                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1201         }
1202         else
1203         {
1204           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1205                   graphics, graphics);
1206         }
1207       }
1208     };
1209
1210     String fileTitle = alignFrame.getTitle();
1211     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1212             fileTitle);
1213     int imageWidth = aDimension.getWidth();
1214     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1215     String of = MessageManager.getString("label.alignment");
1216     exporter.doExport(file, this, imageWidth, imageHeight, of);
1217   }
1218
1219   /**
1220    * Calculates and returns a suitable width and height (in pixels) for an
1221    * exported image
1222    * 
1223    * @return
1224    */
1225   public AlignmentDimension getAlignmentDimension()
1226   {
1227     int maxwidth = av.getAlignment().getVisibleWidth();
1228
1229     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1230             + getScalePanel().getHeight();
1231     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1232
1233     if (av.getWrapAlignment())
1234     {
1235       height = getWrappedHeight();
1236       if (Jalview.isHeadlessMode())
1237       {
1238         // need to obtain default alignment width and then add in any
1239         // additional allowance for id margin
1240         // this duplicates the calculation in getWrappedHeight but adjusts for
1241         // offscreen idWith
1242         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1243                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1244                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1245       }
1246       else
1247       {
1248         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1249       }
1250
1251     }
1252     else if (av.isShowAnnotation())
1253     {
1254       height += getAnnotationPanel().adjustPanelHeight() + 3;
1255     }
1256     return new AlignmentDimension(width, height);
1257
1258   }
1259
1260   public void makePNGImageMap(File imgMapFile, String imageName)
1261   {
1262     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1263     // ////////////////////////////////////////////
1264     int idWidth = getVisibleIdWidth(false);
1265     FontMetrics fm = getFontMetrics(av.getFont());
1266     int scaleHeight = av.getCharHeight() + fm.getDescent();
1267
1268     // Gen image map
1269     // ////////////////////////////////
1270     if (imgMapFile != null)
1271     {
1272       try
1273       {
1274         int sSize = av.getAlignment().getHeight();
1275         int alwidth = av.getAlignment().getWidth();
1276         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1277         out.println(HTMLOutput.getImageMapHTML());
1278         out.println("<img src=\"" + imageName
1279                 + "\" border=\"0\" usemap=\"#Map\" >"
1280                 + "<map name=\"Map\">");
1281
1282         for (int s = 0; s < sSize; s++)
1283         {
1284           int sy = s * av.getCharHeight() + scaleHeight;
1285
1286           SequenceI seq = av.getAlignment().getSequenceAt(s);
1287           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1288           for (int column = 0; column < alwidth; column++)
1289           {
1290             StringBuilder text = new StringBuilder(512);
1291             String triplet = null;
1292             if (av.getAlignment().isNucleotide())
1293             {
1294               triplet = ResidueProperties.nucleotideName.get(seq
1295                       .getCharAt(column) + "");
1296             }
1297             else
1298             {
1299               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1300                       + "");
1301             }
1302
1303             if (triplet == null)
1304             {
1305               continue;
1306             }
1307
1308             int seqPos = seq.findPosition(column);
1309             int gSize = groups.length;
1310             for (int g = 0; g < gSize; g++)
1311             {
1312               if (text.length() < 1)
1313               {
1314                 text.append("<area shape=\"rect\" coords=\"")
1315                         .append((idWidth + column * av.getCharWidth()))
1316                         .append(",").append(sy).append(",")
1317                         .append((idWidth + (column + 1) * av.getCharWidth()))
1318                         .append(",").append((av.getCharHeight() + sy))
1319                         .append("\"").append(" onMouseOver=\"toolTip('")
1320                         .append(seqPos).append(" ").append(triplet);
1321               }
1322
1323               if (groups[g].getStartRes() < column
1324                       && groups[g].getEndRes() > column)
1325               {
1326                 text.append("<br><em>").append(groups[g].getName())
1327                         .append("</em>");
1328               }
1329             }
1330
1331             if (text.length() < 1)
1332             {
1333               text.append("<area shape=\"rect\" coords=\"")
1334                       .append((idWidth + column * av.getCharWidth()))
1335                       .append(",").append(sy).append(",")
1336                       .append((idWidth + (column + 1) * av.getCharWidth()))
1337                       .append(",").append((av.getCharHeight() + sy))
1338                       .append("\"").append(" onMouseOver=\"toolTip('")
1339                       .append(seqPos).append(" ").append(triplet);
1340             }
1341             if (!Comparison.isGap(seq.getCharAt(column)))
1342             {
1343               List<SequenceFeature> features = seq.findFeatures(column, column);
1344               for (SequenceFeature sf : features)
1345               {
1346                 if (sf.isContactFeature())
1347                 {
1348                   text.append("<br>").append(sf.getType()).append(" ")
1349                           .append(sf.getBegin()).append(":")
1350                           .append(sf.getEnd());
1351                 }
1352                 else
1353                 {
1354                   text.append("<br>");
1355                   text.append(sf.getType());
1356                   String description = sf.getDescription();
1357                   if (description != null
1358                           && !sf.getType().equals(description))
1359                   {
1360                     description = description.replace("\"", "&quot;");
1361                     text.append(" ").append(description);
1362                   }
1363                 }
1364                 String status = sf.getStatus();
1365                 if (status != null && !"".equals(status))
1366                 {
1367                   text.append(" (").append(status).append(")");
1368                 }
1369               }
1370               if (text.length() > 1)
1371               {
1372                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1373                 out.println(text.toString());
1374               }
1375             }
1376           }
1377         }
1378         out.println("</map></body></html>");
1379         out.close();
1380
1381       } catch (Exception ex)
1382       {
1383         ex.printStackTrace();
1384       }
1385     } // /////////END OF IMAGE MAP
1386
1387   }
1388
1389   int getWrappedHeight()
1390   {
1391     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1392
1393     if (Jalview.isHeadlessMode())
1394     {
1395       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1396               - vscroll.getPreferredSize().width
1397               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1398     }
1399
1400     int chunkWidth = getSeqPanel().seqCanvas
1401             .getWrappedCanvasWidth(seqPanelWidth);
1402
1403     int hgap = av.getCharHeight();
1404     if (av.getScaleAboveWrapped())
1405     {
1406       hgap += av.getCharHeight();
1407     }
1408
1409     int annotationHeight = 0;
1410     if (av.isShowAnnotation())
1411     {
1412       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1413     }
1414
1415     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1416             + annotationHeight;
1417
1418     int maxwidth = av.getAlignment().getWidth();
1419     if (av.hasHiddenColumns())
1420     {
1421       maxwidth = av.getAlignment().getHiddenColumns()
1422               .absoluteToVisibleColumn(maxwidth) - 1;
1423     }
1424
1425     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1426
1427     return height;
1428   }
1429
1430   /**
1431    * close the panel - deregisters all listeners and nulls any references to
1432    * alignment data.
1433    */
1434   public void closePanel()
1435   {
1436     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1437     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1438     PaintRefresher.RemoveComponent(this);
1439
1440     closeChildFrames();
1441
1442     /*
1443      * try to ensure references are nulled
1444      */
1445     if (annotationPanel != null)
1446     {
1447       annotationPanel.dispose();
1448       annotationPanel = null;
1449     }
1450
1451     if (av != null)
1452     {
1453       av.removePropertyChangeListener(propertyChangeListener);
1454       propertyChangeListener = null;
1455       StructureSelectionManager ssm = av.getStructureSelectionManager();
1456       ssm.removeStructureViewerListener(getSeqPanel(), null);
1457       ssm.removeSelectionListener(getSeqPanel());
1458       ssm.removeCommandListener(av);
1459       ssm.removeStructureViewerListener(getSeqPanel(), null);
1460       ssm.removeSelectionListener(getSeqPanel());
1461       av.dispose();
1462       av = null;
1463     }
1464     else
1465     {
1466       if (Cache.log.isDebugEnabled())
1467       {
1468         Cache.log.warn("Closing alignment panel which is already closed.");
1469       }
1470     }
1471   }
1472
1473   /**
1474    * Close any open dialogs that would be orphaned when this one is closed
1475    */
1476   protected void closeChildFrames()
1477   {
1478     if (overviewPanel != null)
1479     {
1480       overviewPanel.dispose();
1481       overviewPanel = null;
1482     }
1483     if (calculationDialog != null)
1484     {
1485       calculationDialog.closeFrame();
1486       calculationDialog = null;
1487     }
1488   }
1489
1490   /**
1491    * hides or shows dynamic annotation rows based on groups and av state flags
1492    */
1493   public void updateAnnotation()
1494   {
1495     updateAnnotation(false, false);
1496   }
1497
1498   public void updateAnnotation(boolean applyGlobalSettings)
1499   {
1500     updateAnnotation(applyGlobalSettings, false);
1501   }
1502
1503   public void updateAnnotation(boolean applyGlobalSettings,
1504           boolean preserveNewGroupSettings)
1505   {
1506     av.updateGroupAnnotationSettings(applyGlobalSettings,
1507             preserveNewGroupSettings);
1508     adjustAnnotationHeight();
1509   }
1510
1511   @Override
1512   public AlignmentI getAlignment()
1513   {
1514     return av == null ? null : av.getAlignment();
1515   }
1516
1517   @Override
1518   public String getViewName()
1519   {
1520     return av.getViewName();
1521   }
1522
1523   /**
1524    * Make/Unmake this alignment panel the current input focus
1525    * 
1526    * @param b
1527    */
1528   public void setSelected(boolean b)
1529   {
1530     try
1531     {
1532       if (alignFrame.getSplitViewContainer() != null)
1533       {
1534         /*
1535          * bring enclosing SplitFrame to front first if there is one
1536          */
1537         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1538       }
1539       alignFrame.setSelected(b);
1540     } catch (Exception ex)
1541     {
1542     }
1543
1544     if (b)
1545     {
1546       alignFrame.setDisplayedView(this);
1547     }
1548   }
1549
1550   @Override
1551   public StructureSelectionManager getStructureSelectionManager()
1552   {
1553     return av.getStructureSelectionManager();
1554   }
1555
1556   @Override
1557   public void raiseOOMWarning(String string, OutOfMemoryError error)
1558   {
1559     new OOMWarning(string, error, this);
1560   }
1561
1562   @Override
1563   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1564   {
1565
1566     return new FeatureRenderer(this);
1567   }
1568
1569   @Override
1570   public jalview.api.FeatureRenderer getFeatureRenderer()
1571   {
1572     return seqPanel.seqCanvas.getFeatureRenderer();
1573   }
1574
1575   public void updateFeatureRenderer(
1576           jalview.renderer.seqfeatures.FeatureRenderer fr)
1577   {
1578     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1579   }
1580
1581   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1582   {
1583     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1584     {
1585       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1586     }
1587   }
1588
1589   public ScalePanel getScalePanel()
1590   {
1591     return scalePanel;
1592   }
1593
1594   public void setScalePanel(ScalePanel scalePanel)
1595   {
1596     this.scalePanel = scalePanel;
1597   }
1598
1599   public SeqPanel getSeqPanel()
1600   {
1601     return seqPanel;
1602   }
1603
1604   public void setSeqPanel(SeqPanel seqPanel)
1605   {
1606     this.seqPanel = seqPanel;
1607   }
1608
1609   public AnnotationPanel getAnnotationPanel()
1610   {
1611     return annotationPanel;
1612   }
1613
1614   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1615   {
1616     this.annotationPanel = annotationPanel;
1617   }
1618
1619   public AnnotationLabels getAlabels()
1620   {
1621     return alabels;
1622   }
1623
1624   public void setAlabels(AnnotationLabels alabels)
1625   {
1626     this.alabels = alabels;
1627   }
1628
1629   public IdPanel getIdPanel()
1630   {
1631     return idPanel;
1632   }
1633
1634   public void setIdPanel(IdPanel idPanel)
1635   {
1636     this.idPanel = idPanel;
1637   }
1638
1639   /**
1640    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1641    * The aim is to keep the two alignments 'lined up' on their centre columns.
1642    * 
1643    * @param sr
1644    *          holds mapped region(s) of this alignment that we are scrolling
1645    *          'to'; may be modified for sequence offset by this method
1646    * @param verticalOffset
1647    *          the number of visible sequences to show above the mapped region
1648    */
1649   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1650   {
1651     scrollToPosition(sr, verticalOffset, true);
1652   }
1653
1654   /**
1655    * Set a flag to say do not scroll any (cDNA/protein) complement.
1656    * 
1657    * @param b
1658    */
1659   protected void setToScrollComplementPanel(boolean b)
1660   {
1661     this.scrollComplementaryPanel = b;
1662   }
1663
1664   /**
1665    * Get whether to scroll complement panel
1666    * 
1667    * @return true if cDNA/protein complement panels should be scrolled
1668    */
1669   protected boolean isSetToScrollComplementPanel()
1670   {
1671     return this.scrollComplementaryPanel;
1672   }
1673
1674   /**
1675    * Redraw sensibly.
1676    * 
1677    * @adjustHeight if true, try to recalculate panel height for visible
1678    *               annotations
1679    */
1680   protected void refresh(boolean adjustHeight)
1681   {
1682     validateAnnotationDimensions(adjustHeight);
1683     addNotify();
1684     if (adjustHeight)
1685     {
1686       // sort, repaint, update overview
1687       paintAlignment(true, false);
1688     }
1689     else
1690     {
1691       // lightweight repaint
1692       repaint();
1693     }
1694   }
1695
1696   @Override
1697   /**
1698    * Property change event fired when a change is made to the viewport ranges
1699    * object associated with this alignment panel's viewport
1700    */
1701   public void propertyChange(PropertyChangeEvent evt)
1702   {
1703     // update this panel's scroll values based on the new viewport ranges values
1704     ViewportRanges ranges = av.getRanges();
1705     int x = ranges.getStartRes();
1706     int y = ranges.getStartSeq();
1707     setScrollValues(x, y);
1708
1709     // now update any complementary alignment (its viewport ranges object
1710     // is different so does not get automatically updated)
1711     if (isSetToScrollComplementPanel())
1712     {
1713       setToScrollComplementPanel(false);
1714       av.scrollComplementaryAlignment();
1715       setToScrollComplementPanel(true);
1716     }
1717   }
1718
1719   /**
1720    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1721    * reference should be nulled when the dialog is closed.
1722    * 
1723    * @param calculationChooser
1724    */
1725   public void setCalculationDialog(CalculationChooser calculationChooser)
1726   {
1727     calculationDialog = calculationChooser;
1728   }
1729
1730   /**
1731    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1732    * if none is open)
1733    */
1734   public CalculationChooser getCalculationDialog()
1735   {
1736     return calculationDialog;
1737   }
1738
1739   @Override
1740   public SequenceRenderer getSequenceRenderer()
1741   {
1742     return seqPanel.seqCanvas.getSequenceRenderer();
1743   }
1744
1745   public boolean scrollTo(int ostart, int end, int seqIndex,
1746           boolean scrollToNearest, boolean redrawOverview)
1747   {
1748     int startv, endv, starts, ends;// , width;
1749
1750     int start = -1;
1751     if (av.hasHiddenColumns())
1752     {
1753       AlignmentI al = av.getAlignment();
1754       start = al.getHiddenColumns().absoluteToVisibleColumn(ostart);
1755       end = al.getHiddenColumns().absoluteToVisibleColumn(end);
1756       if (start == end)
1757       {
1758         if (!scrollToNearest && !al.getHiddenColumns().isVisible(ostart))
1759         {
1760           // don't scroll - position isn't visible
1761           return false;
1762         }
1763       }
1764     }
1765     else
1766     {
1767       start = ostart;
1768     }
1769
1770     ViewportRanges ranges = av.getRanges();
1771     if (!av.getWrapAlignment())
1772     {
1773       /*
1774        * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
1775        * av.getStartRes()) >= start) { spos=start-1; // seqIn //
1776        * setScrollValues(start - 1, seqIndex); } else if ((endv =
1777        * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
1778        * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
1779        * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
1780        * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
1781        * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
1782        */
1783
1784       // below is scrolling logic up to Jalview 2.8.2
1785       // if ((av.getStartRes() > end)
1786       // || (av.getEndRes() < start)
1787       // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
1788       // {
1789       // if (start > av.getAlignment().getWidth() - hextent)
1790       // {
1791       // start = av.getAlignment().getWidth() - hextent;
1792       // if (start < 0)
1793       // {
1794       // start = 0;
1795       // }
1796       //
1797       // }
1798       // if (seqIndex > av.getAlignment().getHeight() - vextent)
1799       // {
1800       // seqIndex = av.getAlignment().getHeight() - vextent;
1801       // if (seqIndex < 0)
1802       // {
1803       // seqIndex = 0;
1804       // }
1805       // }
1806       // setScrollValues(start, seqIndex);
1807       // }
1808       // logic copied from jalview.gui.AlignmentPanel:
1809       if ((startv = ranges.getStartRes()) >= start)
1810       {
1811         /*
1812          * Scroll left to make start of search results visible
1813          */
1814         setScrollValues(start - 1, seqIndex);
1815       }
1816       else if ((endv = ranges.getEndRes()) <= end)
1817       {
1818         /*
1819          * Scroll right to make end of search results visible
1820          */
1821         setScrollValues(startv + 1 + end - endv, seqIndex);
1822       }
1823       else if ((starts = ranges.getStartSeq()) > seqIndex)
1824       {
1825         /*
1826          * Scroll up to make start of search results visible
1827          */
1828         setScrollValues(ranges.getStartRes(), seqIndex);
1829       }
1830       else if ((ends = ranges.getEndSeq()) <= seqIndex)
1831       {
1832         /*
1833          * Scroll down to make end of search results visible
1834          */
1835         setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 1);
1836       }
1837       /*
1838        * Else results are already visible - no need to scroll
1839        */
1840     }
1841     else
1842     {
1843       ranges.scrollToWrappedVisible(start);
1844     }
1845
1846     paintAlignment(redrawOverview, false);
1847     return true;
1848   }
1849
1850   @Override
1851   public void overviewDone(BufferedImage miniMe)
1852   {
1853     overviewPanel.canvas.finalizeDraw(miniMe);
1854   }
1855
1856
1857   private boolean holdRepaint = false;
1858
1859   public boolean getHoldRepaint()
1860   {
1861     return holdRepaint;
1862   }
1863
1864   public void setHoldRepaint(boolean b)
1865   {
1866     if (holdRepaint == b)
1867     {
1868       return;
1869     }
1870     holdRepaint = b;
1871     if (!b)
1872     {
1873       repaint();
1874     }
1875   }
1876
1877   @Override
1878   public void repaint()
1879   {
1880     if (holdRepaint)
1881     {
1882       // System.out.println("AP repaint holding");
1883       // Platform.stackTrace();
1884       return;
1885     }
1886     super.repaint();
1887   }
1888
1889 }