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