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