JAL-2491 Tidies
[jalview.git] / src / jalview / appletgui / 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.appletgui;
22
23 import jalview.analysis.AnnotationSorter;
24 import jalview.api.AlignViewportI;
25 import jalview.api.AlignmentViewPanel;
26 import jalview.bin.JalviewLite;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.SearchResultsI;
29 import jalview.datamodel.SequenceI;
30 import jalview.structure.StructureSelectionManager;
31 import jalview.viewmodel.ViewportListenerI;
32 import jalview.viewmodel.ViewportRanges;
33
34 import java.awt.BorderLayout;
35 import java.awt.Color;
36 import java.awt.Dimension;
37 import java.awt.FontMetrics;
38 import java.awt.Frame;
39 import java.awt.Graphics;
40 import java.awt.Panel;
41 import java.awt.Scrollbar;
42 import java.awt.event.AdjustmentEvent;
43 import java.awt.event.AdjustmentListener;
44 import java.awt.event.ComponentAdapter;
45 import java.awt.event.ComponentEvent;
46 import java.beans.PropertyChangeEvent;
47 import java.util.List;
48
49 public class AlignmentPanel extends Panel implements AdjustmentListener,
50         AlignmentViewPanel, ViewportListenerI
51 {
52
53   public AlignViewport av;
54
55   OverviewPanel overviewPanel;
56
57   SeqPanel seqPanel;
58
59   IdPanel idPanel;
60
61   IdwidthAdjuster idwidthAdjuster;
62
63   public AlignFrame alignFrame;
64
65   ScalePanel scalePanel;
66
67   AnnotationPanel annotationPanel;
68
69   AnnotationLabels alabels;
70
71   ViewportRanges vpRanges;
72
73   // this value is set false when selection area being dragged
74   boolean fastPaint = true;
75
76   @Override
77   public void finalize() throws Throwable
78   {
79     alignFrame = null;
80     av = null;
81     vpRanges = null;
82     seqPanel = null;
83     seqPanelHolder = null;
84     sequenceHolderPanel = null;
85     scalePanel = null;
86     scalePanelHolder = null;
87     annotationPanel = null;
88     annotationPanelHolder = null;
89     annotationSpaceFillerHolder = null;
90     super.finalize();
91   }
92
93   public AlignmentPanel(AlignFrame af, final AlignViewport av)
94   {
95     try
96     {
97       jbInit();
98     } catch (Exception e)
99     {
100       e.printStackTrace();
101     }
102
103     alignFrame = af;
104     this.av = av;
105     vpRanges = av.getRanges();
106     seqPanel = new SeqPanel(av, this);
107     idPanel = new IdPanel(av, this);
108     scalePanel = new ScalePanel(av, this);
109     idwidthAdjuster = new IdwidthAdjuster(this);
110     annotationPanel = new AnnotationPanel(this);
111     annotationPanelHolder.add(annotationPanel, BorderLayout.CENTER);
112
113     sequenceHolderPanel.add(annotationPanelHolder, BorderLayout.SOUTH);
114     alabels = new AnnotationLabels(this);
115
116     setAnnotationVisible(av.isShowAnnotation());
117
118     idPanelHolder.add(idPanel, BorderLayout.CENTER);
119     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
120     annotationSpaceFillerHolder.add(alabels, BorderLayout.CENTER);
121     scalePanelHolder.add(scalePanel, BorderLayout.CENTER);
122     seqPanelHolder.add(seqPanel, BorderLayout.CENTER);
123
124     fontChanged();
125     setScrollValues(0, 0);
126
127     apvscroll.addAdjustmentListener(this);
128     hscroll.addAdjustmentListener(this);
129     vscroll.addAdjustmentListener(this);
130
131     addComponentListener(new ComponentAdapter()
132     {
133       @Override
134       public void componentResized(ComponentEvent evt)
135       {
136         // reset the viewport ranges when the alignment panel is resized
137         // in particular, this initialises the end residue value when Jalview
138         // is initialised
139         if (av.getWrapAlignment())
140         {
141           int widthInRes = seqPanel.seqCanvas
142                   .getWrappedCanvasWidth(seqPanel.seqCanvas.getWidth());
143           vpRanges.setViewportWidth(widthInRes);
144         }
145         else
146         {
147           int widthInRes = seqPanel.seqCanvas.getWidth()
148                   / av.getCharWidth();
149           int heightInSeq = seqPanel.seqCanvas.getHeight()
150                   / av.getCharHeight();
151
152           vpRanges.setViewportWidth(widthInRes);
153           vpRanges.setViewportHeight(heightInSeq);
154         }
155         // setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
156         if (getSize().height > 0
157                 && annotationPanelHolder.getSize().height > 0)
158         {
159           validateAnnotationDimensions(false);
160         }
161         repaint();
162       }
163
164     });
165
166     Dimension d = calculateIdWidth();
167     idPanel.idCanvas.setSize(d);
168
169     hscrollFillerPanel.setSize(d.width, annotationPanel.getSize().height);
170
171     idPanel.idCanvas.setSize(d.width, seqPanel.seqCanvas.getSize().height);
172     annotationSpaceFillerHolder.setSize(d.width,
173             annotationPanel.getSize().height);
174     alabels.setSize(d.width, annotationPanel.getSize().height);
175     final AlignmentPanel ap = this;
176     av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
177     {
178       @Override
179       public void propertyChange(java.beans.PropertyChangeEvent evt)
180       {
181         if (evt.getPropertyName().equals("alignment"))
182         {
183           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
184           alignmentChanged();
185         }
186       }
187     });
188     av.getRanges().addPropertyChangeListener(this);
189   }
190
191   @Override
192   public AlignViewportI getAlignViewport()
193   {
194     return av;
195   }
196
197   public SequenceRenderer getSequenceRenderer()
198   {
199     return seqPanel.seqCanvas.sr;
200   }
201
202   @Override
203   public jalview.api.FeatureRenderer getFeatureRenderer()
204   {
205     return seqPanel.seqCanvas.fr;
206   }
207
208   @Override
209   public jalview.api.FeatureRenderer cloneFeatureRenderer()
210   {
211     FeatureRenderer nfr = new FeatureRenderer(av);
212     nfr.transferSettings(seqPanel.seqCanvas.fr);
213     return nfr;
214   }
215
216   public void alignmentChanged()
217   {
218     av.alignmentChanged(this);
219
220     if (overviewPanel != null)
221     {
222       overviewPanel.updateOverviewImage();
223     }
224
225     alignFrame.updateEditMenuBar();
226
227     repaint();
228   }
229
230   public void fontChanged()
231   {
232     // set idCanvas bufferedImage to null
233     // to prevent drawing old image
234     idPanel.idCanvas.image = null;
235     FontMetrics fm = getFontMetrics(av.getFont());
236
237     scalePanel.setSize(new Dimension(10, av.getCharHeight()
238             + fm.getDescent()));
239     idwidthAdjuster.setSize(new Dimension(10, av.getCharHeight()
240             + fm.getDescent()));
241     av.updateSequenceIdColours();
242     annotationPanel.image = null;
243     int ap = annotationPanel.adjustPanelHeight(false);
244     Dimension d = calculateIdWidth();
245     d.setSize(d.width + 4, seqPanel.seqCanvas.getSize().height);
246     alabels.setSize(d.width + 4, ap);
247
248     idPanel.idCanvas.setSize(d);
249     hscrollFillerPanel.setSize(d);
250
251     validateAnnotationDimensions(false);
252     annotationPanel.repaint();
253     validate();
254     repaint();
255   }
256
257   public void setIdWidth(int w, int h)
258   {
259     idPanel.idCanvas.setSize(w, h);
260     idPanelHolder.setSize(w, idPanelHolder.getSize().height);
261     annotationSpaceFillerHolder.setSize(w,
262             annotationSpaceFillerHolder.getSize().height);
263     alabels.setSize(w, alabels.getSize().height);
264     validate();
265   }
266
267   Dimension calculateIdWidth()
268   {
269     if (av.nullFrame == null)
270     {
271       av.nullFrame = new Frame();
272       av.nullFrame.addNotify();
273     }
274
275     Graphics g = av.nullFrame.getGraphics();
276
277     FontMetrics fm = g.getFontMetrics(av.font);
278     AlignmentI al = av.getAlignment();
279
280     int i = 0;
281     int idWidth = 0;
282     String id;
283     while (i < al.getHeight() && al.getSequenceAt(i) != null)
284     {
285       SequenceI s = al.getSequenceAt(i);
286       id = s.getDisplayId(av.getShowJVSuffix());
287
288       if (fm.stringWidth(id) > idWidth)
289       {
290         idWidth = fm.stringWidth(id);
291       }
292       i++;
293     }
294
295     // Also check annotation label widths
296     i = 0;
297     if (al.getAlignmentAnnotation() != null)
298     {
299       fm = g.getFontMetrics(av.nullFrame.getFont());
300       while (i < al.getAlignmentAnnotation().length)
301       {
302         String label = al.getAlignmentAnnotation()[i].label;
303         if (fm.stringWidth(label) > idWidth)
304         {
305           idWidth = fm.stringWidth(label);
306         }
307         i++;
308       }
309     }
310
311     return new Dimension(idWidth, idPanel.idCanvas.getSize().height);
312   }
313
314   /**
315    * Highlight the given results on the alignment.
316    * 
317    */
318   public void highlightSearchResults(SearchResultsI results)
319   {
320     scrollToPosition(results);
321     seqPanel.seqCanvas.highlightSearchResults(results);
322   }
323
324   /**
325    * scroll the view to show the position of the highlighted region in results
326    * (if any) and redraw the overview
327    * 
328    * @param results
329    * @return false if results were not found
330    */
331   public boolean scrollToPosition(SearchResultsI results)
332   {
333     return scrollToPosition(results, true);
334   }
335
336   /**
337    * scroll the view to show the position of the highlighted region in results
338    * (if any)
339    * 
340    * @param results
341    * @param redrawOverview
342    *          - when set, the overview will be recalculated (takes longer)
343    * @return false if results were not found
344    */
345   public boolean scrollToPosition(SearchResultsI results,
346           boolean redrawOverview)
347   {
348     return scrollToPosition(results, 0, redrawOverview, false);
349   }
350
351   /**
352    * scroll the view to show the position of the highlighted region in results
353    * (if any)
354    * 
355    * @param results
356    * @param redrawOverview
357    *          - when set, the overview will be recalculated (takes longer)
358    * @return false if results were not found
359    */
360   public boolean scrollToPosition(SearchResultsI results,
361           int verticalOffset,
362           boolean redrawOverview, boolean centre)
363   {
364     // do we need to scroll the panel?
365     if (results != null && results.getSize() > 0)
366     {
367       AlignmentI alignment = av.getAlignment();
368       int seqIndex = alignment.findIndex(results);
369       if (seqIndex == -1)
370       {
371         return false;
372       }
373       /*
374        * allow for offset of target sequence (actually scroll to one above it)
375        */
376
377       SequenceI seq = alignment.getSequenceAt(seqIndex);
378       int[] r = results.getResults(seq, 0, alignment.getWidth());
379       if (r == null)
380       {
381         if (JalviewLite.debug)
382         {// DEBUG
383           System.out
384                   .println("DEBUG: scroll didn't happen - results not within alignment : "
385                           + seq.getStart() + "," + seq.getEnd());
386         }
387         return false;
388       }
389       if (JalviewLite.debug)
390       {
391         // DEBUG
392         /*
393          * System.out.println("DEBUG: scroll: start=" + r[0] +
394          * " av.getStartRes()=" + av.getStartRes() + " end=" + r[1] +
395          * " seq.end=" + seq.getEnd() + " av.getEndRes()=" + av.getEndRes() +
396          * " hextent=" + hextent);
397          */
398       }
399       int start = r[0];
400       int end = r[1];
401
402       /*
403        * To centre results, scroll to positions half the visible width
404        * left/right of the start/end positions
405        */
406       if (centre)
407       {
408         int offset = (vpRanges.getEndRes() - vpRanges.getStartRes() + 1) / 2 - 1;
409         start = Math.max(start - offset, 0);
410         end = Math.min(end + offset, seq.getEnd() - 1);
411       }
412
413       if (start < 0)
414       {
415         return false;
416       }
417       if (end == seq.getEnd())
418       {
419         return false;
420       }
421
422       /*
423        * allow for offset of target sequence (actually scroll to one above it)
424        */
425       seqIndex = Math.max(0, seqIndex - verticalOffset);
426       return scrollTo(start, end, seqIndex, false, redrawOverview);
427     }
428     return true;
429   }
430
431   public boolean scrollTo(int ostart, int end, int seqIndex,
432           boolean scrollToNearest, boolean redrawOverview)
433   {
434     int startv, endv, starts, ends, width;
435
436     int start = -1;
437     if (av.hasHiddenColumns())
438     {
439       start = av.getColumnSelection().findColumnPosition(ostart);
440       end = av.getColumnSelection().findColumnPosition(end);
441       if (start == end)
442       {
443         if (!scrollToNearest && !av.getColumnSelection().isVisible(ostart))
444         {
445           // don't scroll - position isn't visible
446           return false;
447         }
448       }
449     }
450     else
451     {
452       start = ostart;
453     }
454
455     if (!av.getWrapAlignment())
456     {
457       /*
458        * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
459        * av.getStartRes()) >= start) { spos=start-1; // seqIn //
460        * setScrollValues(start - 1, seqIndex); } else if ((endv =
461        * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
462        * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
463        * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
464        * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
465        * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
466        */
467
468       // below is scrolling logic up to Jalview 2.8.2
469       // if ((av.getStartRes() > end)
470       // || (av.getEndRes() < start)
471       // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
472       // {
473       // if (start > av.getAlignment().getWidth() - hextent)
474       // {
475       // start = av.getAlignment().getWidth() - hextent;
476       // if (start < 0)
477       // {
478       // start = 0;
479       // }
480       //
481       // }
482       // if (seqIndex > av.getAlignment().getHeight() - vextent)
483       // {
484       // seqIndex = av.getAlignment().getHeight() - vextent;
485       // if (seqIndex < 0)
486       // {
487       // seqIndex = 0;
488       // }
489       // }
490       // setScrollValues(start, seqIndex);
491       // }
492       // logic copied from jalview.gui.AlignmentPanel:
493       if ((startv = vpRanges.getStartRes()) >= start)
494       {
495         /*
496          * Scroll left to make start of search results visible
497          */
498         setScrollValues(start - 1, seqIndex);
499       }
500       else if ((endv = vpRanges.getEndRes()) <= end)
501       {
502         /*
503          * Scroll right to make end of search results visible
504          */
505         setScrollValues(startv + 1 + end - endv, seqIndex);
506       }
507       else if ((starts = vpRanges.getStartSeq()) > seqIndex)
508       {
509         /*
510          * Scroll up to make start of search results visible
511          */
512         setScrollValues(vpRanges.getStartRes(), seqIndex);
513       }
514       else if ((ends = vpRanges.getEndSeq()) <= seqIndex)
515       {
516         /*
517          * Scroll down to make end of search results visible
518          */
519         setScrollValues(vpRanges.getStartRes(), starts + seqIndex - ends
520                 + 1);
521       }
522       /*
523        * Else results are already visible - no need to scroll
524        */
525     }
526     else
527     {
528       vpRanges.scrollToWrappedVisible(start);
529     }
530
531     paintAlignment(redrawOverview);
532     return true;
533   }
534
535   public OverviewPanel getOverviewPanel()
536   {
537     return overviewPanel;
538   }
539
540   public void setOverviewPanel(OverviewPanel op)
541   {
542     overviewPanel = op;
543   }
544
545   public void setAnnotationVisible(boolean b)
546   {
547     if (!av.getWrapAlignment())
548     {
549       annotationSpaceFillerHolder.setVisible(b);
550       annotationPanelHolder.setVisible(b);
551     }
552     else
553     {
554       annotationSpaceFillerHolder.setVisible(false);
555       annotationPanelHolder.setVisible(false);
556     }
557     validate();
558     repaint();
559   }
560
561   /**
562    * automatically adjust annotation panel height for new annotation whilst
563    * ensuring the alignment is still visible.
564    */
565   @Override
566   public void adjustAnnotationHeight()
567   {
568     // TODO: display vertical annotation scrollbar if necessary
569     // this is called after loading new annotation onto alignment
570     if (alignFrame.getSize().height == 0)
571     {
572       System.out
573               .println("adjustAnnotationHeight frame size zero NEEDS FIXING");
574     }
575     fontChanged();
576     validateAnnotationDimensions(true);
577     apvscroll.addNotify();
578     hscroll.addNotify();
579     validate();
580     paintAlignment(true);
581   }
582
583   /**
584    * Calculate the annotation dimensions and refresh slider values accordingly.
585    * Need to do repaints/notifys afterwards.
586    */
587   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
588   {
589     int rowHeight = av.getCharHeight();
590     int alignmentHeight = rowHeight * av.getAlignment().getHeight();
591     int annotationHeight = av.calcPanelHeight();
592
593     int mheight = annotationHeight;
594     Dimension d = sequenceHolderPanel.getSize();
595
596     int availableHeight = d.height - scalePanelHolder.getHeight();
597
598     if (adjustPanelHeight)
599     {
600       /*
601        * If not enough vertical space, maximize annotation height while keeping
602        * at least two rows of alignment visible
603        */
604       if (annotationHeight + alignmentHeight > availableHeight)
605       {
606         annotationHeight = Math.min(annotationHeight, availableHeight - 2
607                 * rowHeight);
608       }
609     }
610     else
611     {
612       // maintain same window layout whilst updating sliders
613       annotationHeight = annotationPanelHolder.getSize().height;
614     }
615
616     if (availableHeight - annotationHeight < 5)
617     {
618       annotationHeight = availableHeight;
619     }
620
621     annotationPanel.setSize(new Dimension(d.width, annotationHeight));
622     annotationPanelHolder.setSize(new Dimension(d.width, annotationHeight));
623     // seqPanelHolder.setSize(d.width, seqandannot - height);
624     seqPanel.seqCanvas
625             .setSize(d.width, seqPanel.seqCanvas.getSize().height);
626
627     Dimension e = idPanel.getSize();
628     alabels.setSize(new Dimension(e.width, annotationHeight));
629     annotationSpaceFillerHolder.setSize(new Dimension(e.width,
630             annotationHeight));
631
632     int s = apvscroll.getValue();
633     if (s > mheight - annotationHeight)
634     {
635       s = 0;
636     }
637     apvscroll.setValues(s, annotationHeight, 0, mheight);
638     annotationPanel.setScrollOffset(apvscroll.getValue(), false);
639     alabels.setScrollOffset(apvscroll.getValue(), false);
640   }
641
642   public void setWrapAlignment(boolean wrap)
643   {
644     vpRanges.setStartSeq(0);
645     vpRanges.setStartRes(0);
646     scalePanelHolder.setVisible(!wrap);
647
648     hscroll.setVisible(!wrap);
649     idwidthAdjuster.setVisible(!wrap);
650
651     if (wrap)
652     {
653       annotationPanelHolder.setVisible(false);
654       annotationSpaceFillerHolder.setVisible(false);
655     }
656     else if (av.isShowAnnotation())
657     {
658       annotationPanelHolder.setVisible(true);
659       annotationSpaceFillerHolder.setVisible(true);
660     }
661
662     idSpaceFillerPanel1.setVisible(!wrap);
663
664     fontChanged(); // This is so that the scalePanel is resized correctly
665
666     validate();
667     sequenceHolderPanel.validate();
668     repaint();
669
670   }
671
672   int hextent = 0;
673
674   int vextent = 0;
675
676   public void setScrollValues(int xpos, int ypos)
677   {
678     int x = xpos;
679     int y = ypos;
680
681     if (av.getWrapAlignment())
682     {
683       setScrollingForWrappedPanel(x);
684     }
685     else
686     {
687       int width = av.getAlignment().getWidth();
688       int height = av.getAlignment().getHeight();
689
690       if (av.hasHiddenColumns())
691       {
692         width = av.getColumnSelection().findColumnPosition(width);
693       }
694       if (x < 0)
695       {
696         x = 0;
697       }
698
699       hextent = seqPanel.seqCanvas.getSize().width / av.getCharWidth();
700       vextent = seqPanel.seqCanvas.getSize().height / av.getCharHeight();
701
702       if (hextent > width)
703       {
704         hextent = width;
705       }
706
707       if (vextent > height)
708       {
709         vextent = height;
710       }
711
712       if ((hextent + x) > width)
713       {
714         System.err.println("hextent was " + hextent + " and x was " + x);
715
716         x = width - hextent;
717       }
718
719       if ((vextent + y) > height)
720       {
721         y = height - vextent;
722       }
723
724       if (y < 0)
725       {
726         y = 0;
727       }
728
729       if (x < 0)
730       {
731         System.err.println("x was " + x);
732         x = 0;
733       }
734
735       hscroll.setValues(x, hextent, 0, width);
736       vscroll.setValues(y, vextent, 0, height);
737
738       // AWT scrollbar does not fire adjustmentValueChanged for setValues
739       // so also call adjustment code!
740       adjustHorizontal(x);
741       adjustVertical(y);
742
743       sendViewPosition();
744     }
745   }
746
747   /**
748    * Respond to adjustment event when horizontal or vertical scrollbar is
749    * changed
750    * 
751    * @param evt
752    *          adjustment event encoding whether apvscroll, hscroll or vscroll
753    *          changed
754    */
755   @Override
756   public void adjustmentValueChanged(AdjustmentEvent evt)
757   {
758     // Note that this event is NOT fired by the AWT scrollbar when setValues is
759     // called. Instead manually call adjustHorizontal and adjustVertical
760     // directly.
761     if (evt == null || evt.getSource() == apvscroll)
762     {
763       annotationPanel.setScrollOffset(apvscroll.getValue(), false);
764       alabels.setScrollOffset(apvscroll.getValue(), false);
765     }
766     if (evt == null || evt.getSource() == hscroll)
767     {
768       int x = hscroll.getValue();
769       adjustHorizontal(x);
770     }
771
772     if (evt == null || evt.getSource() == vscroll)
773     {
774       int offy = vscroll.getValue();
775       adjustVertical(offy);
776     }
777
778   }
779
780   private void adjustHorizontal(int x)
781   {
782     int oldX = vpRanges.getStartRes();
783     int oldwidth = vpRanges.getViewportWidth();
784     int width = seqPanel.seqCanvas.getWidth() / av.getCharWidth();
785
786     // if we're scrolling to the position we're already at, stop
787     // this prevents infinite recursion of events when the scroll/viewport
788     // ranges values are the same
789     if ((x == oldX) && (width == oldwidth))
790     {
791       return;
792     }
793     vpRanges.setViewportStartAndWidth(x, width);
794
795     if (av.getWrapAlignment() || !fastPaint)
796     {
797       repaint();
798     }
799     sendViewPosition();
800   }
801
802   private void adjustVertical(int offy)
803   {
804     int oldX = vpRanges.getStartRes();
805     int oldwidth = vpRanges.getViewportWidth();
806     int oldY = vpRanges.getStartSeq();
807     int oldheight = vpRanges.getViewportHeight();
808
809     if (av.getWrapAlignment())
810     {
811       int rowSize = seqPanel.seqCanvas
812               .getWrappedCanvasWidth(seqPanel.seqCanvas.getWidth());
813
814       // if we're scrolling to the position we're already at, stop
815       // this prevents infinite recursion of events when the scroll/viewport
816       // ranges values are the same
817       if ((offy * rowSize == oldX) && (oldwidth == rowSize))
818       {
819         return;
820       }
821       else if (offy > -1)
822       {
823         vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
824       }
825     }
826     else
827     {
828       int height = seqPanel.seqCanvas.getHeight() / av.getCharHeight();
829
830       // if we're scrolling to the position we're already at, stop
831       // this prevents infinite recursion of events when the scroll/viewport
832       // ranges values are the same
833       if ((offy == oldY) && (height == oldheight))
834       {
835         return;
836       }
837       vpRanges.setViewportStartAndHeight(offy, height);
838     }
839     if (av.getWrapAlignment() || !fastPaint)
840     {
841       repaint();
842     }
843     sendViewPosition();
844   }
845
846   /**
847    * A helper method to return the AlignmentPanel in the other (complementary)
848    * half of a SplitFrame view. Returns null if not in a SplitFrame.
849    * 
850    * @return
851    */
852   private AlignmentPanel getComplementPanel()
853   {
854     AlignmentPanel ap = null;
855     if (alignFrame != null)
856     {
857       SplitFrame sf = alignFrame.getSplitFrame();
858       if (sf != null)
859       {
860         AlignFrame other = sf.getComplement(alignFrame);
861         if (other != null)
862         {
863           ap = other.alignPanel;
864         }
865       }
866     }
867     return ap;
868   }
869
870   /**
871    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
872    * The aim is to keep the two alignments 'lined up' on their centre columns.
873    * 
874    * @param sr
875    *          holds mapped region(s) of this alignment that we are scrolling
876    *          'to'; may be modified for sequence offset by this method
877    * @param seqOffset
878    *          the number of visible sequences to show above the mapped region
879    */
880   protected void scrollToCentre(SearchResultsI sr, int seqOffset)
881   {
882     /*
883      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
884      * mapped), we can make the scroll-to location a sequence above the one
885      * actually mapped.
886      */
887     SequenceI mappedTo = sr.getResults().get(0).getSequence();
888     List<SequenceI> seqs = av.getAlignment().getSequences();
889
890     /*
891      * This is like AlignmentI.findIndex(seq) but here we are matching the
892      * dataset sequence not the aligned sequence
893      */
894     boolean matched = false;
895     for (SequenceI seq : seqs)
896     {
897       if (mappedTo == seq.getDatasetSequence())
898       {
899         matched = true;
900         break;
901       }
902     }
903     if (!matched)
904     {
905       return; // failsafe, shouldn't happen
906     }
907
908     /*
909      * Scroll to position but centring the target residue. Also set a state flag
910      * to prevent adjustmentValueChanged performing this recursively.
911      */
912     scrollToPosition(sr, seqOffset, true, true);
913   }
914
915   private void sendViewPosition()
916   {
917     StructureSelectionManager.getStructureSelectionManager(av.applet)
918             .sendViewPosition(this, vpRanges.getStartRes(),
919                     vpRanges.getEndRes(), vpRanges.getStartSeq(),
920                     vpRanges.getEndSeq());
921   }
922
923   /**
924    * Repaint the alignment and annotations, and, optionally, any overview window
925    */
926   @Override
927   public void paintAlignment(boolean updateOverview)
928   {
929     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
930             av.isShowAutocalculatedAbove());
931     sorter.sort(getAlignment().getAlignmentAnnotation(),
932             av.getSortAnnotationsBy());
933     repaint();
934
935     if (updateOverview)
936     {
937       // TODO: determine if this paintAlignment changed structure colours
938       jalview.structure.StructureSelectionManager
939               .getStructureSelectionManager(av.applet)
940               .sequenceColoursChanged(this);
941
942       if (overviewPanel != null)
943       {
944         overviewPanel.updateOverviewImage();
945       }
946     }
947   }
948
949   @Override
950   public void update(Graphics g)
951   {
952     paint(g);
953   }
954
955   @Override
956   public void paint(Graphics g)
957   {
958     invalidate();
959     Dimension d = idPanel.idCanvas.getSize();
960     final int canvasHeight = seqPanel.seqCanvas.getSize().height;
961     if (canvasHeight != d.height)
962     {
963       idPanel.idCanvas.setSize(d.width, canvasHeight);
964     }
965
966     setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
967
968     seqPanel.seqCanvas.repaint();
969     idPanel.idCanvas.repaint();
970     if (!av.getWrapAlignment())
971     {
972       if (av.isShowAnnotation())
973       {
974         alabels.repaint();
975         annotationPanel.repaint();
976       }
977       scalePanel.repaint();
978     }
979
980   }
981
982   /*
983    * Set vertical scroll bar parameters for wrapped panel
984    * @param res 
985    *    the residue to scroll to
986    */
987   private void setScrollingForWrappedPanel(int res)
988   {
989     // get the width of the alignment in residues
990     int maxwidth = av.getAlignment().getWidth();
991     if (av.hasHiddenColumns())
992     {
993       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
994     }
995
996     // get the width of the canvas in residues
997     int canvasWidth = seqPanel.seqCanvas
998             .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
999     if (canvasWidth > 0)
1000     {
1001       // position we want to scroll to is number of canvasWidth's to get there
1002       int current = res / canvasWidth;
1003
1004       // max scroll position: add one because extent is 1 and scrollbar value
1005       // can only be set to at most max - extent
1006       int max = maxwidth / canvasWidth + 1;
1007       vscroll.setUnitIncrement(1);
1008       vscroll.setValues(current, 1, 0, max);
1009     }
1010   }
1011
1012   protected Panel sequenceHolderPanel = new Panel();
1013
1014   protected Scrollbar vscroll = new Scrollbar();
1015
1016   protected Scrollbar hscroll = new Scrollbar();
1017
1018   protected Panel seqPanelHolder = new Panel();
1019
1020   protected Panel scalePanelHolder = new Panel();
1021
1022   protected Panel idPanelHolder = new Panel();
1023
1024   protected Panel idSpaceFillerPanel1 = new Panel();
1025
1026   public Panel annotationSpaceFillerHolder = new Panel();
1027
1028   protected Panel hscrollFillerPanel = new Panel();
1029
1030   Panel annotationPanelHolder = new Panel();
1031
1032   protected Scrollbar apvscroll = new Scrollbar();
1033
1034   /*
1035    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
1036    * false, suppresses invoking the same method recursively.
1037    */
1038   private boolean scrollComplementaryPanel = true;
1039
1040   private void jbInit() throws Exception
1041   {
1042     // idPanelHolder.setPreferredSize(new Dimension(70, 10));
1043     this.setLayout(new BorderLayout());
1044
1045     // sequenceHolderPanel.setPreferredSize(new Dimension(150, 150));
1046     sequenceHolderPanel.setLayout(new BorderLayout());
1047     seqPanelHolder.setLayout(new BorderLayout());
1048     scalePanelHolder.setBackground(Color.white);
1049
1050     // scalePanelHolder.setPreferredSize(new Dimension(10, 30));
1051     scalePanelHolder.setLayout(new BorderLayout());
1052     idPanelHolder.setLayout(new BorderLayout());
1053     idSpaceFillerPanel1.setBackground(Color.white);
1054
1055     // idSpaceFillerPanel1.setPreferredSize(new Dimension(10, 30));
1056     idSpaceFillerPanel1.setLayout(new BorderLayout());
1057     annotationSpaceFillerHolder.setBackground(Color.white);
1058
1059     // annotationSpaceFillerHolder.setPreferredSize(new Dimension(10, 80));
1060     annotationSpaceFillerHolder.setLayout(new BorderLayout());
1061     hscroll.setOrientation(Scrollbar.HORIZONTAL);
1062
1063     Panel hscrollHolder = new Panel();
1064     hscrollHolder.setLayout(new BorderLayout());
1065     hscrollFillerPanel.setBackground(Color.white);
1066     apvscroll.setOrientation(Scrollbar.VERTICAL);
1067     apvscroll.setVisible(true);
1068     apvscroll.addAdjustmentListener(this);
1069
1070     annotationPanelHolder.setBackground(Color.white);
1071     annotationPanelHolder.setLayout(new BorderLayout());
1072     annotationPanelHolder.add(apvscroll, BorderLayout.EAST);
1073     // hscrollFillerPanel.setPreferredSize(new Dimension(70, 10));
1074     hscrollHolder.setBackground(Color.white);
1075
1076     // annotationScroller.setPreferredSize(new Dimension(10, 80));
1077     // this.setPreferredSize(new Dimension(220, 166));
1078     seqPanelHolder.setBackground(Color.white);
1079     idPanelHolder.setBackground(Color.white);
1080     sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH);
1081     sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER);
1082     seqPanelHolder.add(vscroll, BorderLayout.EAST);
1083
1084     // Panel3.add(secondaryPanelHolder, BorderLayout.SOUTH);
1085     this.add(idPanelHolder, BorderLayout.WEST);
1086     idPanelHolder.add(idSpaceFillerPanel1, BorderLayout.NORTH);
1087     idPanelHolder.add(annotationSpaceFillerHolder, BorderLayout.SOUTH);
1088     this.add(hscrollHolder, BorderLayout.SOUTH);
1089     hscrollHolder.add(hscroll, BorderLayout.CENTER);
1090     hscrollHolder.add(hscrollFillerPanel, BorderLayout.WEST);
1091     this.add(sequenceHolderPanel, BorderLayout.CENTER);
1092   }
1093
1094   /**
1095    * hides or shows dynamic annotation rows based on groups and av state flags
1096    */
1097   public void updateAnnotation()
1098   {
1099     updateAnnotation(false);
1100   }
1101
1102   public void updateAnnotation(boolean applyGlobalSettings)
1103   {
1104     updateAnnotation(applyGlobalSettings, false);
1105   }
1106
1107   public void updateAnnotation(boolean applyGlobalSettings,
1108           boolean preserveNewGroupSettings)
1109   {
1110     av.updateGroupAnnotationSettings(applyGlobalSettings,
1111             preserveNewGroupSettings);
1112     adjustAnnotationHeight();
1113   }
1114
1115   @Override
1116   public AlignmentI getAlignment()
1117   {
1118     return av.getAlignment();
1119   }
1120
1121   @Override
1122   public String getViewName()
1123   {
1124     return getName();
1125   }
1126
1127   @Override
1128   public StructureSelectionManager getStructureSelectionManager()
1129   {
1130     return StructureSelectionManager
1131             .getStructureSelectionManager(av.applet);
1132   }
1133
1134   @Override
1135   public void raiseOOMWarning(String string, OutOfMemoryError error)
1136   {
1137     // TODO: JAL-960
1138     System.err.println("Out of memory whilst '" + string + "'");
1139     error.printStackTrace();
1140   }
1141
1142   /**
1143    * Set a flag to say we are scrolling to follow a (cDNA/protein) complement.
1144    * 
1145    * @param b
1146    */
1147   protected void setToScrollComplementPanel(boolean b)
1148   {
1149     this.scrollComplementaryPanel = b;
1150   }
1151
1152   /**
1153    * Get whether to scroll complement panel
1154    * 
1155    * @return true if cDNA/protein complement panels should be scrolled
1156    */
1157   protected boolean isSetToScrollComplementPanel()
1158   {
1159     return this.scrollComplementaryPanel;
1160   }
1161
1162   @Override
1163   /**
1164    * Property change event fired when a change is made to the viewport ranges 
1165    * object associated with this alignment panel's viewport
1166    */
1167   public void propertyChange(PropertyChangeEvent evt)
1168   {
1169     // update this panel's scroll values based on the new viewport ranges values
1170     int x = vpRanges.getStartRes();
1171     int y = vpRanges.getStartSeq();
1172     setScrollValues(x, y);
1173
1174     // now update any complementary alignment (its viewport ranges object
1175     // is different so does not get automatically updated)
1176     if (isSetToScrollComplementPanel())
1177     {
1178       setToScrollComplementPanel(false);
1179       av.scrollComplementaryAlignment(getComplementPanel());
1180       setToScrollComplementPanel(true);
1181     }
1182
1183   }
1184
1185 }