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