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