5a2c5ef4d5d2bf9101b6c380c57918e49aef53d9
[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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
26 import java.awt.FontMetrics;
27 import java.awt.Frame;
28 import java.awt.Graphics;
29 import java.awt.Panel;
30 import java.awt.Scrollbar;
31 import java.awt.event.AdjustmentEvent;
32 import java.awt.event.AdjustmentListener;
33 import java.awt.event.ComponentAdapter;
34 import java.awt.event.ComponentEvent;
35 import java.util.List;
36
37 import jalview.analysis.AnnotationSorter;
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.bin.JalviewLite;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.SearchResults;
43 import jalview.datamodel.SequenceI;
44 import jalview.structure.StructureSelectionManager;
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     try
88     {
89       jbInit();
90     } catch (Exception e)
91     {
92       e.printStackTrace();
93     }
94
95     alignFrame = af;
96     this.av = av;
97     seqPanel = new SeqPanel(av, this);
98     idPanel = new IdPanel(av, this);
99     scalePanel = new ScalePanel(av, this);
100     idwidthAdjuster = new IdwidthAdjuster(this);
101     annotationPanel = new AnnotationPanel(this);
102     annotationPanelHolder.add(annotationPanel, BorderLayout.CENTER);
103
104     sequenceHolderPanel.add(annotationPanelHolder, BorderLayout.SOUTH);
105     alabels = new AnnotationLabels(this);
106
107     setAnnotationVisible(av.isShowAnnotation());
108
109     idPanelHolder.add(idPanel, BorderLayout.CENTER);
110     idSpaceFillerPanel1.add(idwidthAdjuster, BorderLayout.CENTER);
111     annotationSpaceFillerHolder.add(alabels, BorderLayout.CENTER);
112     scalePanelHolder.add(scalePanel, BorderLayout.CENTER);
113     seqPanelHolder.add(seqPanel, BorderLayout.CENTER);
114
115     fontChanged();
116     setScrollValues(0, 0);
117
118     apvscroll.addAdjustmentListener(this);
119     hscroll.addAdjustmentListener(this);
120     vscroll.addAdjustmentListener(this);
121
122     addComponentListener(new ComponentAdapter()
123     {
124       public void componentResized(ComponentEvent evt)
125       {
126         setScrollValues(av.getStartRes(), av.getStartSeq());
127         if (getSize().height > 0
128                 && annotationPanelHolder.getSize().height > 0)
129         {
130           validateAnnotationDimensions(false);
131         }
132         repaint();
133       }
134
135     });
136
137     Dimension d = calculateIdWidth();
138     idPanel.idCanvas.setSize(d);
139
140     hscrollFillerPanel.setSize(d.width, annotationPanel.getSize().height);
141
142     idPanel.idCanvas.setSize(d.width, seqPanel.seqCanvas.getSize().height);
143     annotationSpaceFillerHolder.setSize(d.width,
144             annotationPanel.getSize().height);
145     alabels.setSize(d.width, annotationPanel.getSize().height);
146     final AlignmentPanel ap = this;
147     av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
148     {
149       public void propertyChange(java.beans.PropertyChangeEvent evt)
150       {
151         if (evt.getPropertyName().equals("alignment"))
152         {
153           PaintRefresher.Refresh(ap, av.getSequenceSetId(), true, true);
154           alignmentChanged();
155         }
156       }
157     });
158   }
159
160   @Override
161   public AlignViewportI getAlignViewport()
162   {
163     return av;
164   }
165   public SequenceRenderer getSequenceRenderer()
166   {
167     return seqPanel.seqCanvas.sr;
168   }
169   @Override
170   public jalview.api.FeatureRenderer getFeatureRenderer()
171   {
172     return seqPanel.seqCanvas.fr;
173   }
174   @Override
175   public jalview.api.FeatureRenderer cloneFeatureRenderer()
176   {
177     FeatureRenderer nfr = new FeatureRenderer(av);
178     nfr.transferSettings(seqPanel.seqCanvas.fr);
179     return nfr;
180   }
181   public void alignmentChanged()
182   {
183     av.alignmentChanged(this);
184
185     if (overviewPanel != null)
186     {
187       overviewPanel.updateOverviewImage();
188     }
189
190     alignFrame.updateEditMenuBar();
191
192     repaint();
193   }
194
195   public void fontChanged()
196   {
197     // set idCanvas bufferedImage to null
198     // to prevent drawing old image
199     idPanel.idCanvas.image = null;
200     FontMetrics fm = getFontMetrics(av.getFont());
201
202     scalePanel.setSize(new Dimension(10, av.getCharHeight()
203             + fm.getDescent()));
204     idwidthAdjuster.setSize(new Dimension(10, av.getCharHeight()
205             + fm.getDescent()));
206     av.updateSequenceIdColours();
207     annotationPanel.image = null;
208     int ap = annotationPanel.adjustPanelHeight(false);
209     Dimension d = calculateIdWidth();
210     d.setSize(d.width + 4, seqPanel.seqCanvas.getSize().height);
211     alabels.setSize(d.width + 4, ap);
212
213     idPanel.idCanvas.setSize(d);
214     hscrollFillerPanel.setSize(d);
215
216     validateAnnotationDimensions(false);
217     annotationPanel.repaint();
218     validate();
219     repaint();
220
221     if (overviewPanel != null)
222     {
223       overviewPanel.updateOverviewImage();
224     }
225   }
226
227   public void setIdWidth(int w, int h)
228   {
229     idPanel.idCanvas.setSize(w, h);
230     idPanelHolder.setSize(w, idPanelHolder.getSize().height);
231     annotationSpaceFillerHolder.setSize(w,
232             annotationSpaceFillerHolder.getSize().height);
233     alabels.setSize(w, alabels.getSize().height);
234     validate();
235   }
236
237   Dimension calculateIdWidth()
238   {
239     if (av.nullFrame == null)
240     {
241       av.nullFrame = new Frame();
242       av.nullFrame.addNotify();
243     }
244
245     Graphics g = av.nullFrame.getGraphics();
246
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     boolean modified = false;
561     int height = av.calcPanelHeight();
562     int minsize = 0;
563     if (hscroll.isVisible())
564     {
565       height += (minsize = hscroll.getPreferredSize().height);
566     }
567     if (apvscroll.isVisible())
568     {
569       minsize += apvscroll.getPreferredSize().height;
570     }
571     int mheight = height;
572     Dimension d = sequenceHolderPanel.getSize(), e = idPanel.getSize();
573     int seqandannot = d.height - scalePanelHolder.getSize().height;
574
575     if (adjustPanelHeight)
576     {
577       // NOTE: this logic is different in the application. Need a better
578       // algorithm to define behaviour
579       // sets initial preferred height
580       // try and set height according to alignment
581       float sscaling = (float) ((av.getCharHeight() * av.getAlignment()
582               .getHeight()) / (1.0 * mheight));
583       if (sscaling > 0.5)
584       {
585         // if the alignment is too big then
586         // default is 0.5 split
587         height = seqandannot / 2;
588       }
589       else
590       {
591         // otherwise just set the panel so that one row of sequence is visible
592         height = -av.getCharHeight() * 1
593                 + (int) (seqandannot * (1 - sscaling));
594       }
595     }
596     else
597     {
598       // maintain same window layout whilst updating sliders
599       height = annotationPanelHolder.getSize().height;
600     }
601
602     if (seqandannot - height < 5)
603     {
604       height = seqandannot;
605     }
606     annotationPanel.setSize(new Dimension(d.width, height));
607     alabels.setSize(new Dimension(e.width, height));
608     annotationSpaceFillerHolder.setSize(new Dimension(e.width, height));
609     annotationPanelHolder.setSize(new Dimension(d.width, height));
610     // seqPanelHolder.setSize(d.width, seqandannot - height);
611     seqPanel.seqCanvas
612             .setSize(d.width, seqPanel.seqCanvas.getSize().height);
613     int s = apvscroll.getValue();
614     if (s > mheight - height)
615     {
616       s = 0;
617     }
618     apvscroll.setValues(s, height, 0, mheight);
619     annotationPanel.setScrollOffset(apvscroll.getValue(), false);
620     alabels.setScrollOffset(apvscroll.getValue(), false);
621   }
622
623   public void setWrapAlignment(boolean wrap)
624   {
625     av.startSeq = 0;
626     av.startRes = 0;
627     scalePanelHolder.setVisible(!wrap);
628
629     hscroll.setVisible(!wrap);
630     idwidthAdjuster.setVisible(!wrap);
631
632     if (wrap)
633     {
634       annotationPanelHolder.setVisible(false);
635       annotationSpaceFillerHolder.setVisible(false);
636     }
637     else if (av.isShowAnnotation())
638     {
639       annotationPanelHolder.setVisible(true);
640       annotationSpaceFillerHolder.setVisible(true);
641     }
642
643     idSpaceFillerPanel1.setVisible(!wrap);
644
645     fontChanged(); // This is so that the scalePanel is resized correctly
646
647     validate();
648     sequenceHolderPanel.validate();
649     repaint();
650
651   }
652
653   int hextent = 0;
654
655   int vextent = 0;
656
657   // return value is true if the scroll is valid
658   public boolean scrollUp(boolean up)
659   {
660     if (up)
661     {
662       if (vscroll.getValue() < 1)
663       {
664         return false;
665       }
666       setScrollValues(hscroll.getValue(), vscroll.getValue() - 1);
667     }
668     else
669     {
670       if (vextent + vscroll.getValue() >= av.getAlignment().getHeight())
671       {
672         return false;
673       }
674       setScrollValues(hscroll.getValue(), vscroll.getValue() + 1);
675     }
676
677     repaint();
678     return true;
679   }
680
681   public boolean scrollRight(boolean right)
682   {
683     if (!right)
684     {
685       if (hscroll.getValue() < 1)
686       {
687         return false;
688       }
689       setScrollValues(hscroll.getValue() - 1, vscroll.getValue());
690     }
691     else
692     {
693       if (hextent + hscroll.getValue() >= av.getAlignment().getWidth())
694       {
695         return false;
696       }
697       setScrollValues(hscroll.getValue() + 1, vscroll.getValue());
698     }
699
700     repaint();
701     return true;
702   }
703
704   public void setScrollValues(int x, int y)
705   {
706     int width = av.getAlignment().getWidth();
707     int height = av.getAlignment().getHeight();
708
709     if (av.hasHiddenColumns())
710     {
711       width = av.getColumnSelection().findColumnPosition(width);
712     }
713     if (x < 0)
714     {
715       x = 0;
716     }
717     ;
718
719     hextent = seqPanel.seqCanvas.getSize().width / av.getCharWidth();
720     vextent = seqPanel.seqCanvas.getSize().height / av.getCharHeight();
721
722     if (hextent > width)
723     {
724       hextent = width;
725     }
726
727     if (vextent > height)
728     {
729       vextent = height;
730     }
731
732     if ((hextent + x) > width)
733     {
734       System.err.println("hextent was " + hextent + " and x was " + x);
735
736       x = width - hextent;
737     }
738
739     if ((vextent + y) > height)
740     {
741       y = height - vextent;
742     }
743
744     if (y < 0)
745     {
746       y = 0;
747     }
748
749     if (x < 0)
750     {
751       System.err.println("x was " + x);
752       x = 0;
753     }
754
755     av.setStartSeq(y);
756
757     int endSeq = y + vextent;
758     if (endSeq > av.getAlignment().getHeight())
759     {
760       endSeq = av.getAlignment().getHeight();
761     }
762
763     av.setEndSeq(endSeq);
764     av.setStartRes(x);
765     av.setEndRes((x + (seqPanel.seqCanvas.getSize().width / av
766             .getCharWidth())) - 1);
767
768     hscroll.setValues(x, hextent, 0, width);
769     vscroll.setValues(y, vextent, 0, height);
770
771     if (overviewPanel != null)
772     {
773       overviewPanel.setBoxPosition();
774     }
775     sendViewPosition();
776
777   }
778
779   public void adjustmentValueChanged(AdjustmentEvent evt)
780   {
781     int oldX = av.getStartRes();
782     int oldY = av.getStartSeq();
783
784     if (evt == null || evt.getSource() == apvscroll)
785     {
786       annotationPanel.setScrollOffset(apvscroll.getValue(), false);
787       alabels.setScrollOffset(apvscroll.getValue(), false);
788       // annotationPanel.image=null;
789       // alabels.image=null;
790       // alabels.repaint();
791       // annotationPanel.repaint();
792     }
793     if (evt == null || evt.getSource() == hscroll)
794     {
795       int x = hscroll.getValue();
796       av.setStartRes(x);
797       av.setEndRes(x + seqPanel.seqCanvas.getSize().width
798               / av.getCharWidth() - 1);
799     }
800
801     if (evt == null || evt.getSource() == vscroll)
802     {
803       int offy = vscroll.getValue();
804       if (av.getWrapAlignment())
805       {
806         int rowSize = seqPanel.seqCanvas
807                 .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
808         av.setStartRes(vscroll.getValue() * rowSize);
809         av.setEndRes((vscroll.getValue() + 1) * rowSize);
810       }
811       else
812       {
813         av.setStartSeq(offy);
814         av.setEndSeq(offy + seqPanel.seqCanvas.getSize().height
815                 / av.getCharHeight());
816       }
817     }
818
819     if (overviewPanel != null)
820     {
821       overviewPanel.setBoxPosition();
822     }
823
824     int scrollX = av.startRes - oldX;
825     int scrollY = av.startSeq - oldY;
826
827     if (av.getWrapAlignment() || !fastPaint || av.MAC)
828     {
829       repaint();
830     }
831     else
832     {
833       // Make sure we're not trying to draw a panel
834       // larger than the visible window
835       if (scrollX > av.endRes - av.startRes)
836       {
837         scrollX = av.endRes - av.startRes;
838       }
839       else if (scrollX < av.startRes - av.endRes)
840       {
841         scrollX = av.startRes - av.endRes;
842       }
843
844       idPanel.idCanvas.fastPaint(scrollY);
845       seqPanel.seqCanvas.fastPaint(scrollX, scrollY);
846
847       scalePanel.repaint();
848       if (av.isShowAnnotation())
849       {
850         annotationPanel.fastPaint(av.getStartRes() - oldX);
851       }
852     }
853     sendViewPosition();
854
855     /*
856      * If there is one, scroll the (Protein/cDNA) complementary alignment to
857      * match, unless we are ourselves doing that.
858      */
859     if (isFollowingComplementScroll())
860     {
861       setFollowingComplementScroll(false);
862     }
863     else
864     {
865       AlignmentPanel ap = getComplementPanel();
866       av.scrollComplementaryAlignment(ap);
867     }
868
869   }
870
871   /**
872    * A helper method to return the AlignmentPanel in the other (complementary)
873    * half of a SplitFrame view. Returns null if not in a SplitFrame.
874    * 
875    * @return
876    */
877   private AlignmentPanel getComplementPanel()
878   {
879     AlignmentPanel ap = null;
880     if (alignFrame != null)
881     {
882       SplitFrame sf = alignFrame.getSplitFrame();
883       if (sf != null)
884       {
885         AlignFrame other = sf.getComplement(alignFrame);
886         if (other != null)
887         {
888           ap = other.alignPanel;
889         }
890       }
891     }
892     return ap;
893   }
894
895   /**
896    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
897    * The aim is to keep the two alignments 'lined up' on their centre columns.
898    * 
899    * @param sr
900    *          holds mapped region(s) of this alignment that we are scrolling
901    *          'to'; may be modified for sequence offset by this method
902    * @param seqOffset
903    *          the number of visible sequences to show above the mapped region
904    */
905   protected void scrollToCentre(SearchResults sr, int seqOffset)
906   {
907     /*
908      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
909      * mapped), we can make the scroll-to location a sequence above the one
910      * actually mapped.
911      */
912     SequenceI mappedTo = sr.getResultSequence(0);
913     List<SequenceI> seqs = av.getAlignment().getSequences();
914
915     /*
916      * This is like AlignmentI.findIndex(seq) but here we are matching the
917      * dataset sequence not the aligned sequence
918      */
919     int sequenceIndex = 0;
920     boolean matched = false;
921     for (SequenceI seq : seqs)
922     {
923       if (mappedTo == seq.getDatasetSequence())
924       {
925         matched = true;
926         break;
927       }
928       sequenceIndex++;
929     }
930     if (!matched)
931     {
932       return; // failsafe, shouldn't happen
933     }
934     sequenceIndex = Math.max(0, sequenceIndex - seqOffset);
935     sr.getResults().get(0)
936             .setSequence(av.getAlignment().getSequenceAt(sequenceIndex));
937
938     /*
939      * Scroll to position but centring the target residue. Also set a state flag
940      * to prevent adjustmentValueChanged performing this recursively.
941      */
942     setFollowingComplementScroll(true);
943     scrollToPosition(sr, true, true);
944   }
945
946   private void sendViewPosition()
947   {
948     StructureSelectionManager.getStructureSelectionManager(av.applet)
949             .sendViewPosition(this, av.startRes, av.endRes, av.startSeq,
950                     av.endSeq);
951   }
952
953   /**
954    * Repaint the alignment and annotations, and, optionally, any overview window
955    */
956   public void paintAlignment(boolean updateOverview)
957   {
958     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
959             av.isShowAutocalculatedAbove());
960     sorter.sort(getAlignment().getAlignmentAnnotation(),
961             av.getSortAnnotationsBy());
962     repaint();
963
964     if (updateOverview)
965     {
966       jalview.structure.StructureSelectionManager
967               .getStructureSelectionManager(av.applet)
968               .sequenceColoursChanged(this);
969
970       if (overviewPanel != null)
971       {
972         overviewPanel.updateOverviewImage();
973       }
974     }
975   }
976
977   public void update(Graphics g)
978   {
979     paint(g);
980   }
981
982   public void paint(Graphics g)
983   {
984     invalidate();
985     Dimension d = idPanel.idCanvas.getSize();
986     idPanel.idCanvas.setSize(d.width, seqPanel.seqCanvas.getSize().height);
987
988     if (av.getWrapAlignment())
989     {
990       int maxwidth = av.getAlignment().getWidth();
991
992       if (av.hasHiddenColumns())
993       {
994         maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
995       }
996
997       int canvasWidth = seqPanel.seqCanvas
998               .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
999
1000       if (canvasWidth > 0)
1001       {
1002         int max = maxwidth / canvasWidth;
1003         vscroll.setMaximum(1 + max);
1004         vscroll.setUnitIncrement(1);
1005         vscroll.setVisibleAmount(1);
1006       }
1007     }
1008     else
1009     {
1010       setScrollValues(av.getStartRes(), av.getStartSeq());
1011     }
1012
1013     seqPanel.seqCanvas.repaint();
1014     idPanel.idCanvas.repaint();
1015     if (!av.getWrapAlignment())
1016     {
1017       if (av.isShowAnnotation())
1018       {
1019         alabels.repaint();
1020         annotationPanel.repaint();
1021       }
1022       scalePanel.repaint();
1023     }
1024
1025   }
1026
1027   protected Panel sequenceHolderPanel = new Panel();
1028
1029   protected Scrollbar vscroll = new Scrollbar();
1030
1031   protected Scrollbar hscroll = new Scrollbar();
1032
1033   protected Panel seqPanelHolder = new Panel();
1034
1035   protected Panel scalePanelHolder = new Panel();
1036
1037   protected Panel idPanelHolder = new Panel();
1038
1039   protected Panel idSpaceFillerPanel1 = new Panel();
1040
1041   public Panel annotationSpaceFillerHolder = new Panel();
1042
1043   protected Panel hscrollFillerPanel = new Panel();
1044
1045   Panel annotationPanelHolder = new Panel();
1046
1047   protected Scrollbar apvscroll = new Scrollbar();
1048
1049   /*
1050    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
1051    * true, suppresses invoking the same method recursively.
1052    */
1053   private boolean followingComplementScroll;
1054
1055   private void jbInit() throws Exception
1056   {
1057     // idPanelHolder.setPreferredSize(new Dimension(70, 10));
1058     this.setLayout(new BorderLayout());
1059
1060     // sequenceHolderPanel.setPreferredSize(new Dimension(150, 150));
1061     sequenceHolderPanel.setLayout(new BorderLayout());
1062     seqPanelHolder.setLayout(new BorderLayout());
1063     scalePanelHolder.setBackground(Color.white);
1064
1065     // scalePanelHolder.setPreferredSize(new Dimension(10, 30));
1066     scalePanelHolder.setLayout(new BorderLayout());
1067     idPanelHolder.setLayout(new BorderLayout());
1068     idSpaceFillerPanel1.setBackground(Color.white);
1069
1070     // idSpaceFillerPanel1.setPreferredSize(new Dimension(10, 30));
1071     idSpaceFillerPanel1.setLayout(new BorderLayout());
1072     annotationSpaceFillerHolder.setBackground(Color.white);
1073
1074     // annotationSpaceFillerHolder.setPreferredSize(new Dimension(10, 80));
1075     annotationSpaceFillerHolder.setLayout(new BorderLayout());
1076     hscroll.setOrientation(Scrollbar.HORIZONTAL);
1077
1078     Panel hscrollHolder = new Panel();
1079     hscrollHolder.setLayout(new BorderLayout());
1080     hscrollFillerPanel.setBackground(Color.white);
1081     apvscroll.setOrientation(Scrollbar.VERTICAL);
1082     apvscroll.setVisible(true);
1083     apvscroll.addAdjustmentListener(this);
1084
1085     annotationPanelHolder.setBackground(Color.white);
1086     annotationPanelHolder.setLayout(new BorderLayout());
1087     annotationPanelHolder.add(apvscroll, BorderLayout.EAST);
1088     // hscrollFillerPanel.setPreferredSize(new Dimension(70, 10));
1089     hscrollHolder.setBackground(Color.white);
1090
1091     // annotationScroller.setPreferredSize(new Dimension(10, 80));
1092     // this.setPreferredSize(new Dimension(220, 166));
1093     seqPanelHolder.setBackground(Color.white);
1094     idPanelHolder.setBackground(Color.white);
1095     sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH);
1096     sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER);
1097     seqPanelHolder.add(vscroll, BorderLayout.EAST);
1098
1099     // Panel3.add(secondaryPanelHolder, BorderLayout.SOUTH);
1100     this.add(idPanelHolder, BorderLayout.WEST);
1101     idPanelHolder.add(idSpaceFillerPanel1, BorderLayout.NORTH);
1102     idPanelHolder.add(annotationSpaceFillerHolder, BorderLayout.SOUTH);
1103     this.add(hscrollHolder, BorderLayout.SOUTH);
1104     hscrollHolder.add(hscroll, BorderLayout.CENTER);
1105     hscrollHolder.add(hscrollFillerPanel, BorderLayout.WEST);
1106     this.add(sequenceHolderPanel, BorderLayout.CENTER);
1107   }
1108
1109   /**
1110    * hides or shows dynamic annotation rows based on groups and av state flags
1111    */
1112   public void updateAnnotation()
1113   {
1114     updateAnnotation(false);
1115   }
1116
1117   public void updateAnnotation(boolean applyGlobalSettings)
1118   {
1119     updateAnnotation(applyGlobalSettings, false);
1120   }
1121
1122   public void updateAnnotation(boolean applyGlobalSettings,
1123           boolean preserveNewGroupSettings)
1124   {
1125     av.updateGroupAnnotationSettings(applyGlobalSettings,
1126             preserveNewGroupSettings);
1127     adjustAnnotationHeight();
1128   }
1129
1130   @Override
1131   public AlignmentI getAlignment()
1132   {
1133     return av.getAlignment();
1134   }
1135
1136   @Override
1137   public String getViewName()
1138   {
1139     return getName();
1140   }
1141
1142   @Override
1143   public StructureSelectionManager getStructureSelectionManager()
1144   {
1145     return StructureSelectionManager
1146             .getStructureSelectionManager(av.applet);
1147   }
1148
1149   @Override
1150   public void raiseOOMWarning(String string, OutOfMemoryError error)
1151   {
1152     // TODO: JAL-960
1153     System.err.println("Out of memory whilst '" + string + "'");
1154     error.printStackTrace();
1155   }
1156
1157   /**
1158    * Set a flag to say we are scrolling to follow a (cDNA/protein) complement.
1159    * 
1160    * @param b
1161    */
1162   protected void setFollowingComplementScroll(boolean b)
1163   {
1164     this.followingComplementScroll = b;
1165   }
1166
1167   protected boolean isFollowingComplementScroll()
1168   {
1169     return this.followingComplementScroll;
1170   }
1171
1172 }