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