Merge branch 'improvement/JAL-4250_secondary_structure_annotation_antialias' into...
[jalview.git] / src / jalview / gui / AlignmentPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Container;
26 import java.awt.Dimension;
27 import java.awt.Font;
28 import java.awt.FontMetrics;
29 import java.awt.Graphics;
30 import java.awt.Graphics2D;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.awt.print.PageFormat;
36 import java.awt.print.Printable;
37 import java.awt.print.PrinterException;
38 import java.beans.PropertyChangeEvent;
39 import java.beans.PropertyChangeListener;
40 import java.io.File;
41 import java.io.FileWriter;
42 import java.io.PrintWriter;
43 import java.util.List;
44
45 import javax.swing.SwingUtilities;
46
47 import jalview.analysis.AnnotationSorter;
48 import jalview.api.AlignViewportI;
49 import jalview.api.AlignmentViewPanel;
50 import jalview.bin.Cache;
51 import jalview.bin.Console;
52 import jalview.bin.Jalview;
53 import jalview.datamodel.AlignmentI;
54 import jalview.datamodel.HiddenColumns;
55 import jalview.datamodel.SearchResultsI;
56 import jalview.datamodel.SequenceFeature;
57 import jalview.datamodel.SequenceGroup;
58 import jalview.datamodel.SequenceI;
59 import jalview.gui.ImageExporter.ImageWriterI;
60 import jalview.io.HTMLOutput;
61 import jalview.io.exceptions.ImageOutputException;
62 import jalview.jbgui.GAlignmentPanel;
63 import jalview.math.AlignmentDimension;
64 import jalview.schemes.ResidueProperties;
65 import jalview.structure.StructureSelectionManager;
66 import jalview.util.Comparison;
67 import jalview.util.ImageMaker;
68 import jalview.util.MessageManager;
69 import jalview.util.imagemaker.BitmapImageSizing;
70 import jalview.viewmodel.ViewportListenerI;
71 import jalview.viewmodel.ViewportRanges;
72
73 /**
74  * DOCUMENT ME!
75  * 
76  * @author $author$
77  * @version $Revision: 1.161 $
78  */
79 @SuppressWarnings("serial")
80 public class AlignmentPanel extends GAlignmentPanel implements
81         AdjustmentListener, Printable, AlignmentViewPanel, ViewportListenerI
82 {
83   /*
84    * spare space in pixels between sequence id and alignment panel
85    */
86   private static final int ID_WIDTH_PADDING = 4;
87
88   public AlignViewport av;
89
90   OverviewPanel overviewPanel;
91
92   private SeqPanel seqPanel;
93
94   private IdPanel idPanel;
95
96   IdwidthAdjuster idwidthAdjuster;
97
98   public AlignFrame alignFrame;
99
100   private ScalePanel scalePanel;
101
102   private AnnotationPanel annotationPanel;
103
104   private AnnotationLabels alabels;
105
106   private int hextent = 0;
107
108   private int vextent = 0;
109
110   /*
111    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
112    * false, suppresses invoking the same method recursively.
113    */
114   private boolean scrollComplementaryPanel = true;
115
116   private PropertyChangeListener propertyChangeListener;
117
118   private CalculationChooser calculationDialog;
119
120   /**
121    * Creates a new AlignmentPanel object.
122    * 
123    * @param af
124    * @param av
125    */
126   public AlignmentPanel(AlignFrame af, final AlignViewport av)
127   {
128     // setBackground(Color.white); // BH 2019
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
146     scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
147     seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
148
149     setScrollValues(0, 0);
150
151     hscroll.addAdjustmentListener(this);
152     vscroll.addAdjustmentListener(this);
153
154     addComponentListener(new ComponentAdapter()
155     {
156       @Override
157       public void componentResized(ComponentEvent evt)
158       {
159         // reset the viewport ranges when the alignment panel is resized
160         // in particular, this initialises the end residue value when Jalview
161         // is initialised
162         ViewportRanges ranges = av.getRanges();
163         if (av.getWrapAlignment())
164         {
165           int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
166                   getSeqPanel().seqCanvas.getWidth());
167           ranges.setViewportWidth(widthInRes);
168         }
169         else
170         {
171           int widthInRes = getSeqPanel().seqCanvas.getWidth()
172                   / av.getCharWidth();
173           int heightInSeq = getSeqPanel().seqCanvas.getHeight()
174                   / av.getCharHeight();
175
176           ranges.setViewportWidth(widthInRes);
177           ranges.setViewportHeight(heightInSeq);
178         }
179       }
180
181     });
182
183     final AlignmentPanel ap = this;
184     propertyChangeListener = new PropertyChangeListener()
185     {
186       @Override
187       public void propertyChange(PropertyChangeEvent evt)
188       {
189         if (evt.getPropertyName().equals("alignment"))
190         {
191           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
192           alignmentChanged();
193         }
194       }
195     };
196     av.addPropertyChangeListener(propertyChangeListener);
197
198     av.getRanges().addPropertyChangeListener(this);
199     fontChanged();
200     adjustAnnotationHeight();
201     updateLayout();
202   }
203
204   @Override
205   public AlignViewportI getAlignViewport()
206   {
207     return av;
208   }
209
210   public void alignmentChanged()
211   {
212     av.alignmentChanged(this);
213
214     if (getCalculationDialog() != null)
215     {
216       getCalculationDialog().validateCalcTypes();
217     }
218
219     alignFrame.updateEditMenuBar();
220
221     // no idea if we need to update structure
222     paintAlignment(true, true);
223
224   }
225
226   /**
227    * DOCUMENT ME!
228    */
229   public void fontChanged()
230   {
231     // set idCanvas bufferedImage to null
232     // to prevent drawing old image
233     FontMetrics fm = getFontMetrics(av.getFont());
234
235     // update the flag controlling whether the grid is too small to render the
236     // font
237     av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
238
239     scalePanelHolder.setPreferredSize(
240             new Dimension(10, av.getCharHeight() + fm.getDescent()));
241     idSpaceFillerPanel1.setPreferredSize(
242             new Dimension(10, av.getCharHeight() + fm.getDescent()));
243     idwidthAdjuster.invalidate();
244     scalePanelHolder.invalidate();
245     // BH 2018 getIdPanel().getIdCanvas().gg = null;
246     getSeqPanel().seqCanvas.img = null;
247     getAnnotationPanel().adjustPanelHeight();
248
249     Dimension d = calculateIdWidth();
250     getIdPanel().getIdCanvas().setPreferredSize(d);
251     hscrollFillerPanel.setPreferredSize(d);
252
253     repaint();
254   }
255
256   /**
257    * Calculates the width of the alignment labels based on the displayed names
258    * and any bounds on label width set in preferences. The calculated width is
259    * also set as a property of the viewport.
260    * 
261    * @return Dimension giving the maximum width of the alignment label panel
262    *         that should be used.
263    */
264   public Dimension calculateIdWidth()
265   {
266     int oldWidth = av.getIdWidth();
267
268     // calculate sensible default width when no preference is available
269     Dimension r = null;
270     if (av.getIdWidth() < 0)
271     {
272       int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
273       int idWidth = Math.min(afwidth - 200, 2 * afwidth / 3);
274       int maxwidth = Math.max(IdwidthAdjuster.MIN_ID_WIDTH, idWidth);
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
285     /*
286      * fudge: if desired width has changed, update layout
287      * (see also paintComponent - updates layout on a repaint)
288      */
289     if (r.width != oldWidth)
290     {
291       idPanelHolder.setPreferredSize(r);
292       validate();
293     }
294     return r;
295   }
296
297   /**
298    * Calculate the width of the alignment labels based on the displayed names
299    * and any bounds on label width set in preferences.
300    * 
301    * @param maxwidth
302    *          -1 or maximum width allowed for IdWidth
303    * @return Dimension giving the maximum width of the alignment label panel
304    *         that should be used.
305    */
306   protected Dimension calculateIdWidth(int maxwidth)
307   {
308     Container c = new Container();
309
310     FontMetrics fm = c.getFontMetrics(
311             new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
312
313     AlignmentI al = av.getAlignment();
314     int i = 0;
315     int idWidth = 0;
316
317     while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
318     {
319       SequenceI s = al.getSequenceAt(i);
320       String id = s.getDisplayId(av.getShowJVSuffix());
321       int stringWidth = fm.stringWidth(id);
322       idWidth = Math.max(idWidth, stringWidth);
323       i++;
324     }
325
326     // Also check annotation label widths
327     i = 0;
328
329     if (al.getAlignmentAnnotation() != null)
330     {
331       fm = c.getFontMetrics(getAlabels().getFont());
332
333       while (i < al.getAlignmentAnnotation().length)
334       {
335         String label = al.getAlignmentAnnotation()[i].label;
336         int stringWidth = fm.stringWidth(label);
337         idWidth = Math.max(idWidth, stringWidth);
338         i++;
339       }
340     }
341
342     int w = maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth);
343     w += ID_WIDTH_PADDING;
344
345     return new Dimension(w, 12);
346   }
347
348   /**
349    * Highlight the given results on the alignment
350    * 
351    */
352   public void highlightSearchResults(SearchResultsI results)
353   {
354     boolean scrolled = scrollToPosition(results, 0, false);
355
356     boolean fastPaint = !(scrolled && av.getWrapAlignment());
357
358     getSeqPanel().seqCanvas.highlightSearchResults(results, fastPaint);
359   }
360
361   /**
362    * Scroll the view to show the position of the highlighted region in results
363    * (if any)
364    * 
365    * @param searchResults
366    * @return
367    */
368   public boolean scrollToPosition(SearchResultsI searchResults)
369   {
370     return scrollToPosition(searchResults, 0, false);
371   }
372
373   /**
374    * Scrolls the view (if necessary) to show the position of the first
375    * highlighted region in results (if any). Answers true if the view was
376    * scrolled, or false if no matched region was found, or it is already
377    * visible.
378    * 
379    * @param results
380    * @param verticalOffset
381    *          if greater than zero, allows scrolling to a position below the
382    *          first displayed sequence
383    * @param centre
384    *          if true, try to centre the search results horizontally in the view
385    * @return
386    */
387   protected boolean scrollToPosition(SearchResultsI results,
388           int verticalOffset, boolean centre)
389   {
390     int startv, endv, starts, ends;
391     ViewportRanges ranges = av.getRanges();
392
393     if (results == null || results.isEmpty() || av == null
394             || av.getAlignment() == null)
395     {
396       return false;
397     }
398     int seqIndex = av.getAlignment().findIndex(results);
399     if (seqIndex == -1)
400     {
401       return false;
402     }
403     SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
404
405     int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
406     if (r == null)
407     {
408       return false;
409     }
410     int start = r[0];
411     int end = r[1];
412
413     /*
414      * To centre results, scroll to positions half the visible width
415      * left/right of the start/end positions
416      */
417     if (centre)
418     {
419       int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
420       start = Math.max(start - offset, 0);
421       end = end + offset - 1;
422     }
423     if (start < 0)
424     {
425       return false;
426     }
427     if (end == seq.getEnd())
428     {
429       return false;
430     }
431
432     if (av.hasHiddenColumns())
433     {
434       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
435       start = hidden.absoluteToVisibleColumn(start);
436       end = hidden.absoluteToVisibleColumn(end);
437       if (start == end)
438       {
439         if (!hidden.isVisible(r[0]))
440         {
441           // don't scroll - position isn't visible
442           return false;
443         }
444       }
445     }
446
447     /*
448      * allow for offset of target sequence (actually scroll to one above it)
449      */
450     seqIndex = Math.max(0, seqIndex - verticalOffset);
451     boolean scrollNeeded = true;
452
453     if (!av.getWrapAlignment())
454     {
455       if ((startv = ranges.getStartRes()) >= start)
456       {
457         /*
458          * Scroll left to make start of search results visible
459          */
460         setScrollValues(start, seqIndex);
461       }
462       else if ((endv = ranges.getEndRes()) <= end)
463       {
464         /*
465          * Scroll right to make end of search results visible
466          */
467         setScrollValues(startv + end - endv, seqIndex);
468       }
469       else if ((starts = ranges.getStartSeq()) > seqIndex)
470       {
471         /*
472          * Scroll up to make start of search results visible
473          */
474         setScrollValues(ranges.getStartRes(), seqIndex);
475       }
476       else if ((ends = ranges.getEndSeq()) <= seqIndex)
477       {
478         /*
479          * Scroll down to make end of search results visible
480          */
481         setScrollValues(ranges.getStartRes(), starts + seqIndex - ends + 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     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();
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           Console.warn(
815                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
816
817           // scroll to start of panel
818           ranges.setStartRes(0);
819           ranges.setStartSeq(0);
820         }
821       });
822     }
823     repaint();
824   }
825
826   /* (non-Javadoc)
827    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
828    */
829   @Override
830   public void paintAlignment(boolean updateOverview,
831           boolean updateStructures)
832   {
833     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
834             av.isShowAutocalculatedAbove());
835     sorter.sort(getAlignment().getAlignmentAnnotation(),
836             av.getSortAnnotationsBy());
837     repaint();
838
839     if (updateStructures)
840     {
841       av.getStructureSelectionManager().sequenceColoursChanged(this);
842     }
843     if (updateOverview)
844     {
845
846       if (overviewPanel != null)
847       {
848         overviewPanel.updateOverviewImage();
849       }
850     }
851   }
852
853   @Override
854   public void paintComponent(Graphics g)
855   {
856     invalidate(); // needed so that the id width adjuster works correctly
857
858     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
859     idPanelHolder.setPreferredSize(d);
860     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
861
862     validate(); // needed so that the id width adjuster works correctly
863
864     /*
865      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
866      * though I still think this call should be elsewhere.
867      */
868     ViewportRanges ranges = av.getRanges();
869     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
870     super.paintComponent(g);
871   }
872
873   /**
874    * Set vertical scroll bar position, and number of increments, for wrapped
875    * panel
876    * 
877    * @param topLeftColumn
878    *          the column position at top left (0..)
879    */
880   private void setScrollingForWrappedPanel(int topLeftColumn)
881   {
882     ViewportRanges ranges = av.getRanges();
883     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
884     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
885
886     /*
887      * a scrollbar's value can be set to at most (maximum-extent)
888      * so we add extent (1) to the maxScroll value
889      */
890     vscroll.setUnitIncrement(1);
891     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
892   }
893
894   /**
895    * DOCUMENT ME!
896    * 
897    * @param pg
898    *          DOCUMENT ME!
899    * @param pf
900    *          DOCUMENT ME!
901    * @param pi
902    *          DOCUMENT ME!
903    * 
904    * @return DOCUMENT ME!
905    * 
906    * @throws PrinterException
907    *           DOCUMENT ME!
908    */
909   @Override
910   public int print(Graphics pg, PageFormat pf, int pi)
911           throws PrinterException
912   {
913     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
914
915     int pwidth = (int) pf.getImageableWidth();
916     int pheight = (int) pf.getImageableHeight();
917
918     if (av.getWrapAlignment())
919     {
920       return printWrappedAlignment(pwidth, pheight, pi, pg);
921     }
922     else
923     {
924       return printUnwrapped(pwidth, pheight, pi, pg, pg);
925     }
926   }
927
928   /**
929    * Draws the alignment image, including sequence ids, sequences, and
930    * annotation labels and annotations if shown, on either one or two Graphics
931    * contexts.
932    * 
933    * @param pageWidth
934    *          in pixels
935    * @param pageHeight
936    *          in pixels
937    * @param pageIndex
938    *          (0, 1, ...)
939    * @param idGraphics
940    *          the graphics context for sequence ids and annotation labels
941    * @param alignmentGraphics
942    *          the graphics context for sequences and annotations (may or may not
943    *          be the same context as idGraphics)
944    * @return
945    * @throws PrinterException
946    */
947   public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
948           Graphics idGraphics, Graphics alignmentGraphics)
949           throws PrinterException
950   {
951     final int idWidth = getVisibleIdWidth(false);
952
953     /*
954      * Get the horizontal offset to where we draw the sequences.
955      * This is idWidth if using a single Graphics context, else zero.
956      */
957     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
958             : idWidth;
959
960     FontMetrics fm = getFontMetrics(av.getFont());
961     final int charHeight = av.getCharHeight();
962     final int scaleHeight = charHeight + fm.getDescent();
963
964     idGraphics.setColor(Color.white);
965     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
966     idGraphics.setFont(av.getFont());
967
968     /*
969      * How many sequences and residues can we fit on a printable page?
970      */
971     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
972
973     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
974
975     final int alignmentWidth = av.getAlignment().getVisibleWidth();
976     int pagesWide = (alignmentWidth / totalRes) + 1;
977
978     final int startRes = (pageIndex % pagesWide) * totalRes;
979     final int endRes = Math.min(startRes + totalRes - 1,
980             alignmentWidth - 1);
981
982     final int startSeq = (pageIndex / pagesWide) * totalSeq;
983     final int alignmentHeight = av.getAlignment().getHeight();
984     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
985
986     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
987
988     if (av.isShowAnnotation())
989     {
990       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
991     }
992
993     pagesHigh /= pageHeight;
994
995     if (pageIndex >= (pagesWide * pagesHigh))
996     {
997       return Printable.NO_SUCH_PAGE;
998     }
999     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
1000
1001     /*
1002      * draw the Scale at horizontal offset, then reset to top left (0, 0)
1003      */
1004     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
1005     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
1006             pageWidth - idWidth, scaleHeight);
1007     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1008
1009     /*
1010      * Draw the sequence ids, offset for scale height,
1011      * then reset to top left (0, 0)
1012      */
1013     idGraphics.translate(0, scaleHeight);
1014     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1015     List<SequenceI> selection = av.getSelectionGroup() == null ? null
1016             : av.getSelectionGroup().getSequences(null);
1017     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1018             selection);
1019
1020     idGraphics.setFont(av.getFont());
1021     idGraphics.translate(0, -scaleHeight);
1022
1023     /*
1024      * draw the sequences, offset for scale height, and id width (if using a
1025      * single graphics context), then reset to (0, scale height)
1026      */
1027     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1028     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1029             startRes, endRes, startSeq, endSeq - 1);
1030     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1031
1032     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1033     {
1034       /*
1035        * draw annotation labels; drawComponent() translates by
1036        * getScrollOffset(), so compensate for that first;
1037        * then reset to (0, scale height)
1038        */
1039       int offset = getAlabels().getScrollOffset();
1040       idGraphics.translate(0, -offset);
1041       idGraphics.translate(0, alignmentDrawnHeight);
1042       getAlabels().drawComponent(idGraphics, idWidth);
1043       idGraphics.translate(0, -alignmentDrawnHeight);
1044
1045       /*
1046        * draw the annotations starting at 
1047        * (idOffset, alignmentHeight) from (0, scaleHeight)
1048        */
1049       alignmentGraphics.translate(alignmentGraphicsOffset,
1050               alignmentDrawnHeight);
1051       updateLayout();
1052       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1053               alignmentGraphics, -1, startRes, endRes + 1);
1054     }
1055
1056     return Printable.PAGE_EXISTS;
1057   }
1058
1059   /**
1060    * Prints one page of an alignment in wrapped mode. Returns
1061    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1062    * no page could be drawn (page number out of range).
1063    * 
1064    * @param pageWidth
1065    * @param pageHeight
1066    * @param pageNumber
1067    *          (0, 1, ...)
1068    * @param g
1069    * 
1070    * @return
1071    * 
1072    * @throws PrinterException
1073    */
1074   public int printWrappedAlignment(int pageWidth, int pageHeight,
1075           int pageNumber, Graphics g) throws PrinterException
1076   {
1077     getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1078             getHeight());
1079     int annotationHeight = 0;
1080     if (av.isShowAnnotation())
1081     {
1082       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1083     }
1084
1085     int hgap = av.getCharHeight();
1086     if (av.getScaleAboveWrapped())
1087     {
1088       hgap += av.getCharHeight();
1089     }
1090
1091     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1092             + annotationHeight;
1093
1094     int idWidth = getVisibleIdWidth(false);
1095
1096     int maxwidth = av.getAlignment().getVisibleWidth();
1097
1098     int resWidth = getSeqPanel().seqCanvas
1099             .getWrappedCanvasWidth(pageWidth - idWidth);
1100     av.getRanges().setViewportStartAndWidth(0, resWidth);
1101
1102     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1103
1104     g.setColor(Color.white);
1105     g.fillRect(0, 0, pageWidth, pageHeight);
1106     g.setFont(av.getFont());
1107     g.setColor(Color.black);
1108
1109     /*
1110      * method: print the whole wrapped alignment, but with a clip region that
1111      * is restricted to the requested page; this supports selective print of 
1112      * single pages or ranges, (at the cost of repeated processing in the 
1113      * 'normal' case, when all pages are printed)
1114      */
1115     g.translate(0, -pageNumber * pageHeight);
1116
1117     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1118
1119     /*
1120      * draw sequence ids and annotation labels (if shown)
1121      */
1122     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1123     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1124
1125     g.translate(idWidth, 0);
1126
1127     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1128             pageWidth - idWidth, totalHeight, 0);
1129
1130     if ((pageNumber * pageHeight) < totalHeight)
1131     {
1132       return Printable.PAGE_EXISTS;
1133     }
1134     else
1135     {
1136       return Printable.NO_SUCH_PAGE;
1137     }
1138   }
1139
1140   /**
1141    * get current sequence ID panel width, or nominal value if panel were to be
1142    * displayed using default settings
1143    * 
1144    * @return
1145    */
1146   public int getVisibleIdWidth()
1147   {
1148     return getVisibleIdWidth(true);
1149   }
1150
1151   /**
1152    * get current sequence ID panel width, or nominal value if panel were to be
1153    * displayed using default settings
1154    * 
1155    * @param onscreen
1156    *          indicate if the Id width for onscreen or offscreen display should
1157    *          be returned
1158    * @return
1159    */
1160   protected int getVisibleIdWidth(boolean onscreen)
1161   {
1162     // see if rendering offscreen - check preferences and calc width accordingly
1163     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1164     {
1165       return calculateIdWidth(-1).width;
1166     }
1167     Integer idwidth = onscreen ? null
1168             : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1169     if (idwidth != null)
1170     {
1171       return idwidth.intValue() + ID_WIDTH_PADDING;
1172     }
1173
1174     int w = getIdPanel().getWidth();
1175     return (w > 0 ? w : calculateIdWidth().width);
1176   }
1177
1178   void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer)
1179           throws ImageOutputException
1180   {
1181     makeAlignmentImage(type, file, renderer,
1182             BitmapImageSizing.nullBitmapImageSizing());
1183   }
1184
1185   /**
1186    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1187    * writes it to the specified file
1188    * 
1189    * @param type
1190    * @param file
1191    * @param textrenderer
1192    * @param bitmapscale
1193    */
1194   void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1195           BitmapImageSizing userBis) throws ImageOutputException
1196   {
1197     final int borderBottomOffset = 5;
1198
1199     AlignmentDimension aDimension = getAlignmentDimension();
1200     // todo use a lambda function in place of callback here?
1201     ImageWriterI writer = new ImageWriterI()
1202     {
1203       @Override
1204       public void exportImage(Graphics graphics) throws Exception
1205       {
1206         if (av.getWrapAlignment())
1207         {
1208           printWrappedAlignment(aDimension.getWidth(),
1209                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1210         }
1211         else
1212         {
1213           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1214                   graphics, graphics);
1215         }
1216       }
1217     };
1218
1219     String fileTitle = alignFrame.getTitle();
1220     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1221             fileTitle);
1222     int imageWidth = aDimension.getWidth();
1223     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1224     String of = MessageManager.getString("label.alignment");
1225     exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1226             userBis);
1227   }
1228
1229   /**
1230    * Calculates and returns a suitable width and height (in pixels) for an
1231    * exported image
1232    * 
1233    * @return
1234    */
1235   public AlignmentDimension getAlignmentDimension()
1236   {
1237     int maxwidth = av.getAlignment().getVisibleWidth();
1238
1239     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1240             + getScalePanel().getHeight();
1241     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1242
1243     if (av.getWrapAlignment())
1244     {
1245       height = getWrappedHeight();
1246       if (Jalview.isHeadlessMode())
1247       {
1248         // need to obtain default alignment width and then add in any
1249         // additional allowance for id margin
1250         // this duplicates the calculation in getWrappedHeight but adjusts for
1251         // offscreen idWith
1252         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1253                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1254                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1255       }
1256       else
1257       {
1258         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1259       }
1260
1261     }
1262     else if (av.isShowAnnotation())
1263     {
1264       height += getAnnotationPanel().adjustPanelHeight() + 3;
1265     }
1266     return new AlignmentDimension(width, height);
1267
1268   }
1269
1270   public void makePNGImageMap(File imgMapFile, String imageName)
1271           throws ImageOutputException
1272   {
1273     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1274     // ////////////////////////////////////////////
1275     int idWidth = getVisibleIdWidth(false);
1276     FontMetrics fm = getFontMetrics(av.getFont());
1277     int scaleHeight = av.getCharHeight() + fm.getDescent();
1278
1279     // Gen image map
1280     // ////////////////////////////////
1281     if (imgMapFile != null)
1282     {
1283       try
1284       {
1285         int sSize = av.getAlignment().getHeight();
1286         int alwidth = av.getAlignment().getWidth();
1287         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1288         out.println(HTMLOutput.getImageMapHTML());
1289         out.println("<img src=\"" + imageName
1290                 + "\" border=\"0\" usemap=\"#Map\" >"
1291                 + "<map name=\"Map\">");
1292
1293         for (int s = 0; s < sSize; s++)
1294         {
1295           int sy = s * av.getCharHeight() + scaleHeight;
1296
1297           SequenceI seq = av.getAlignment().getSequenceAt(s);
1298           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1299           for (int column = 0; column < alwidth; column++)
1300           {
1301             StringBuilder text = new StringBuilder(512);
1302             String triplet = null;
1303             if (av.getAlignment().isNucleotide())
1304             {
1305               triplet = ResidueProperties.nucleotideName
1306                       .get(seq.getCharAt(column) + "");
1307             }
1308             else
1309             {
1310               triplet = ResidueProperties.aa2Triplet
1311                       .get(seq.getCharAt(column) + "");
1312             }
1313
1314             if (triplet == null)
1315             {
1316               continue;
1317             }
1318
1319             int seqPos = seq.findPosition(column);
1320             int gSize = groups.length;
1321             for (int g = 0; g < gSize; g++)
1322             {
1323               if (text.length() < 1)
1324               {
1325                 text.append("<area shape=\"rect\" coords=\"")
1326                         .append((idWidth + column * av.getCharWidth()))
1327                         .append(",").append(sy).append(",")
1328                         .append((idWidth
1329                                 + (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,
1356                       column);
1357               for (SequenceFeature sf : features)
1358               {
1359                 if (sf.isContactFeature())
1360                 {
1361                   text.append("<br>").append(sf.getType()).append(" ")
1362                           .append(sf.getBegin()).append(":")
1363                           .append(sf.getEnd());
1364                 }
1365                 else
1366                 {
1367                   text.append("<br>");
1368                   text.append(sf.getType());
1369                   String description = sf.getDescription();
1370                   if (description != null
1371                           && !sf.getType().equals(description))
1372                   {
1373                     description = description.replace("\"", "&quot;");
1374                     text.append(" ").append(description);
1375                   }
1376                 }
1377                 String status = sf.getStatus();
1378                 if (status != null && !"".equals(status))
1379                 {
1380                   text.append(" (").append(status).append(")");
1381                 }
1382               }
1383               if (text.length() > 1)
1384               {
1385                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1386                 out.println(text.toString());
1387               }
1388             }
1389           }
1390         }
1391         out.println("</map></body></html>");
1392         out.close();
1393
1394       } catch (Exception ex)
1395       {
1396         throw new ImageOutputException(
1397                 "couldn't write ImageMap due to unexpected error", ex);
1398       }
1399     } // /////////END OF IMAGE MAP
1400
1401   }
1402
1403   /**
1404    * Answers the height of the entire alignment in pixels, assuming it is in
1405    * wrapped mode
1406    * 
1407    * @return
1408    */
1409   int getWrappedHeight()
1410   {
1411     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1412
1413     if (System.getProperty("java.awt.headless") != null
1414             && System.getProperty("java.awt.headless").equals("true"))
1415     {
1416       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1417               - vscroll.getPreferredSize().width
1418               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1419     }
1420
1421     int chunkWidth = getSeqPanel().seqCanvas
1422             .getWrappedCanvasWidth(seqPanelWidth);
1423
1424     int hgap = av.getCharHeight();
1425     if (av.getScaleAboveWrapped())
1426     {
1427       hgap += av.getCharHeight();
1428     }
1429
1430     int annotationHeight = 0;
1431     if (av.isShowAnnotation())
1432     {
1433       hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1434       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1435     }
1436
1437     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1438             + annotationHeight;
1439
1440     int maxwidth = av.getAlignment().getWidth();
1441     if (av.hasHiddenColumns())
1442     {
1443       maxwidth = av.getAlignment().getHiddenColumns()
1444               .absoluteToVisibleColumn(maxwidth) - 1;
1445     }
1446
1447     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1448
1449     return height;
1450   }
1451
1452   /**
1453    * close the panel - deregisters all listeners and nulls any references to
1454    * alignment data.
1455    */
1456   public void closePanel()
1457   {
1458     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1459     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1460     PaintRefresher.RemoveComponent(this);
1461
1462     closeChildFrames();
1463
1464     /*
1465      * try to ensure references are nulled
1466      */
1467     if (annotationPanel != null)
1468     {
1469       annotationPanel.dispose();
1470       annotationPanel = null;
1471     }
1472
1473     if (av != null)
1474     {
1475       av.removePropertyChangeListener(propertyChangeListener);
1476       propertyChangeListener = null;
1477       StructureSelectionManager ssm = av.getStructureSelectionManager();
1478       ssm.removeStructureViewerListener(getSeqPanel(), null);
1479       ssm.removeSelectionListener(getSeqPanel());
1480       ssm.removeCommandListener(av);
1481       ssm.removeStructureViewerListener(getSeqPanel(), null);
1482       ssm.removeSelectionListener(getSeqPanel());
1483       av.dispose();
1484       av = null;
1485     }
1486     else
1487     {
1488       if (Console.isDebugEnabled())
1489       {
1490         Console.warn("Closing alignment panel which is already closed.");
1491       }
1492     }
1493   }
1494
1495   /**
1496    * Close any open dialogs that would be orphaned when this one is closed
1497    */
1498   protected void closeChildFrames()
1499   {
1500     if (overviewPanel != null)
1501     {
1502       overviewPanel.dispose();
1503       overviewPanel = null;
1504     }
1505     if (calculationDialog != null)
1506     {
1507       calculationDialog.closeFrame();
1508       calculationDialog = null;
1509     }
1510   }
1511
1512   /**
1513    * hides or shows dynamic annotation rows based on groups and av state flags
1514    */
1515   public void updateAnnotation()
1516   {
1517     updateAnnotation(false, false);
1518   }
1519
1520   public void updateAnnotation(boolean applyGlobalSettings)
1521   {
1522     updateAnnotation(applyGlobalSettings, false);
1523   }
1524
1525   public void updateAnnotation(boolean applyGlobalSettings,
1526           boolean preserveNewGroupSettings)
1527   {
1528     av.updateGroupAnnotationSettings(applyGlobalSettings,
1529             preserveNewGroupSettings);
1530     adjustAnnotationHeight();
1531   }
1532
1533   @Override
1534   public AlignmentI getAlignment()
1535   {
1536     return av == null ? null : av.getAlignment();
1537   }
1538
1539   @Override
1540   public String getViewName()
1541   {
1542     return av.getViewName();
1543   }
1544
1545   /**
1546    * Make/Unmake this alignment panel the current input focus
1547    * 
1548    * @param b
1549    */
1550   public void setSelected(boolean b)
1551   {
1552     try
1553     {
1554       if (alignFrame.getSplitViewContainer() != null)
1555       {
1556         /*
1557          * bring enclosing SplitFrame to front first if there is one
1558          */
1559         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1560       }
1561       alignFrame.setSelected(b);
1562     } catch (Exception ex)
1563     {
1564     }
1565     if (b)
1566     {
1567       setAlignFrameView();
1568     }
1569   }
1570
1571   public void setAlignFrameView()
1572   {
1573     alignFrame.setDisplayedView(this);
1574   }
1575
1576   @Override
1577   public StructureSelectionManager getStructureSelectionManager()
1578   {
1579     return av.getStructureSelectionManager();
1580   }
1581
1582   @Override
1583   public void raiseOOMWarning(String string, OutOfMemoryError error)
1584   {
1585     new OOMWarning(string, error, this);
1586   }
1587
1588   @Override
1589   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1590   {
1591
1592     return new FeatureRenderer(this);
1593   }
1594
1595   @Override
1596   public jalview.api.FeatureRenderer getFeatureRenderer()
1597   {
1598     return seqPanel.seqCanvas.getFeatureRenderer();
1599   }
1600
1601   public void updateFeatureRenderer(
1602           jalview.renderer.seqfeatures.FeatureRenderer fr)
1603   {
1604     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1605   }
1606
1607   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1608   {
1609     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1610     {
1611       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1612     }
1613   }
1614
1615   public ScalePanel getScalePanel()
1616   {
1617     return scalePanel;
1618   }
1619
1620   public void setScalePanel(ScalePanel scalePanel)
1621   {
1622     this.scalePanel = scalePanel;
1623   }
1624
1625   public SeqPanel getSeqPanel()
1626   {
1627     return seqPanel;
1628   }
1629
1630   public void setSeqPanel(SeqPanel seqPanel)
1631   {
1632     this.seqPanel = seqPanel;
1633   }
1634
1635   public AnnotationPanel getAnnotationPanel()
1636   {
1637     return annotationPanel;
1638   }
1639
1640   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1641   {
1642     this.annotationPanel = annotationPanel;
1643   }
1644
1645   public AnnotationLabels getAlabels()
1646   {
1647     return alabels;
1648   }
1649
1650   public void setAlabels(AnnotationLabels alabels)
1651   {
1652     this.alabels = alabels;
1653   }
1654
1655   public IdPanel getIdPanel()
1656   {
1657     return idPanel;
1658   }
1659
1660   public void setIdPanel(IdPanel idPanel)
1661   {
1662     this.idPanel = idPanel;
1663   }
1664
1665   /**
1666    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1667    * The aim is to keep the two alignments 'lined up' on their centre columns.
1668    * 
1669    * @param sr
1670    *          holds mapped region(s) of this alignment that we are scrolling
1671    *          'to'; may be modified for sequence offset by this method
1672    * @param verticalOffset
1673    *          the number of visible sequences to show above the mapped region
1674    */
1675   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1676   {
1677     scrollToPosition(sr, verticalOffset, true);
1678   }
1679
1680   /**
1681    * Set a flag to say do not scroll any (cDNA/protein) complement.
1682    * 
1683    * @param b
1684    */
1685   protected void setToScrollComplementPanel(boolean b)
1686   {
1687     this.scrollComplementaryPanel = b;
1688   }
1689
1690   /**
1691    * Get whether to scroll complement panel
1692    * 
1693    * @return true if cDNA/protein complement panels should be scrolled
1694    */
1695   protected boolean isSetToScrollComplementPanel()
1696   {
1697     return this.scrollComplementaryPanel;
1698   }
1699
1700   /**
1701    * Redraw sensibly.
1702    * 
1703    * @adjustHeight if true, try to recalculate panel height for visible
1704    *               annotations
1705    */
1706   protected void refresh(boolean adjustHeight)
1707   {
1708     validateAnnotationDimensions(adjustHeight);
1709     addNotify();
1710     if (adjustHeight)
1711     {
1712       // sort, repaint, update overview
1713       paintAlignment(true, false);
1714     }
1715     else
1716     {
1717       // lightweight repaint
1718       repaint();
1719     }
1720   }
1721
1722   @Override
1723   /**
1724    * Property change event fired when a change is made to the viewport ranges
1725    * object associated with this alignment panel's viewport
1726    */
1727   public void propertyChange(PropertyChangeEvent evt)
1728   {
1729     // update this panel's scroll values based on the new viewport ranges values
1730     ViewportRanges ranges = av.getRanges();
1731     int x = ranges.getStartRes();
1732     int y = ranges.getStartSeq();
1733     setScrollValues(x, y);
1734
1735     // now update any complementary alignment (its viewport ranges object
1736     // is different so does not get automatically updated)
1737     if (isSetToScrollComplementPanel())
1738     {
1739       setToScrollComplementPanel(false);
1740       av.scrollComplementaryAlignment();
1741       setToScrollComplementPanel(true);
1742     }
1743   }
1744
1745   /**
1746    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1747    * reference should be nulled when the dialog is closed.
1748    * 
1749    * @param calculationChooser
1750    */
1751   public void setCalculationDialog(CalculationChooser calculationChooser)
1752   {
1753     calculationDialog = calculationChooser;
1754   }
1755
1756   /**
1757    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1758    * if none is open)
1759    */
1760   public CalculationChooser getCalculationDialog()
1761   {
1762     return calculationDialog;
1763   }
1764
1765   /**
1766    * Constructs and sets the title for the Overview window (if there is one),
1767    * including the align frame's title, and view name (if applicable). Returns
1768    * the title, or null if this panel has no Overview window open.
1769    * 
1770    * @param alignFrame
1771    * @return
1772    */
1773   public String setOverviewTitle(AlignFrame alignFrame)
1774   {
1775     if (this.overviewPanel == null)
1776     {
1777       return null;
1778     }
1779     String overviewTitle = MessageManager
1780             .formatMessage("label.overview_params", new Object[]
1781             { alignFrame.getTitle() });
1782     String viewName = getViewName();
1783     if (viewName != null)
1784     {
1785       overviewTitle += (" " + viewName);
1786     }
1787     overviewPanel.setTitle(overviewTitle);
1788     return overviewTitle;
1789   }
1790
1791   /**
1792    * If this alignment panel has an Overview panel open, closes it
1793    */
1794   public void closeOverviewPanel()
1795   {
1796     if (overviewPanel != null)
1797     {
1798       overviewPanel.close();
1799       overviewPanel = null;
1800     }
1801   }
1802
1803 }