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