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