Merge branch 'features/JAL-2435splitScreenFont' into develop
[jalview.git] / src / jalview / appletgui / SeqPanel.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.api.AlignViewportI;
24 import jalview.commands.EditCommand;
25 import jalview.commands.EditCommand.Action;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.ColumnSelection;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.SearchResultMatchI;
30 import jalview.datamodel.SearchResults;
31 import jalview.datamodel.SearchResultsI;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceGroup;
35 import jalview.datamodel.SequenceI;
36 import jalview.schemes.ResidueProperties;
37 import jalview.structure.SelectionListener;
38 import jalview.structure.SelectionSource;
39 import jalview.structure.SequenceListener;
40 import jalview.structure.StructureSelectionManager;
41 import jalview.structure.VamsasSource;
42 import jalview.util.MappingUtils;
43 import jalview.util.MessageManager;
44 import jalview.viewmodel.AlignmentViewport;
45 import jalview.viewmodel.ViewportRanges;
46
47 import java.awt.BorderLayout;
48 import java.awt.Font;
49 import java.awt.FontMetrics;
50 import java.awt.Panel;
51 import java.awt.Point;
52 import java.awt.event.InputEvent;
53 import java.awt.event.MouseEvent;
54 import java.awt.event.MouseListener;
55 import java.awt.event.MouseMotionListener;
56 import java.util.Vector;
57
58 public class SeqPanel extends Panel implements MouseMotionListener,
59         MouseListener, SequenceListener, SelectionListener
60 {
61
62   public SeqCanvas seqCanvas;
63
64   public AlignmentPanel ap;
65
66   protected int lastres;
67
68   protected int startseq;
69
70   protected AlignViewport av;
71
72   // if character is inserted or deleted, we will need to recalculate the
73   // conservation
74   boolean seqEditOccurred = false;
75
76   ScrollThread scrollThread = null;
77
78   boolean mouseDragging = false;
79
80   boolean editingSeqs = false;
81
82   boolean groupEditing = false;
83
84   int oldSeq = -1;
85
86   boolean changeEndSeq = false;
87
88   boolean changeStartSeq = false;
89
90   boolean changeEndRes = false;
91
92   boolean changeStartRes = false;
93
94   SequenceGroup stretchGroup = null;
95
96   StringBuffer keyboardNo1;
97
98   StringBuffer keyboardNo2;
99
100   boolean mouseWheelPressed = false;
101
102   Point lastMousePress;
103
104   EditCommand editCommand;
105
106   StructureSelectionManager ssm;
107
108   public SeqPanel(AlignViewport avp, AlignmentPanel p)
109   {
110     this.av = avp;
111
112     seqCanvas = new SeqCanvas(avp);
113     setLayout(new BorderLayout());
114     add(seqCanvas);
115
116     ap = p;
117
118     seqCanvas.addMouseMotionListener(this);
119     seqCanvas.addMouseListener(this);
120     ssm = StructureSelectionManager.getStructureSelectionManager(av.applet);
121     ssm.addStructureViewerListener(this);
122     ssm.addSelectionListener(this);
123
124     seqCanvas.repaint();
125   }
126
127   void endEditing()
128   {
129     if (editCommand != null && editCommand.getSize() > 0)
130     {
131       ap.alignFrame.addHistoryItem(editCommand);
132       av.firePropertyChange("alignment", null, av.getAlignment()
133               .getSequences());
134     }
135
136     startseq = -1;
137     lastres = -1;
138     editingSeqs = false;
139     groupEditing = false;
140     keyboardNo1 = null;
141     keyboardNo2 = null;
142     editCommand = null;
143   }
144
145   void setCursorRow()
146   {
147     seqCanvas.cursorY = getKeyboardNo1() - 1;
148     scrollToVisible();
149   }
150
151   void setCursorColumn()
152   {
153     seqCanvas.cursorX = getKeyboardNo1() - 1;
154     scrollToVisible();
155   }
156
157   void setCursorRowAndColumn()
158   {
159     if (keyboardNo2 == null)
160     {
161       keyboardNo2 = new StringBuffer();
162     }
163     else
164     {
165       seqCanvas.cursorX = getKeyboardNo1() - 1;
166       seqCanvas.cursorY = getKeyboardNo2() - 1;
167       scrollToVisible();
168     }
169   }
170
171   void setCursorPosition()
172   {
173     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
174
175     seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
176     scrollToVisible();
177   }
178
179   void moveCursor(int dx, int dy)
180   {
181     seqCanvas.cursorX += dx;
182     seqCanvas.cursorY += dy;
183     if (av.hasHiddenColumns()
184             && !av.getAlignment().getHiddenColumns()
185                     .isVisible(seqCanvas.cursorX))
186     {
187       int original = seqCanvas.cursorX - dx;
188       int maxWidth = av.getAlignment().getWidth();
189
190       while (!av.getAlignment().getHiddenColumns()
191               .isVisible(seqCanvas.cursorX)
192               && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
193       {
194         seqCanvas.cursorX += dx;
195       }
196
197       if (seqCanvas.cursorX >= maxWidth
198               || !av.getAlignment().getHiddenColumns()
199                       .isVisible(seqCanvas.cursorX))
200       {
201         seqCanvas.cursorX = original;
202       }
203     }
204     scrollToVisible();
205   }
206
207   void scrollToVisible()
208   {
209     if (seqCanvas.cursorX < 0)
210     {
211       seqCanvas.cursorX = 0;
212     }
213     else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
214     {
215       seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
216     }
217
218     if (seqCanvas.cursorY < 0)
219     {
220       seqCanvas.cursorY = 0;
221     }
222     else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
223     {
224       seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
225     }
226
227     endEditing();
228     if (av.getWrapAlignment())
229     {
230       ap.scrollToWrappedVisible(seqCanvas.cursorX);
231     }
232     else
233     {
234       ViewportRanges ranges = av.getRanges();
235       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
236       while (seqCanvas.cursorY < ranges.getStartSeq())
237       {
238         ap.scrollUp(true);
239       }
240       while (seqCanvas.cursorY + 1 > ranges.getEndSeq())
241       {
242         ap.scrollUp(false);
243       }
244       while (seqCanvas.cursorX < hidden.adjustForHiddenColumns(ranges
245               .getStartRes()))
246       {
247
248         if (!ap.scrollRight(false))
249         {
250           break;
251         }
252       }
253       while (seqCanvas.cursorX > hidden.adjustForHiddenColumns(ranges
254               .getEndRes()))
255       {
256         if (!ap.scrollRight(true))
257         {
258           break;
259         }
260       }
261     }
262     setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
263             seqCanvas.cursorX, seqCanvas.cursorY);
264
265     seqCanvas.repaint();
266   }
267
268   void setSelectionAreaAtCursor(boolean topLeft)
269   {
270     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
271
272     if (av.getSelectionGroup() != null)
273     {
274       SequenceGroup sg = av.getSelectionGroup();
275       // Find the top and bottom of this group
276       int min = av.getAlignment().getHeight(), max = 0;
277       for (int i = 0; i < sg.getSize(); i++)
278       {
279         int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
280         if (index > max)
281         {
282           max = index;
283         }
284         if (index < min)
285         {
286           min = index;
287         }
288       }
289
290       max++;
291
292       if (topLeft)
293       {
294         sg.setStartRes(seqCanvas.cursorX);
295         if (sg.getEndRes() < seqCanvas.cursorX)
296         {
297           sg.setEndRes(seqCanvas.cursorX);
298         }
299
300         min = seqCanvas.cursorY;
301       }
302       else
303       {
304         sg.setEndRes(seqCanvas.cursorX);
305         if (sg.getStartRes() > seqCanvas.cursorX)
306         {
307           sg.setStartRes(seqCanvas.cursorX);
308         }
309
310         max = seqCanvas.cursorY + 1;
311       }
312
313       if (min > max)
314       {
315         // Only the user can do this
316         av.setSelectionGroup(null);
317       }
318       else
319       {
320         // Now add any sequences between min and max
321         sg.clear();
322         for (int i = min; i < max; i++)
323         {
324           sg.addSequence(av.getAlignment().getSequenceAt(i), false);
325         }
326       }
327     }
328
329     if (av.getSelectionGroup() == null)
330     {
331       SequenceGroup sg = new SequenceGroup();
332       sg.setStartRes(seqCanvas.cursorX);
333       sg.setEndRes(seqCanvas.cursorX);
334       sg.addSequence(sequence, false);
335       av.setSelectionGroup(sg);
336     }
337     ap.paintAlignment(false);
338     av.sendSelection();
339   }
340
341   void insertGapAtCursor(boolean group)
342   {
343     groupEditing = group;
344     startseq = seqCanvas.cursorY;
345     lastres = seqCanvas.cursorX;
346     editSequence(true, seqCanvas.cursorX + getKeyboardNo1());
347     endEditing();
348   }
349
350   void deleteGapAtCursor(boolean group)
351   {
352     groupEditing = group;
353     startseq = seqCanvas.cursorY;
354     lastres = seqCanvas.cursorX + getKeyboardNo1();
355     editSequence(false, seqCanvas.cursorX);
356     endEditing();
357   }
358
359   void numberPressed(char value)
360   {
361     if (keyboardNo1 == null)
362     {
363       keyboardNo1 = new StringBuffer();
364     }
365
366     if (keyboardNo2 != null)
367     {
368       keyboardNo2.append(value);
369     }
370     else
371     {
372       keyboardNo1.append(value);
373     }
374   }
375
376   int getKeyboardNo1()
377   {
378     try
379     {
380       if (keyboardNo1 != null)
381       {
382         int value = Integer.parseInt(keyboardNo1.toString());
383         keyboardNo1 = null;
384         return value;
385       }
386     } catch (Exception x)
387     {
388     }
389     keyboardNo1 = null;
390     return 1;
391   }
392
393   int getKeyboardNo2()
394   {
395     try
396     {
397       if (keyboardNo2 != null)
398       {
399         int value = Integer.parseInt(keyboardNo2.toString());
400         keyboardNo2 = null;
401         return value;
402       }
403     } catch (Exception x)
404     {
405     }
406     keyboardNo2 = null;
407     return 1;
408   }
409
410   /**
411    * Set status message in alignment panel
412    * 
413    * @param sequence
414    *          aligned sequence object
415    * @param res
416    *          alignment column
417    * @param seq
418    *          index of sequence in alignment
419    * @return position of res in sequence
420    */
421   void setStatusMessage(SequenceI sequence, int res, int seq)
422   {
423     // TODO remove duplication of identical gui method
424     StringBuilder text = new StringBuilder(32);
425     String seqno = seq == -1 ? "" : " " + (seq + 1);
426     text.append("Sequence" + seqno + " ID: " + sequence.getName());
427
428     String residue = null;
429     /*
430      * Try to translate the display character to residue name (null for gap).
431      */
432     final String displayChar = String.valueOf(sequence.getCharAt(res));
433     if (av.getAlignment().isNucleotide())
434     {
435       residue = ResidueProperties.nucleotideName.get(displayChar);
436       if (residue != null)
437       {
438         text.append(" Nucleotide: ").append(residue);
439       }
440     }
441     else
442     {
443       residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
444               .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
445               .get(displayChar));
446       if (residue != null)
447       {
448         text.append(" Residue: ").append(residue);
449       }
450     }
451
452     int pos = -1;
453     if (residue != null)
454     {
455       pos = sequence.findPosition(res);
456       text.append(" (").append(Integer.toString(pos)).append(")");
457     }
458
459     ap.alignFrame.statusBar.setText(text.toString());
460   }
461
462   /**
463    * Set the status bar message to highlight the first matched position in
464    * search results.
465    * 
466    * @param results
467    * @return true if results were matched, false if not
468    */
469   private boolean setStatusMessage(SearchResultsI results)
470   {
471     AlignmentI al = this.av.getAlignment();
472     int sequenceIndex = al.findIndex(results);
473     if (sequenceIndex == -1)
474     {
475       return false;
476     }
477     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
478     for (SearchResultMatchI m : results.getResults())
479     {
480       SequenceI seq = m.getSequence();
481       if (seq.getDatasetSequence() != null)
482       {
483         seq = seq.getDatasetSequence();
484       }
485
486       if (seq == ds)
487       {
488         /*
489          * Convert position in sequence (base 1) to sequence character array
490          * index (base 0)
491          */
492         int start = m.getStart() - m.getSequence().getStart();
493         setStatusMessage(seq, start, sequenceIndex);
494         return true;
495       }
496     }
497     return false;
498   }
499
500   @Override
501   public void mousePressed(MouseEvent evt)
502   {
503     lastMousePress = evt.getPoint();
504
505     // For now, ignore the mouseWheel font resizing on Macs
506     // As the Button2_mask always seems to be true
507     if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK
508             && !av.MAC)
509     {
510       mouseWheelPressed = true;
511       return;
512     }
513
514     if (evt.isShiftDown() || evt.isControlDown() || evt.isAltDown())
515     {
516       if (evt.isControlDown() || evt.isAltDown())
517       {
518         groupEditing = true;
519       }
520       editingSeqs = true;
521     }
522     else
523     {
524       doMousePressedDefineMode(evt);
525       return;
526     }
527
528     int seq = findSeq(evt);
529     int res = findRes(evt);
530
531     if (seq < 0 || res < 0)
532     {
533       return;
534     }
535
536     if ((seq < av.getAlignment().getHeight())
537             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
538     {
539       startseq = seq;
540       lastres = res;
541     }
542     else
543     {
544       startseq = -1;
545       lastres = -1;
546     }
547
548     return;
549   }
550
551   @Override
552   public void mouseClicked(MouseEvent evt)
553   {
554     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
555     if (evt.getClickCount() > 1)
556     {
557       if (av.getSelectionGroup() != null
558               && av.getSelectionGroup().getSize() == 1
559               && av.getSelectionGroup().getEndRes()
560                       - av.getSelectionGroup().getStartRes() < 2)
561       {
562         av.setSelectionGroup(null);
563       }
564
565       SequenceFeature[] features = findFeaturesAtRes(sequence,
566               sequence.findPosition(findRes(evt)));
567
568       if (features != null && features.length > 0)
569       {
570         SearchResultsI highlight = new SearchResults();
571         highlight.addResult(sequence, features[0].getBegin(),
572                 features[0].getEnd());
573         seqCanvas.highlightSearchResults(highlight);
574       }
575       if (features != null && features.length > 0)
576       {
577         seqCanvas.getFeatureRenderer().amendFeatures(
578                 new SequenceI[] { sequence }, features, false, ap, null);
579
580         seqCanvas.highlightSearchResults(null);
581       }
582     }
583   }
584
585   @Override
586   public void mouseReleased(MouseEvent evt)
587   {
588     mouseDragging = false;
589     mouseWheelPressed = false;
590     ap.paintAlignment(true);
591
592     if (!editingSeqs)
593     {
594       doMouseReleasedDefineMode(evt);
595       return;
596     }
597
598     endEditing();
599
600   }
601
602   int startWrapBlock = -1;
603
604   int wrappedBlock = -1;
605
606   int findRes(MouseEvent evt)
607   {
608     int res = 0;
609     int x = evt.getX();
610
611     if (av.getWrapAlignment())
612     {
613
614       int hgap = av.getCharHeight();
615       if (av.getScaleAboveWrapped())
616       {
617         hgap += av.getCharHeight();
618       }
619
620       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
621               + hgap + seqCanvas.getAnnotationHeight();
622
623       int y = evt.getY();
624       y -= hgap;
625       x -= seqCanvas.LABEL_WEST;
626
627       int cwidth = seqCanvas.getWrappedCanvasWidth(getSize().width);
628       if (cwidth < 1)
629       {
630         return 0;
631       }
632
633       wrappedBlock = y / cHeight;
634       wrappedBlock += av.getRanges().getStartRes() / cwidth;
635
636       res = wrappedBlock * cwidth + x / av.getCharWidth();
637
638     }
639     else
640     {
641       res = (x / av.getCharWidth()) + av.getRanges().getStartRes();
642     }
643
644     if (av.hasHiddenColumns())
645     {
646       res = av.getAlignment().getHiddenColumns()
647               .adjustForHiddenColumns(res);
648     }
649
650     return res;
651
652   }
653
654   int findSeq(MouseEvent evt)
655   {
656     final int sqnum = findAlRow(evt);
657     return (sqnum < 0) ? 0 : sqnum;
658   }
659
660   /**
661    * 
662    * @param evt
663    * @return row in alignment that was selected (or -1 for column selection)
664    */
665   private int findAlRow(MouseEvent evt)
666   {
667     int seq = 0;
668     int y = evt.getY();
669
670     if (av.getWrapAlignment())
671     {
672       int hgap = av.getCharHeight();
673       if (av.getScaleAboveWrapped())
674       {
675         hgap += av.getCharHeight();
676       }
677
678       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
679               + hgap + seqCanvas.getAnnotationHeight();
680
681       y -= hgap;
682
683       seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
684               .getHeight() - 1);
685       if (seq < 0)
686       {
687         seq = -1;
688       }
689     }
690     else
691     {
692       seq = Math.min((y / av.getCharHeight())
693               + av.getRanges().getStartSeq(),
694               av
695               .getAlignment().getHeight() - 1);
696       if (seq < 0)
697       {
698         seq = -1;
699       }
700     }
701
702     return seq;
703   }
704
705   public void doMousePressed(MouseEvent evt)
706   {
707
708     int seq = findSeq(evt);
709     int res = findRes(evt);
710
711     if (seq < av.getAlignment().getHeight()
712             && res < av.getAlignment().getSequenceAt(seq).getLength())
713     {
714       // char resstr = align.getSequenceAt(seq).getSequence().charAt(res);
715       // Find the residue's position in the sequence (res is the position
716       // in the alignment
717
718       startseq = seq;
719       lastres = res;
720     }
721     else
722     {
723       startseq = -1;
724       lastres = -1;
725     }
726
727     return;
728   }
729
730   String lastMessage;
731
732   @Override
733   public void mouseOverSequence(SequenceI sequence, int index, int pos)
734   {
735     String tmp = sequence.hashCode() + index + "";
736     if (lastMessage == null || !lastMessage.equals(tmp))
737     {
738       ssm.mouseOverSequence(sequence, index, pos, av);
739     }
740
741     lastMessage = tmp;
742   }
743
744   @Override
745   public void highlightSequence(SearchResultsI results)
746   {
747     if (av.isFollowHighlight())
748     {
749       if (ap.scrollToPosition(results, true))
750       {
751         ap.alignFrame.repaint();
752       }
753     }
754     setStatusMessage(results);
755     seqCanvas.highlightSearchResults(results);
756
757   }
758
759   @Override
760   public VamsasSource getVamsasSource()
761   {
762     return this.ap == null ? null : this.ap.av;
763   }
764
765   @Override
766   public void updateColours(SequenceI seq, int index)
767   {
768     System.out.println("update the seqPanel colours");
769     // repaint();
770   }
771
772   @Override
773   public void mouseMoved(MouseEvent evt)
774   {
775     int res = findRes(evt);
776     int seq = findSeq(evt);
777
778     if (seq >= av.getAlignment().getHeight() || seq < 0 || res < 0)
779     {
780       if (tooltip != null)
781       {
782         tooltip.setTip("");
783       }
784       return;
785     }
786
787     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
788     if (res > sequence.getLength())
789     {
790       if (tooltip != null)
791       {
792         tooltip.setTip("");
793       }
794       return;
795     }
796
797     int respos = sequence.findPosition(res);
798     if (ssm != null)
799     {
800       mouseOverSequence(sequence, res, respos);
801     }
802
803     StringBuilder text = new StringBuilder();
804     text.append("Sequence ").append(Integer.toString(seq + 1))
805             .append(" ID: ").append(sequence.getName());
806
807     String obj = null;
808     final String ch = String.valueOf(sequence.getCharAt(res));
809     if (av.getAlignment().isNucleotide())
810     {
811       obj = ResidueProperties.nucleotideName.get(ch);
812       if (obj != null)
813       {
814         text.append(" Nucleotide: ").append(obj);
815       }
816     }
817     else
818     {
819       obj = "X".equalsIgnoreCase(ch) ? "X" : ResidueProperties.aa2Triplet
820               .get(ch);
821       if (obj != null)
822       {
823         text.append(" Residue: ").append(obj);
824       }
825     }
826
827     if (obj != null)
828     {
829       text.append(" (").append(Integer.toString(respos)).append(")");
830     }
831
832     ap.alignFrame.statusBar.setText(text.toString());
833
834     StringBuilder tooltipText = new StringBuilder();
835     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
836     if (groups != null)
837     {
838       for (int g = 0; g < groups.length; g++)
839       {
840         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
841         {
842           if (!groups[g].getName().startsWith("JTreeGroup")
843                   && !groups[g].getName().startsWith("JGroup"))
844           {
845             tooltipText.append(groups[g].getName()).append(" ");
846           }
847           if (groups[g].getDescription() != null)
848           {
849             tooltipText.append(groups[g].getDescription());
850           }
851           tooltipText.append("\n");
852         }
853       }
854     }
855
856     // use aa to see if the mouse pointer is on a
857     SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
858             sequence.findPosition(res));
859
860     int index = 0;
861     while (index < allFeatures.length)
862     {
863       SequenceFeature sf = allFeatures[index];
864
865       tooltipText.append(sf.getType() + " " + sf.begin + ":" + sf.end);
866
867       if (sf.getDescription() != null)
868       {
869         tooltipText.append(" " + sf.getDescription());
870       }
871
872       if (sf.getValue("status") != null)
873       {
874         String status = sf.getValue("status").toString();
875         if (status.length() > 0)
876         {
877           tooltipText.append(" (" + sf.getValue("status") + ")");
878         }
879       }
880       tooltipText.append("\n");
881
882       index++;
883     }
884
885     if (tooltip == null)
886     {
887       tooltip = new Tooltip(tooltipText.toString(), seqCanvas);
888     }
889     else
890     {
891       tooltip.setTip(tooltipText.toString());
892     }
893   }
894
895   SequenceFeature[] findFeaturesAtRes(SequenceI sequence, int res)
896   {
897     Vector tmp = new Vector();
898     SequenceFeature[] features = sequence.getSequenceFeatures();
899     if (features != null)
900     {
901       for (int i = 0; i < features.length; i++)
902       {
903         if (av.getFeaturesDisplayed() == null
904                 || !av.getFeaturesDisplayed().isVisible(
905                         features[i].getType()))
906         {
907           continue;
908         }
909
910         if (features[i].featureGroup != null
911                 && !seqCanvas.fr.checkGroupVisibility(
912                         features[i].featureGroup, false))
913         {
914           continue;
915         }
916
917         if ((features[i].getBegin() <= res)
918                 && (features[i].getEnd() >= res))
919         {
920           tmp.addElement(features[i]);
921         }
922       }
923     }
924
925     features = new SequenceFeature[tmp.size()];
926     tmp.copyInto(features);
927
928     return features;
929   }
930
931   Tooltip tooltip;
932
933   /**
934    * set when the current UI interaction has resulted in a change that requires
935    * overview shading to be recalculated. this could be changed to something
936    * more expressive that indicates what actually has changed, so selective
937    * redraws can be applied
938    */
939   private boolean needOverviewUpdate; // TODO: refactor to avcontroller
940
941   @Override
942   public void mouseDragged(MouseEvent evt)
943   {
944     if (mouseWheelPressed)
945     {
946       int oldWidth = av.getCharWidth();
947
948       // Which is bigger, left-right or up-down?
949       if (Math.abs(evt.getY() - lastMousePress.y) > Math.abs(evt.getX()
950               - lastMousePress.x))
951       {
952         int fontSize = av.font.getSize();
953
954         if (evt.getY() < lastMousePress.y && av.getCharHeight() > 1)
955         {
956           fontSize--;
957         }
958         else if (evt.getY() > lastMousePress.y)
959         {
960           fontSize++;
961         }
962
963         if (fontSize < 1)
964         {
965           fontSize = 1;
966         }
967
968         av.setFont(
969                 new Font(av.font.getName(), av.font.getStyle(), fontSize),
970                 true);
971         av.setCharWidth(oldWidth);
972       }
973       else
974       {
975         if (evt.getX() < lastMousePress.x && av.getCharWidth() > 1)
976         {
977           av.setCharWidth(av.getCharWidth() - 1);
978         }
979         else if (evt.getX() > lastMousePress.x)
980         {
981           av.setCharWidth(av.getCharWidth() + 1);
982         }
983
984         if (av.getCharWidth() < 1)
985         {
986           av.setCharWidth(1);
987         }
988       }
989
990       ap.fontChanged();
991
992       FontMetrics fm = getFontMetrics(av.getFont());
993       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
994
995       lastMousePress = evt.getPoint();
996
997       ap.paintAlignment(false);
998       ap.annotationPanel.image = null;
999       return;
1000     }
1001
1002     if (!editingSeqs)
1003     {
1004       doMouseDraggedDefineMode(evt);
1005       return;
1006     }
1007
1008     int res = findRes(evt);
1009
1010     if (res < 0)
1011     {
1012       res = 0;
1013     }
1014
1015     if ((lastres == -1) || (lastres == res))
1016     {
1017       return;
1018     }
1019
1020     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1021     {
1022       // dragLeft, delete gap
1023       editSequence(false, res);
1024     }
1025     else
1026     {
1027       editSequence(true, res);
1028     }
1029
1030     mouseDragging = true;
1031     if (scrollThread != null)
1032     {
1033       scrollThread.setEvent(evt);
1034     }
1035
1036   }
1037
1038   synchronized void editSequence(boolean insertGap, int startres)
1039   {
1040     int fixedLeft = -1;
1041     int fixedRight = -1;
1042     boolean fixedColumns = false;
1043     SequenceGroup sg = av.getSelectionGroup();
1044
1045     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1046
1047     if (!groupEditing && av.hasHiddenRows())
1048     {
1049       if (av.isHiddenRepSequence(seq))
1050       {
1051         sg = av.getRepresentedSequences(seq);
1052         groupEditing = true;
1053       }
1054     }
1055
1056     StringBuffer message = new StringBuffer();
1057     if (groupEditing)
1058     {
1059       message.append(MessageManager.getString("action.edit_group")).append(
1060               ":");
1061       if (editCommand == null)
1062       {
1063         editCommand = new EditCommand(
1064                 MessageManager.getString("action.edit_group"));
1065       }
1066     }
1067     else
1068     {
1069       message.append(MessageManager.getString("label.edit_sequence"))
1070               .append(" " + seq.getName());
1071       String label = seq.getName();
1072       if (label.length() > 10)
1073       {
1074         label = label.substring(0, 10);
1075       }
1076       if (editCommand == null)
1077       {
1078         editCommand = new EditCommand(MessageManager.formatMessage(
1079                 "label.edit_params", new String[] { label }));
1080       }
1081     }
1082
1083     if (insertGap)
1084     {
1085       message.append(" insert ");
1086     }
1087     else
1088     {
1089       message.append(" delete ");
1090     }
1091
1092     message.append(Math.abs(startres - lastres) + " gaps.");
1093     ap.alignFrame.statusBar.setText(message.toString());
1094
1095     // Are we editing within a selection group?
1096     if (groupEditing
1097             || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1098                     .contains(seq)))
1099     {
1100       fixedColumns = true;
1101
1102       // sg might be null as the user may only see 1 sequence,
1103       // but the sequence represents a group
1104       if (sg == null)
1105       {
1106         if (!av.isHiddenRepSequence(seq))
1107         {
1108           endEditing();
1109           return;
1110         }
1111
1112         sg = av.getRepresentedSequences(seq);
1113       }
1114
1115       fixedLeft = sg.getStartRes();
1116       fixedRight = sg.getEndRes();
1117
1118       if ((startres < fixedLeft && lastres >= fixedLeft)
1119               || (startres >= fixedLeft && lastres < fixedLeft)
1120               || (startres > fixedRight && lastres <= fixedRight)
1121               || (startres <= fixedRight && lastres > fixedRight))
1122       {
1123         endEditing();
1124         return;
1125       }
1126
1127       if (fixedLeft > startres)
1128       {
1129         fixedRight = fixedLeft - 1;
1130         fixedLeft = 0;
1131       }
1132       else if (fixedRight < startres)
1133       {
1134         fixedLeft = fixedRight;
1135         fixedRight = -1;
1136       }
1137     }
1138
1139     if (av.hasHiddenColumns())
1140     {
1141       fixedColumns = true;
1142       int y1 = av.getAlignment().getHiddenColumns()
1143               .getHiddenBoundaryLeft(startres);
1144       int y2 = av.getAlignment().getHiddenColumns()
1145               .getHiddenBoundaryRight(startres);
1146
1147       if ((insertGap && startres > y1 && lastres < y1)
1148               || (!insertGap && startres < y2 && lastres > y2))
1149       {
1150         endEditing();
1151         return;
1152       }
1153
1154       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1155       // Selection spans a hidden region
1156       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1157       {
1158         if (startres >= y2)
1159         {
1160           fixedLeft = y2;
1161         }
1162         else
1163         {
1164           fixedRight = y2 - 1;
1165         }
1166       }
1167     }
1168
1169     if (groupEditing)
1170     {
1171       SequenceI[] groupSeqs = sg.getSequences(av.getHiddenRepSequences())
1172               .toArray(new SequenceI[0]);
1173
1174       // drag to right
1175       if (insertGap)
1176       {
1177         // If the user has selected the whole sequence, and is dragging to
1178         // the right, we can still extend the alignment and selectionGroup
1179         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1180                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1181         {
1182           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1183           fixedRight = sg.getEndRes();
1184         }
1185
1186         // Is it valid with fixed columns??
1187         // Find the next gap before the end
1188         // of the visible region boundary
1189         boolean blank = false;
1190         for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1191         {
1192           blank = true;
1193
1194           for (SequenceI gs : groupSeqs)
1195           {
1196             for (int j = 0; j < startres - lastres; j++)
1197             {
1198               if (!jalview.util.Comparison.isGap(gs.getCharAt(fixedRight
1199                       - j)))
1200               {
1201                 blank = false;
1202                 break;
1203               }
1204             }
1205           }
1206           if (blank)
1207           {
1208             break;
1209           }
1210         }
1211
1212         if (!blank)
1213         {
1214           if (sg.getSize() == av.getAlignment().getHeight())
1215           {
1216             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1217                     .getHiddenColumns().getHiddenBoundaryRight(startres)))
1218             {
1219               endEditing();
1220               return;
1221             }
1222
1223             int alWidth = av.getAlignment().getWidth();
1224             if (av.hasHiddenRows())
1225             {
1226               int hwidth = av.getAlignment().getHiddenSequences()
1227                       .getWidth();
1228               if (hwidth > alWidth)
1229               {
1230                 alWidth = hwidth;
1231               }
1232             }
1233             // We can still insert gaps if the selectionGroup
1234             // contains all the sequences
1235             sg.setEndRes(sg.getEndRes() + startres - lastres);
1236             fixedRight = alWidth + startres - lastres;
1237           }
1238           else
1239           {
1240             endEditing();
1241             return;
1242           }
1243         }
1244       }
1245
1246       // drag to left
1247       else if (!insertGap)
1248       {
1249         // / Are we able to delete?
1250         // ie are all columns blank?
1251
1252         for (SequenceI gs : groupSeqs)
1253         {
1254           for (int j = startres; j < lastres; j++)
1255           {
1256             if (gs.getLength() <= j)
1257             {
1258               continue;
1259             }
1260
1261             if (!jalview.util.Comparison.isGap(gs.getCharAt(j)))
1262             {
1263               // Not a gap, block edit not valid
1264               endEditing();
1265               return;
1266             }
1267           }
1268         }
1269       }
1270
1271       if (insertGap)
1272       {
1273         // dragging to the right
1274         if (fixedColumns && fixedRight != -1)
1275         {
1276           for (int j = lastres; j < startres; j++)
1277           {
1278             insertChar(j, groupSeqs, fixedRight);
1279           }
1280         }
1281         else
1282         {
1283           editCommand.appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1284                   startres - lastres, av.getAlignment(), true);
1285         }
1286       }
1287       else
1288       {
1289         // dragging to the left
1290         if (fixedColumns && fixedRight != -1)
1291         {
1292           for (int j = lastres; j > startres; j--)
1293           {
1294             deleteChar(startres, groupSeqs, fixedRight);
1295           }
1296         }
1297         else
1298         {
1299           editCommand.appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1300                   lastres - startres, av.getAlignment(), true);
1301         }
1302
1303       }
1304     }
1305     else
1306     // ///Editing a single sequence///////////
1307     {
1308       if (insertGap)
1309       {
1310         // dragging to the right
1311         if (fixedColumns && fixedRight != -1)
1312         {
1313           for (int j = lastres; j < startres; j++)
1314           {
1315             insertChar(j, new SequenceI[] { seq }, fixedRight);
1316           }
1317         }
1318         else
1319         {
1320           editCommand.appendEdit(Action.INSERT_GAP,
1321                   new SequenceI[] { seq }, lastres, startres - lastres,
1322                   av.getAlignment(), true);
1323         }
1324       }
1325       else
1326       {
1327         // dragging to the left
1328         if (fixedColumns && fixedRight != -1)
1329         {
1330           for (int j = lastres; j > startres; j--)
1331           {
1332             if (!jalview.util.Comparison.isGap(seq.getCharAt(startres)))
1333             {
1334               endEditing();
1335               break;
1336             }
1337             deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1338           }
1339         }
1340         else
1341         {
1342           // could be a keyboard edit trying to delete none gaps
1343           int max = 0;
1344           for (int m = startres; m < lastres; m++)
1345           {
1346             if (!jalview.util.Comparison.isGap(seq.getCharAt(m)))
1347             {
1348               break;
1349             }
1350             max++;
1351           }
1352
1353           if (max > 0)
1354           {
1355             editCommand.appendEdit(Action.DELETE_GAP,
1356                     new SequenceI[] { seq }, startres, max,
1357                     av.getAlignment(), true);
1358           }
1359         }
1360       }
1361     }
1362
1363     lastres = startres;
1364     seqCanvas.repaint();
1365   }
1366
1367   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1368   {
1369     int blankColumn = fixedColumn;
1370     for (int s = 0; s < seq.length; s++)
1371     {
1372       // Find the next gap before the end of the visible region boundary
1373       // If lastCol > j, theres a boundary after the gap insertion
1374
1375       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1376       {
1377         if (jalview.util.Comparison.isGap(seq[s].getCharAt(blankColumn)))
1378         {
1379           // Theres a space, so break and insert the gap
1380           break;
1381         }
1382       }
1383
1384       if (blankColumn <= j)
1385       {
1386         blankColumn = fixedColumn;
1387         endEditing();
1388         return;
1389       }
1390     }
1391
1392     editCommand.appendEdit(Action.DELETE_GAP, seq, blankColumn, 1,
1393             av.getAlignment(), true);
1394
1395     editCommand.appendEdit(Action.INSERT_GAP, seq, j, 1, av.getAlignment(),
1396             true);
1397
1398   }
1399
1400   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1401   {
1402
1403     editCommand.appendEdit(Action.DELETE_GAP, seq, j, 1, av.getAlignment(),
1404             true);
1405
1406     editCommand.appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1,
1407             av.getAlignment(), true);
1408   }
1409
1410   // ////////////////////////////////////////
1411   // ///Everything below this is for defining the boundary of the rubberband
1412   // ////////////////////////////////////////
1413   public void doMousePressedDefineMode(MouseEvent evt)
1414   {
1415     if (scrollThread != null)
1416     {
1417       scrollThread.running = false;
1418       scrollThread = null;
1419     }
1420
1421     int res = findRes(evt);
1422     int seq = findSeq(evt);
1423     oldSeq = seq;
1424     startWrapBlock = wrappedBlock;
1425
1426     if (seq == -1)
1427     {
1428       return;
1429     }
1430
1431     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1432
1433     if (sequence == null || res > sequence.getLength())
1434     {
1435       return;
1436     }
1437
1438     stretchGroup = av.getSelectionGroup();
1439
1440     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1441     {
1442       stretchGroup = av.getAlignment().findGroup(sequence, res);
1443       if (stretchGroup != null)
1444       {
1445         // only update the current selection if the popup menu has a group to
1446         // focus on
1447         av.setSelectionGroup(stretchGroup);
1448       }
1449     }
1450
1451     // DETECT RIGHT MOUSE BUTTON IN AWT
1452     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK)
1453     {
1454       SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
1455               sequence.findPosition(res));
1456
1457       Vector<String> links = null;
1458       if (allFeatures != null)
1459       {
1460         for (int i = 0; i < allFeatures.length; i++)
1461         {
1462           if (allFeatures[i].links != null)
1463           {
1464             if (links == null)
1465             {
1466               links = new Vector<String>();
1467             }
1468             for (int j = 0; j < allFeatures[i].links.size(); j++)
1469             {
1470               links.addElement(allFeatures[i].links.elementAt(j));
1471             }
1472           }
1473         }
1474       }
1475       APopupMenu popup = new APopupMenu(ap, null, links);
1476       this.add(popup);
1477       popup.show(this, evt.getX(), evt.getY());
1478       return;
1479     }
1480
1481     if (av.cursorMode)
1482     {
1483       seqCanvas.cursorX = findRes(evt);
1484       seqCanvas.cursorY = findSeq(evt);
1485       seqCanvas.repaint();
1486       return;
1487     }
1488
1489     // Only if left mouse button do we want to change group sizes
1490
1491     if (stretchGroup == null)
1492     {
1493       // define a new group here
1494       SequenceGroup sg = new SequenceGroup();
1495       sg.setStartRes(res);
1496       sg.setEndRes(res);
1497       sg.addSequence(sequence, false);
1498       av.setSelectionGroup(sg);
1499       stretchGroup = sg;
1500
1501       if (av.getConservationSelected())
1502       {
1503         SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1504                 ap.getViewName());
1505       }
1506       if (av.getAbovePIDThreshold())
1507       {
1508         SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1509                 ap.getViewName());
1510       }
1511
1512     }
1513   }
1514
1515   public void doMouseReleasedDefineMode(MouseEvent evt)
1516   {
1517     if (stretchGroup == null)
1518     {
1519       return;
1520     }
1521     // always do this - annotation has own state
1522     // but defer colourscheme update until hidden sequences are passed in
1523     boolean vischange = stretchGroup.recalcConservation(true);
1524     // here we rely on stretchGroup == av.getSelection()
1525     needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1526     if (stretchGroup.cs != null)
1527     {
1528       stretchGroup.cs.alignmentChanged(stretchGroup,
1529               av.getHiddenRepSequences());
1530
1531       if (stretchGroup.cs.conservationApplied())
1532       {
1533         SliderPanel.setConservationSlider(ap, stretchGroup.cs,
1534                 stretchGroup.getName());
1535       }
1536       if (stretchGroup.cs.getThreshold() > 0)
1537       {
1538         SliderPanel.setPIDSliderSource(ap, stretchGroup.cs,
1539                 stretchGroup.getName());
1540       }
1541     }
1542     PaintRefresher.Refresh(ap, av.getSequenceSetId());
1543     ap.paintAlignment(needOverviewUpdate);
1544     needOverviewUpdate = false;
1545     changeEndRes = false;
1546     changeStartRes = false;
1547     stretchGroup = null;
1548     av.sendSelection();
1549   }
1550
1551   public void doMouseDraggedDefineMode(MouseEvent evt)
1552   {
1553     int res = findRes(evt);
1554     int y = findSeq(evt);
1555
1556     if (wrappedBlock != startWrapBlock)
1557     {
1558       return;
1559     }
1560
1561     if (stretchGroup == null)
1562     {
1563       return;
1564     }
1565
1566     mouseDragging = true;
1567
1568     if (y > av.getAlignment().getHeight())
1569     {
1570       y = av.getAlignment().getHeight() - 1;
1571     }
1572
1573     if (res >= av.getAlignment().getWidth())
1574     {
1575       res = av.getAlignment().getWidth() - 1;
1576     }
1577
1578     if (stretchGroup.getEndRes() == res)
1579     {
1580       // Edit end res position of selected group
1581       changeEndRes = true;
1582     }
1583     else if (stretchGroup.getStartRes() == res)
1584     {
1585       // Edit start res position of selected group
1586       changeStartRes = true;
1587     }
1588
1589     if (res < 0)
1590     {
1591       res = 0;
1592     }
1593
1594     if (changeEndRes)
1595     {
1596       if (res > (stretchGroup.getStartRes() - 1))
1597       {
1598         stretchGroup.setEndRes(res);
1599         needOverviewUpdate |= av.isSelectionDefinedGroup();
1600       }
1601     }
1602     else if (changeStartRes)
1603     {
1604       if (res < (stretchGroup.getEndRes() + 1))
1605       {
1606         stretchGroup.setStartRes(res);
1607         needOverviewUpdate |= av.isSelectionDefinedGroup();
1608       }
1609     }
1610
1611     int dragDirection = 0;
1612
1613     if (y > oldSeq)
1614     {
1615       dragDirection = 1;
1616     }
1617     else if (y < oldSeq)
1618     {
1619       dragDirection = -1;
1620     }
1621
1622     while ((y != oldSeq) && (oldSeq > -1)
1623             && (y < av.getAlignment().getHeight()))
1624     {
1625       // This routine ensures we don't skip any sequences, as the
1626       // selection is quite slow.
1627       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1628
1629       oldSeq += dragDirection;
1630
1631       if (oldSeq < 0)
1632       {
1633         break;
1634       }
1635
1636       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1637
1638       if (stretchGroup.getSequences(null).contains(nextSeq))
1639       {
1640         stretchGroup.deleteSequence(seq, false);
1641         needOverviewUpdate |= av.isSelectionDefinedGroup();
1642       }
1643       else
1644       {
1645         if (seq != null)
1646         {
1647           stretchGroup.addSequence(seq, false);
1648         }
1649
1650         stretchGroup.addSequence(nextSeq, false);
1651         needOverviewUpdate |= av.isSelectionDefinedGroup();
1652       }
1653     }
1654
1655     if (oldSeq < 0)
1656     {
1657       oldSeq = -1;
1658     }
1659
1660     if (res > av.getRanges().getEndRes()
1661             || res < av.getRanges().getStartRes()
1662             || y < av.getRanges().getStartSeq()
1663             || y > av.getRanges().getEndSeq())
1664     {
1665       mouseExited(evt);
1666     }
1667
1668     if (scrollThread != null)
1669     {
1670       scrollThread.setEvent(evt);
1671     }
1672
1673     seqCanvas.repaint();
1674   }
1675
1676   @Override
1677   public void mouseEntered(MouseEvent e)
1678   {
1679     if (oldSeq < 0)
1680     {
1681       oldSeq = 0;
1682     }
1683
1684     if (scrollThread != null)
1685     {
1686       scrollThread.running = false;
1687       scrollThread = null;
1688     }
1689   }
1690
1691   @Override
1692   public void mouseExited(MouseEvent e)
1693   {
1694     if (av.getWrapAlignment())
1695     {
1696       return;
1697     }
1698
1699     if (mouseDragging && scrollThread == null)
1700     {
1701       scrollThread = new ScrollThread();
1702     }
1703   }
1704
1705   void scrollCanvas(MouseEvent evt)
1706   {
1707     if (evt == null)
1708     {
1709       if (scrollThread != null)
1710       {
1711         scrollThread.running = false;
1712         scrollThread = null;
1713       }
1714       mouseDragging = false;
1715     }
1716     else
1717     {
1718       if (scrollThread == null)
1719       {
1720         scrollThread = new ScrollThread();
1721       }
1722
1723       mouseDragging = true;
1724       scrollThread.setEvent(evt);
1725     }
1726
1727   }
1728
1729   // this class allows scrolling off the bottom of the visible alignment
1730   class ScrollThread extends Thread
1731   {
1732     MouseEvent evt;
1733
1734     boolean running = false;
1735
1736     public ScrollThread()
1737     {
1738       start();
1739     }
1740
1741     public void setEvent(MouseEvent e)
1742     {
1743       evt = e;
1744     }
1745
1746     public void stopScrolling()
1747     {
1748       running = false;
1749     }
1750
1751     @Override
1752     public void run()
1753     {
1754       running = true;
1755       while (running)
1756       {
1757
1758         if (evt != null)
1759         {
1760
1761           if (mouseDragging && evt.getY() < 0
1762                   && av.getRanges().getStartSeq() > 0)
1763           {
1764             running = ap.scrollUp(true);
1765           }
1766
1767           if (mouseDragging && evt.getY() >= getSize().height
1768                   && av.getAlignment().getHeight() > av.getRanges()
1769                           .getEndSeq())
1770           {
1771             running = ap.scrollUp(false);
1772           }
1773
1774           if (mouseDragging && evt.getX() < 0)
1775           {
1776             running = ap.scrollRight(false);
1777           }
1778
1779           else if (mouseDragging && evt.getX() >= getSize().width)
1780           {
1781             running = ap.scrollRight(true);
1782           }
1783         }
1784
1785         try
1786         {
1787           Thread.sleep(75);
1788         } catch (Exception ex)
1789         {
1790         }
1791       }
1792     }
1793   }
1794
1795   /**
1796    * modify current selection according to a received message.
1797    */
1798   @Override
1799   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1800           HiddenColumns hidden, SelectionSource source)
1801   {
1802     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1803     // handles selection messages...
1804     // TODO: extend config options to allow user to control if selections may be
1805     // shared between viewports.
1806     if (av != null
1807             && (av == source || !av.followSelection || (source instanceof AlignViewport && ((AlignmentViewport) source)
1808                     .getSequenceSetId().equals(av.getSequenceSetId()))))
1809     {
1810       return;
1811     }
1812
1813     /*
1814      * Check for selection in a view of which this one is a dna/protein
1815      * complement.
1816      */
1817     if (selectionFromTranslation(seqsel, colsel, hidden, source))
1818     {
1819       return;
1820     }
1821
1822     // do we want to thread this ? (contention with seqsel and colsel locks, I
1823     // suspect)
1824     /*
1825      * only copy colsel if there is a real intersection between
1826      * sequence selection and this panel's alignment
1827      */
1828     boolean repaint = false;
1829     boolean copycolsel = false;
1830     if (av.getSelectionGroup() == null || !av.isSelectionGroupChanged(true))
1831     {
1832       SequenceGroup sgroup = null;
1833       if (seqsel != null && seqsel.getSize() > 0)
1834       {
1835         if (av.getAlignment() == null)
1836         {
1837           System.out
1838                   .println("Selection message: alignviewport av SeqSetId="
1839                           + av.getSequenceSetId() + " ViewId="
1840                           + av.getViewId()
1841                           + " 's alignment is NULL! returning immediatly.");
1842           return;
1843         }
1844         sgroup = seqsel.intersect(av.getAlignment(),
1845                 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
1846         if ((sgroup != null && sgroup.getSize() > 0))
1847         {
1848           copycolsel = true;
1849         }
1850       }
1851       if (sgroup != null && sgroup.getSize() > 0)
1852       {
1853         av.setSelectionGroup(sgroup);
1854       }
1855       else
1856       {
1857         av.setSelectionGroup(null);
1858       }
1859       repaint = av.isSelectionGroupChanged(true);
1860     }
1861     if (copycolsel
1862             && (av.getColumnSelection() == null || !av
1863                     .isColSelChanged(true)))
1864     {
1865       // the current selection is unset or from a previous message
1866       // so import the new colsel.
1867       if (colsel == null || colsel.isEmpty())
1868       {
1869         if (av.getColumnSelection() != null)
1870         {
1871           av.getColumnSelection().clear();
1872         }
1873       }
1874       else
1875       {
1876         // TODO: shift colSel according to the intersecting sequences
1877         if (av.getColumnSelection() == null)
1878         {
1879           av.setColumnSelection(new ColumnSelection(colsel));
1880         }
1881         else
1882         {
1883           av.getColumnSelection().setElementsFrom(colsel,
1884                   av.getAlignment().getHiddenColumns());
1885         }
1886       }
1887       repaint |= av.isColSelChanged(true);
1888     }
1889     if (copycolsel
1890             && av.hasHiddenColumns()
1891             && (av.getColumnSelection() == null || av.getAlignment()
1892                     .getHiddenColumns().getHiddenRegions() == null))
1893     {
1894       System.err.println("Bad things");
1895     }
1896     if (repaint)
1897     {
1898       ap.scalePanelHolder.repaint();
1899       ap.repaint();
1900     }
1901   }
1902
1903   /**
1904    * scroll to the given row/column - or nearest visible location
1905    * 
1906    * @param row
1907    * @param column
1908    */
1909   public void scrollTo(int row, int column)
1910   {
1911
1912     row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
1913     column = column < 0 ? ap.av.getRanges().getStartRes() : column;
1914     ap.scrollTo(column, column, row, true, true);
1915   }
1916
1917   /**
1918    * scroll to the given row - or nearest visible location
1919    * 
1920    * @param row
1921    */
1922   public void scrollToRow(int row)
1923   {
1924
1925     row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
1926     ap.scrollTo(ap.av.getRanges().getStartRes(), ap.av.getRanges()
1927             .getStartRes(), row, true, true);
1928   }
1929
1930   /**
1931    * scroll to the given column - or nearest visible location
1932    * 
1933    * @param column
1934    */
1935   public void scrollToColumn(int column)
1936   {
1937
1938     column = column < 0 ? ap.av.getRanges().getStartRes() : column;
1939     ap.scrollTo(column, column, ap.av.getRanges().getStartSeq(), true, true);
1940   }
1941
1942   /**
1943    * If this panel is a cdna/protein translation view of the selection source,
1944    * tries to map the source selection to a local one, and returns true. Else
1945    * returns false.
1946    * 
1947    * @param seqsel
1948    * @param colsel
1949    * @param source
1950    */
1951   protected boolean selectionFromTranslation(SequenceGroup seqsel,
1952           ColumnSelection colsel, HiddenColumns hidden,
1953           SelectionSource source)
1954   {
1955     if (!(source instanceof AlignViewportI))
1956     {
1957       return false;
1958     }
1959     final AlignViewportI sourceAv = (AlignViewportI) source;
1960     if (sourceAv.getCodingComplement() != av
1961             && av.getCodingComplement() != sourceAv)
1962     {
1963       return false;
1964     }
1965
1966     /*
1967      * Map sequence selection
1968      */
1969     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
1970     av.setSelectionGroup(sg);
1971     av.isSelectionGroupChanged(true);
1972
1973     /*
1974      * Map column selection
1975      */
1976     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
1977     // av);
1978     ColumnSelection cs = new ColumnSelection();
1979     HiddenColumns hs = new HiddenColumns();
1980     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
1981     av.setColumnSelection(cs);
1982     av.getAlignment().setHiddenColumns(hs);
1983
1984     ap.scalePanelHolder.repaint();
1985     ap.repaint();
1986
1987     return true;
1988   }
1989
1990 }