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