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