JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / appletgui / AlignmentPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
3  * Copyright (C) 2015 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
166   public SequenceRenderer getSequenceRenderer()
167   {
168     return seqPanel.seqCanvas.sr;
169   }
170
171   @Override
172   public jalview.api.FeatureRenderer getFeatureRenderer()
173   {
174     return seqPanel.seqCanvas.fr;
175   }
176
177   @Override
178   public jalview.api.FeatureRenderer cloneFeatureRenderer()
179   {
180     FeatureRenderer nfr = new FeatureRenderer(av);
181     nfr.transferSettings(seqPanel.seqCanvas.fr);
182     return nfr;
183   }
184
185   public void alignmentChanged()
186   {
187     av.alignmentChanged(this);
188
189     if (overviewPanel != null)
190     {
191       overviewPanel.updateOverviewImage();
192     }
193
194     alignFrame.updateEditMenuBar();
195
196     repaint();
197   }
198
199   public void fontChanged()
200   {
201     // set idCanvas bufferedImage to null
202     // to prevent drawing old image
203     idPanel.idCanvas.image = null;
204     FontMetrics fm = getFontMetrics(av.getFont());
205
206     scalePanel.setSize(new Dimension(10, av.getCharHeight()
207             + fm.getDescent()));
208     idwidthAdjuster.setSize(new Dimension(10, av.getCharHeight()
209             + fm.getDescent()));
210     av.updateSequenceIdColours();
211     annotationPanel.image = null;
212     int ap = annotationPanel.adjustPanelHeight(false);
213     Dimension d = calculateIdWidth();
214     d.setSize(d.width + 4, seqPanel.seqCanvas.getSize().height);
215     alabels.setSize(d.width + 4, ap);
216
217     idPanel.idCanvas.setSize(d);
218     hscrollFillerPanel.setSize(d);
219
220     validateAnnotationDimensions(false);
221     annotationPanel.repaint();
222     validate();
223     repaint();
224
225     if (overviewPanel != null)
226     {
227       overviewPanel.updateOverviewImage();
228     }
229   }
230
231   public void setIdWidth(int w, int h)
232   {
233     idPanel.idCanvas.setSize(w, h);
234     idPanelHolder.setSize(w, idPanelHolder.getSize().height);
235     annotationSpaceFillerHolder.setSize(w,
236             annotationSpaceFillerHolder.getSize().height);
237     alabels.setSize(w, alabels.getSize().height);
238     validate();
239   }
240
241   Dimension calculateIdWidth()
242   {
243     if (av.nullFrame == null)
244     {
245       av.nullFrame = new Frame();
246       av.nullFrame.addNotify();
247     }
248
249     Graphics g = av.nullFrame.getGraphics();
250
251     FontMetrics fm = g.getFontMetrics(av.font);
252     AlignmentI al = av.getAlignment();
253
254     int i = 0;
255     int idWidth = 0;
256     String id;
257     while (i < al.getHeight() && al.getSequenceAt(i) != null)
258     {
259       SequenceI s = al.getSequenceAt(i);
260       id = s.getDisplayId(av.getShowJVSuffix());
261
262       if (fm.stringWidth(id) > idWidth)
263       {
264         idWidth = fm.stringWidth(id);
265       }
266       i++;
267     }
268
269     // Also check annotation label widths
270     i = 0;
271     if (al.getAlignmentAnnotation() != null)
272     {
273       fm = g.getFontMetrics(av.nullFrame.getFont());
274       while (i < al.getAlignmentAnnotation().length)
275       {
276         String label = al.getAlignmentAnnotation()[i].label;
277         if (fm.stringWidth(label) > idWidth)
278         {
279           idWidth = fm.stringWidth(label);
280         }
281         i++;
282       }
283     }
284
285     return new Dimension(idWidth, idPanel.idCanvas.getSize().height);
286   }
287
288   /**
289    * Highlight the given results on the alignment.
290    * 
291    */
292   public void highlightSearchResults(SearchResults results)
293   {
294     scrollToPosition(results);
295     seqPanel.seqCanvas.highlightSearchResults(results);
296   }
297
298   /**
299    * scroll the view to show the position of the highlighted region in results
300    * (if any) and redraw the overview
301    * 
302    * @param results
303    * @return false if results were not found
304    */
305   public boolean scrollToPosition(SearchResults results)
306   {
307     return scrollToPosition(results, true);
308   }
309
310   /**
311    * scroll the view to show the position of the highlighted region in results
312    * (if any)
313    * 
314    * @param results
315    * @param redrawOverview
316    *          - when set, the overview will be recalculated (takes longer)
317    * @return false if results were not found
318    */
319   public boolean scrollToPosition(SearchResults results,
320           boolean redrawOverview)
321   {
322     return scrollToPosition(results, redrawOverview, false);
323   }
324
325   /**
326    * scroll the view to show the position of the highlighted region in results
327    * (if any)
328    * 
329    * @param results
330    * @param redrawOverview
331    *          - when set, the overview will be recalculated (takes longer)
332    * @return false if results were not found
333    */
334   public boolean scrollToPosition(SearchResults results,
335           boolean redrawOverview, boolean centre)
336   {
337     // do we need to scroll the panel?
338     if (results != null && results.getSize() > 0)
339     {
340       AlignmentI alignment = av.getAlignment();
341       int seqIndex = alignment.findIndex(results);
342       if (seqIndex == -1)
343       {
344         return false;
345       }
346       SequenceI seq = alignment.getSequenceAt(seqIndex);
347       int[] r = results.getResults(seq, 0, alignment.getWidth());
348       if (r == null)
349       {
350         if (JalviewLite.debug)
351         {// DEBUG
352           System.out
353                   .println("DEBUG: scroll didn't happen - results not within alignment : "
354                           + seq.getStart() + "," + seq.getEnd());
355         }
356         return false;
357       }
358       if (JalviewLite.debug)
359       {
360         // DEBUG
361         /*
362          * System.out.println("DEBUG: scroll: start=" + r[0] +
363          * " av.getStartRes()=" + av.getStartRes() + " end=" + r[1] +
364          * " seq.end=" + seq.getEnd() + " av.getEndRes()=" + av.getEndRes() +
365          * " hextent=" + hextent);
366          */
367       }
368       int start = r[0];
369       int end = r[1];
370
371       /*
372        * To centre results, scroll to positions half the visible width
373        * left/right of the start/end positions
374        */
375       if (centre)
376       {
377         int offset = (av.getEndRes() - av.getStartRes() + 1) / 2 - 1;
378         start = Math.max(start - offset, 0);
379         end = Math.min(end + offset, seq.getEnd() - 1);
380       }
381
382       if (start < 0)
383       {
384         return false;
385       }
386       if (end == seq.getEnd())
387       {
388         return false;
389       }
390       return scrollTo(start, end, seqIndex, false, redrawOverview);
391     }
392     return true;
393   }
394
395   public boolean scrollTo(int ostart, int end, int seqIndex,
396           boolean scrollToNearest, boolean redrawOverview)
397   {
398     int startv, endv, starts, ends, width;
399
400     int start = -1;
401     if (av.hasHiddenColumns())
402     {
403       start = av.getColumnSelection().findColumnPosition(ostart);
404       end = av.getColumnSelection().findColumnPosition(end);
405       if (start == end)
406       {
407         if (!scrollToNearest && !av.getColumnSelection().isVisible(ostart))
408         {
409           // don't scroll - position isn't visible
410           return false;
411         }
412       }
413     }
414     else
415     {
416       start = ostart;
417     }
418     if (!av.getWrapAlignment())
419     {
420       /*
421        * int spos=av.getStartRes(),sqpos=av.getStartSeq(); if ((startv =
422        * av.getStartRes()) >= start) { spos=start-1; // seqIn //
423        * setScrollValues(start - 1, seqIndex); } else if ((endv =
424        * av.getEndRes()) <= end) { // setScrollValues(spos=startv + 1 + end -
425        * endv, seqIndex); spos=startv + 1 + end - endv; } else if ((starts =
426        * av.getStartSeq()) > seqIndex) { setScrollValues(av.getStartRes(),
427        * seqIndex); } else if ((ends = av.getEndSeq()) <= seqIndex) {
428        * setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1); }
429        */
430
431       // below is scrolling logic up to Jalview 2.8.2
432       // if ((av.getStartRes() > end)
433       // || (av.getEndRes() < start)
434       // || ((av.getStartSeq() > seqIndex) || (av.getEndSeq() < seqIndex)))
435       // {
436       // if (start > av.getAlignment().getWidth() - hextent)
437       // {
438       // start = av.getAlignment().getWidth() - hextent;
439       // if (start < 0)
440       // {
441       // start = 0;
442       // }
443       //
444       // }
445       // if (seqIndex > av.getAlignment().getHeight() - vextent)
446       // {
447       // seqIndex = av.getAlignment().getHeight() - vextent;
448       // if (seqIndex < 0)
449       // {
450       // seqIndex = 0;
451       // }
452       // }
453       // setScrollValues(start, seqIndex);
454       // }
455       // logic copied from jalview.gui.AlignmentPanel:
456       if ((startv = av.getStartRes()) >= start)
457       {
458         /*
459          * Scroll left to make start of search results visible
460          */
461         setScrollValues(start - 1, seqIndex);
462       }
463       else if ((endv = av.getEndRes()) <= end)
464       {
465         /*
466          * Scroll right to make end of search results visible
467          */
468         setScrollValues(startv + 1 + end - endv, seqIndex);
469       }
470       else if ((starts = av.getStartSeq()) > seqIndex)
471       {
472         /*
473          * Scroll up to make start of search results visible
474          */
475         setScrollValues(av.getStartRes(), seqIndex);
476       }
477       else if ((ends = av.getEndSeq()) <= seqIndex)
478       {
479         /*
480          * Scroll down to make end of search results visible
481          */
482         setScrollValues(av.getStartRes(), starts + seqIndex - ends + 1);
483       }
484       /*
485        * Else results are already visible - no need to scroll
486        */
487     }
488     else
489     {
490       scrollToWrappedVisible(start);
491     }
492     if (redrawOverview && overviewPanel != null)
493     {
494       overviewPanel.setBoxPosition();
495     }
496     paintAlignment(redrawOverview);
497     return true;
498   }
499
500   void scrollToWrappedVisible(int res)
501   {
502     int cwidth = seqPanel.seqCanvas
503             .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
504     if (res <= av.getStartRes() || res >= (av.getStartRes() + cwidth))
505     {
506       vscroll.setValue(res / cwidth);
507       av.startRes = vscroll.getValue() * cwidth;
508     }
509   }
510
511   public OverviewPanel getOverviewPanel()
512   {
513     return overviewPanel;
514   }
515
516   public void setOverviewPanel(OverviewPanel op)
517   {
518     overviewPanel = op;
519   }
520
521   public void setAnnotationVisible(boolean b)
522   {
523     if (!av.getWrapAlignment())
524     {
525       annotationSpaceFillerHolder.setVisible(b);
526       annotationPanelHolder.setVisible(b);
527     }
528     else
529     {
530       annotationSpaceFillerHolder.setVisible(false);
531       annotationPanelHolder.setVisible(false);
532     }
533     validate();
534     repaint();
535   }
536
537   /**
538    * automatically adjust annotation panel height for new annotation whilst
539    * ensuring the alignment is still visible.
540    */
541   public void adjustAnnotationHeight()
542   {
543     // TODO: display vertical annotation scrollbar if necessary
544     // this is called after loading new annotation onto alignment
545     if (alignFrame.getSize().height == 0)
546     {
547       System.out
548               .println("adjustAnnotationHeight frame size zero NEEDS FIXING");
549     }
550     fontChanged();
551     validateAnnotationDimensions(true);
552     apvscroll.addNotify();
553     hscroll.addNotify();
554     validate();
555     paintAlignment(true);
556   }
557
558   /**
559    * Calculate the annotation dimensions and refresh slider values accordingly.
560    * Need to do repaints/notifys afterwards.
561    */
562   protected void validateAnnotationDimensions(boolean adjustPanelHeight)
563   {
564     int rowHeight = av.getCharHeight();
565     int alignmentHeight = rowHeight * av.getAlignment().getHeight();
566     int annotationHeight = av.calcPanelHeight();
567
568     int mheight = annotationHeight;
569     Dimension d = sequenceHolderPanel.getSize();
570
571     int availableHeight = d.height - scalePanelHolder.getHeight();
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       // TODO: determine if this paintAlignment changed structure colours
961       jalview.structure.StructureSelectionManager
962               .getStructureSelectionManager(av.applet)
963               .sequenceColoursChanged(this);
964
965       if (overviewPanel != null)
966       {
967         overviewPanel.updateOverviewImage();
968       }
969     }
970   }
971
972   public void update(Graphics g)
973   {
974     paint(g);
975   }
976
977   public void paint(Graphics g)
978   {
979     invalidate();
980     Dimension d = idPanel.idCanvas.getSize();
981     final int canvasHeight = seqPanel.seqCanvas.getSize().height;
982     if (canvasHeight != d.height)
983     {
984       idPanel.idCanvas.setSize(d.width, canvasHeight);
985     }
986
987     if (av.getWrapAlignment())
988     {
989       int maxwidth = av.getAlignment().getWidth();
990
991       if (av.hasHiddenColumns())
992       {
993         maxwidth = av.getColumnSelection().findColumnPosition(maxwidth) - 1;
994       }
995
996       int canvasWidth = seqPanel.seqCanvas
997               .getWrappedCanvasWidth(seqPanel.seqCanvas.getSize().width);
998
999       if (canvasWidth > 0)
1000       {
1001         int max = maxwidth / canvasWidth;
1002         vscroll.setMaximum(1 + max);
1003         vscroll.setUnitIncrement(1);
1004         vscroll.setVisibleAmount(1);
1005       }
1006     }
1007     else
1008     {
1009       setScrollValues(av.getStartRes(), av.getStartSeq());
1010     }
1011
1012     seqPanel.seqCanvas.repaint();
1013     idPanel.idCanvas.repaint();
1014     if (!av.getWrapAlignment())
1015     {
1016       if (av.isShowAnnotation())
1017       {
1018         alabels.repaint();
1019         annotationPanel.repaint();
1020       }
1021       scalePanel.repaint();
1022     }
1023
1024   }
1025
1026   protected Panel sequenceHolderPanel = new Panel();
1027
1028   protected Scrollbar vscroll = new Scrollbar();
1029
1030   protected Scrollbar hscroll = new Scrollbar();
1031
1032   protected Panel seqPanelHolder = new Panel();
1033
1034   protected Panel scalePanelHolder = new Panel();
1035
1036   protected Panel idPanelHolder = new Panel();
1037
1038   protected Panel idSpaceFillerPanel1 = new Panel();
1039
1040   public Panel annotationSpaceFillerHolder = new Panel();
1041
1042   protected Panel hscrollFillerPanel = new Panel();
1043
1044   Panel annotationPanelHolder = new Panel();
1045
1046   protected Scrollbar apvscroll = new Scrollbar();
1047
1048   /*
1049    * Flag set while scrolling to follow complementary cDNA/protein scroll. When
1050    * true, suppresses invoking the same method recursively.
1051    */
1052   private boolean followingComplementScroll;
1053
1054   private void jbInit() throws Exception
1055   {
1056     // idPanelHolder.setPreferredSize(new Dimension(70, 10));
1057     this.setLayout(new BorderLayout());
1058
1059     // sequenceHolderPanel.setPreferredSize(new Dimension(150, 150));
1060     sequenceHolderPanel.setLayout(new BorderLayout());
1061     seqPanelHolder.setLayout(new BorderLayout());
1062     scalePanelHolder.setBackground(Color.white);
1063
1064     // scalePanelHolder.setPreferredSize(new Dimension(10, 30));
1065     scalePanelHolder.setLayout(new BorderLayout());
1066     idPanelHolder.setLayout(new BorderLayout());
1067     idSpaceFillerPanel1.setBackground(Color.white);
1068
1069     // idSpaceFillerPanel1.setPreferredSize(new Dimension(10, 30));
1070     idSpaceFillerPanel1.setLayout(new BorderLayout());
1071     annotationSpaceFillerHolder.setBackground(Color.white);
1072
1073     // annotationSpaceFillerHolder.setPreferredSize(new Dimension(10, 80));
1074     annotationSpaceFillerHolder.setLayout(new BorderLayout());
1075     hscroll.setOrientation(Scrollbar.HORIZONTAL);
1076
1077     Panel hscrollHolder = new Panel();
1078     hscrollHolder.setLayout(new BorderLayout());
1079     hscrollFillerPanel.setBackground(Color.white);
1080     apvscroll.setOrientation(Scrollbar.VERTICAL);
1081     apvscroll.setVisible(true);
1082     apvscroll.addAdjustmentListener(this);
1083
1084     annotationPanelHolder.setBackground(Color.white);
1085     annotationPanelHolder.setLayout(new BorderLayout());
1086     annotationPanelHolder.add(apvscroll, BorderLayout.EAST);
1087     // hscrollFillerPanel.setPreferredSize(new Dimension(70, 10));
1088     hscrollHolder.setBackground(Color.white);
1089
1090     // annotationScroller.setPreferredSize(new Dimension(10, 80));
1091     // this.setPreferredSize(new Dimension(220, 166));
1092     seqPanelHolder.setBackground(Color.white);
1093     idPanelHolder.setBackground(Color.white);
1094     sequenceHolderPanel.add(scalePanelHolder, BorderLayout.NORTH);
1095     sequenceHolderPanel.add(seqPanelHolder, BorderLayout.CENTER);
1096     seqPanelHolder.add(vscroll, BorderLayout.EAST);
1097
1098     // Panel3.add(secondaryPanelHolder, BorderLayout.SOUTH);
1099     this.add(idPanelHolder, BorderLayout.WEST);
1100     idPanelHolder.add(idSpaceFillerPanel1, BorderLayout.NORTH);
1101     idPanelHolder.add(annotationSpaceFillerHolder, BorderLayout.SOUTH);
1102     this.add(hscrollHolder, BorderLayout.SOUTH);
1103     hscrollHolder.add(hscroll, BorderLayout.CENTER);
1104     hscrollHolder.add(hscrollFillerPanel, BorderLayout.WEST);
1105     this.add(sequenceHolderPanel, BorderLayout.CENTER);
1106   }
1107
1108   /**
1109    * hides or shows dynamic annotation rows based on groups and av state flags
1110    */
1111   public void updateAnnotation()
1112   {
1113     updateAnnotation(false);
1114   }
1115
1116   public void updateAnnotation(boolean applyGlobalSettings)
1117   {
1118     updateAnnotation(applyGlobalSettings, false);
1119   }
1120
1121   public void updateAnnotation(boolean applyGlobalSettings,
1122           boolean preserveNewGroupSettings)
1123   {
1124     av.updateGroupAnnotationSettings(applyGlobalSettings,
1125             preserveNewGroupSettings);
1126     adjustAnnotationHeight();
1127   }
1128
1129   @Override
1130   public AlignmentI getAlignment()
1131   {
1132     return av.getAlignment();
1133   }
1134
1135   @Override
1136   public String getViewName()
1137   {
1138     return getName();
1139   }
1140
1141   @Override
1142   public StructureSelectionManager getStructureSelectionManager()
1143   {
1144     return StructureSelectionManager
1145             .getStructureSelectionManager(av.applet);
1146   }
1147
1148   @Override
1149   public void raiseOOMWarning(String string, OutOfMemoryError error)
1150   {
1151     // TODO: JAL-960
1152     System.err.println("Out of memory whilst '" + string + "'");
1153     error.printStackTrace();
1154   }
1155
1156   /**
1157    * Set a flag to say we are scrolling to follow a (cDNA/protein) complement.
1158    * 
1159    * @param b
1160    */
1161   protected void setFollowingComplementScroll(boolean b)
1162   {
1163     this.followingComplementScroll = b;
1164   }
1165
1166   protected boolean isFollowingComplementScroll()
1167   {
1168     return this.followingComplementScroll;
1169   }
1170
1171 }