502ab9dc14ff63a1ae9a6a0b949e351f58462dfd
[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   public AlignViewport av;
77
78   OverviewPanel overviewPanel;
79
80   private SeqPanel seqPanel;
81
82   private IdPanel idPanel;
83
84   private boolean headless;
85
86   IdwidthAdjuster idwidthAdjuster;
87
88   /** DOCUMENT ME!! */
89   public AlignFrame alignFrame;
90
91   private ScalePanel scalePanel;
92
93   private AnnotationPanel annotationPanel;
94
95   private AnnotationLabels alabels;
96
97   private int hextent = 0;
98
99   private int vextent = 0;
100
101   /*
102    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
103    * false, suppresses invoking the same method recursively.
104    */
105   private boolean scrollComplementaryPanel = true;
106
107   private PropertyChangeListener propertyChangeListener;
108
109   private CalculationChooser calculationDialog;
110
111   /**
112    * Creates a new AlignmentPanel object.
113    * 
114    * @param af
115    * @param av
116    */
117   public AlignmentPanel(AlignFrame af, final AlignViewport av)
118   {
119     alignFrame = af;
120     this.av = av;
121     setSeqPanel(new SeqPanel(av, this));
122     setIdPanel(new IdPanel(av, this));
123
124     setScalePanel(new ScalePanel(av, this));
125
126     idPanelHolder.add(getIdPanel(), BorderLayout.CENTER);
127     idwidthAdjuster = new IdwidthAdjuster(this);
128     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
129
130     setAnnotationPanel(new AnnotationPanel(this));
131     setAlabels(new AnnotationLabels(this));
132
133     annotationScroller.setViewportView(getAnnotationPanel());
134     annotationSpaceFillerHolder.add(getAlabels(), BorderLayout.CENTER);
135
136     scalePanelHolder.add(getScalePanel(), BorderLayout.CENTER);
137     seqPanelHolder.add(getSeqPanel(), BorderLayout.CENTER);
138
139     setScrollValues(0, 0);
140
141     hscroll.addAdjustmentListener(this);
142     vscroll.addAdjustmentListener(this);
143
144     addComponentListener(new ComponentAdapter()
145     {
146       @Override
147       public void componentResized(ComponentEvent evt)
148       {
149         // reset the viewport ranges when the alignment panel is resized
150         // in particular, this initialises the end residue value when Jalview
151         // is initialised
152         ViewportRanges ranges = av.getRanges();
153         if (av.getWrapAlignment())
154         {
155           int widthInRes = getSeqPanel().seqCanvas.getWrappedCanvasWidth(
156                   getSeqPanel().seqCanvas.getWidth());
157           ranges.setViewportWidth(widthInRes);
158         }
159         else
160         {
161           int widthInRes = getSeqPanel().seqCanvas.getWidth()
162                   / av.getCharWidth();
163           int heightInSeq = getSeqPanel().seqCanvas.getHeight()
164                   / av.getCharHeight();
165
166           ranges.setViewportWidth(widthInRes);
167           ranges.setViewportHeight(heightInSeq);
168         }
169       }
170
171     });
172
173     final AlignmentPanel ap = this;
174     propertyChangeListener = new PropertyChangeListener()
175     {
176       @Override
177       public void propertyChange(PropertyChangeEvent evt)
178       {
179         if (evt.getPropertyName().equals("alignment"))
180         {
181           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
182           alignmentChanged();
183         }
184       }
185     };
186     av.addPropertyChangeListener(propertyChangeListener);
187
188     av.getRanges().addPropertyChangeListener(this);
189     fontChanged();
190     adjustAnnotationHeight();
191     updateLayout();
192   }
193
194   @Override
195   public AlignViewportI getAlignViewport()
196   {
197     return av;
198   }
199
200   public void alignmentChanged()
201   {
202     av.alignmentChanged(this);
203
204     if (getCalculationDialog() != null)
205     {
206       getCalculationDialog().validateCalcTypes();
207     }
208
209     alignFrame.updateEditMenuBar();
210
211     // no idea if we need to update structure
212     paintAlignment(true, true);
213
214   }
215
216   /**
217    * DOCUMENT ME!
218    */
219   public void fontChanged()
220   {
221     // set idCanvas bufferedImage to null
222     // to prevent drawing old image
223     FontMetrics fm = getFontMetrics(av.getFont());
224
225     scalePanelHolder.setPreferredSize(
226             new Dimension(10, av.getCharHeight() + fm.getDescent()));
227     idSpaceFillerPanel1.setPreferredSize(
228             new Dimension(10, av.getCharHeight() + fm.getDescent()));
229     idwidthAdjuster.invalidate();
230     scalePanelHolder.invalidate();
231     getIdPanel().getIdCanvas().gg = null;
232     getSeqPanel().seqCanvas.img = null;
233     getAnnotationPanel().adjustPanelHeight();
234
235     Dimension d = calculateIdWidth();
236
237     d.setSize(d.width + 4, d.height);
238     getIdPanel().getIdCanvas().setPreferredSize(d);
239     hscrollFillerPanel.setPreferredSize(d);
240
241     repaint();
242   }
243
244   /**
245    * Calculate the width of the alignment labels based on the displayed names
246    * and any bounds on label width set in preferences.
247    * 
248    * @return Dimension giving the maximum width of the alignment label panel
249    *         that should be used.
250    */
251   public Dimension calculateIdWidth()
252   {
253     // calculate sensible default width when no preference is available
254     Dimension r = null;
255     if (av.getIdWidth() < 0)
256     {
257       int afwidth = (alignFrame != null ? alignFrame.getWidth() : 300);
258       int maxwidth = Math.max(20, Math.min(afwidth - 200, 2 * afwidth / 3));
259       r = calculateIdWidth(maxwidth);
260       av.setIdWidth(r.width);
261     }
262     else
263     {
264       r = new Dimension();
265       r.width = av.getIdWidth();
266       r.height = 0;
267     }
268     return r;
269   }
270
271   /**
272    * Calculate the width of the alignment labels based on the displayed names
273    * and any bounds on label width set in preferences.
274    * 
275    * @param maxwidth
276    *          -1 or maximum width allowed for IdWidth
277    * @return Dimension giving the maximum width of the alignment label panel
278    *         that should be used.
279    */
280   public Dimension calculateIdWidth(int maxwidth)
281   {
282     Container c = new Container();
283
284     FontMetrics fm = c.getFontMetrics(
285             new Font(av.font.getName(), Font.ITALIC, av.font.getSize()));
286
287     AlignmentI al = av.getAlignment();
288     int i = 0;
289     int idWidth = 0;
290     String id;
291
292     while ((i < al.getHeight()) && (al.getSequenceAt(i) != null))
293     {
294       SequenceI s = al.getSequenceAt(i);
295
296       id = s.getDisplayId(av.getShowJVSuffix());
297
298       if (fm.stringWidth(id) > idWidth)
299       {
300         idWidth = fm.stringWidth(id);
301       }
302
303       i++;
304     }
305
306     // Also check annotation label widths
307     i = 0;
308
309     if (al.getAlignmentAnnotation() != null)
310     {
311       fm = c.getFontMetrics(getAlabels().getFont());
312
313       while (i < al.getAlignmentAnnotation().length)
314       {
315         String label = al.getAlignmentAnnotation()[i].label;
316
317         if (fm.stringWidth(label) > idWidth)
318         {
319           idWidth = fm.stringWidth(label);
320         }
321
322         i++;
323       }
324     }
325
326     return new Dimension(
327             maxwidth < 0 ? idWidth : Math.min(maxwidth, idWidth), 12);
328   }
329
330   /**
331    * Highlight the given results on the alignment
332    * 
333    */
334   public void highlightSearchResults(SearchResultsI results)
335   {
336     boolean scrolled = scrollToPosition(results, 0, false);
337
338     boolean noFastPaint = scrolled && av.getWrapAlignment();
339
340     getSeqPanel().seqCanvas.highlightSearchResults(results, noFastPaint);
341   }
342
343   /**
344    * Scroll the view to show the position of the highlighted region in results
345    * (if any)
346    * 
347    * @param searchResults
348    * @return
349    */
350   public boolean scrollToPosition(SearchResultsI searchResults)
351   {
352     return scrollToPosition(searchResults, 0, false);
353   }
354
355   /**
356    * Scrolls the view (if necessary) to show the position of the first
357    * highlighted region in results (if any). Answers true if the view was
358    * scrolled, or false if no matched region was found, or it is already
359    * visible.
360    * 
361    * @param results
362    * @param verticalOffset
363    *          if greater than zero, allows scrolling to a position below the
364    *          first displayed sequence
365    * @param centre
366    *          if true, try to centre the search results horizontally in the view
367    * @return
368    */
369   protected boolean scrollToPosition(SearchResultsI results,
370           int verticalOffset, boolean centre)
371   {
372     int startv, endv, starts, ends;
373     ViewportRanges ranges = av.getRanges();
374
375     if (results == null || results.isEmpty() || av == null
376             || av.getAlignment() == null)
377     {
378       return false;
379     }
380     int seqIndex = av.getAlignment().findIndex(results);
381     if (seqIndex == -1)
382     {
383       return false;
384     }
385     SequenceI seq = av.getAlignment().getSequenceAt(seqIndex);
386
387     int[] r = results.getResults(seq, 0, av.getAlignment().getWidth());
388     if (r == null)
389     {
390       return false;
391     }
392     int start = r[0];
393     int end = r[1];
394
395     /*
396      * To centre results, scroll to positions half the visible width
397      * left/right of the start/end positions
398      */
399     if (centre)
400     {
401       int offset = (ranges.getEndRes() - ranges.getStartRes() + 1) / 2 - 1;
402       start = Math.max(start - offset, 0);
403       end = end + offset - 1;
404     }
405     if (start < 0)
406     {
407       return false;
408     }
409     if (end == seq.getEnd())
410     {
411       return false;
412     }
413
414     if (av.hasHiddenColumns())
415     {
416       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
417       start = hidden.absoluteToVisibleColumn(start);
418       end = hidden.absoluteToVisibleColumn(end);
419       if (start == end)
420       {
421         if (!hidden.isVisible(r[0]))
422         {
423           // don't scroll - position isn't visible
424           return false;
425         }
426       }
427     }
428
429     /*
430      * allow for offset of target sequence (actually scroll to one above it)
431      */
432     seqIndex = Math.max(0, seqIndex - verticalOffset);
433     boolean scrollNeeded = true;
434
435     if (!av.getWrapAlignment())
436     {
437       if ((startv = ranges.getStartRes()) >= start)
438       {
439         /*
440          * Scroll left to make start of search results visible
441          */
442         setScrollValues(start, seqIndex);
443       }
444       else if ((endv = ranges.getEndRes()) <= end)
445       {
446         /*
447          * Scroll right to make end of search results visible
448          */
449         setScrollValues(startv + end - endv, seqIndex);
450       }
451       else if ((starts = ranges.getStartSeq()) > seqIndex)
452       {
453         /*
454          * Scroll up to make start of search results visible
455          */
456         setScrollValues(ranges.getStartRes(), seqIndex);
457       }
458       else if ((ends = ranges.getEndSeq()) <= seqIndex)
459       {
460         /*
461          * Scroll down to make end of search results visible
462          */
463         setScrollValues(ranges.getStartRes(), starts + seqIndex - ends
464                 + 1);
465       }
466       /*
467        * Else results are already visible - no need to scroll
468        */
469       scrollNeeded = false;
470     }
471     else
472     {
473       scrollNeeded = ranges.scrollToWrappedVisible(start);
474     }
475
476     paintAlignment(false, false);
477
478     return scrollNeeded;
479   }
480
481   /**
482    * DOCUMENT ME!
483    * 
484    * @return DOCUMENT ME!
485    */
486   public OverviewPanel getOverviewPanel()
487   {
488     return overviewPanel;
489   }
490
491   /**
492    * DOCUMENT ME!
493    * 
494    * @param op
495    *          DOCUMENT ME!
496    */
497   public void setOverviewPanel(OverviewPanel op)
498   {
499     overviewPanel = op;
500   }
501
502   /**
503    * 
504    * @param b
505    *          Hide or show annotation panel
506    * 
507    */
508   public void setAnnotationVisible(boolean b)
509   {
510     if (!av.getWrapAlignment())
511     {
512       annotationSpaceFillerHolder.setVisible(b);
513       annotationScroller.setVisible(b);
514     }
515     repaint();
516   }
517
518   /**
519    * automatically adjust annotation panel height for new annotation whilst
520    * ensuring the alignment is still visible.
521    */
522   @Override
523   public void adjustAnnotationHeight()
524   {
525     // TODO: display vertical annotation scrollbar if necessary
526     // this is called after loading new annotation onto alignment
527     if (alignFrame.getHeight() == 0)
528     {
529       System.out.println("NEEDS FIXING");
530     }
531     validateAnnotationDimensions(true);
532     addNotify();
533     // TODO: many places call this method and also paintAlignment with various
534     // different settings. this means multiple redraws are triggered...
535     paintAlignment(true, av.needToUpdateStructureViews());
536   }
537
538   /**
539    * calculate the annotation dimensions and refresh slider values accordingly.
540    * need to do repaints/notifys afterwards.
541    */
542   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
543   {
544     int annotationHeight = getAnnotationPanel().adjustPanelHeight();
545     annotationHeight = getAnnotationPanel()
546             .adjustForAlignFrame(adjustPanelHeight, annotationHeight);
547
548     hscroll.addNotify();
549     annotationScroller.setPreferredSize(
550             new Dimension(annotationScroller.getWidth(), annotationHeight));
551
552     Dimension e = idPanel.getSize();
553     alabels.setSize(new Dimension(e.width, annotationHeight));
554
555     annotationSpaceFillerHolder.setPreferredSize(new Dimension(
556             annotationSpaceFillerHolder.getWidth(), annotationHeight));
557     annotationScroller.validate();
558     annotationScroller.addNotify();
559   }
560
561   /**
562    * update alignment layout for viewport settings
563    * 
564    * @param wrap
565    *          DOCUMENT ME!
566    */
567   public void updateLayout()
568   {
569     fontChanged();
570     setAnnotationVisible(av.isShowAnnotation());
571     boolean wrap = av.getWrapAlignment();
572     ViewportRanges ranges = av.getRanges();
573     ranges.setStartSeq(0);
574     scalePanelHolder.setVisible(!wrap);
575     hscroll.setVisible(!wrap);
576     idwidthAdjuster.setVisible(!wrap);
577
578     if (wrap)
579     {
580       annotationScroller.setVisible(false);
581       annotationSpaceFillerHolder.setVisible(false);
582     }
583     else if (av.isShowAnnotation())
584     {
585       annotationScroller.setVisible(true);
586       annotationSpaceFillerHolder.setVisible(true);
587       validateAnnotationDimensions(false);
588     }
589
590     int canvasWidth = getSeqPanel().seqCanvas.getWidth();
591     if (canvasWidth > 0)
592     { // may not yet be laid out
593       if (wrap)
594       {
595         int widthInRes = getSeqPanel().seqCanvas
596                 .getWrappedCanvasWidth(canvasWidth);
597         ranges.setViewportWidth(widthInRes);
598       }
599       else
600       {
601         int widthInRes = (canvasWidth / av.getCharWidth());
602         int heightInSeq = (getSeqPanel().seqCanvas.getHeight()
603                 / av.getCharHeight());
604
605         ranges.setViewportWidth(widthInRes);
606         ranges.setViewportHeight(heightInSeq);
607       }
608     }
609
610     idSpaceFillerPanel1.setVisible(!wrap);
611
612     repaint();
613   }
614
615   /**
616    * Adjust row/column scrollers to show a visible position in the alignment.
617    * 
618    * @param x
619    *          visible column to scroll to
620    * @param y
621    *          visible row to scroll to
622    * 
623    */
624   public void setScrollValues(int xpos, int ypos)
625   {
626     int x = xpos;
627     int y = ypos;
628
629     if (av == null || av.getAlignment() == null)
630     {
631       return;
632     }
633
634     if (av.getWrapAlignment())
635     {
636       setScrollingForWrappedPanel(x);
637     }
638     else
639     {
640       int width = av.getAlignment().getVisibleWidth();
641       int height = av.getAlignment().getHeight();
642
643       hextent = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
644       vextent = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
645
646       if (hextent > width)
647       {
648         hextent = width;
649       }
650
651       if (vextent > height)
652       {
653         vextent = height;
654       }
655
656       if ((hextent + x) > width)
657       {
658         x = width - hextent;
659       }
660
661       if ((vextent + y) > height)
662       {
663         y = height - vextent;
664       }
665
666       if (y < 0)
667       {
668         y = 0;
669       }
670
671       if (x < 0)
672       {
673         x = 0;
674       }
675
676       // update the scroll values
677       hscroll.setValues(x, hextent, 0, width);
678       vscroll.setValues(y, vextent, 0, height);
679     }
680   }
681
682   /**
683    * Respond to adjustment event when horizontal or vertical scrollbar is
684    * changed
685    * 
686    * @param evt
687    *          adjustment event encoding whether hscroll or vscroll changed
688    */
689   @Override
690   public void adjustmentValueChanged(AdjustmentEvent evt)
691   {
692     if (av.getWrapAlignment())
693     {
694       adjustScrollingWrapped(evt);
695       return;
696     }
697
698     ViewportRanges ranges = av.getRanges();
699
700     if (evt.getSource() == hscroll)
701     {
702       int oldX = ranges.getStartRes();
703       int oldwidth = ranges.getViewportWidth();
704       int x = hscroll.getValue();
705       int width = getSeqPanel().seqCanvas.getWidth() / av.getCharWidth();
706
707       // if we're scrolling to the position we're already at, stop
708       // this prevents infinite recursion of events when the scroll/viewport
709       // ranges values are the same
710       if ((x == oldX) && (width == oldwidth))
711       {
712         return;
713       }
714       ranges.setViewportStartAndWidth(x, width);
715     }
716     else if (evt.getSource() == vscroll)
717     {
718       int oldY = ranges.getStartSeq();
719       int oldheight = ranges.getViewportHeight();
720       int y = vscroll.getValue();
721       int height = getSeqPanel().seqCanvas.getHeight() / av.getCharHeight();
722
723       // if we're scrolling to the position we're already at, stop
724       // this prevents infinite recursion of events when the scroll/viewport
725       // ranges values are the same
726       if ((y == oldY) && (height == oldheight))
727       {
728         return;
729       }
730       ranges.setViewportStartAndHeight(y, height);
731     }
732     repaint();
733   }
734
735   /**
736    * Responds to a scroll change by setting the start position of the viewport.
737    * Does
738    * 
739    * @param evt
740    */
741   protected void adjustScrollingWrapped(AdjustmentEvent evt)
742   {
743     if (evt.getSource() == hscroll)
744     {
745       return; // no horizontal scroll when wrapped
746     }
747     final ViewportRanges ranges = av.getRanges();
748
749     if (evt.getSource() == vscroll)
750     {
751       int newY = vscroll.getValue();
752
753       /*
754        * if we're scrolling to the position we're already at, stop
755        * this prevents infinite recursion of events when the scroll/viewport
756        * ranges values are the same
757        */
758       int oldX = ranges.getStartRes();
759       int oldY = ranges.getWrappedScrollPosition(oldX);
760       if (oldY == newY)
761       {
762         return;
763       }
764       if (newY > -1)
765       {
766         /*
767          * limit page up/down to one width's worth of positions
768          */
769         int rowSize = ranges.getViewportWidth();
770         int newX = newY > oldY ? oldX + rowSize : oldX - rowSize;
771         ranges.setViewportStartAndWidth(Math.max(0, newX), rowSize);
772       }
773     }
774     else
775     {
776       // This is only called if file loaded is a jar file that
777       // was wrapped when saved and user has wrap alignment true
778       // as preference setting
779       SwingUtilities.invokeLater(new Runnable()
780       {
781         @Override
782         public void run()
783         {
784           // When updating scrolling to use ViewportChange events, this code
785           // could not be validated and it is not clear if it is now being
786           // called. Log warning here in case it is called and unforeseen
787           // problems occur
788           Cache.log.warn(
789                   "Unexpected path through code: Wrapped jar file opened with wrap alignment set in preferences");
790
791           // scroll to start of panel
792           ranges.setStartRes(0);
793           ranges.setStartSeq(0);
794         }
795       });
796     }
797     repaint();
798   }
799
800   /* (non-Javadoc)
801    * @see jalview.api.AlignmentViewPanel#paintAlignment(boolean)
802    */
803   @Override
804   public void paintAlignment(boolean updateOverview,
805           boolean updateStructures)
806   {
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    * Sorts annotations according to currently selected preference
825    */
826   void sortAnnotations()
827   {
828     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
829             av.isShowAutocalculatedAbove());
830     sorter.sort(getAlignment().getAlignmentAnnotation(),
831             av.getSortAnnotationsBy());
832   }
833
834   /**
835    * DOCUMENT ME!
836    * 
837    * @param g
838    *          DOCUMENT ME!
839    */
840   @Override
841   public void paintComponent(Graphics g)
842   {
843     invalidate(); // needed so that the id width adjuster works correctly
844
845     Dimension d = getIdPanel().getIdCanvas().getPreferredSize();
846     idPanelHolder.setPreferredSize(d);
847     hscrollFillerPanel.setPreferredSize(new Dimension(d.width, 12));
848
849     validate(); // needed so that the id width adjuster works correctly
850
851     /*
852      * set scroll bar positions - tried to remove but necessary for split panel to resize correctly
853      * though I still think this call should be elsewhere.
854      */
855     ViewportRanges ranges = av.getRanges();
856     setScrollValues(ranges.getStartRes(), ranges.getStartSeq());
857   }
858
859   /**
860    * Set vertical scroll bar position, and number of increments, for wrapped
861    * panel
862    * 
863    * @param topLeftColumn
864    *          the column position at top left (0..)
865    */
866   private void setScrollingForWrappedPanel(int topLeftColumn)
867   {
868     ViewportRanges ranges = av.getRanges();
869     int scrollPosition = ranges.getWrappedScrollPosition(topLeftColumn);
870     int maxScroll = ranges.getWrappedMaxScroll(topLeftColumn);
871
872     /*
873      * a scrollbar's value can be set to at most (maximum-extent)
874      * so we add extent (1) to the maxScroll value
875      */
876     vscroll.setUnitIncrement(1);
877     vscroll.setValues(scrollPosition, 1, 0, maxScroll + 1);
878   }
879
880   /**
881    * DOCUMENT ME!
882    * 
883    * @param pg
884    *          DOCUMENT ME!
885    * @param pf
886    *          DOCUMENT ME!
887    * @param pi
888    *          DOCUMENT ME!
889    * 
890    * @return DOCUMENT ME!
891    * 
892    * @throws PrinterException
893    *           DOCUMENT ME!
894    */
895   @Override
896   public int print(Graphics pg, PageFormat pf, int pi)
897           throws PrinterException
898   {
899     pg.translate((int) pf.getImageableX(), (int) pf.getImageableY());
900
901     int pwidth = (int) pf.getImageableWidth();
902     int pheight = (int) pf.getImageableHeight();
903
904     if (av.getWrapAlignment())
905     {
906       return printWrappedAlignment(pwidth, pheight, pi, pg);
907     }
908     else
909     {
910       return printUnwrapped(pwidth, pheight, pi, pg, pg);
911     }
912   }
913
914   /**
915    * Draws the alignment image, including sequence ids, sequences, and
916    * annotation labels and annotations if shown, on either one or two Graphics
917    * contexts.
918    * 
919    * @param pageWidth
920    *          in pixels
921    * @param pageHeight
922    *          in pixels
923    * @param pageIndex
924    *          (0, 1, ...)
925    * @param idGraphics
926    *          the graphics context for sequence ids and annotation labels
927    * @param alignmentGraphics
928    *          the graphics context for sequences and annotations (may or may not
929    *          be the same context as idGraphics)
930    * @return
931    * @throws PrinterException
932    */
933   public int printUnwrapped(int pageWidth, int pageHeight, int pageIndex,
934           Graphics idGraphics, Graphics alignmentGraphics)
935           throws PrinterException
936   {
937     final int idWidth = getVisibleIdWidth(false);
938
939     /*
940      * Get the horizontal offset to where we draw the sequences.
941      * This is idWidth if using a single Graphics context, else zero.
942      */
943     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
944             : idWidth;
945
946     FontMetrics fm = getFontMetrics(av.getFont());
947     final int charHeight = av.getCharHeight();
948     final int scaleHeight = charHeight + fm.getDescent();
949
950     idGraphics.setColor(Color.white);
951     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
952     idGraphics.setFont(av.getFont());
953
954     /*
955      * How many sequences and residues can we fit on a printable page?
956      */
957     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
958
959     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
960
961     final int alignmentWidth = av.getAlignment().getVisibleWidth();
962     int pagesWide = (alignmentWidth / totalRes) + 1;
963
964     final int startRes = (pageIndex % pagesWide) * totalRes;
965     final int endRes = Math.min(startRes + totalRes - 1,
966             alignmentWidth - 1);
967
968     final int startSeq = (pageIndex / pagesWide) * totalSeq;
969     final int alignmentHeight = av.getAlignment().getHeight();
970     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
971
972     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
973
974     if (av.isShowAnnotation())
975     {
976       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
977     }
978
979     pagesHigh /= pageHeight;
980
981     if (pageIndex >= (pagesWide * pagesHigh))
982     {
983       return Printable.NO_SUCH_PAGE;
984     }
985     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
986
987     /*
988      * draw the Scale at horizontal offset, then reset to top left (0, 0)
989      */
990     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
991     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
992             pageWidth - idWidth, scaleHeight);
993     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
994
995     /*
996      * Draw the sequence ids, offset for scale height,
997      * then reset to top left (0, 0)
998      */
999     idGraphics.translate(0, scaleHeight);
1000     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1001     List<SequenceI> selection = av.getSelectionGroup() == null ? null
1002             : av.getSelectionGroup().getSequences(null);
1003     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
1004             selection);
1005
1006     idGraphics.setFont(av.getFont());
1007     idGraphics.translate(0, -scaleHeight);
1008
1009     /*
1010      * draw the sequences, offset for scale height, and id width (if using a
1011      * single graphics context), then reset to (0, scale height)
1012      */
1013     alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1014     getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics, startRes,
1015             endRes, startSeq, endSeq - 1);
1016     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1017
1018     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1019     {
1020       /*
1021        * draw annotation labels; drawComponent() translates by
1022        * getScrollOffset(), so compensate for that first;
1023        * then reset to (0, scale height)
1024        */
1025       int offset = getAlabels().getScrollOffset();
1026       idGraphics.translate(0, -offset);
1027       idGraphics.translate(0, alignmentDrawnHeight);
1028       getAlabels().drawComponent(idGraphics, idWidth);
1029       idGraphics.translate(0, -alignmentDrawnHeight);
1030
1031       /*
1032        * draw the annotations starting at 
1033        * (idOffset, alignmentHeight) from (0, scaleHeight)
1034        */
1035       alignmentGraphics.translate(alignmentGraphicsOffset,
1036               alignmentDrawnHeight);
1037       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1038               alignmentGraphics, -1, startRes, endRes + 1);
1039     }
1040
1041     return Printable.PAGE_EXISTS;
1042   }
1043
1044   /**
1045    * Prints one page of an alignment in wrapped mode. Returns
1046    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1047    * no page could be drawn (page number out of range).
1048    * 
1049    * @param pageWidth
1050    * @param pageHeight
1051    * @param pageNumber
1052    *          (0, 1, ...)
1053    * @param g
1054    * 
1055    * @return
1056    * 
1057    * @throws PrinterException
1058    */
1059   public int printWrappedAlignment(int pageWidth, int pageHeight, int pageNumber,
1060           Graphics g) throws PrinterException
1061   {
1062     int annotationHeight = 0;
1063     if (av.isShowAnnotation())
1064     {
1065       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1066     }
1067
1068     int hgap = av.getCharHeight();
1069     if (av.getScaleAboveWrapped())
1070     {
1071       hgap += av.getCharHeight();
1072     }
1073
1074     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1075             + annotationHeight;
1076
1077     int idWidth = getVisibleIdWidth(false);
1078
1079     int maxwidth = av.getAlignment().getVisibleWidth();
1080
1081     int resWidth = getSeqPanel().seqCanvas
1082             .getWrappedCanvasWidth(pageWidth - idWidth);
1083
1084     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1085
1086     g.setColor(Color.white);
1087     g.fillRect(0, 0, pageWidth, pageHeight);
1088     g.setFont(av.getFont());
1089     g.setColor(Color.black);
1090
1091     /*
1092      * method: print the whole wrapped alignment, but with a clip region that
1093      * is restricted to the requested page; this supports selective print of 
1094      * single  pages or ranges, (at the cost of some repeated processing in 
1095      * the 'normal' case, when all pages are printed)
1096      */
1097     g.translate(0, -pageNumber * pageHeight);
1098
1099     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1100
1101     /*
1102      * draw sequence ids and annotation labels (if shown)
1103      */
1104     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1105     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1106
1107     g.translate(idWidth, 0);
1108
1109     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g, pageWidth - idWidth,
1110             totalHeight, 0);
1111
1112     if ((pageNumber * pageHeight) < totalHeight)
1113     {
1114       return Printable.PAGE_EXISTS;
1115     }
1116     else
1117     {
1118       return Printable.NO_SUCH_PAGE;
1119     }
1120   }
1121
1122   /**
1123    * get current sequence ID panel width, or nominal value if panel were to be
1124    * displayed using default settings
1125    * 
1126    * @return
1127    */
1128   public int getVisibleIdWidth()
1129   {
1130     return getVisibleIdWidth(true);
1131   }
1132
1133   /**
1134    * get current sequence ID panel width, or nominal value if panel were to be
1135    * displayed using default settings
1136    * 
1137    * @param onscreen
1138    *          indicate if the Id width for onscreen or offscreen display should
1139    *          be returned
1140    * @return
1141    */
1142   public int getVisibleIdWidth(boolean onscreen)
1143   {
1144     // see if rendering offscreen - check preferences and calc width accordingly
1145     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1146     {
1147       return calculateIdWidth(-1).width + 4;
1148     }
1149     Integer idwidth = null;
1150     if (onscreen || (idwidth = Cache
1151             .getIntegerProperty("FIGURE_FIXEDIDWIDTH")) == null)
1152     {
1153       int w = getIdPanel().getWidth();
1154       return (w > 0 ? w : calculateIdWidth().width + 4);
1155     }
1156     return idwidth.intValue() + 4;
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   int getWrappedHeight()
1425   {
1426     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1427
1428     if (System.getProperty("java.awt.headless") != null
1429             && System.getProperty("java.awt.headless").equals("true"))
1430     {
1431       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1432               - vscroll.getPreferredSize().width
1433               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1434     }
1435
1436     int chunkWidth = getSeqPanel().seqCanvas
1437             .getWrappedCanvasWidth(seqPanelWidth);
1438
1439     int hgap = av.getCharHeight();
1440     if (av.getScaleAboveWrapped())
1441     {
1442       hgap += av.getCharHeight();
1443     }
1444
1445     int annotationHeight = 0;
1446     if (av.isShowAnnotation())
1447     {
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 }