JAL-2491 Renamed comp scrolling flag for consistency; small tweaks
[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 x, int y)
677   {
678     if (av.getWrapAlignment())
679     {
680       setScrollingForWrappedPanel(x);
681     }
682     else
683     {
684
685       int width = av.getAlignment().getWidth();
686       int height = av.getAlignment().getHeight();
687
688       if (av.hasHiddenColumns())
689       {
690         width = av.getColumnSelection().findColumnPosition(width);
691       }
692       if (x < 0)
693       {
694         x = 0;
695       }
696
697       hextent = seqPanel.seqCanvas.getSize().width / av.getCharWidth();
698       vextent = seqPanel.seqCanvas.getSize().height / av.getCharHeight();
699
700       if (hextent > width)
701       {
702         hextent = width;
703       }
704
705       if (vextent > height)
706       {
707         vextent = height;
708       }
709
710       if ((hextent + x) > width)
711       {
712         System.err.println("hextent was " + hextent + " and x was " + x);
713
714         x = width - hextent;
715       }
716
717       if ((vextent + y) > height)
718       {
719         y = height - vextent;
720       }
721
722       if (y < 0)
723       {
724         y = 0;
725       }
726
727       if (x < 0)
728       {
729         System.err.println("x was " + x);
730         x = 0;
731       }
732
733       hscroll.setValues(x, hextent, 0, width);
734       vscroll.setValues(y, vextent, 0, height);
735
736       // AWT scrollbar does not fire adjustmentValueChanged for setValues
737       // so also call adjustment code!
738       adjustHorizontal(x);
739       adjustVertical(y);
740
741       sendViewPosition();
742     }
743   }
744
745   @Override
746   public void adjustmentValueChanged(AdjustmentEvent evt)
747   {
748     if (evt == null || evt.getSource() == apvscroll)
749     {
750       annotationPanel.setScrollOffset(apvscroll.getValue(), false);
751       alabels.setScrollOffset(apvscroll.getValue(), false);
752     }
753     if (evt == null || evt.getSource() == hscroll)
754     {
755       int x = hscroll.getValue();
756       adjustHorizontal(x);
757     }
758
759     if (evt == null || evt.getSource() == vscroll)
760     {
761       int offy = vscroll.getValue();
762       adjustVertical(offy);
763     }
764
765   }
766
767   private void adjustHorizontal(int x)
768   {
769     int oldX = vpRanges.getStartRes();
770     int oldwidth = vpRanges.getViewportWidth();
771     int width = seqPanel.seqCanvas.getWidth() / av.getCharWidth();
772
773     // if we're scrolling to the position we're already at, stop
774     // this prevents infinite recursion of events when the scroll/viewport
775     // ranges values are the same
776     if ((x == oldX) && (width == oldwidth))
777     {
778       return;
779     }
780     vpRanges.setViewportStartAndWidth(x, width);
781
782     if (av.getWrapAlignment() || !fastPaint)
783     {
784       repaint();
785     }
786     sendViewPosition();
787   }
788
789   private void adjustVertical(int offy)
790   {
791     int oldX = vpRanges.getStartRes();
792     int oldwidth = vpRanges.getViewportWidth();
793     int oldY = vpRanges.getStartSeq();
794     int oldheight = vpRanges.getViewportHeight();
795
796     if (av.getWrapAlignment())
797     {
798       int rowSize = seqPanel.seqCanvas
799               .getWrappedCanvasWidth(seqPanel.seqCanvas.getWidth());
800
801       // if we're scrolling to the position we're already at, stop
802       // this prevents infinite recursion of events when the scroll/viewport
803       // ranges values are the same
804       if ((offy * rowSize == oldX) && (oldwidth == rowSize))
805       {
806         return;
807       }
808       else if (offy > -1)
809       {
810         vpRanges.setViewportStartAndWidth(offy * rowSize, rowSize);
811       }
812     }
813     else
814     {
815       int height = seqPanel.seqCanvas.getHeight() / av.getCharHeight();
816
817       // if we're scrolling to the position we're already at, stop
818       // this prevents infinite recursion of events when the scroll/viewport
819       // ranges values are the same
820       if ((offy == oldY) && (height == oldheight))
821       {
822         return;
823       }
824       vpRanges.setViewportStartAndHeight(offy, height);
825     }
826     if (av.getWrapAlignment() || !fastPaint)
827     {
828       repaint();
829     }
830     sendViewPosition();
831   }
832
833   /**
834    * A helper method to return the AlignmentPanel in the other (complementary)
835    * half of a SplitFrame view. Returns null if not in a SplitFrame.
836    * 
837    * @return
838    */
839   private AlignmentPanel getComplementPanel()
840   {
841     AlignmentPanel ap = null;
842     if (alignFrame != null)
843     {
844       SplitFrame sf = alignFrame.getSplitFrame();
845       if (sf != null)
846       {
847         AlignFrame other = sf.getComplement(alignFrame);
848         if (other != null)
849         {
850           ap = other.alignPanel;
851         }
852       }
853     }
854     return ap;
855   }
856
857   /**
858    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
859    * The aim is to keep the two alignments 'lined up' on their centre columns.
860    * 
861    * @param sr
862    *          holds mapped region(s) of this alignment that we are scrolling
863    *          'to'; may be modified for sequence offset by this method
864    * @param seqOffset
865    *          the number of visible sequences to show above the mapped region
866    */
867   protected void scrollToCentre(SearchResultsI sr, int seqOffset)
868   {
869     /*
870      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
871      * mapped), we can make the scroll-to location a sequence above the one
872      * actually mapped.
873      */
874     SequenceI mappedTo = sr.getResults().get(0).getSequence();
875     List<SequenceI> seqs = av.getAlignment().getSequences();
876
877     /*
878      * This is like AlignmentI.findIndex(seq) but here we are matching the
879      * dataset sequence not the aligned sequence
880      */
881     boolean matched = false;
882     for (SequenceI seq : seqs)
883     {
884       if (mappedTo == seq.getDatasetSequence())
885       {
886         matched = true;
887         break;
888       }
889     }
890     if (!matched)
891     {
892       return; // failsafe, shouldn't happen
893     }
894
895     /*
896      * Scroll to position but centring the target residue. Also set a state flag
897      * to prevent adjustmentValueChanged performing this recursively.
898      */
899     // setFollowingComplementScroll(true);
900     // this should be scrollToPosition(sr,verticalOffset,
901     scrollToPosition(sr, seqOffset, true, true);
902   }
903
904   private void sendViewPosition()
905   {
906     StructureSelectionManager.getStructureSelectionManager(av.applet)
907             .sendViewPosition(this, vpRanges.getStartRes(),
908                     vpRanges.getEndRes(), vpRanges.getStartSeq(),
909                     vpRanges.getEndSeq());
910   }
911
912   /**
913    * Repaint the alignment and annotations, and, optionally, any overview window
914    */
915   @Override
916   public void paintAlignment(boolean updateOverview)
917   {
918     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
919             av.isShowAutocalculatedAbove());
920     sorter.sort(getAlignment().getAlignmentAnnotation(),
921             av.getSortAnnotationsBy());
922     repaint();
923
924     if (updateOverview)
925     {
926       // TODO: determine if this paintAlignment changed structure colours
927       jalview.structure.StructureSelectionManager
928               .getStructureSelectionManager(av.applet)
929               .sequenceColoursChanged(this);
930
931       if (overviewPanel != null)
932       {
933         overviewPanel.updateOverviewImage();
934       }
935     }
936   }
937
938   @Override
939   public void update(Graphics g)
940   {
941     paint(g);
942   }
943
944   @Override
945   public void paint(Graphics g)
946   {
947     invalidate();
948     Dimension d = idPanel.idCanvas.getSize();
949     final int canvasHeight = seqPanel.seqCanvas.getSize().height;
950     if (canvasHeight != d.height)
951     {
952       idPanel.idCanvas.setSize(d.width, canvasHeight);
953     }
954
955     setScrollValues(vpRanges.getStartRes(), vpRanges.getStartSeq());
956
957     seqPanel.seqCanvas.repaint();
958     idPanel.idCanvas.repaint();
959     if (!av.getWrapAlignment())
960     {
961       if (av.isShowAnnotation())
962       {
963         alabels.repaint();
964         annotationPanel.repaint();
965       }
966       scalePanel.repaint();
967     }
968
969   }
970
971   /*
972    * Set vertical scroll bar parameters for wrapped panel
973    * @param res 
974    *    the residue to scroll to
975    */
976   private void setScrollingForWrappedPanel(int res)
977   {
978     // get the width of the alignment in residues
979     int maxwidth = av.getAlignment().getWidth();
980     if (av.hasHiddenColumns())
981     {
982       maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
983     }
984
985     // get the width of the canvas in residues
986     int canvasWidth = seqPanel.seqCanvas
987             .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
988     if (canvasWidth > 0)
989     {
990       // position we want to scroll to is number of canvasWidth's to get there
991       int current = res / canvasWidth;
992
993       // max scroll position: add one because extent is 1 and scrollbar value
994       // can only be set to at most max - extent
995       int max = maxwidth / canvasWidth + 1;
996       vscroll.setUnitIncrement(1);
997       vscroll.setValues(current, 1, 0, max);
998     }
999   }
1000
1001   protected Panel sequenceHolderPanel = new Panel();
1002
1003   protected Scrollbar vscroll = new Scrollbar();
1004
1005   protected Scrollbar hscroll = new Scrollbar();
1006
1007   protected Panel seqPanelHolder = new Panel();
1008
1009   protected Panel scalePanelHolder = new Panel();
1010
1011   protected Panel idPanelHolder = new Panel();
1012
1013   protected Panel idSpaceFillerPanel1 = new Panel();
1014
1015   public Panel annotationSpaceFillerHolder = new Panel();
1016
1017   protected Panel hscrollFillerPanel = new Panel();
1018
1019   Panel annotationPanelHolder = new Panel();
1020
1021   protected Scrollbar apvscroll = new Scrollbar();
1022
1023   /*
1024    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
1025    * false, suppresses invoking the same method recursively.
1026    */
1027   private boolean scrollComplementaryPanel = true;
1028
1029   private void jbInit() throws Exception
1030   {
1031     // idPanelHolder.setPreferredSize(new Dimension(70, 10));
1032     this.setLayout(new BorderLayout());
1033
1034     // sequenceHolderPanel.setPreferredSize(new Dimension(150, 150));
1035     sequenceHolderPanel.setLayout(new BorderLayout());
1036     seqPanelHolder.setLayout(new BorderLayout());
1037     scalePanelHolder.setBackground(Color.white);
1038
1039     // scalePanelHolder.setPreferredSize(new Dimension(10, 30));
1040     scalePanelHolder.setLayout(new BorderLayout());
1041     idPanelHolder.setLayout(new BorderLayout());
1042     idSpaceFillerPanel1.setBackground(Color.white);
1043
1044     // idSpaceFillerPanel1.setPreferredSize(new Dimension(10, 30));
1045     idSpaceFillerPanel1.setLayout(new BorderLayout());
1046     annotationSpaceFillerHolder.setBackground(Color.white);
1047
1048     // annotationSpaceFillerHolder.setPreferredSize(new Dimension(10, 80));
1049     annotationSpaceFillerHolder.setLayout(new BorderLayout());
1050     hscroll.setOrientation(Scrollbar.HORIZONTAL);
1051
1052     Panel hscrollHolder = new Panel();
1053     hscrollHolder.setLayout(new BorderLayout());
1054     hscrollFillerPanel.setBackground(Color.white);
1055     apvscroll.setOrientation(Scrollbar.VERTICAL);
1056     apvscroll.setVisible(true);
1057     apvscroll.addAdjustmentListener(this);
1058
1059     annotationPanelHolder.setBackground(Color.white);
1060     annotationPanelHolder.setLayout(new BorderLayout());
1061     annotationPanelHolder.add(apvscroll, BorderLayout.EAST);
1062     // hscrollFillerPanel.setPreferredSize(new Dimension(70, 10));
1063     hscrollHolder.setBackground(Color.white);
1064
1065     // annotationScroller.setPreferredSize(new Dimension(10, 80));
1066     // this.setPreferredSize(new Dimension(220, 166));
1067     seqPanelHolder.setBackground(Color.white);
1068     idPanelHolder.setBackground(Color.white);
1069     sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH);
1070     sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER);
1071     seqPanelHolder.add(vscroll, BorderLayout.EAST);
1072
1073     // Panel3.add(secondaryPanelHolder, BorderLayout.SOUTH);
1074     this.add(idPanelHolder, BorderLayout.WEST);
1075     idPanelHolder.add(idSpaceFillerPanel1, BorderLayout.NORTH);
1076     idPanelHolder.add(annotationSpaceFillerHolder, BorderLayout.SOUTH);
1077     this.add(hscrollHolder, BorderLayout.SOUTH);
1078     hscrollHolder.add(hscroll, BorderLayout.CENTER);
1079     hscrollHolder.add(hscrollFillerPanel, BorderLayout.WEST);
1080     this.add(sequenceHolderPanel, BorderLayout.CENTER);
1081   }
1082
1083   /**
1084    * hides or shows dynamic annotation rows based on groups and av state flags
1085    */
1086   public void updateAnnotation()
1087   {
1088     updateAnnotation(false);
1089   }
1090
1091   public void updateAnnotation(boolean applyGlobalSettings)
1092   {
1093     updateAnnotation(applyGlobalSettings, false);
1094   }
1095
1096   public void updateAnnotation(boolean applyGlobalSettings,
1097           boolean preserveNewGroupSettings)
1098   {
1099     av.updateGroupAnnotationSettings(applyGlobalSettings,
1100             preserveNewGroupSettings);
1101     adjustAnnotationHeight();
1102   }
1103
1104   @Override
1105   public AlignmentI getAlignment()
1106   {
1107     return av.getAlignment();
1108   }
1109
1110   @Override
1111   public String getViewName()
1112   {
1113     return getName();
1114   }
1115
1116   @Override
1117   public StructureSelectionManager getStructureSelectionManager()
1118   {
1119     return StructureSelectionManager
1120             .getStructureSelectionManager(av.applet);
1121   }
1122
1123   @Override
1124   public void raiseOOMWarning(String string, OutOfMemoryError error)
1125   {
1126     // TODO: JAL-960
1127     System.err.println("Out of memory whilst '" + string + "'");
1128     error.printStackTrace();
1129   }
1130
1131   /**
1132    * Set a flag to say we are scrolling to follow a (cDNA/protein) complement.
1133    * 
1134    * @param b
1135    */
1136   protected void setToScrollComplementPanel(boolean b)
1137   {
1138     this.scrollComplementaryPanel = b;
1139   }
1140
1141   protected boolean isSetToScrollComplementPanel()
1142   {
1143     return this.scrollComplementaryPanel;
1144   }
1145
1146   @Override
1147   /**
1148    * Property change event fired when a change is made to the viewport ranges 
1149    * object associated with this alignment panel's viewport
1150    */
1151   public void propertyChange(PropertyChangeEvent evt)
1152   {
1153     // update this panel's scroll values based on the new viewport ranges values
1154     int x = vpRanges.getStartRes();
1155     int y = vpRanges.getStartSeq();
1156     setScrollValues(x, y);
1157
1158     // now update any complementary alignment (its viewport ranges object
1159     // is different so does not get automatically updated)
1160     if (isSetToScrollComplementPanel())
1161     {
1162       setToScrollComplementPanel(false);
1163       av.scrollComplementaryAlignment(getComplementPanel());
1164       setToScrollComplementPanel(true);
1165     }
1166
1167   }
1168
1169 }