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