JAL-4090 JAL-4243 bio.tools json file release notes
[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) throws ImageOutputException
1179   {
1180     makeAlignmentImage(type, file, renderer,
1181             BitmapImageSizing.nullBitmapImageSizing());
1182   }
1183
1184   /**
1185    * Builds an image of the alignment of the specified type (EPS/PNG/SVG) and
1186    * writes it to the specified file
1187    * 
1188    * @param type
1189    * @param file
1190    * @param textrenderer
1191    * @param bitmapscale
1192    */
1193   void makeAlignmentImage(ImageMaker.TYPE type, File file, String renderer,
1194           BitmapImageSizing userBis) throws ImageOutputException
1195   {
1196     final int borderBottomOffset = 5;
1197
1198     AlignmentDimension aDimension = getAlignmentDimension();
1199     // todo use a lambda function in place of callback here?
1200     ImageWriterI writer = new ImageWriterI()
1201     {
1202       @Override
1203       public void exportImage(Graphics graphics) throws Exception
1204       {
1205         if (av.getWrapAlignment())
1206         {
1207           printWrappedAlignment(aDimension.getWidth(),
1208                   aDimension.getHeight() + borderBottomOffset, 0, graphics);
1209         }
1210         else
1211         {
1212           printUnwrapped(aDimension.getWidth(), aDimension.getHeight(), 0,
1213                   graphics, graphics);
1214         }
1215       }
1216     };
1217
1218     String fileTitle = alignFrame.getTitle();
1219     ImageExporter exporter = new ImageExporter(writer, alignFrame, type,
1220             fileTitle);
1221     int imageWidth = aDimension.getWidth();
1222     int imageHeight = aDimension.getHeight() + borderBottomOffset;
1223     String of = MessageManager.getString("label.alignment");
1224     exporter.doExport(file, this, imageWidth, imageHeight, of, renderer,
1225             userBis);
1226   }
1227
1228   /**
1229    * Calculates and returns a suitable width and height (in pixels) for an
1230    * exported image
1231    * 
1232    * @return
1233    */
1234   public AlignmentDimension getAlignmentDimension()
1235   {
1236     int maxwidth = av.getAlignment().getVisibleWidth();
1237
1238     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1239             + getScalePanel().getHeight();
1240     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1241
1242     if (av.getWrapAlignment())
1243     {
1244       height = getWrappedHeight();
1245       if (Jalview.isHeadlessMode())
1246       {
1247         // need to obtain default alignment width and then add in any
1248         // additional allowance for id margin
1249         // this duplicates the calculation in getWrappedHeight but adjusts for
1250         // offscreen idWith
1251         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1252                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1253                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1254       }
1255       else
1256       {
1257         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1258       }
1259
1260     }
1261     else if (av.isShowAnnotation())
1262     {
1263       height += getAnnotationPanel().adjustPanelHeight() + 3;
1264     }
1265     return new AlignmentDimension(width, height);
1266
1267   }
1268
1269   public void makePNGImageMap(File imgMapFile, String imageName) throws ImageOutputException
1270   {
1271     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1272     // ////////////////////////////////////////////
1273     int idWidth = getVisibleIdWidth(false);
1274     FontMetrics fm = getFontMetrics(av.getFont());
1275     int scaleHeight = av.getCharHeight() + fm.getDescent();
1276
1277     // Gen image map
1278     // ////////////////////////////////
1279     if (imgMapFile != null)
1280     {
1281       try
1282       {
1283         int sSize = av.getAlignment().getHeight();
1284         int alwidth = av.getAlignment().getWidth();
1285         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1286         out.println(HTMLOutput.getImageMapHTML());
1287         out.println("<img src=\"" + imageName
1288                 + "\" border=\"0\" usemap=\"#Map\" >"
1289                 + "<map name=\"Map\">");
1290
1291         for (int s = 0; s < sSize; s++)
1292         {
1293           int sy = s * av.getCharHeight() + scaleHeight;
1294
1295           SequenceI seq = av.getAlignment().getSequenceAt(s);
1296           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1297           for (int column = 0; column < alwidth; column++)
1298           {
1299             StringBuilder text = new StringBuilder(512);
1300             String triplet = null;
1301             if (av.getAlignment().isNucleotide())
1302             {
1303               triplet = ResidueProperties.nucleotideName
1304                       .get(seq.getCharAt(column) + "");
1305             }
1306             else
1307             {
1308               triplet = ResidueProperties.aa2Triplet
1309                       .get(seq.getCharAt(column) + "");
1310             }
1311
1312             if (triplet == null)
1313             {
1314               continue;
1315             }
1316
1317             int seqPos = seq.findPosition(column);
1318             int gSize = groups.length;
1319             for (int g = 0; g < gSize; g++)
1320             {
1321               if (text.length() < 1)
1322               {
1323                 text.append("<area shape=\"rect\" coords=\"")
1324                         .append((idWidth + column * av.getCharWidth()))
1325                         .append(",").append(sy).append(",")
1326                         .append((idWidth
1327                                 + (column + 1) * av.getCharWidth()))
1328                         .append(",").append((av.getCharHeight() + sy))
1329                         .append("\"").append(" onMouseOver=\"toolTip('")
1330                         .append(seqPos).append(" ").append(triplet);
1331               }
1332
1333               if (groups[g].getStartRes() < column
1334                       && groups[g].getEndRes() > column)
1335               {
1336                 text.append("<br><em>").append(groups[g].getName())
1337                         .append("</em>");
1338               }
1339             }
1340
1341             if (text.length() < 1)
1342             {
1343               text.append("<area shape=\"rect\" coords=\"")
1344                       .append((idWidth + column * av.getCharWidth()))
1345                       .append(",").append(sy).append(",")
1346                       .append((idWidth + (column + 1) * av.getCharWidth()))
1347                       .append(",").append((av.getCharHeight() + sy))
1348                       .append("\"").append(" onMouseOver=\"toolTip('")
1349                       .append(seqPos).append(" ").append(triplet);
1350             }
1351             if (!Comparison.isGap(seq.getCharAt(column)))
1352             {
1353               List<SequenceFeature> features = seq.findFeatures(column,
1354                       column);
1355               for (SequenceFeature sf : features)
1356               {
1357                 if (sf.isContactFeature())
1358                 {
1359                   text.append("<br>").append(sf.getType()).append(" ")
1360                           .append(sf.getBegin()).append(":")
1361                           .append(sf.getEnd());
1362                 }
1363                 else
1364                 {
1365                   text.append("<br>");
1366                   text.append(sf.getType());
1367                   String description = sf.getDescription();
1368                   if (description != null
1369                           && !sf.getType().equals(description))
1370                   {
1371                     description = description.replace("\"", "&quot;");
1372                     text.append(" ").append(description);
1373                   }
1374                 }
1375                 String status = sf.getStatus();
1376                 if (status != null && !"".equals(status))
1377                 {
1378                   text.append(" (").append(status).append(")");
1379                 }
1380               }
1381               if (text.length() > 1)
1382               {
1383                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1384                 out.println(text.toString());
1385               }
1386             }
1387           }
1388         }
1389         out.println("</map></body></html>");
1390         out.close();
1391
1392       } catch (Exception ex)
1393       {
1394         throw new ImageOutputException("couldn't write ImageMap due to unexpected error",ex);
1395       }
1396     } // /////////END OF IMAGE MAP
1397
1398   }
1399
1400   /**
1401    * Answers the height of the entire alignment in pixels, assuming it is in
1402    * wrapped mode
1403    * 
1404    * @return
1405    */
1406   int getWrappedHeight()
1407   {
1408     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1409
1410     if (System.getProperty("java.awt.headless") != null
1411             && System.getProperty("java.awt.headless").equals("true"))
1412     {
1413       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1414               - vscroll.getPreferredSize().width
1415               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1416     }
1417
1418     int chunkWidth = getSeqPanel().seqCanvas
1419             .getWrappedCanvasWidth(seqPanelWidth);
1420
1421     int hgap = av.getCharHeight();
1422     if (av.getScaleAboveWrapped())
1423     {
1424       hgap += av.getCharHeight();
1425     }
1426
1427     int annotationHeight = 0;
1428     if (av.isShowAnnotation())
1429     {
1430       hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1431       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1432     }
1433
1434     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1435             + annotationHeight;
1436
1437     int maxwidth = av.getAlignment().getWidth();
1438     if (av.hasHiddenColumns())
1439     {
1440       maxwidth = av.getAlignment().getHiddenColumns()
1441               .absoluteToVisibleColumn(maxwidth) - 1;
1442     }
1443
1444     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1445
1446     return height;
1447   }
1448
1449   /**
1450    * close the panel - deregisters all listeners and nulls any references to
1451    * alignment data.
1452    */
1453   public void closePanel()
1454   {
1455     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1456     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1457     PaintRefresher.RemoveComponent(this);
1458
1459     closeChildFrames();
1460
1461     /*
1462      * try to ensure references are nulled
1463      */
1464     if (annotationPanel != null)
1465     {
1466       annotationPanel.dispose();
1467       annotationPanel = null;
1468     }
1469
1470     if (av != null)
1471     {
1472       av.removePropertyChangeListener(propertyChangeListener);
1473       propertyChangeListener = null;
1474       StructureSelectionManager ssm = av.getStructureSelectionManager();
1475       ssm.removeStructureViewerListener(getSeqPanel(), null);
1476       ssm.removeSelectionListener(getSeqPanel());
1477       ssm.removeCommandListener(av);
1478       ssm.removeStructureViewerListener(getSeqPanel(), null);
1479       ssm.removeSelectionListener(getSeqPanel());
1480       av.dispose();
1481       av = null;
1482     }
1483     else
1484     {
1485       if (Console.isDebugEnabled())
1486       {
1487         Console.warn("Closing alignment panel which is already closed.");
1488       }
1489     }
1490   }
1491
1492   /**
1493    * Close any open dialogs that would be orphaned when this one is closed
1494    */
1495   protected void closeChildFrames()
1496   {
1497     if (overviewPanel != null)
1498     {
1499       overviewPanel.dispose();
1500       overviewPanel = null;
1501     }
1502     if (calculationDialog != null)
1503     {
1504       calculationDialog.closeFrame();
1505       calculationDialog = null;
1506     }
1507   }
1508
1509   /**
1510    * hides or shows dynamic annotation rows based on groups and av state flags
1511    */
1512   public void updateAnnotation()
1513   {
1514     updateAnnotation(false, false);
1515   }
1516
1517   public void updateAnnotation(boolean applyGlobalSettings)
1518   {
1519     updateAnnotation(applyGlobalSettings, false);
1520   }
1521
1522   public void updateAnnotation(boolean applyGlobalSettings,
1523           boolean preserveNewGroupSettings)
1524   {
1525     av.updateGroupAnnotationSettings(applyGlobalSettings,
1526             preserveNewGroupSettings);
1527     adjustAnnotationHeight();
1528   }
1529
1530   @Override
1531   public AlignmentI getAlignment()
1532   {
1533     return av == null ? null : av.getAlignment();
1534   }
1535
1536   @Override
1537   public String getViewName()
1538   {
1539     return av.getViewName();
1540   }
1541
1542   /**
1543    * Make/Unmake this alignment panel the current input focus
1544    * 
1545    * @param b
1546    */
1547   public void setSelected(boolean b)
1548   {
1549     try
1550     {
1551       if (alignFrame.getSplitViewContainer() != null)
1552       {
1553         /*
1554          * bring enclosing SplitFrame to front first if there is one
1555          */
1556         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1557       }
1558       alignFrame.setSelected(b);
1559     } catch (Exception ex)
1560     {
1561     }
1562     if (b)
1563     {
1564       setAlignFrameView();
1565     }
1566   }
1567
1568   public void setAlignFrameView()
1569   {
1570     alignFrame.setDisplayedView(this);
1571   }
1572
1573   @Override
1574   public StructureSelectionManager getStructureSelectionManager()
1575   {
1576     return av.getStructureSelectionManager();
1577   }
1578
1579   @Override
1580   public void raiseOOMWarning(String string, OutOfMemoryError error)
1581   {
1582     new OOMWarning(string, error, this);
1583   }
1584
1585   @Override
1586   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1587   {
1588
1589     return new FeatureRenderer(this);
1590   }
1591
1592   @Override
1593   public jalview.api.FeatureRenderer getFeatureRenderer()
1594   {
1595     return seqPanel.seqCanvas.getFeatureRenderer();
1596   }
1597
1598   public void updateFeatureRenderer(
1599           jalview.renderer.seqfeatures.FeatureRenderer fr)
1600   {
1601     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1602   }
1603
1604   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1605   {
1606     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1607     {
1608       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1609     }
1610   }
1611
1612   public ScalePanel getScalePanel()
1613   {
1614     return scalePanel;
1615   }
1616
1617   public void setScalePanel(ScalePanel scalePanel)
1618   {
1619     this.scalePanel = scalePanel;
1620   }
1621
1622   public SeqPanel getSeqPanel()
1623   {
1624     return seqPanel;
1625   }
1626
1627   public void setSeqPanel(SeqPanel seqPanel)
1628   {
1629     this.seqPanel = seqPanel;
1630   }
1631
1632   public AnnotationPanel getAnnotationPanel()
1633   {
1634     return annotationPanel;
1635   }
1636
1637   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1638   {
1639     this.annotationPanel = annotationPanel;
1640   }
1641
1642   public AnnotationLabels getAlabels()
1643   {
1644     return alabels;
1645   }
1646
1647   public void setAlabels(AnnotationLabels alabels)
1648   {
1649     this.alabels = alabels;
1650   }
1651
1652   public IdPanel getIdPanel()
1653   {
1654     return idPanel;
1655   }
1656
1657   public void setIdPanel(IdPanel idPanel)
1658   {
1659     this.idPanel = idPanel;
1660   }
1661
1662   /**
1663    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1664    * The aim is to keep the two alignments 'lined up' on their centre columns.
1665    * 
1666    * @param sr
1667    *          holds mapped region(s) of this alignment that we are scrolling
1668    *          'to'; may be modified for sequence offset by this method
1669    * @param verticalOffset
1670    *          the number of visible sequences to show above the mapped region
1671    */
1672   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1673   {
1674     scrollToPosition(sr, verticalOffset, true);
1675   }
1676
1677   /**
1678    * Set a flag to say do not scroll any (cDNA/protein) complement.
1679    * 
1680    * @param b
1681    */
1682   protected void setToScrollComplementPanel(boolean b)
1683   {
1684     this.scrollComplementaryPanel = b;
1685   }
1686
1687   /**
1688    * Get whether to scroll complement panel
1689    * 
1690    * @return true if cDNA/protein complement panels should be scrolled
1691    */
1692   protected boolean isSetToScrollComplementPanel()
1693   {
1694     return this.scrollComplementaryPanel;
1695   }
1696
1697   /**
1698    * Redraw sensibly.
1699    * 
1700    * @adjustHeight if true, try to recalculate panel height for visible
1701    *               annotations
1702    */
1703   protected void refresh(boolean adjustHeight)
1704   {
1705     validateAnnotationDimensions(adjustHeight);
1706     addNotify();
1707     if (adjustHeight)
1708     {
1709       // sort, repaint, update overview
1710       paintAlignment(true, false);
1711     }
1712     else
1713     {
1714       // lightweight repaint
1715       repaint();
1716     }
1717   }
1718
1719   @Override
1720   /**
1721    * Property change event fired when a change is made to the viewport ranges
1722    * object associated with this alignment panel's viewport
1723    */
1724   public void propertyChange(PropertyChangeEvent evt)
1725   {
1726     // update this panel's scroll values based on the new viewport ranges values
1727     ViewportRanges ranges = av.getRanges();
1728     int x = ranges.getStartRes();
1729     int y = ranges.getStartSeq();
1730     setScrollValues(x, y);
1731
1732     // now update any complementary alignment (its viewport ranges object
1733     // is different so does not get automatically updated)
1734     if (isSetToScrollComplementPanel())
1735     {
1736       setToScrollComplementPanel(false);
1737       av.scrollComplementaryAlignment();
1738       setToScrollComplementPanel(true);
1739     }
1740   }
1741
1742   /**
1743    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1744    * reference should be nulled when the dialog is closed.
1745    * 
1746    * @param calculationChooser
1747    */
1748   public void setCalculationDialog(CalculationChooser calculationChooser)
1749   {
1750     calculationDialog = calculationChooser;
1751   }
1752
1753   /**
1754    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1755    * if none is open)
1756    */
1757   public CalculationChooser getCalculationDialog()
1758   {
1759     return calculationDialog;
1760   }
1761
1762   /**
1763    * Constructs and sets the title for the Overview window (if there is one),
1764    * including the align frame's title, and view name (if applicable). Returns
1765    * the title, or null if this panel has no Overview window open.
1766    * 
1767    * @param alignFrame
1768    * @return
1769    */
1770   public String setOverviewTitle(AlignFrame alignFrame)
1771   {
1772     if (this.overviewPanel == null)
1773     {
1774       return null;
1775     }
1776     String overviewTitle = MessageManager
1777             .formatMessage("label.overview_params", new Object[]
1778             { alignFrame.getTitle() });
1779     String viewName = getViewName();
1780     if (viewName != null)
1781     {
1782       overviewTitle += (" " + viewName);
1783     }
1784     overviewPanel.setTitle(overviewTitle);
1785     return overviewTitle;
1786   }
1787
1788   /**
1789    * If this alignment panel has an Overview panel open, closes it
1790    */
1791   public void closeOverviewPanel()
1792   {
1793     if (overviewPanel != null)
1794     {
1795       overviewPanel.close();
1796       overviewPanel = null;
1797     }
1798   }
1799
1800 }