JAL-845 linked protein/dna 'slave' further PoC functionality
[jalview.git] / src / jalview / gui / SeqPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.AlignedCodonFrame;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.SearchResults;
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.MessageManager;
43
44 import java.awt.BorderLayout;
45 import java.awt.Color;
46 import java.awt.Font;
47 import java.awt.FontMetrics;
48 import java.awt.Point;
49 import java.awt.event.MouseEvent;
50 import java.awt.event.MouseListener;
51 import java.awt.event.MouseMotionListener;
52 import java.awt.event.MouseWheelEvent;
53 import java.awt.event.MouseWheelListener;
54 import java.util.List;
55 import java.util.Vector;
56
57 import javax.swing.JOptionPane;
58 import javax.swing.JPanel;
59 import javax.swing.ToolTipManager;
60
61 /**
62  * DOCUMENT ME!
63  * 
64  * @author $author$
65  * @version $Revision: 1.130 $
66  */
67 public class SeqPanel extends JPanel implements MouseListener,
68         MouseMotionListener, MouseWheelListener, SequenceListener,
69         SelectionListener
70
71 {
72   /** DOCUMENT ME!! */
73   public SeqCanvas seqCanvas;
74
75   /** DOCUMENT ME!! */
76   public AlignmentPanel ap;
77
78   protected int lastres;
79
80   protected int startseq;
81
82   protected AlignViewport av;
83
84   ScrollThread scrollThread = null;
85
86   boolean mouseDragging = false;
87
88   boolean editingSeqs = false;
89
90   boolean groupEditing = false;
91
92   // ////////////////////////////////////////
93   // ///Everything below this is for defining the boundary of the rubberband
94   // ////////////////////////////////////////
95   int oldSeq = -1;
96
97   boolean changeEndSeq = false;
98
99   boolean changeStartSeq = false;
100
101   boolean changeEndRes = false;
102
103   boolean changeStartRes = false;
104
105   SequenceGroup stretchGroup = null;
106
107   boolean remove = false;
108
109   Point lastMousePress;
110
111   boolean mouseWheelPressed = false;
112
113   StringBuffer keyboardNo1;
114
115   StringBuffer keyboardNo2;
116
117   java.net.URL linkImageURL;
118
119   private final SequenceAnnotationReport seqARep;
120
121   StringBuffer tooltipText = new StringBuffer();
122
123   String tmpString;
124
125   EditCommand editCommand;
126
127   StructureSelectionManager ssm;
128
129   /**
130    * Creates a new SeqPanel object.
131    * 
132    * @param avp
133    *          DOCUMENT ME!
134    * @param p
135    *          DOCUMENT ME!
136    */
137   public SeqPanel(AlignViewport av, AlignmentPanel ap)
138   {
139     linkImageURL = getClass().getResource("/images/link.gif");
140     seqARep = new SequenceAnnotationReport(linkImageURL.toString());
141     ToolTipManager.sharedInstance().registerComponent(this);
142     ToolTipManager.sharedInstance().setInitialDelay(0);
143     ToolTipManager.sharedInstance().setDismissDelay(10000);
144     this.av = av;
145     setBackground(Color.white);
146
147     seqCanvas = new SeqCanvas(ap);
148     setLayout(new BorderLayout());
149     add(seqCanvas, BorderLayout.CENTER);
150
151     this.ap = ap;
152
153     if (!av.isDataset())
154     {
155       addMouseMotionListener(this);
156       addMouseListener(this);
157       addMouseWheelListener(this);
158       ssm = av.getStructureSelectionManager();
159       ssm.addStructureViewerListener(this);
160       ssm.addSelectionListener(this);
161     }
162   }
163
164   int startWrapBlock = -1;
165
166   int wrappedBlock = -1;
167
168   int findRes(MouseEvent evt)
169   {
170     int res = 0;
171     int x = evt.getX();
172
173     if (av.wrapAlignment)
174     {
175
176       int hgap = av.charHeight;
177       if (av.scaleAboveWrapped)
178       {
179         hgap += av.charHeight;
180       }
181
182       int cHeight = av.getAlignment().getHeight() * av.charHeight + hgap
183               + seqCanvas.getAnnotationHeight();
184
185       int y = evt.getY();
186       y -= hgap;
187       x -= seqCanvas.LABEL_WEST;
188
189       int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
190       if (cwidth < 1)
191       {
192         return 0;
193       }
194
195       wrappedBlock = y / cHeight;
196       wrappedBlock += av.getStartRes() / cwidth;
197
198       res = wrappedBlock * cwidth + x / av.getCharWidth();
199
200     }
201     else
202     {
203       if (x > seqCanvas.getWidth() + seqCanvas.getWidth())
204       {
205         // make sure we calculate relative to visible alignment, rather than
206         // right-hand gutter
207         x = seqCanvas.getX() + seqCanvas.getWidth();
208       }
209       res = (x / av.getCharWidth()) + av.getStartRes();
210     }
211
212     if (av.hasHiddenColumns())
213     {
214       res = av.getColumnSelection().adjustForHiddenColumns(res);
215     }
216
217     return res;
218
219   }
220
221   int findSeq(MouseEvent evt)
222   {
223     int seq = 0;
224     int y = evt.getY();
225
226     if (av.wrapAlignment)
227     {
228       int hgap = av.charHeight;
229       if (av.scaleAboveWrapped)
230       {
231         hgap += av.charHeight;
232       }
233
234       int cHeight = av.getAlignment().getHeight() * av.charHeight + hgap
235               + seqCanvas.getAnnotationHeight();
236
237       y -= hgap;
238
239       seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
240               .getHeight() - 1);
241     }
242     else
243     {
244       seq = Math.min((y / av.getCharHeight()) + av.getStartSeq(), av
245               .getAlignment().getHeight() - 1);
246     }
247
248     return seq;
249   }
250
251   SequenceFeature[] findFeaturesAtRes(SequenceI sequence, int res)
252   {
253     Vector tmp = new Vector();
254     SequenceFeature[] features = sequence.getSequenceFeatures();
255     if (features != null)
256     {
257       for (int i = 0; i < features.length; i++)
258       {
259         if (av.featuresDisplayed == null
260                 || !av.featuresDisplayed.containsKey(features[i].getType()))
261         {
262           continue;
263         }
264
265         if (features[i].featureGroup != null
266                 && seqCanvas.fr.featureGroups != null
267                 && seqCanvas.fr.featureGroups
268                         .containsKey(features[i].featureGroup)
269                 && !((Boolean) seqCanvas.fr.featureGroups
270                         .get(features[i].featureGroup)).booleanValue())
271         {
272           continue;
273         }
274
275         if ((features[i].getBegin() <= res)
276                 && (features[i].getEnd() >= res))
277         {
278           tmp.addElement(features[i]);
279         }
280       }
281     }
282
283     features = new SequenceFeature[tmp.size()];
284     tmp.copyInto(features);
285
286     return features;
287   }
288
289   /**
290    * When all of a sequence of edits are complete, put the resulting edit list
291    * on the history stack (undo list), and reset flags for editing in progress.
292    */
293   void endEditing()
294   {
295     try
296     {
297       if (editCommand != null && editCommand.getSize() > 0)
298       {
299         ap.alignFrame.addHistoryItem(editCommand);
300         av.firePropertyChange("alignment", null, av.getAlignment()
301                 .getSequences());
302       }
303     } finally
304     {
305       /*
306        * Tidy up come what may...
307        */
308       startseq = -1;
309       lastres = -1;
310       editingSeqs = false;
311       groupEditing = false;
312       keyboardNo1 = null;
313       keyboardNo2 = null;
314       editCommand = null;
315     }
316   }
317
318   void setCursorRow()
319   {
320     seqCanvas.cursorY = getKeyboardNo1() - 1;
321     scrollToVisible();
322   }
323
324   void setCursorColumn()
325   {
326     seqCanvas.cursorX = getKeyboardNo1() - 1;
327     scrollToVisible();
328   }
329
330   void setCursorRowAndColumn()
331   {
332     if (keyboardNo2 == null)
333     {
334       keyboardNo2 = new StringBuffer();
335     }
336     else
337     {
338       seqCanvas.cursorX = getKeyboardNo1() - 1;
339       seqCanvas.cursorY = getKeyboardNo2() - 1;
340       scrollToVisible();
341     }
342   }
343
344   void setCursorPosition()
345   {
346     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
347
348     seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
349     scrollToVisible();
350   }
351
352   void moveCursor(int dx, int dy)
353   {
354     seqCanvas.cursorX += dx;
355     seqCanvas.cursorY += dy;
356     if (av.hasHiddenColumns()
357             && !av.getColumnSelection().isVisible(seqCanvas.cursorX))
358     {
359       int original = seqCanvas.cursorX - dx;
360       int maxWidth = av.getAlignment().getWidth();
361
362       while (!av.getColumnSelection().isVisible(seqCanvas.cursorX)
363               && seqCanvas.cursorX < maxWidth && seqCanvas.cursorX > 0)
364       {
365         seqCanvas.cursorX += dx;
366       }
367
368       if (seqCanvas.cursorX >= maxWidth
369               || !av.getColumnSelection().isVisible(seqCanvas.cursorX))
370       {
371         seqCanvas.cursorX = original;
372       }
373     }
374
375     scrollToVisible();
376   }
377
378   void scrollToVisible()
379   {
380     if (seqCanvas.cursorX < 0)
381     {
382       seqCanvas.cursorX = 0;
383     }
384     else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
385     {
386       seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
387     }
388
389     if (seqCanvas.cursorY < 0)
390     {
391       seqCanvas.cursorY = 0;
392     }
393     else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
394     {
395       seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
396     }
397
398     endEditing();
399     if (av.wrapAlignment)
400     {
401       ap.scrollToWrappedVisible(seqCanvas.cursorX);
402     }
403     else
404     {
405       while (seqCanvas.cursorY < av.startSeq)
406       {
407         ap.scrollUp(true);
408       }
409       while (seqCanvas.cursorY + 1 > av.endSeq)
410       {
411         ap.scrollUp(false);
412       }
413       if (!av.wrapAlignment)
414       {
415         while (seqCanvas.cursorX < av.getColumnSelection()
416                 .adjustForHiddenColumns(av.startRes))
417         {
418           if (!ap.scrollRight(false))
419           {
420             break;
421           }
422         }
423         while (seqCanvas.cursorX > av.getColumnSelection()
424                 .adjustForHiddenColumns(av.endRes))
425         {
426           if (!ap.scrollRight(true))
427           {
428             break;
429           }
430         }
431       }
432     }
433     setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
434             seqCanvas.cursorX, seqCanvas.cursorY);
435
436     seqCanvas.repaint();
437   }
438
439   void setSelectionAreaAtCursor(boolean topLeft)
440   {
441     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
442
443     if (av.getSelectionGroup() != null)
444     {
445       SequenceGroup sg = av.getSelectionGroup();
446       // Find the top and bottom of this group
447       int min = av.getAlignment().getHeight(), max = 0;
448       for (int i = 0; i < sg.getSize(); i++)
449       {
450         int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
451         if (index > max)
452         {
453           max = index;
454         }
455         if (index < min)
456         {
457           min = index;
458         }
459       }
460
461       max++;
462
463       if (topLeft)
464       {
465         sg.setStartRes(seqCanvas.cursorX);
466         if (sg.getEndRes() < seqCanvas.cursorX)
467         {
468           sg.setEndRes(seqCanvas.cursorX);
469         }
470
471         min = seqCanvas.cursorY;
472       }
473       else
474       {
475         sg.setEndRes(seqCanvas.cursorX);
476         if (sg.getStartRes() > seqCanvas.cursorX)
477         {
478           sg.setStartRes(seqCanvas.cursorX);
479         }
480
481         max = seqCanvas.cursorY + 1;
482       }
483
484       if (min > max)
485       {
486         // Only the user can do this
487         av.setSelectionGroup(null);
488       }
489       else
490       {
491         // Now add any sequences between min and max
492         sg.getSequences(null).clear();
493         for (int i = min; i < max; i++)
494         {
495           sg.addSequence(av.getAlignment().getSequenceAt(i), false);
496         }
497       }
498     }
499
500     if (av.getSelectionGroup() == null)
501     {
502       SequenceGroup sg = new SequenceGroup();
503       sg.setStartRes(seqCanvas.cursorX);
504       sg.setEndRes(seqCanvas.cursorX);
505       sg.addSequence(sequence, false);
506       av.setSelectionGroup(sg);
507     }
508
509     ap.paintAlignment(false);
510     av.sendSelection();
511   }
512
513   void insertGapAtCursor(boolean group)
514   {
515     groupEditing = group;
516     startseq = seqCanvas.cursorY;
517     lastres = seqCanvas.cursorX;
518     editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
519     endEditing();
520   }
521
522   void deleteGapAtCursor(boolean group)
523   {
524     groupEditing = group;
525     startseq = seqCanvas.cursorY;
526     lastres = seqCanvas.cursorX + getKeyboardNo1();
527     editSequence(false, false, seqCanvas.cursorX);
528     endEditing();
529   }
530
531   void insertNucAtCursor(boolean group, String nuc)
532   {
533     groupEditing = group;
534     startseq = seqCanvas.cursorY;
535     lastres = seqCanvas.cursorX;
536     editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
537     endEditing();
538   }
539
540   void numberPressed(char value)
541   {
542     if (keyboardNo1 == null)
543     {
544       keyboardNo1 = new StringBuffer();
545     }
546
547     if (keyboardNo2 != null)
548     {
549       keyboardNo2.append(value);
550     }
551     else
552     {
553       keyboardNo1.append(value);
554     }
555   }
556
557   int getKeyboardNo1()
558   {
559     try
560     {
561       if (keyboardNo1 != null)
562       {
563         int value = Integer.parseInt(keyboardNo1.toString());
564         keyboardNo1 = null;
565         return value;
566       }
567     } catch (Exception x)
568     {
569     }
570     keyboardNo1 = null;
571     return 1;
572   }
573
574   int getKeyboardNo2()
575   {
576     try
577     {
578       if (keyboardNo2 != null)
579       {
580         int value = Integer.parseInt(keyboardNo2.toString());
581         keyboardNo2 = null;
582         return value;
583       }
584     } catch (Exception x)
585     {
586     }
587     keyboardNo2 = null;
588     return 1;
589   }
590
591   /**
592    * DOCUMENT ME!
593    * 
594    * @param evt
595    *          DOCUMENT ME!
596    */
597   @Override
598   public void mouseReleased(MouseEvent evt)
599   {
600     mouseDragging = false;
601     mouseWheelPressed = false;
602
603     if (!editingSeqs)
604     {
605       doMouseReleasedDefineMode(evt);
606       return;
607     }
608
609     endEditing();
610   }
611
612   /**
613    * DOCUMENT ME!
614    * 
615    * @param evt
616    *          DOCUMENT ME!
617    */
618   @Override
619   public void mousePressed(MouseEvent evt)
620   {
621     lastMousePress = evt.getPoint();
622
623     if (javax.swing.SwingUtilities.isMiddleMouseButton(evt))
624     {
625       mouseWheelPressed = true;
626       return;
627     }
628
629     if (evt.isShiftDown() || evt.isAltDown() || evt.isControlDown())
630     {
631       if (evt.isAltDown() || evt.isControlDown())
632       {
633         groupEditing = true;
634       }
635       editingSeqs = true;
636     }
637     else
638     {
639       doMousePressedDefineMode(evt);
640       return;
641     }
642
643     int seq = findSeq(evt);
644     int res = findRes(evt);
645
646     if (seq < 0 || res < 0)
647     {
648       return;
649     }
650
651     if ((seq < av.getAlignment().getHeight())
652             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
653     {
654       startseq = seq;
655       lastres = res;
656     }
657     else
658     {
659       startseq = -1;
660       lastres = -1;
661     }
662
663     return;
664   }
665
666   String lastMessage;
667
668   public void mouseOverSequence(SequenceI sequence, int index, int pos)
669   {
670     String tmp = sequence.hashCode() + " " + index + " " + pos;
671
672     if (lastMessage == null || !lastMessage.equals(tmp))
673     {
674       // System.err.println("mouseOver Sequence: "+tmp);
675       ssm.mouseOverSequence(sequence, index, pos, av);
676     }
677     lastMessage = tmp;
678   }
679
680   @Override
681   public void highlightSequence(SearchResults results)
682   {
683     if (av.followHighlight)
684     {
685       if (ap.scrollToPosition(results, false))
686       {
687         seqCanvas.revalidate();
688       }
689     }
690     seqCanvas.highlightSearchResults(results);
691   }
692
693   @Override
694   public VamsasSource getVamsasSource()
695   {
696     return this.ap == null ? null : this.ap.av;
697   }
698   public void updateColours(SequenceI seq, int index)
699   {
700     System.out.println("update the seqPanel colours");
701     // repaint();
702   }
703
704   /**
705    * DOCUMENT ME!
706    * 
707    * @param evt
708    *          DOCUMENT ME!
709    */
710   @Override
711   public void mouseMoved(MouseEvent evt)
712   {
713     if (editingSeqs)
714     {
715       // This is because MacOSX creates a mouseMoved
716       // If control is down, other platforms will not.
717       mouseDragged(evt);
718     }
719
720     int res = findRes(evt);
721     int seq = findSeq(evt);
722     int pos;
723     if (res < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
724     {
725       return;
726     }
727
728     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
729
730     if (res >= sequence.getLength())
731     {
732       return;
733     }
734
735     pos = setStatusMessage(sequence, res, seq);
736     if (ssm != null && pos > -1)
737     {
738       mouseOverSequence(sequence, res, pos);
739     }
740
741     tooltipText.setLength(6); // Cuts the buffer back to <html>
742
743     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
744     if (groups != null)
745     {
746       for (int g = 0; g < groups.length; g++)
747       {
748         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
749         {
750           if (!groups[g].getName().startsWith("JTreeGroup")
751                   && !groups[g].getName().startsWith("JGroup"))
752           {
753             tooltipText.append(groups[g].getName());
754           }
755
756           if (groups[g].getDescription() != null)
757           {
758             tooltipText.append(": " + groups[g].getDescription());
759           }
760         }
761       }
762     }
763
764     // use aa to see if the mouse pointer is on a
765     if (av.showSequenceFeatures)
766     {
767       int rpos;
768       SequenceFeature[] features = findFeaturesAtRes(
769               sequence.getDatasetSequence(),
770               rpos = sequence.findPosition(res));
771       seqARep.appendFeatures(tooltipText, rpos, features,
772               this.ap.seqPanel.seqCanvas.fr.minmax);
773     }
774     if (tooltipText.length() == 6) // <html></html>
775     {
776       setToolTipText(null);
777       lastTooltip = null;
778     }
779     else
780     {
781       if (lastTooltip == null
782               || !lastTooltip.equals(tooltipText.toString()))
783       {
784         String formatedTooltipText = JvSwingUtils.wrapTooltip(true,
785                 tooltipText.toString());
786         // String formatedTooltipText = tooltipText.toString();
787         setToolTipText(formatedTooltipText);
788         lastTooltip = tooltipText.toString();
789       }
790
791     }
792
793   }
794
795   private Point lastp = null;
796
797   /*
798    * (non-Javadoc)
799    * 
800    * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
801    */
802   public Point getToolTipLocation(MouseEvent event)
803   {
804     int x = event.getX(), w = getWidth();
805     int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
806     // close to edge
807     Point p = lastp;
808     if (!event.isShiftDown() || p == null)
809     {
810       p = (tooltipText != null && tooltipText.length() > 6) ? new Point(
811               event.getX() + wdth, event.getY() - 20) : null;
812     }
813     /*
814      * TODO: try to modify position region is not obcured by tooltip
815      */
816     return lastp = p;
817   }
818
819   String lastTooltip;
820
821   /**
822    * Set status message in alignment panel
823    * 
824    * @param sequence
825    *          aligned sequence object
826    * @param res
827    *          alignment column
828    * @param seq
829    *          index of sequence in alignment
830    * @return position of res in sequence
831    */
832   int setStatusMessage(SequenceI sequence, int res, int seq)
833   {
834     int pos = -1;
835     StringBuilder text = new StringBuilder(32);
836     text.append("Sequence " + (seq + 1) + " ID: " + sequence.getName());
837
838     String residue = null;
839     /*
840      * Try to translate the display character to residue name (null for gap).
841      */
842     final String displayChar = String.valueOf(sequence.getCharAt(res));
843     if (av.getAlignment().isNucleotide())
844     {
845       residue = ResidueProperties.nucleotideName.get(displayChar);
846       if (residue != null)
847       {
848         text.append(" Nucleotide: ").append(residue);
849       }
850     }
851     else
852     {
853       residue = "X".equalsIgnoreCase(displayChar) ? "STOP"
854               : ResidueProperties.aa2Triplet.get(displayChar);
855       if (residue != null)
856       {
857         text.append(" Residue: ").append(residue);
858       }
859     }
860
861     if (residue != null)
862     {
863       pos = sequence.findPosition(res);
864       text.append(" (").append(Integer.toString(pos)).append(")");
865     }
866     ap.alignFrame.statusBar.setText(text.toString());
867     return pos;
868   }
869
870   /**
871    * DOCUMENT ME!
872    * 
873    * @param evt
874    *          DOCUMENT ME!
875    */
876   @Override
877   public void mouseDragged(MouseEvent evt)
878   {
879     if (mouseWheelPressed)
880     {
881       int oldWidth = av.charWidth;
882
883       // Which is bigger, left-right or up-down?
884       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
885               .getX() - lastMousePress.getX()))
886       {
887         int fontSize = av.font.getSize();
888
889         if (evt.getY() < lastMousePress.getY())
890         {
891           fontSize--;
892         }
893         else if (evt.getY() > lastMousePress.getY())
894         {
895           fontSize++;
896         }
897
898         if (fontSize < 1)
899         {
900           fontSize = 1;
901         }
902
903         av.setFont(new Font(av.font.getName(), av.font.getStyle(), fontSize));
904         av.charWidth = oldWidth;
905         ap.fontChanged();
906       }
907       else
908       {
909         if (evt.getX() < lastMousePress.getX() && av.charWidth > 1)
910         {
911           av.charWidth--;
912         }
913         else if (evt.getX() > lastMousePress.getX())
914         {
915           av.charWidth++;
916         }
917
918         ap.paintAlignment(false);
919       }
920
921       FontMetrics fm = getFontMetrics(av.getFont());
922       av.validCharWidth = fm.charWidth('M') <= av.charWidth;
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       SequenceFeature[] features = findFeaturesAtRes(
1427               sequence.getDatasetSequence(),
1428               sequence.findPosition(findRes(evt)));
1429
1430       if (features != null && features.length > 0)
1431       {
1432         SearchResults highlight = new SearchResults();
1433         highlight.addResult(sequence, features[0].getBegin(),
1434                 features[0].getEnd());
1435         seqCanvas.highlightSearchResults(highlight);
1436       }
1437       if (features != null && features.length > 0)
1438       {
1439         seqCanvas.getFeatureRenderer().amendFeatures(new SequenceI[]
1440         { sequence }, features, 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.wrapAlignment && 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       SequenceFeature[] allFeatures = findFeaturesAtRes(
1556               sequence.getDatasetSequence(), sequence.findPosition(res));
1557       Vector links = new Vector();
1558       for (int i = 0; i < allFeatures.length; i++)
1559       {
1560         if (allFeatures[i].links != null)
1561         {
1562           for (int j = 0; j < allFeatures[i].links.size(); j++)
1563           {
1564             links.addElement(allFeatures[i].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 && ((AlignViewport) 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 'slave'.
1892      */
1893     if (selectionAsSlave(seqsel, colsel, source))
1894     {
1895       return;
1896     }
1897
1898     // do we want to thread this ? (contention with seqsel and colsel locks, I
1899     // suspect)
1900     // rules are: colsel is copied if there is a real intersection between
1901     // sequence selection
1902     boolean repaint = false;
1903     boolean copycolsel = true;
1904
1905     SequenceGroup sgroup = null;
1906     if (seqsel != null && seqsel.getSize() > 0)
1907     {
1908       if (av.getAlignment() == null)
1909       {
1910         jalview.bin.Cache.log.warn("alignviewport av SeqSetId="
1911                 + av.getSequenceSetId() + " ViewId=" + av.getViewId()
1912                 + " 's alignment is NULL! returning immediately.");
1913         return;
1914       }
1915       sgroup = seqsel.intersect(av.getAlignment(),
1916               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
1917       if ((sgroup == null || sgroup.getSize() == 0)
1918               || (colsel == null || colsel.size() == 0))
1919       {
1920         // don't copy columns if the region didn't intersect.
1921         copycolsel = false;
1922       }
1923     }
1924     if (sgroup != null && sgroup.getSize() > 0)
1925     {
1926       av.setSelectionGroup(sgroup);
1927     }
1928     else
1929     {
1930       av.setSelectionGroup(null);
1931     }
1932     av.isSelectionGroupChanged(true);
1933     repaint = true;
1934
1935     if (copycolsel)
1936     {
1937       // the current selection is unset or from a previous message
1938       // so import the new colsel.
1939       if (colsel == null || colsel.size() == 0)
1940       {
1941         if (av.getColumnSelection() != null)
1942         {
1943           av.getColumnSelection().clear();
1944           repaint = true;
1945         }
1946       }
1947       else
1948       {
1949         // TODO: shift colSel according to the intersecting sequences
1950         if (av.getColumnSelection() == null)
1951         {
1952           av.setColumnSelection(new ColumnSelection(colsel));
1953         }
1954         else
1955         {
1956           av.getColumnSelection().setElementsFrom(colsel);
1957         }
1958       }
1959       av.isColSelChanged(true);
1960       repaint = true;
1961     }
1962
1963     if (copycolsel
1964             && av.hasHiddenColumns()
1965             && (av.getColumnSelection() == null || av.getColumnSelection()
1966                     .getHiddenColumns() == null))
1967     {
1968       System.err.println("Bad things");
1969     }
1970     if (repaint) // always true!
1971     {
1972       // probably finessing with multiple redraws here
1973       PaintRefresher.Refresh(this, av.getSequenceSetId());
1974       // ap.paintAlignment(false);
1975     }
1976   }
1977
1978   /**
1979    * If this panel is a 'slave' of the selection source, tries to map the source
1980    * selection to a local one, and returns true. Else returns false.
1981    * 
1982    * @param seqsel
1983    * @param colsel
1984    * @param source
1985    */
1986   protected boolean selectionAsSlave(SequenceGroup seqsel,
1987           ColumnSelection colsel, SelectionSource source)
1988   {
1989     if (!(source instanceof AlignViewportI)) {
1990       return false;
1991     }
1992     final AlignViewportI sourceAv = (AlignViewportI) source;
1993     if (sourceAv.getSlave() != av)
1994     {
1995       return false;
1996     }
1997
1998     /*
1999      * Map sequence selection. Note the SequenceGroup holds aligned sequences,
2000      * the mappings hold dataset sequences.
2001      */
2002     AlignedCodonFrame[] codonFrames = sourceAv.getAlignment()
2003             .getCodonFrames();
2004     SequenceGroup sg = new SequenceGroup();
2005     for (SequenceI selected : seqsel.getSequences())
2006     {
2007       for (AlignedCodonFrame acf : codonFrames)
2008       {
2009         SequenceI dnaSeq = acf.getDnaForAaSeq(selected);
2010         if (dnaSeq != null)
2011         {
2012           for (SequenceI seq : av.getAlignment().getSequences())
2013           {
2014             if (seq.getDatasetSequence() == dnaSeq)
2015             {
2016               sg.addSequence(seq, false);
2017               break;
2018             }
2019           }
2020         }
2021       }
2022     }
2023     av.setSelectionGroup(sg);
2024     av.isSelectionGroupChanged(true);
2025     // ((AlignmentViewport) slave).firePropertyChange("alignment", null, slave
2026     // .getAlignment()
2027     // .getSequences());
2028
2029     /*
2030      * Map column selection
2031      */
2032     // TODO
2033
2034     AlignmentPanel ap = av.getAlignPanel();
2035     PaintRefresher.Refresh(this, av.getSequenceSetId());
2036
2037     return true;
2038   }
2039 }