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