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