quick hack re JAL-1278
[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(false, 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(boolean exportSeqPanel, int pageWidth,
923           int pageHeight, int pageIndex,
924           Graphics idGraphics, Graphics alignmentGraphics)
925           throws PrinterException
926   {
927     final int idWidth = getVisibleIdWidth(false);
928
929     /*
930      * Get the horizontal offset to where we draw the sequences.
931      * This is idWidth if using a single Graphics context, else zero.
932      */
933     final int alignmentGraphicsOffset = idGraphics != alignmentGraphics ? 0
934             : idWidth;
935
936     FontMetrics fm = getFontMetrics(av.getFont());
937     final int charHeight = av.getCharHeight();
938     final int scaleHeight = charHeight + fm.getDescent();
939
940     idGraphics.setColor(Color.white);
941     idGraphics.fillRect(0, 0, pageWidth, pageHeight);
942     idGraphics.setFont(av.getFont());
943
944     /*
945      * How many sequences and residues can we fit on a printable page?
946      */
947     final int totalRes = (pageWidth - idWidth) / av.getCharWidth();
948
949     final int totalSeq = (pageHeight - scaleHeight) / charHeight - 1;
950
951     final int alignmentWidth = av.getAlignment().getVisibleWidth();
952     int pagesWide = (alignmentWidth / totalRes) + 1;
953
954     final int startRes = (pageIndex % pagesWide) * totalRes;
955     final int endRes = Math.min(startRes + totalRes - 1,
956             alignmentWidth - 1);
957
958     final int startSeq = (pageIndex / pagesWide) * totalSeq;
959     final int alignmentHeight = av.getAlignment().getHeight();
960     final int endSeq = Math.min(startSeq + totalSeq, alignmentHeight);
961
962     int pagesHigh = ((alignmentHeight / totalSeq) + 1) * pageHeight;
963
964     if (av.isShowAnnotation())
965     {
966       pagesHigh += getAnnotationPanel().adjustPanelHeight() + 3;
967     }
968
969     pagesHigh /= pageHeight;
970
971     if (pageIndex >= (pagesWide * pagesHigh))
972     {
973       return Printable.NO_SUCH_PAGE;
974     }
975     final int alignmentDrawnHeight = (endSeq - startSeq) * charHeight + 3;
976
977     /*
978      * draw the Scale at horizontal offset, then reset to top left (0, 0)
979      */
980     alignmentGraphics.translate(alignmentGraphicsOffset, 0);
981     getScalePanel().drawScale(alignmentGraphics, startRes, endRes,
982             pageWidth - idWidth, scaleHeight);
983     alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
984
985     /*
986      * Draw the sequence ids, offset for scale height,
987      * then reset to top left (0, 0)
988      */
989     idGraphics.translate(0, scaleHeight);
990     IdCanvas idCanvas = getIdPanel().getIdCanvas();
991     List<SequenceI> selection = av.getSelectionGroup() == null ? null
992             : av.getSelectionGroup().getSequences(null);
993     idCanvas.drawIds((Graphics2D) idGraphics, av, startSeq, endSeq - 1,
994             selection);
995
996     idGraphics.setFont(av.getFont());
997     idGraphics.translate(0, -scaleHeight);
998
999     if (!exportSeqPanel)
1000     {
1001       /*
1002        * draw the sequences, offset for scale height, and id width (if using a
1003        * single graphics context), then reset to (0, scale height)
1004        */
1005       alignmentGraphics.translate(alignmentGraphicsOffset, scaleHeight);
1006       getSeqPanel().seqCanvas.drawPanelForPrinting(alignmentGraphics,
1007               startRes, endRes, startSeq, endSeq - 1);
1008       alignmentGraphics.translate(-alignmentGraphicsOffset, 0);
1009     }
1010
1011     if (av.isShowAnnotation() && (endSeq == alignmentHeight))
1012     {
1013       /*
1014        * draw annotation labels; drawComponent() translates by
1015        * getScrollOffset(), so compensate for that first;
1016        * then reset to (0, scale height)
1017        */
1018       int offset = getAlabels().getScrollOffset();
1019       idGraphics.translate(0, -offset);
1020       idGraphics.translate(0, alignmentDrawnHeight);
1021       getAlabels().drawComponent(idGraphics, idWidth);
1022       idGraphics.translate(0, -alignmentDrawnHeight);
1023
1024       /*
1025        * draw the annotations starting at 
1026        * (idOffset, alignmentHeight) from (0, scaleHeight)
1027        */
1028       alignmentGraphics.translate(alignmentGraphicsOffset,
1029               alignmentDrawnHeight);
1030       getAnnotationPanel().renderer.drawComponent(getAnnotationPanel(), av,
1031               alignmentGraphics, -1, startRes, endRes + 1);
1032     }
1033
1034     return Printable.PAGE_EXISTS;
1035   }
1036
1037   /**
1038    * Prints one page of an alignment in wrapped mode. Returns
1039    * Printable.PAGE_EXISTS (0) if a page was drawn, or Printable.NO_SUCH_PAGE if
1040    * no page could be drawn (page number out of range).
1041    * 
1042    * @param pageWidth
1043    * @param pageHeight
1044    * @param pageNumber
1045    *          (0, 1, ...)
1046    * @param g
1047    * 
1048    * @return
1049    * 
1050    * @throws PrinterException
1051    */
1052   public int printWrappedAlignment(int pageWidth,
1053           int pageHeight, int pageNumber,
1054           Graphics g) throws PrinterException
1055   {
1056     getSeqPanel().seqCanvas.calculateWrappedGeometry(getWidth(),
1057             getHeight());
1058     int annotationHeight = 0;
1059     if (av.isShowAnnotation())
1060     {
1061       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1062     }
1063
1064     int hgap = av.getCharHeight();
1065     if (av.getScaleAboveWrapped())
1066     {
1067       hgap += av.getCharHeight();
1068     }
1069
1070     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1071             + annotationHeight;
1072
1073     int idWidth = getVisibleIdWidth(false);
1074
1075     int maxwidth = av.getAlignment().getVisibleWidth();
1076
1077     int resWidth = getSeqPanel().seqCanvas
1078             .getWrappedCanvasWidth(pageWidth - idWidth);
1079     av.getRanges().setViewportStartAndWidth(0, resWidth);
1080
1081     int totalHeight = cHeight * (maxwidth / resWidth + 1);
1082
1083     g.setColor(Color.white);
1084     g.fillRect(0, 0, pageWidth, pageHeight);
1085     g.setFont(av.getFont());
1086     g.setColor(Color.black);
1087
1088     /*
1089      * method: print the whole wrapped alignment, but with a clip region that
1090      * is restricted to the requested page; this supports selective print of 
1091      * single pages or ranges, (at the cost of repeated processing in the 
1092      * 'normal' case, when all pages are printed)
1093      */
1094     g.translate(0, -pageNumber * pageHeight);
1095
1096     g.setClip(0, pageNumber * pageHeight, pageWidth, pageHeight);
1097
1098     /*
1099      * draw sequence ids and annotation labels (if shown)
1100      */
1101     IdCanvas idCanvas = getIdPanel().getIdCanvas();
1102     idCanvas.drawIdsWrapped((Graphics2D) g, av, 0, totalHeight);
1103
1104     g.translate(idWidth, 0);
1105
1106     getSeqPanel().seqCanvas.drawWrappedPanelForPrinting(g,
1107             pageWidth - idWidth,
1108             totalHeight, 0);
1109
1110     if ((pageNumber * pageHeight) < totalHeight)
1111     {
1112       return Printable.PAGE_EXISTS;
1113     }
1114     else
1115     {
1116       return Printable.NO_SUCH_PAGE;
1117     }
1118   }
1119
1120   /**
1121    * get current sequence ID panel width, or nominal value if panel were to be
1122    * displayed using default settings
1123    * 
1124    * @return
1125    */
1126   public int getVisibleIdWidth()
1127   {
1128     return getVisibleIdWidth(true);
1129   }
1130
1131   /**
1132    * get current sequence ID panel width, or nominal value if panel were to be
1133    * displayed using default settings
1134    * 
1135    * @param onscreen
1136    *          indicate if the Id width for onscreen or offscreen display should
1137    *          be returned
1138    * @return
1139    */
1140   protected int getVisibleIdWidth(boolean onscreen)
1141   {
1142     // see if rendering offscreen - check preferences and calc width accordingly
1143     if (!onscreen && Cache.getDefault("FIGURE_AUTOIDWIDTH", false))
1144     {
1145       return calculateIdWidth(-1).width;
1146     }
1147     Integer idwidth = onscreen ? null
1148             : Cache.getIntegerProperty("FIGURE_FIXEDIDWIDTH");
1149     if (idwidth != null)
1150     {
1151       return idwidth.intValue() + ID_WIDTH_PADDING;
1152     }
1153
1154     int w = getIdPanel().getWidth();
1155     return (w > 0 ? w : calculateIdWidth().width);
1156   }
1157
1158   void makeAlignmentImage(jalview.util.ImageMaker.TYPE type, File file)
1159   {
1160     makeAlignmentImage(type, file, jalview.bin.Cache
1161             .getDefault("IMAGE_EXPORT_NOSEQUENCES", false));
1162   }
1163
1164   public void makeAlignmentImage(jalview.util.ImageMaker.TYPE type,
1165           File file, boolean exportSeqPanel)
1166   {
1167     int boarderBottomOffset = 5;
1168     long pSessionId = System.currentTimeMillis();
1169     headless = (System.getProperty("java.awt.headless") != null
1170             && System.getProperty("java.awt.headless").equals("true"));
1171     if (alignFrame != null && !headless)
1172     {
1173       if (file != null)
1174       {
1175         alignFrame.setProgressBar(MessageManager
1176                 .formatMessage("status.saving_file", new Object[]
1177                 { type.getLabel() }), pSessionId);
1178       }
1179     }
1180     try
1181     {
1182       AlignmentDimension aDimension = getAlignmentDimension();
1183       try
1184       {
1185         jalview.util.ImageMaker im;
1186         final String imageAction, imageTitle;
1187         if (type == jalview.util.ImageMaker.TYPE.PNG)
1188         {
1189           imageAction = "Create PNG image from alignment";
1190           imageTitle = null;
1191         }
1192         else if (type == jalview.util.ImageMaker.TYPE.EPS)
1193         {
1194           imageAction = "Create EPS file from alignment";
1195           imageTitle = alignFrame.getTitle();
1196         }
1197         else
1198         {
1199           imageAction = "Create SVG file from alignment";
1200           imageTitle = alignFrame.getTitle();
1201         }
1202
1203         im = new jalview.util.ImageMaker(this, type, imageAction,
1204                 aDimension.getWidth(),
1205                 aDimension.getHeight() + boarderBottomOffset, file,
1206                 imageTitle, alignFrame, pSessionId, headless);
1207         Graphics graphics = im.getGraphics();
1208         if (av.getWrapAlignment())
1209         {
1210           if (graphics != null)
1211           {
1212             printWrappedAlignment(aDimension.getWidth(),
1213                     aDimension.getHeight() + boarderBottomOffset, 0,
1214                     graphics);
1215             im.writeImage();
1216           }
1217         }
1218         else
1219         {
1220           if (graphics != null)
1221           {
1222             printUnwrapped(exportSeqPanel, aDimension.getWidth(),
1223                     aDimension.getHeight(), 0,
1224                     graphics, graphics);
1225             im.writeImage();
1226           }
1227         }
1228
1229       } catch (OutOfMemoryError err)
1230       {
1231         // Be noisy here.
1232         System.out.println("########################\n" + "OUT OF MEMORY "
1233                 + file + "\n" + "########################");
1234         new OOMWarning("Creating Image for " + file, err);
1235         // System.out.println("Create IMAGE: " + err);
1236       } catch (Exception ex)
1237       {
1238         ex.printStackTrace();
1239       }
1240     } finally
1241     {
1242
1243     }
1244   }
1245
1246   public AlignmentDimension getAlignmentDimension()
1247   {
1248     int maxwidth = av.getAlignment().getVisibleWidth();
1249
1250     int height = ((av.getAlignment().getHeight() + 1) * av.getCharHeight())
1251             + getScalePanel().getHeight();
1252     int width = getVisibleIdWidth(false) + (maxwidth * av.getCharWidth());
1253
1254     if (av.getWrapAlignment())
1255     {
1256       height = getWrappedHeight();
1257       if (headless)
1258       {
1259         // need to obtain default alignment width and then add in any
1260         // additional allowance for id margin
1261         // this duplicates the calculation in getWrappedHeight but adjusts for
1262         // offscreen idWith
1263         width = alignFrame.getWidth() - vscroll.getPreferredSize().width
1264                 - alignFrame.getInsets().left - alignFrame.getInsets().right
1265                 - getVisibleIdWidth() + getVisibleIdWidth(false);
1266       }
1267       else
1268       {
1269         width = getSeqPanel().getWidth() + getVisibleIdWidth(false);
1270       }
1271
1272     }
1273     else if (av.isShowAnnotation())
1274     {
1275       height += getAnnotationPanel().adjustPanelHeight() + 3;
1276     }
1277     return new AlignmentDimension(width, height);
1278
1279   }
1280
1281   /**
1282    * DOCUMENT ME!
1283    */
1284   public void makeEPS(File epsFile)
1285   {
1286     makeAlignmentImage(jalview.util.ImageMaker.TYPE.EPS, epsFile);
1287   }
1288
1289   /**
1290    * DOCUMENT ME!
1291    */
1292   public void makePNG(File pngFile)
1293   {
1294     makeAlignmentImage(jalview.util.ImageMaker.TYPE.PNG, pngFile);
1295   }
1296
1297   public void makeSVG(File svgFile)
1298   {
1299     makeAlignmentImage(jalview.util.ImageMaker.TYPE.SVG, svgFile);
1300   }
1301
1302   public void makePNGImageMap(File imgMapFile, String imageName)
1303   {
1304     // /////ONLY WORKS WITH NON WRAPPED ALIGNMENTS
1305     // ////////////////////////////////////////////
1306     int idWidth = getVisibleIdWidth(false);
1307     FontMetrics fm = getFontMetrics(av.getFont());
1308     int scaleHeight = av.getCharHeight() + fm.getDescent();
1309
1310     // Gen image map
1311     // ////////////////////////////////
1312     if (imgMapFile != null)
1313     {
1314       try
1315       {
1316         int sSize = av.getAlignment().getHeight();
1317         int alwidth = av.getAlignment().getWidth();
1318         PrintWriter out = new PrintWriter(new FileWriter(imgMapFile));
1319         out.println(HTMLOutput.getImageMapHTML());
1320         out.println("<img src=\"" + imageName
1321                 + "\" border=\"0\" usemap=\"#Map\" >"
1322                 + "<map name=\"Map\">");
1323
1324         for (int s = 0; s < sSize; s++)
1325         {
1326           int sy = s * av.getCharHeight() + scaleHeight;
1327
1328           SequenceI seq = av.getAlignment().getSequenceAt(s);
1329           SequenceGroup[] groups = av.getAlignment().findAllGroups(seq);
1330           for (int column = 0; column < alwidth; column++)
1331           {
1332             StringBuilder text = new StringBuilder(512);
1333             String triplet = null;
1334             if (av.getAlignment().isNucleotide())
1335             {
1336               triplet = ResidueProperties.nucleotideName.get(seq
1337                       .getCharAt(column) + "");
1338             }
1339             else
1340             {
1341               triplet = ResidueProperties.aa2Triplet.get(seq.getCharAt(column)
1342                       + "");
1343             }
1344
1345             if (triplet == null)
1346             {
1347               continue;
1348             }
1349
1350             int seqPos = seq.findPosition(column);
1351             int gSize = groups.length;
1352             for (int g = 0; g < gSize; g++)
1353             {
1354               if (text.length() < 1)
1355               {
1356                 text.append("<area shape=\"rect\" coords=\"")
1357                         .append((idWidth + column * av.getCharWidth()))
1358                         .append(",").append(sy).append(",")
1359                         .append((idWidth + (column + 1) * av.getCharWidth()))
1360                         .append(",").append((av.getCharHeight() + sy))
1361                         .append("\"").append(" onMouseOver=\"toolTip('")
1362                         .append(seqPos).append(" ").append(triplet);
1363               }
1364
1365               if (groups[g].getStartRes() < column
1366                       && groups[g].getEndRes() > column)
1367               {
1368                 text.append("<br><em>").append(groups[g].getName())
1369                         .append("</em>");
1370               }
1371             }
1372
1373             if (text.length() < 1)
1374             {
1375               text.append("<area shape=\"rect\" coords=\"")
1376                       .append((idWidth + column * av.getCharWidth()))
1377                       .append(",").append(sy).append(",")
1378                       .append((idWidth + (column + 1) * av.getCharWidth()))
1379                       .append(",").append((av.getCharHeight() + sy))
1380                       .append("\"").append(" onMouseOver=\"toolTip('")
1381                       .append(seqPos).append(" ").append(triplet);
1382             }
1383             if (!Comparison.isGap(seq.getCharAt(column)))
1384             {
1385               List<SequenceFeature> features = seq.findFeatures(column, column);
1386               for (SequenceFeature sf : features)
1387               {
1388                 if (sf.isContactFeature())
1389                 {
1390                   text.append("<br>").append(sf.getType()).append(" ")
1391                           .append(sf.getBegin()).append(":")
1392                           .append(sf.getEnd());
1393                 }
1394                 else
1395                 {
1396                   text.append("<br>");
1397                   text.append(sf.getType());
1398                   String description = sf.getDescription();
1399                   if (description != null
1400                           && !sf.getType().equals(description))
1401                   {
1402                     description = description.replace("\"", "&quot;");
1403                     text.append(" ").append(description);
1404                   }
1405                 }
1406                 String status = sf.getStatus();
1407                 if (status != null && !"".equals(status))
1408                 {
1409                   text.append(" (").append(status).append(")");
1410                 }
1411               }
1412               if (text.length() > 1)
1413               {
1414                 text.append("')\"; onMouseOut=\"toolTip()\";  href=\"#\">");
1415                 out.println(text.toString());
1416               }
1417             }
1418           }
1419         }
1420         out.println("</map></body></html>");
1421         out.close();
1422
1423       } catch (Exception ex)
1424       {
1425         ex.printStackTrace();
1426       }
1427     } // /////////END OF IMAGE MAP
1428
1429   }
1430
1431   /**
1432    * Answers the height of the entire alignment in pixels, assuming it is in
1433    * wrapped mode
1434    * 
1435    * @return
1436    */
1437   int getWrappedHeight()
1438   {
1439     int seqPanelWidth = getSeqPanel().seqCanvas.getWidth();
1440
1441     if (System.getProperty("java.awt.headless") != null
1442             && System.getProperty("java.awt.headless").equals("true"))
1443     {
1444       seqPanelWidth = alignFrame.getWidth() - getVisibleIdWidth()
1445               - vscroll.getPreferredSize().width
1446               - alignFrame.getInsets().left - alignFrame.getInsets().right;
1447     }
1448
1449     int chunkWidth = getSeqPanel().seqCanvas
1450             .getWrappedCanvasWidth(seqPanelWidth);
1451
1452     int hgap = av.getCharHeight();
1453     if (av.getScaleAboveWrapped())
1454     {
1455       hgap += av.getCharHeight();
1456     }
1457
1458     int annotationHeight = 0;
1459     if (av.isShowAnnotation())
1460     {
1461       hgap += SeqCanvas.SEQS_ANNOTATION_GAP;
1462       annotationHeight = getAnnotationPanel().adjustPanelHeight();
1463     }
1464
1465     int cHeight = av.getAlignment().getHeight() * av.getCharHeight() + hgap
1466             + annotationHeight;
1467
1468     int maxwidth = av.getAlignment().getWidth();
1469     if (av.hasHiddenColumns())
1470     {
1471       maxwidth = av.getAlignment().getHiddenColumns()
1472               .absoluteToVisibleColumn(maxwidth) - 1;
1473     }
1474
1475     int height = ((maxwidth / chunkWidth) + 1) * cHeight;
1476
1477     return height;
1478   }
1479
1480   /**
1481    * close the panel - deregisters all listeners and nulls any references to
1482    * alignment data.
1483    */
1484   public void closePanel()
1485   {
1486     PaintRefresher.RemoveComponent(getSeqPanel().seqCanvas);
1487     PaintRefresher.RemoveComponent(getIdPanel().getIdCanvas());
1488     PaintRefresher.RemoveComponent(this);
1489
1490     closeChildFrames();
1491
1492     /*
1493      * try to ensure references are nulled
1494      */
1495     if (annotationPanel != null)
1496     {
1497       annotationPanel.dispose();
1498       annotationPanel = null;
1499     }
1500
1501     if (av != null)
1502     {
1503       av.removePropertyChangeListener(propertyChangeListener);
1504       propertyChangeListener = null;
1505       StructureSelectionManager ssm = av.getStructureSelectionManager();
1506       ssm.removeStructureViewerListener(getSeqPanel(), null);
1507       ssm.removeSelectionListener(getSeqPanel());
1508       ssm.removeCommandListener(av);
1509       ssm.removeStructureViewerListener(getSeqPanel(), null);
1510       ssm.removeSelectionListener(getSeqPanel());
1511       av.dispose();
1512       av = null;
1513     }
1514     else
1515     {
1516       if (Cache.log.isDebugEnabled())
1517       {
1518         Cache.log.warn("Closing alignment panel which is already closed.");
1519       }
1520     }
1521   }
1522
1523   /**
1524    * Close any open dialogs that would be orphaned when this one is closed
1525    */
1526   protected void closeChildFrames()
1527   {
1528     if (overviewPanel != null)
1529     {
1530       overviewPanel.dispose();
1531       overviewPanel = null;
1532     }
1533     if (calculationDialog != null)
1534     {
1535       calculationDialog.closeFrame();
1536       calculationDialog = null;
1537     }
1538   }
1539
1540   /**
1541    * hides or shows dynamic annotation rows based on groups and av state flags
1542    */
1543   public void updateAnnotation()
1544   {
1545     updateAnnotation(false, false);
1546   }
1547
1548   public void updateAnnotation(boolean applyGlobalSettings)
1549   {
1550     updateAnnotation(applyGlobalSettings, false);
1551   }
1552
1553   public void updateAnnotation(boolean applyGlobalSettings,
1554           boolean preserveNewGroupSettings)
1555   {
1556     av.updateGroupAnnotationSettings(applyGlobalSettings,
1557             preserveNewGroupSettings);
1558     adjustAnnotationHeight();
1559   }
1560
1561   @Override
1562   public AlignmentI getAlignment()
1563   {
1564     return av == null ? null : av.getAlignment();
1565   }
1566
1567   @Override
1568   public String getViewName()
1569   {
1570     return av.getViewName();
1571   }
1572
1573   /**
1574    * Make/Unmake this alignment panel the current input focus
1575    * 
1576    * @param b
1577    */
1578   public void setSelected(boolean b)
1579   {
1580     try
1581     {
1582       if (alignFrame.getSplitViewContainer() != null)
1583       {
1584         /*
1585          * bring enclosing SplitFrame to front first if there is one
1586          */
1587         ((SplitFrame) alignFrame.getSplitViewContainer()).setSelected(b);
1588       }
1589       alignFrame.setSelected(b);
1590     } catch (Exception ex)
1591     {
1592     }
1593
1594     if (b)
1595     {
1596       alignFrame.setDisplayedView(this);
1597     }
1598   }
1599
1600   @Override
1601   public StructureSelectionManager getStructureSelectionManager()
1602   {
1603     return av.getStructureSelectionManager();
1604   }
1605
1606   @Override
1607   public void raiseOOMWarning(String string, OutOfMemoryError error)
1608   {
1609     new OOMWarning(string, error, this);
1610   }
1611
1612   @Override
1613   public jalview.api.FeatureRenderer cloneFeatureRenderer()
1614   {
1615
1616     return new FeatureRenderer(this);
1617   }
1618
1619   @Override
1620   public jalview.api.FeatureRenderer getFeatureRenderer()
1621   {
1622     return seqPanel.seqCanvas.getFeatureRenderer();
1623   }
1624
1625   public void updateFeatureRenderer(
1626           jalview.renderer.seqfeatures.FeatureRenderer fr)
1627   {
1628     fr.transferSettings(getSeqPanel().seqCanvas.getFeatureRenderer());
1629   }
1630
1631   public void updateFeatureRendererFrom(jalview.api.FeatureRenderer fr)
1632   {
1633     if (getSeqPanel().seqCanvas.getFeatureRenderer() != null)
1634     {
1635       getSeqPanel().seqCanvas.getFeatureRenderer().transferSettings(fr);
1636     }
1637   }
1638
1639   public ScalePanel getScalePanel()
1640   {
1641     return scalePanel;
1642   }
1643
1644   public void setScalePanel(ScalePanel scalePanel)
1645   {
1646     this.scalePanel = scalePanel;
1647   }
1648
1649   public SeqPanel getSeqPanel()
1650   {
1651     return seqPanel;
1652   }
1653
1654   public void setSeqPanel(SeqPanel seqPanel)
1655   {
1656     this.seqPanel = seqPanel;
1657   }
1658
1659   public AnnotationPanel getAnnotationPanel()
1660   {
1661     return annotationPanel;
1662   }
1663
1664   public void setAnnotationPanel(AnnotationPanel annotationPanel)
1665   {
1666     this.annotationPanel = annotationPanel;
1667   }
1668
1669   public AnnotationLabels getAlabels()
1670   {
1671     return alabels;
1672   }
1673
1674   public void setAlabels(AnnotationLabels alabels)
1675   {
1676     this.alabels = alabels;
1677   }
1678
1679   public IdPanel getIdPanel()
1680   {
1681     return idPanel;
1682   }
1683
1684   public void setIdPanel(IdPanel idPanel)
1685   {
1686     this.idPanel = idPanel;
1687   }
1688
1689   /**
1690    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
1691    * The aim is to keep the two alignments 'lined up' on their centre columns.
1692    * 
1693    * @param sr
1694    *          holds mapped region(s) of this alignment that we are scrolling
1695    *          'to'; may be modified for sequence offset by this method
1696    * @param verticalOffset
1697    *          the number of visible sequences to show above the mapped region
1698    */
1699   protected void scrollToCentre(SearchResultsI sr, int verticalOffset)
1700   {
1701     scrollToPosition(sr, verticalOffset, true);
1702   }
1703
1704   /**
1705    * Set a flag to say do not scroll any (cDNA/protein) complement.
1706    * 
1707    * @param b
1708    */
1709   protected void setToScrollComplementPanel(boolean b)
1710   {
1711     this.scrollComplementaryPanel = b;
1712   }
1713
1714   /**
1715    * Get whether to scroll complement panel
1716    * 
1717    * @return true if cDNA/protein complement panels should be scrolled
1718    */
1719   protected boolean isSetToScrollComplementPanel()
1720   {
1721     return this.scrollComplementaryPanel;
1722   }
1723
1724   /**
1725    * Redraw sensibly.
1726    * 
1727    * @adjustHeight if true, try to recalculate panel height for visible
1728    *               annotations
1729    */
1730   protected void refresh(boolean adjustHeight)
1731   {
1732     validateAnnotationDimensions(adjustHeight);
1733     addNotify();
1734     if (adjustHeight)
1735     {
1736       // sort, repaint, update overview
1737       paintAlignment(true, false);
1738     }
1739     else
1740     {
1741       // lightweight repaint
1742       repaint();
1743     }
1744   }
1745
1746   @Override
1747   /**
1748    * Property change event fired when a change is made to the viewport ranges
1749    * object associated with this alignment panel's viewport
1750    */
1751   public void propertyChange(PropertyChangeEvent evt)
1752   {
1753     // update this panel's scroll values based on the new viewport ranges values
1754     ViewportRanges ranges = av.getRanges();
1755     int x = ranges.getStartRes();
1756     int y = ranges.getStartSeq();
1757     setScrollValues(x, y);
1758
1759     // now update any complementary alignment (its viewport ranges object
1760     // is different so does not get automatically updated)
1761     if (isSetToScrollComplementPanel())
1762     {
1763       setToScrollComplementPanel(false);
1764       av.scrollComplementaryAlignment();
1765       setToScrollComplementPanel(true);
1766     }
1767   }
1768
1769   /**
1770    * Set the reference to the PCA/Tree chooser dialog for this panel. This
1771    * reference should be nulled when the dialog is closed.
1772    * 
1773    * @param calculationChooser
1774    */
1775   public void setCalculationDialog(CalculationChooser calculationChooser)
1776   {
1777     calculationDialog = calculationChooser;
1778   }
1779
1780   /**
1781    * Returns the reference to the PCA/Tree chooser dialog for this panel (null
1782    * if none is open)
1783    */
1784   public CalculationChooser getCalculationDialog()
1785   {
1786     return calculationDialog;
1787   }
1788 }