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