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