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