JAL-1799 equivalent logic in applet
[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.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 java.awt.Frame;
37 import java.awt.Graphics;
38 import java.awt.Panel;
39 import java.awt.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     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     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.getSize().height;
568     if (hscroll.isVisible())
569     {
570       availableHeight -= hscroll.getPreferredSize().height;
571     }
572
573     if (adjustPanelHeight)
574     {
575       /*
576        * If not enough vertical space, maximize annotation height while keeping
577        * at least two rows of alignment visible
578        */
579       if (annotationHeight + alignmentHeight > availableHeight)
580       {
581         annotationHeight = Math.min(annotationHeight, availableHeight - 2
582                 * rowHeight);
583       }
584     }
585     else
586     {
587       // maintain same window layout whilst updating sliders
588       annotationHeight = annotationPanelHolder.getSize().height;
589     }
590
591     if (availableHeight - annotationHeight < 5)
592     {
593       annotationHeight = availableHeight;
594     }
595
596     annotationPanel.setSize(new Dimension(d.width, annotationHeight));
597     annotationPanelHolder.setSize(new Dimension(d.width, annotationHeight));
598     // seqPanelHolder.setSize(d.width, seqandannot - height);
599     seqPanel.seqCanvas
600             .setSize(d.width, seqPanel.seqCanvas.getSize().height);
601
602     Dimension e = idPanel.getSize();
603     alabels.setSize(new Dimension(e.width, annotationHeight));
604     annotationSpaceFillerHolder.setSize(new Dimension(e.width,
605             annotationHeight));
606
607     int s = apvscroll.getValue();
608     if (s > mheight - annotationHeight)
609     {
610       s = 0;
611     }
612     apvscroll.setValues(s, annotationHeight, 0, mheight);
613     annotationPanel.setScrollOffset(apvscroll.getValue(), false);
614     alabels.setScrollOffset(apvscroll.getValue(), false);
615   }
616
617   public void setWrapAlignment(boolean wrap)
618   {
619     av.startSeq = 0;
620     av.startRes = 0;
621     scalePanelHolder.setVisible(!wrap);
622
623     hscroll.setVisible(!wrap);
624     idwidthAdjuster.setVisible(!wrap);
625
626     if (wrap)
627     {
628       annotationPanelHolder.setVisible(false);
629       annotationSpaceFillerHolder.setVisible(false);
630     }
631     else if (av.isShowAnnotation())
632     {
633       annotationPanelHolder.setVisible(true);
634       annotationSpaceFillerHolder.setVisible(true);
635     }
636
637     idSpaceFillerPanel1.setVisible(!wrap);
638
639     fontChanged(); // This is so that the scalePanel is resized correctly
640
641     validate();
642     sequenceHolderPanel.validate();
643     repaint();
644
645   }
646
647   int hextent = 0;
648
649   int vextent = 0;
650
651   // return value is true if the scroll is valid
652   public boolean scrollUp(boolean up)
653   {
654     if (up)
655     {
656       if (vscroll.getValue() < 1)
657       {
658         return false;
659       }
660       setScrollValues(hscroll.getValue(), vscroll.getValue() - 1);
661     }
662     else
663     {
664       if (vextent + vscroll.getValue() >= av.getAlignment().getHeight())
665       {
666         return false;
667       }
668       setScrollValues(hscroll.getValue(), vscroll.getValue() + 1);
669     }
670
671     repaint();
672     return true;
673   }
674
675   public boolean scrollRight(boolean right)
676   {
677     if (!right)
678     {
679       if (hscroll.getValue() < 1)
680       {
681         return false;
682       }
683       setScrollValues(hscroll.getValue() - 1, vscroll.getValue());
684     }
685     else
686     {
687       if (hextent + hscroll.getValue() >= av.getAlignment().getWidth())
688       {
689         return false;
690       }
691       setScrollValues(hscroll.getValue() + 1, vscroll.getValue());
692     }
693
694     repaint();
695     return true;
696   }
697
698   public void setScrollValues(int x, int y)
699   {
700     int width = av.getAlignment().getWidth();
701     int height = av.getAlignment().getHeight();
702
703     if (av.hasHiddenColumns())
704     {
705       width = av.getColumnSelection().findColumnPosition(width);
706     }
707     if (x < 0)
708     {
709       x = 0;
710     }
711     ;
712
713     hextent = seqPanel.seqCanvas.getSize().width / av.getCharWidth();
714     vextent = seqPanel.seqCanvas.getSize().height / av.getCharHeight();
715
716     if (hextent > width)
717     {
718       hextent = width;
719     }
720
721     if (vextent > height)
722     {
723       vextent = height;
724     }
725
726     if ((hextent + x) > width)
727     {
728       System.err.println("hextent was " + hextent + " and x was " + x);
729
730       x = width - hextent;
731     }
732
733     if ((vextent + y) > height)
734     {
735       y = height - vextent;
736     }
737
738     if (y < 0)
739     {
740       y = 0;
741     }
742
743     if (x < 0)
744     {
745       System.err.println("x was " + x);
746       x = 0;
747     }
748
749     av.setStartSeq(y);
750
751     int endSeq = y + vextent;
752     if (endSeq > av.getAlignment().getHeight())
753     {
754       endSeq = av.getAlignment().getHeight();
755     }
756
757     av.setEndSeq(endSeq);
758     av.setStartRes(x);
759     av.setEndRes((x + (seqPanel.seqCanvas.getSize().width / av
760             .getCharWidth())) - 1);
761
762     hscroll.setValues(x, hextent, 0, width);
763     vscroll.setValues(y, vextent, 0, height);
764
765     if (overviewPanel != null)
766     {
767       overviewPanel.setBoxPosition();
768     }
769     sendViewPosition();
770
771   }
772
773   public void adjustmentValueChanged(AdjustmentEvent evt)
774   {
775     int oldX = av.getStartRes();
776     int oldY = av.getStartSeq();
777
778     if (evt == null || evt.getSource() == apvscroll)
779     {
780       annotationPanel.setScrollOffset(apvscroll.getValue(), false);
781       alabels.setScrollOffset(apvscroll.getValue(), false);
782       // annotationPanel.image=null;
783       // alabels.image=null;
784       // alabels.repaint();
785       // annotationPanel.repaint();
786     }
787     if (evt == null || evt.getSource() == hscroll)
788     {
789       int x = hscroll.getValue();
790       av.setStartRes(x);
791       av.setEndRes(x + seqPanel.seqCanvas.getSize().width
792               / av.getCharWidth() - 1);
793     }
794
795     if (evt == null || evt.getSource() == vscroll)
796     {
797       int offy = vscroll.getValue();
798       if (av.getWrapAlignment())
799       {
800         int rowSize = seqPanel.seqCanvas
801                 .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
802         av.setStartRes(vscroll.getValue() * rowSize);
803         av.setEndRes((vscroll.getValue() + 1) * rowSize);
804       }
805       else
806       {
807         av.setStartSeq(offy);
808         av.setEndSeq(offy + seqPanel.seqCanvas.getSize().height
809                 / av.getCharHeight());
810       }
811     }
812
813     if (overviewPanel != null)
814     {
815       overviewPanel.setBoxPosition();
816     }
817
818     int scrollX = av.startRes - oldX;
819     int scrollY = av.startSeq - oldY;
820
821     if (av.getWrapAlignment() || !fastPaint || av.MAC)
822     {
823       repaint();
824     }
825     else
826     {
827       // Make sure we're not trying to draw a panel
828       // larger than the visible window
829       if (scrollX > av.endRes - av.startRes)
830       {
831         scrollX = av.endRes - av.startRes;
832       }
833       else if (scrollX < av.startRes - av.endRes)
834       {
835         scrollX = av.startRes - av.endRes;
836       }
837
838       idPanel.idCanvas.fastPaint(scrollY);
839       seqPanel.seqCanvas.fastPaint(scrollX, scrollY);
840
841       scalePanel.repaint();
842       if (av.isShowAnnotation())
843       {
844         annotationPanel.fastPaint(av.getStartRes() - oldX);
845       }
846     }
847     sendViewPosition();
848
849     /*
850      * If there is one, scroll the (Protein/cDNA) complementary alignment to
851      * match, unless we are ourselves doing that.
852      */
853     if (isFollowingComplementScroll())
854     {
855       setFollowingComplementScroll(false);
856     }
857     else
858     {
859       AlignmentPanel ap = getComplementPanel();
860       av.scrollComplementaryAlignment(ap);
861     }
862
863   }
864
865   /**
866    * A helper method to return the AlignmentPanel in the other (complementary)
867    * half of a SplitFrame view. Returns null if not in a SplitFrame.
868    * 
869    * @return
870    */
871   private AlignmentPanel getComplementPanel()
872   {
873     AlignmentPanel ap = null;
874     if (alignFrame != null)
875     {
876       SplitFrame sf = alignFrame.getSplitFrame();
877       if (sf != null)
878       {
879         AlignFrame other = sf.getComplement(alignFrame);
880         if (other != null)
881         {
882           ap = other.alignPanel;
883         }
884       }
885     }
886     return ap;
887   }
888
889   /**
890    * Follow a scrolling change in the (cDNA/Protein) complementary alignment.
891    * The aim is to keep the two alignments 'lined up' on their centre columns.
892    * 
893    * @param sr
894    *          holds mapped region(s) of this alignment that we are scrolling
895    *          'to'; may be modified for sequence offset by this method
896    * @param seqOffset
897    *          the number of visible sequences to show above the mapped region
898    */
899   protected void scrollToCentre(SearchResults sr, int seqOffset)
900   {
901     /*
902      * To avoid jumpy vertical scrolling (if some sequences are gapped or not
903      * mapped), we can make the scroll-to location a sequence above the one
904      * actually mapped.
905      */
906     SequenceI mappedTo = sr.getResultSequence(0);
907     List<SequenceI> seqs = av.getAlignment().getSequences();
908
909     /*
910      * This is like AlignmentI.findIndex(seq) but here we are matching the
911      * dataset sequence not the aligned sequence
912      */
913     int sequenceIndex = 0;
914     boolean matched = false;
915     for (SequenceI seq : seqs)
916     {
917       if (mappedTo == seq.getDatasetSequence())
918       {
919         matched = true;
920         break;
921       }
922       sequenceIndex++;
923     }
924     if (!matched)
925     {
926       return; // failsafe, shouldn't happen
927     }
928     sequenceIndex = Math.max(0, sequenceIndex - seqOffset);
929     sr.getResults().get(0)
930             .setSequence(av.getAlignment().getSequenceAt(sequenceIndex));
931
932     /*
933      * Scroll to position but centring the target residue. Also set a state flag
934      * to prevent adjustmentValueChanged performing this recursively.
935      */
936     setFollowingComplementScroll(true);
937     scrollToPosition(sr, true, true);
938   }
939
940   private void sendViewPosition()
941   {
942     StructureSelectionManager.getStructureSelectionManager(av.applet)
943             .sendViewPosition(this, av.startRes, av.endRes, av.startSeq,
944                     av.endSeq);
945   }
946
947   /**
948    * Repaint the alignment and annotations, and, optionally, any overview window
949    */
950   public void paintAlignment(boolean updateOverview)
951   {
952     final AnnotationSorter sorter = new AnnotationSorter(getAlignment(),
953             av.isShowAutocalculatedAbove());
954     sorter.sort(getAlignment().getAlignmentAnnotation(),
955             av.getSortAnnotationsBy());
956     repaint();
957
958     if (updateOverview)
959     {
960       jalview.structure.StructureSelectionManager
961               .getStructureSelectionManager(av.applet)
962               .sequenceColoursChanged(this);
963
964       if (overviewPanel != null)
965       {
966         overviewPanel.updateOverviewImage();
967       }
968     }
969   }
970
971   public void update(Graphics g)
972   {
973     paint(g);
974   }
975
976   public void paint(Graphics g)
977   {
978     invalidate();
979     Dimension d = idPanel.idCanvas.getSize();
980     final int canvasHeight = seqPanel.seqCanvas.getSize().height;
981     if (canvasHeight != d.height)
982     {
983       idPanel.idCanvas.setSize(d.width, canvasHeight);
984     }
985
986     if (av.getWrapAlignment())
987     {
988       int maxwidth = av.getAlignment().getWidth();
989
990       if (av.hasHiddenColumns())
991       {
992         maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
993       }
994
995       int canvasWidth = seqPanel.seqCanvas
996               .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
997
998       if (canvasWidth > 0)
999       {
1000         int max = maxwidth / canvasWidth;
1001         vscroll.setMaximum(1 + max);
1002         vscroll.setUnitIncrement(1);
1003         vscroll.setVisibleAmount(1);
1004       }
1005     }
1006     else
1007     {
1008       setScrollValues(av.getStartRes(), av.getStartSeq());
1009     }
1010
1011     seqPanel.seqCanvas.repaint();
1012     idPanel.idCanvas.repaint();
1013     if (!av.getWrapAlignment())
1014     {
1015       if (av.isShowAnnotation())
1016       {
1017         alabels.repaint();
1018         annotationPanel.repaint();
1019       }
1020       scalePanel.repaint();
1021     }
1022
1023   }
1024
1025   protected Panel sequenceHolderPanel = new Panel();
1026
1027   protected Scrollbar vscroll = new Scrollbar();
1028
1029   protected Scrollbar hscroll = new Scrollbar();
1030
1031   protected Panel seqPanelHolder = new Panel();
1032
1033   protected Panel scalePanelHolder = new Panel();
1034
1035   protected Panel idPanelHolder = new Panel();
1036
1037   protected Panel idSpaceFillerPanel1 = new Panel();
1038
1039   public Panel annotationSpaceFillerHolder = new Panel();
1040
1041   protected Panel hscrollFillerPanel = new Panel();
1042
1043   Panel annotationPanelHolder = new Panel();
1044
1045   protected Scrollbar apvscroll = new Scrollbar();
1046
1047   /*
1048    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
1049    * true, suppresses invoking the same method recursively.
1050    */
1051   private boolean followingComplementScroll;
1052
1053   private void jbInit() throws Exception
1054   {
1055     // idPanelHolder.setPreferredSize(new Dimension(70, 10));
1056     this.setLayout(new BorderLayout());
1057
1058     // sequenceHolderPanel.setPreferredSize(new Dimension(150, 150));
1059     sequenceHolderPanel.setLayout(new BorderLayout());
1060     seqPanelHolder.setLayout(new BorderLayout());
1061     scalePanelHolder.setBackground(Color.white);
1062
1063     // scalePanelHolder.setPreferredSize(new Dimension(10, 30));
1064     scalePanelHolder.setLayout(new BorderLayout());
1065     idPanelHolder.setLayout(new BorderLayout());
1066     idSpaceFillerPanel1.setBackground(Color.white);
1067
1068     // idSpaceFillerPanel1.setPreferredSize(new Dimension(10, 30));
1069     idSpaceFillerPanel1.setLayout(new BorderLayout());
1070     annotationSpaceFillerHolder.setBackground(Color.white);
1071
1072     // annotationSpaceFillerHolder.setPreferredSize(new Dimension(10, 80));
1073     annotationSpaceFillerHolder.setLayout(new BorderLayout());
1074     hscroll.setOrientation(Scrollbar.HORIZONTAL);
1075
1076     Panel hscrollHolder = new Panel();
1077     hscrollHolder.setLayout(new BorderLayout());
1078     hscrollFillerPanel.setBackground(Color.white);
1079     apvscroll.setOrientation(Scrollbar.VERTICAL);
1080     apvscroll.setVisible(true);
1081     apvscroll.addAdjustmentListener(this);
1082
1083     annotationPanelHolder.setBackground(Color.white);
1084     annotationPanelHolder.setLayout(new BorderLayout());
1085     annotationPanelHolder.add(apvscroll, BorderLayout.EAST);
1086     // hscrollFillerPanel.setPreferredSize(new Dimension(70, 10));
1087     hscrollHolder.setBackground(Color.white);
1088
1089     // annotationScroller.setPreferredSize(new Dimension(10, 80));
1090     // this.setPreferredSize(new Dimension(220, 166));
1091     seqPanelHolder.setBackground(Color.white);
1092     idPanelHolder.setBackground(Color.white);
1093     sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH);
1094     sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER);
1095     seqPanelHolder.add(vscroll, BorderLayout.EAST);
1096
1097     // Panel3.add(secondaryPanelHolder, BorderLayout.SOUTH);
1098     this.add(idPanelHolder, BorderLayout.WEST);
1099     idPanelHolder.add(idSpaceFillerPanel1, BorderLayout.NORTH);
1100     idPanelHolder.add(annotationSpaceFillerHolder, BorderLayout.SOUTH);
1101     this.add(hscrollHolder, BorderLayout.SOUTH);
1102     hscrollHolder.add(hscroll, BorderLayout.CENTER);
1103     hscrollHolder.add(hscrollFillerPanel, BorderLayout.WEST);
1104     this.add(sequenceHolderPanel, BorderLayout.CENTER);
1105   }
1106
1107   /**
1108    * hides or shows dynamic annotation rows based on groups and av state flags
1109    */
1110   public void updateAnnotation()
1111   {
1112     updateAnnotation(false);
1113   }
1114
1115   public void updateAnnotation(boolean applyGlobalSettings)
1116   {
1117     updateAnnotation(applyGlobalSettings, false);
1118   }
1119
1120   public void updateAnnotation(boolean applyGlobalSettings,
1121           boolean preserveNewGroupSettings)
1122   {
1123     av.updateGroupAnnotationSettings(applyGlobalSettings,
1124             preserveNewGroupSettings);
1125     adjustAnnotationHeight();
1126   }
1127
1128   @Override
1129   public AlignmentI getAlignment()
1130   {
1131     return av.getAlignment();
1132   }
1133
1134   @Override
1135   public String getViewName()
1136   {
1137     return getName();
1138   }
1139
1140   @Override
1141   public StructureSelectionManager getStructureSelectionManager()
1142   {
1143     return StructureSelectionManager
1144             .getStructureSelectionManager(av.applet);
1145   }
1146
1147   @Override
1148   public void raiseOOMWarning(String string, OutOfMemoryError error)
1149   {
1150     // TODO: JAL-960
1151     System.err.println("Out of memory whilst '" + string + "'");
1152     error.printStackTrace();
1153   }
1154
1155   /**
1156    * Set a flag to say we are scrolling to follow a (cDNA/protein) complement.
1157    * 
1158    * @param b
1159    */
1160   protected void setFollowingComplementScroll(boolean b)
1161   {
1162     this.followingComplementScroll = b;
1163   }
1164
1165   protected boolean isFollowingComplementScroll()
1166   {
1167     return this.followingComplementScroll;
1168   }
1169
1170 }