Merge remote-tracking branch 'origin/develop' into bug/JAL-2491
[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       av.getRanges().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         ranges.scrollUp(true);
239       }
240       while (seqCanvas.cursorY + 1 > ranges.getEndSeq())
241       {
242         ranges.scrollUp(false);
243       }
244       while (seqCanvas.cursorX < hidden.adjustForHiddenColumns(ranges
245               .getStartRes()))
246       {
247
248         if (!ranges.scrollRight(false))
249         {
250           break;
251         }
252       }
253       while (seqCanvas.cursorX > hidden.adjustForHiddenColumns(ranges
254               .getEndRes()))
255       {
256         if (!ranges.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       // don't allow highlight of protein/cDNA to also scroll a complementary
750       // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
751       // over residue to change abruptly, causing highlighted residue in panel 2
752       // to change, causing a scroll in panel 1 etc)
753       ap.setToScrollComplementPanel(false);
754       if (ap.scrollToPosition(results, true))
755       {
756         ap.alignFrame.repaint();
757       }
758       ap.setToScrollComplementPanel(true);
759     }
760     setStatusMessage(results);
761     seqCanvas.highlightSearchResults(results);
762
763   }
764
765   @Override
766   public VamsasSource getVamsasSource()
767   {
768     return this.ap == null ? null : this.ap.av;
769   }
770
771   @Override
772   public void updateColours(SequenceI seq, int index)
773   {
774     System.out.println("update the seqPanel colours");
775     // repaint();
776   }
777
778   @Override
779   public void mouseMoved(MouseEvent evt)
780   {
781     int res = findRes(evt);
782     int seq = findSeq(evt);
783
784     if (seq >= av.getAlignment().getHeight() || seq < 0 || res < 0)
785     {
786       if (tooltip != null)
787       {
788         tooltip.setTip("");
789       }
790       return;
791     }
792
793     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
794     if (res > sequence.getLength())
795     {
796       if (tooltip != null)
797       {
798         tooltip.setTip("");
799       }
800       return;
801     }
802
803     int respos = sequence.findPosition(res);
804     if (ssm != null)
805     {
806       mouseOverSequence(sequence, res, respos);
807     }
808
809     StringBuilder text = new StringBuilder();
810     text.append("Sequence ").append(Integer.toString(seq + 1))
811             .append(" ID: ").append(sequence.getName());
812
813     String obj = null;
814     final String ch = String.valueOf(sequence.getCharAt(res));
815     if (av.getAlignment().isNucleotide())
816     {
817       obj = ResidueProperties.nucleotideName.get(ch);
818       if (obj != null)
819       {
820         text.append(" Nucleotide: ").append(obj);
821       }
822     }
823     else
824     {
825       obj = "X".equalsIgnoreCase(ch) ? "X" : ResidueProperties.aa2Triplet
826               .get(ch);
827       if (obj != null)
828       {
829         text.append(" Residue: ").append(obj);
830       }
831     }
832
833     if (obj != null)
834     {
835       text.append(" (").append(Integer.toString(respos)).append(")");
836     }
837
838     ap.alignFrame.statusBar.setText(text.toString());
839
840     StringBuilder tooltipText = new StringBuilder();
841     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
842     if (groups != null)
843     {
844       for (int g = 0; g < groups.length; g++)
845       {
846         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
847         {
848           if (!groups[g].getName().startsWith("JTreeGroup")
849                   && !groups[g].getName().startsWith("JGroup"))
850           {
851             tooltipText.append(groups[g].getName()).append(" ");
852           }
853           if (groups[g].getDescription() != null)
854           {
855             tooltipText.append(groups[g].getDescription());
856           }
857           tooltipText.append("\n");
858         }
859       }
860     }
861
862     // use aa to see if the mouse pointer is on a
863     SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
864             sequence.findPosition(res));
865
866     int index = 0;
867     while (index < allFeatures.length)
868     {
869       SequenceFeature sf = allFeatures[index];
870
871       tooltipText.append(sf.getType() + " " + sf.begin + ":" + sf.end);
872
873       if (sf.getDescription() != null)
874       {
875         tooltipText.append(" " + sf.getDescription());
876       }
877
878       if (sf.getValue("status") != null)
879       {
880         String status = sf.getValue("status").toString();
881         if (status.length() > 0)
882         {
883           tooltipText.append(" (" + sf.getValue("status") + ")");
884         }
885       }
886       tooltipText.append("\n");
887
888       index++;
889     }
890
891     if (tooltip == null)
892     {
893       tooltip = new Tooltip(tooltipText.toString(), seqCanvas);
894     }
895     else
896     {
897       tooltip.setTip(tooltipText.toString());
898     }
899   }
900
901   SequenceFeature[] findFeaturesAtRes(SequenceI sequence, int res)
902   {
903     Vector tmp = new Vector();
904     SequenceFeature[] features = sequence.getSequenceFeatures();
905     if (features != null)
906     {
907       for (int i = 0; i < features.length; i++)
908       {
909         if (av.getFeaturesDisplayed() == null
910                 || !av.getFeaturesDisplayed().isVisible(
911                         features[i].getType()))
912         {
913           continue;
914         }
915
916         if (features[i].featureGroup != null
917                 && !seqCanvas.fr.checkGroupVisibility(
918                         features[i].featureGroup, false))
919         {
920           continue;
921         }
922
923         if ((features[i].getBegin() <= res)
924                 && (features[i].getEnd() >= res))
925         {
926           tmp.addElement(features[i]);
927         }
928       }
929     }
930
931     features = new SequenceFeature[tmp.size()];
932     tmp.copyInto(features);
933
934     return features;
935   }
936
937   Tooltip tooltip;
938
939   /**
940    * set when the current UI interaction has resulted in a change that requires
941    * overview shading to be recalculated. this could be changed to something
942    * more expressive that indicates what actually has changed, so selective
943    * redraws can be applied
944    */
945   private boolean needOverviewUpdate; // TODO: refactor to avcontroller
946
947   @Override
948   public void mouseDragged(MouseEvent evt)
949   {
950     if (mouseWheelPressed)
951     {
952       int oldWidth = av.getCharWidth();
953
954       // Which is bigger, left-right or up-down?
955       if (Math.abs(evt.getY() - lastMousePress.y) > Math.abs(evt.getX()
956               - lastMousePress.x))
957       {
958         int fontSize = av.font.getSize();
959
960         if (evt.getY() < lastMousePress.y && av.getCharHeight() > 1)
961         {
962           fontSize--;
963         }
964         else if (evt.getY() > lastMousePress.y)
965         {
966           fontSize++;
967         }
968
969         if (fontSize < 1)
970         {
971           fontSize = 1;
972         }
973
974         av.setFont(
975                 new Font(av.font.getName(), av.font.getStyle(), fontSize),
976                 true);
977         av.setCharWidth(oldWidth);
978       }
979       else
980       {
981         if (evt.getX() < lastMousePress.x && av.getCharWidth() > 1)
982         {
983           av.setCharWidth(av.getCharWidth() - 1);
984         }
985         else if (evt.getX() > lastMousePress.x)
986         {
987           av.setCharWidth(av.getCharWidth() + 1);
988         }
989
990         if (av.getCharWidth() < 1)
991         {
992           av.setCharWidth(1);
993         }
994       }
995
996       ap.fontChanged();
997
998       FontMetrics fm = getFontMetrics(av.getFont());
999       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1000
1001       lastMousePress = evt.getPoint();
1002
1003       ap.paintAlignment(false);
1004       ap.annotationPanel.image = null;
1005       return;
1006     }
1007
1008     if (!editingSeqs)
1009     {
1010       doMouseDraggedDefineMode(evt);
1011       return;
1012     }
1013
1014     int res = findRes(evt);
1015
1016     if (res < 0)
1017     {
1018       res = 0;
1019     }
1020
1021     if ((lastres == -1) || (lastres == res))
1022     {
1023       return;
1024     }
1025
1026     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1027     {
1028       // dragLeft, delete gap
1029       editSequence(false, res);
1030     }
1031     else
1032     {
1033       editSequence(true, res);
1034     }
1035
1036     mouseDragging = true;
1037     if (scrollThread != null)
1038     {
1039       scrollThread.setEvent(evt);
1040     }
1041
1042   }
1043
1044   synchronized void editSequence(boolean insertGap, int startres)
1045   {
1046     int fixedLeft = -1;
1047     int fixedRight = -1;
1048     boolean fixedColumns = false;
1049     SequenceGroup sg = av.getSelectionGroup();
1050
1051     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1052
1053     if (!groupEditing && av.hasHiddenRows())
1054     {
1055       if (av.isHiddenRepSequence(seq))
1056       {
1057         sg = av.getRepresentedSequences(seq);
1058         groupEditing = true;
1059       }
1060     }
1061
1062     StringBuffer message = new StringBuffer();
1063     if (groupEditing)
1064     {
1065       message.append(MessageManager.getString("action.edit_group")).append(
1066               ":");
1067       if (editCommand == null)
1068       {
1069         editCommand = new EditCommand(
1070                 MessageManager.getString("action.edit_group"));
1071       }
1072     }
1073     else
1074     {
1075       message.append(MessageManager.getString("label.edit_sequence"))
1076               .append(" " + seq.getName());
1077       String label = seq.getName();
1078       if (label.length() > 10)
1079       {
1080         label = label.substring(0, 10);
1081       }
1082       if (editCommand == null)
1083       {
1084         editCommand = new EditCommand(MessageManager.formatMessage(
1085                 "label.edit_params", new String[] { label }));
1086       }
1087     }
1088
1089     if (insertGap)
1090     {
1091       message.append(" insert ");
1092     }
1093     else
1094     {
1095       message.append(" delete ");
1096     }
1097
1098     message.append(Math.abs(startres - lastres) + " gaps.");
1099     ap.alignFrame.statusBar.setText(message.toString());
1100
1101     // Are we editing within a selection group?
1102     if (groupEditing
1103             || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1104                     .contains(seq)))
1105     {
1106       fixedColumns = true;
1107
1108       // sg might be null as the user may only see 1 sequence,
1109       // but the sequence represents a group
1110       if (sg == null)
1111       {
1112         if (!av.isHiddenRepSequence(seq))
1113         {
1114           endEditing();
1115           return;
1116         }
1117
1118         sg = av.getRepresentedSequences(seq);
1119       }
1120
1121       fixedLeft = sg.getStartRes();
1122       fixedRight = sg.getEndRes();
1123
1124       if ((startres < fixedLeft && lastres >= fixedLeft)
1125               || (startres >= fixedLeft && lastres < fixedLeft)
1126               || (startres > fixedRight && lastres <= fixedRight)
1127               || (startres <= fixedRight && lastres > fixedRight))
1128       {
1129         endEditing();
1130         return;
1131       }
1132
1133       if (fixedLeft > startres)
1134       {
1135         fixedRight = fixedLeft - 1;
1136         fixedLeft = 0;
1137       }
1138       else if (fixedRight < startres)
1139       {
1140         fixedLeft = fixedRight;
1141         fixedRight = -1;
1142       }
1143     }
1144
1145     if (av.hasHiddenColumns())
1146     {
1147       fixedColumns = true;
1148       int y1 = av.getAlignment().getHiddenColumns()
1149               .getHiddenBoundaryLeft(startres);
1150       int y2 = av.getAlignment().getHiddenColumns()
1151               .getHiddenBoundaryRight(startres);
1152
1153       if ((insertGap && startres > y1 && lastres < y1)
1154               || (!insertGap && startres < y2 && lastres > y2))
1155       {
1156         endEditing();
1157         return;
1158       }
1159
1160       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1161       // Selection spans a hidden region
1162       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1163       {
1164         if (startres >= y2)
1165         {
1166           fixedLeft = y2;
1167         }
1168         else
1169         {
1170           fixedRight = y2 - 1;
1171         }
1172       }
1173     }
1174
1175     if (groupEditing)
1176     {
1177       SequenceI[] groupSeqs = sg.getSequences(av.getHiddenRepSequences())
1178               .toArray(new SequenceI[0]);
1179
1180       // drag to right
1181       if (insertGap)
1182       {
1183         // If the user has selected the whole sequence, and is dragging to
1184         // the right, we can still extend the alignment and selectionGroup
1185         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1186                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1187         {
1188           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1189           fixedRight = sg.getEndRes();
1190         }
1191
1192         // Is it valid with fixed columns??
1193         // Find the next gap before the end
1194         // of the visible region boundary
1195         boolean blank = false;
1196         for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1197         {
1198           blank = true;
1199
1200           for (SequenceI gs : groupSeqs)
1201           {
1202             for (int j = 0; j < startres - lastres; j++)
1203             {
1204               if (!jalview.util.Comparison.isGap(gs.getCharAt(fixedRight
1205                       - j)))
1206               {
1207                 blank = false;
1208                 break;
1209               }
1210             }
1211           }
1212           if (blank)
1213           {
1214             break;
1215           }
1216         }
1217
1218         if (!blank)
1219         {
1220           if (sg.getSize() == av.getAlignment().getHeight())
1221           {
1222             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1223                     .getHiddenColumns().getHiddenBoundaryRight(startres)))
1224             {
1225               endEditing();
1226               return;
1227             }
1228
1229             int alWidth = av.getAlignment().getWidth();
1230             if (av.hasHiddenRows())
1231             {
1232               int hwidth = av.getAlignment().getHiddenSequences()
1233                       .getWidth();
1234               if (hwidth > alWidth)
1235               {
1236                 alWidth = hwidth;
1237               }
1238             }
1239             // We can still insert gaps if the selectionGroup
1240             // contains all the sequences
1241             sg.setEndRes(sg.getEndRes() + startres - lastres);
1242             fixedRight = alWidth + startres - lastres;
1243           }
1244           else
1245           {
1246             endEditing();
1247             return;
1248           }
1249         }
1250       }
1251
1252       // drag to left
1253       else if (!insertGap)
1254       {
1255         // / Are we able to delete?
1256         // ie are all columns blank?
1257
1258         for (SequenceI gs : groupSeqs)
1259         {
1260           for (int j = startres; j < lastres; j++)
1261           {
1262             if (gs.getLength() <= j)
1263             {
1264               continue;
1265             }
1266
1267             if (!jalview.util.Comparison.isGap(gs.getCharAt(j)))
1268             {
1269               // Not a gap, block edit not valid
1270               endEditing();
1271               return;
1272             }
1273           }
1274         }
1275       }
1276
1277       if (insertGap)
1278       {
1279         // dragging to the right
1280         if (fixedColumns && fixedRight != -1)
1281         {
1282           for (int j = lastres; j < startres; j++)
1283           {
1284             insertChar(j, groupSeqs, fixedRight);
1285           }
1286         }
1287         else
1288         {
1289           editCommand.appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1290                   startres - lastres, av.getAlignment(), true);
1291         }
1292       }
1293       else
1294       {
1295         // dragging to the left
1296         if (fixedColumns && fixedRight != -1)
1297         {
1298           for (int j = lastres; j > startres; j--)
1299           {
1300             deleteChar(startres, groupSeqs, fixedRight);
1301           }
1302         }
1303         else
1304         {
1305           editCommand.appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1306                   lastres - startres, av.getAlignment(), true);
1307         }
1308
1309       }
1310     }
1311     else
1312     // ///Editing a single sequence///////////
1313     {
1314       if (insertGap)
1315       {
1316         // dragging to the right
1317         if (fixedColumns && fixedRight != -1)
1318         {
1319           for (int j = lastres; j < startres; j++)
1320           {
1321             insertChar(j, new SequenceI[] { seq }, fixedRight);
1322           }
1323         }
1324         else
1325         {
1326           editCommand.appendEdit(Action.INSERT_GAP,
1327                   new SequenceI[] { seq }, lastres, startres - lastres,
1328                   av.getAlignment(), true);
1329         }
1330       }
1331       else
1332       {
1333         // dragging to the left
1334         if (fixedColumns && fixedRight != -1)
1335         {
1336           for (int j = lastres; j > startres; j--)
1337           {
1338             if (!jalview.util.Comparison.isGap(seq.getCharAt(startres)))
1339             {
1340               endEditing();
1341               break;
1342             }
1343             deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1344           }
1345         }
1346         else
1347         {
1348           // could be a keyboard edit trying to delete none gaps
1349           int max = 0;
1350           for (int m = startres; m < lastres; m++)
1351           {
1352             if (!jalview.util.Comparison.isGap(seq.getCharAt(m)))
1353             {
1354               break;
1355             }
1356             max++;
1357           }
1358
1359           if (max > 0)
1360           {
1361             editCommand.appendEdit(Action.DELETE_GAP,
1362                     new SequenceI[] { seq }, startres, max,
1363                     av.getAlignment(), true);
1364           }
1365         }
1366       }
1367     }
1368
1369     lastres = startres;
1370     seqCanvas.repaint();
1371   }
1372
1373   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1374   {
1375     int blankColumn = fixedColumn;
1376     for (int s = 0; s < seq.length; s++)
1377     {
1378       // Find the next gap before the end of the visible region boundary
1379       // If lastCol > j, theres a boundary after the gap insertion
1380
1381       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1382       {
1383         if (jalview.util.Comparison.isGap(seq[s].getCharAt(blankColumn)))
1384         {
1385           // Theres a space, so break and insert the gap
1386           break;
1387         }
1388       }
1389
1390       if (blankColumn <= j)
1391       {
1392         blankColumn = fixedColumn;
1393         endEditing();
1394         return;
1395       }
1396     }
1397
1398     editCommand.appendEdit(Action.DELETE_GAP, seq, blankColumn, 1,
1399             av.getAlignment(), true);
1400
1401     editCommand.appendEdit(Action.INSERT_GAP, seq, j, 1, av.getAlignment(),
1402             true);
1403
1404   }
1405
1406   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1407   {
1408
1409     editCommand.appendEdit(Action.DELETE_GAP, seq, j, 1, av.getAlignment(),
1410             true);
1411
1412     editCommand.appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1,
1413             av.getAlignment(), true);
1414   }
1415
1416   // ////////////////////////////////////////
1417   // ///Everything below this is for defining the boundary of the rubberband
1418   // ////////////////////////////////////////
1419   public void doMousePressedDefineMode(MouseEvent evt)
1420   {
1421     if (scrollThread != null)
1422     {
1423       scrollThread.running = false;
1424       scrollThread = null;
1425     }
1426
1427     int res = findRes(evt);
1428     int seq = findSeq(evt);
1429     oldSeq = seq;
1430     startWrapBlock = wrappedBlock;
1431
1432     if (seq == -1)
1433     {
1434       return;
1435     }
1436
1437     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1438
1439     if (sequence == null || res > sequence.getLength())
1440     {
1441       return;
1442     }
1443
1444     stretchGroup = av.getSelectionGroup();
1445
1446     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1447     {
1448       stretchGroup = av.getAlignment().findGroup(sequence, res);
1449       if (stretchGroup != null)
1450       {
1451         // only update the current selection if the popup menu has a group to
1452         // focus on
1453         av.setSelectionGroup(stretchGroup);
1454       }
1455     }
1456
1457     // DETECT RIGHT MOUSE BUTTON IN AWT
1458     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK)
1459     {
1460       SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
1461               sequence.findPosition(res));
1462
1463       Vector<String> links = null;
1464       if (allFeatures != null)
1465       {
1466         for (int i = 0; i < allFeatures.length; i++)
1467         {
1468           if (allFeatures[i].links != null)
1469           {
1470             if (links == null)
1471             {
1472               links = new Vector<String>();
1473             }
1474             for (int j = 0; j < allFeatures[i].links.size(); j++)
1475             {
1476               links.addElement(allFeatures[i].links.elementAt(j));
1477             }
1478           }
1479         }
1480       }
1481       APopupMenu popup = new APopupMenu(ap, null, links);
1482       this.add(popup);
1483       popup.show(this, evt.getX(), evt.getY());
1484       return;
1485     }
1486
1487     if (av.cursorMode)
1488     {
1489       seqCanvas.cursorX = findRes(evt);
1490       seqCanvas.cursorY = findSeq(evt);
1491       seqCanvas.repaint();
1492       return;
1493     }
1494
1495     // Only if left mouse button do we want to change group sizes
1496
1497     if (stretchGroup == null)
1498     {
1499       // define a new group here
1500       SequenceGroup sg = new SequenceGroup();
1501       sg.setStartRes(res);
1502       sg.setEndRes(res);
1503       sg.addSequence(sequence, false);
1504       av.setSelectionGroup(sg);
1505       stretchGroup = sg;
1506
1507       if (av.getConservationSelected())
1508       {
1509         SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1510                 ap.getViewName());
1511       }
1512       if (av.getAbovePIDThreshold())
1513       {
1514         SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1515                 ap.getViewName());
1516       }
1517
1518     }
1519   }
1520
1521   public void doMouseReleasedDefineMode(MouseEvent evt)
1522   {
1523     if (stretchGroup == null)
1524     {
1525       return;
1526     }
1527     // always do this - annotation has own state
1528     // but defer colourscheme update until hidden sequences are passed in
1529     boolean vischange = stretchGroup.recalcConservation(true);
1530     // here we rely on stretchGroup == av.getSelection()
1531     needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1532     if (stretchGroup.cs != null)
1533     {
1534       stretchGroup.cs.alignmentChanged(stretchGroup,
1535               av.getHiddenRepSequences());
1536
1537       if (stretchGroup.cs.conservationApplied())
1538       {
1539         SliderPanel.setConservationSlider(ap, stretchGroup.cs,
1540                 stretchGroup.getName());
1541       }
1542       if (stretchGroup.cs.getThreshold() > 0)
1543       {
1544         SliderPanel.setPIDSliderSource(ap, stretchGroup.cs,
1545                 stretchGroup.getName());
1546       }
1547     }
1548     PaintRefresher.Refresh(ap, av.getSequenceSetId());
1549     ap.paintAlignment(needOverviewUpdate);
1550     needOverviewUpdate = false;
1551     changeEndRes = false;
1552     changeStartRes = false;
1553     stretchGroup = null;
1554     av.sendSelection();
1555   }
1556
1557   public void doMouseDraggedDefineMode(MouseEvent evt)
1558   {
1559     int res = findRes(evt);
1560     int y = findSeq(evt);
1561
1562     if (wrappedBlock != startWrapBlock)
1563     {
1564       return;
1565     }
1566
1567     if (stretchGroup == null)
1568     {
1569       return;
1570     }
1571
1572     mouseDragging = true;
1573
1574     if (y > av.getAlignment().getHeight())
1575     {
1576       y = av.getAlignment().getHeight() - 1;
1577     }
1578
1579     if (res >= av.getAlignment().getWidth())
1580     {
1581       res = av.getAlignment().getWidth() - 1;
1582     }
1583
1584     if (stretchGroup.getEndRes() == res)
1585     {
1586       // Edit end res position of selected group
1587       changeEndRes = true;
1588     }
1589     else if (stretchGroup.getStartRes() == res)
1590     {
1591       // Edit start res position of selected group
1592       changeStartRes = true;
1593     }
1594
1595     if (res < 0)
1596     {
1597       res = 0;
1598     }
1599
1600     if (changeEndRes)
1601     {
1602       if (res > (stretchGroup.getStartRes() - 1))
1603       {
1604         stretchGroup.setEndRes(res);
1605         needOverviewUpdate |= av.isSelectionDefinedGroup();
1606       }
1607     }
1608     else if (changeStartRes)
1609     {
1610       if (res < (stretchGroup.getEndRes() + 1))
1611       {
1612         stretchGroup.setStartRes(res);
1613         needOverviewUpdate |= av.isSelectionDefinedGroup();
1614       }
1615     }
1616
1617     int dragDirection = 0;
1618
1619     if (y > oldSeq)
1620     {
1621       dragDirection = 1;
1622     }
1623     else if (y < oldSeq)
1624     {
1625       dragDirection = -1;
1626     }
1627
1628     while ((y != oldSeq) && (oldSeq > -1)
1629             && (y < av.getAlignment().getHeight()))
1630     {
1631       // This routine ensures we don't skip any sequences, as the
1632       // selection is quite slow.
1633       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1634
1635       oldSeq += dragDirection;
1636
1637       if (oldSeq < 0)
1638       {
1639         break;
1640       }
1641
1642       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1643
1644       if (stretchGroup.getSequences(null).contains(nextSeq))
1645       {
1646         stretchGroup.deleteSequence(seq, false);
1647         needOverviewUpdate |= av.isSelectionDefinedGroup();
1648       }
1649       else
1650       {
1651         if (seq != null)
1652         {
1653           stretchGroup.addSequence(seq, false);
1654         }
1655
1656         stretchGroup.addSequence(nextSeq, false);
1657         needOverviewUpdate |= av.isSelectionDefinedGroup();
1658       }
1659     }
1660
1661     if (oldSeq < 0)
1662     {
1663       oldSeq = -1;
1664     }
1665
1666     if (res > av.getRanges().getEndRes()
1667             || res < av.getRanges().getStartRes()
1668             || y < av.getRanges().getStartSeq()
1669             || y > av.getRanges().getEndSeq())
1670     {
1671       mouseExited(evt);
1672     }
1673
1674     if (scrollThread != null)
1675     {
1676       scrollThread.setEvent(evt);
1677     }
1678
1679     seqCanvas.repaint();
1680   }
1681
1682   @Override
1683   public void mouseEntered(MouseEvent e)
1684   {
1685     if (oldSeq < 0)
1686     {
1687       oldSeq = 0;
1688     }
1689
1690     if (scrollThread != null)
1691     {
1692       scrollThread.running = false;
1693       scrollThread = null;
1694     }
1695   }
1696
1697   @Override
1698   public void mouseExited(MouseEvent e)
1699   {
1700     if (av.getWrapAlignment())
1701     {
1702       return;
1703     }
1704
1705     if (mouseDragging && scrollThread == null)
1706     {
1707       scrollThread = new ScrollThread();
1708     }
1709   }
1710
1711   void scrollCanvas(MouseEvent evt)
1712   {
1713     if (evt == null)
1714     {
1715       if (scrollThread != null)
1716       {
1717         scrollThread.running = false;
1718         scrollThread = null;
1719       }
1720       mouseDragging = false;
1721     }
1722     else
1723     {
1724       if (scrollThread == null)
1725       {
1726         scrollThread = new ScrollThread();
1727       }
1728
1729       mouseDragging = true;
1730       scrollThread.setEvent(evt);
1731     }
1732
1733   }
1734
1735   // this class allows scrolling off the bottom of the visible alignment
1736   class ScrollThread extends Thread
1737   {
1738     MouseEvent evt;
1739
1740     boolean running = false;
1741
1742     public ScrollThread()
1743     {
1744       start();
1745     }
1746
1747     public void setEvent(MouseEvent e)
1748     {
1749       evt = e;
1750     }
1751
1752     public void stopScrolling()
1753     {
1754       running = false;
1755     }
1756
1757     @Override
1758     public void run()
1759     {
1760       running = true;
1761       while (running)
1762       {
1763
1764         if (evt != null)
1765         {
1766
1767           if (mouseDragging && evt.getY() < 0
1768                   && av.getRanges().getStartSeq() > 0)
1769           {
1770             running = av.getRanges().scrollUp(true);
1771           }
1772
1773           if (mouseDragging && evt.getY() >= getSize().height
1774                   && av.getAlignment().getHeight() > av.getRanges()
1775                           .getEndSeq())
1776           {
1777             running = av.getRanges().scrollUp(false);
1778           }
1779
1780           if (mouseDragging && evt.getX() < 0)
1781           {
1782             running = av.getRanges().scrollRight(false);
1783           }
1784
1785           else if (mouseDragging && evt.getX() >= getSize().width)
1786           {
1787             running = av.getRanges().scrollRight(true);
1788           }
1789         }
1790
1791         try
1792         {
1793           Thread.sleep(75);
1794         } catch (Exception ex)
1795         {
1796         }
1797       }
1798     }
1799   }
1800
1801   /**
1802    * modify current selection according to a received message.
1803    */
1804   @Override
1805   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1806           HiddenColumns hidden, SelectionSource source)
1807   {
1808     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1809     // handles selection messages...
1810     // TODO: extend config options to allow user to control if selections may be
1811     // shared between viewports.
1812     if (av != null
1813             && (av == source || !av.followSelection || (source instanceof AlignViewport && ((AlignmentViewport) source)
1814                     .getSequenceSetId().equals(av.getSequenceSetId()))))
1815     {
1816       return;
1817     }
1818
1819     /*
1820      * Check for selection in a view of which this one is a dna/protein
1821      * complement.
1822      */
1823     if (selectionFromTranslation(seqsel, colsel, hidden, source))
1824     {
1825       return;
1826     }
1827
1828     // do we want to thread this ? (contention with seqsel and colsel locks, I
1829     // suspect)
1830     /*
1831      * only copy colsel if there is a real intersection between
1832      * sequence selection and this panel's alignment
1833      */
1834     boolean repaint = false;
1835     boolean copycolsel = false;
1836     if (av.getSelectionGroup() == null || !av.isSelectionGroupChanged(true))
1837     {
1838       SequenceGroup sgroup = null;
1839       if (seqsel != null && seqsel.getSize() > 0)
1840       {
1841         if (av.getAlignment() == null)
1842         {
1843           System.out
1844                   .println("Selection message: alignviewport av SeqSetId="
1845                           + av.getSequenceSetId() + " ViewId="
1846                           + av.getViewId()
1847                           + " 's alignment is NULL! returning immediatly.");
1848           return;
1849         }
1850         sgroup = seqsel.intersect(av.getAlignment(),
1851                 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
1852         if ((sgroup != null && sgroup.getSize() > 0))
1853         {
1854           copycolsel = true;
1855         }
1856       }
1857       if (sgroup != null && sgroup.getSize() > 0)
1858       {
1859         av.setSelectionGroup(sgroup);
1860       }
1861       else
1862       {
1863         av.setSelectionGroup(null);
1864       }
1865       repaint = av.isSelectionGroupChanged(true);
1866     }
1867     if (copycolsel
1868             && (av.getColumnSelection() == null || !av
1869                     .isColSelChanged(true)))
1870     {
1871       // the current selection is unset or from a previous message
1872       // so import the new colsel.
1873       if (colsel == null || colsel.isEmpty())
1874       {
1875         if (av.getColumnSelection() != null)
1876         {
1877           av.getColumnSelection().clear();
1878         }
1879       }
1880       else
1881       {
1882         // TODO: shift colSel according to the intersecting sequences
1883         if (av.getColumnSelection() == null)
1884         {
1885           av.setColumnSelection(new ColumnSelection(colsel));
1886         }
1887         else
1888         {
1889           av.getColumnSelection().setElementsFrom(colsel,
1890                   av.getAlignment().getHiddenColumns());
1891         }
1892       }
1893       repaint |= av.isColSelChanged(true);
1894     }
1895     if (copycolsel
1896             && av.hasHiddenColumns()
1897             && (av.getColumnSelection() == null || av.getAlignment()
1898                     .getHiddenColumns().getHiddenRegions() == null))
1899     {
1900       System.err.println("Bad things");
1901     }
1902     if (repaint)
1903     {
1904       ap.scalePanelHolder.repaint();
1905       ap.repaint();
1906     }
1907   }
1908
1909   /**
1910    * scroll to the given row/column - or nearest visible location
1911    * 
1912    * @param row
1913    * @param column
1914    */
1915   public void scrollTo(int row, int column)
1916   {
1917
1918     row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
1919     column = column < 0 ? ap.av.getRanges().getStartRes() : column;
1920     ap.scrollTo(column, column, row, true, true);
1921   }
1922
1923   /**
1924    * scroll to the given row - or nearest visible location
1925    * 
1926    * @param row
1927    */
1928   public void scrollToRow(int row)
1929   {
1930
1931     row = row < 0 ? ap.av.getRanges().getStartSeq() : row;
1932     ap.scrollTo(ap.av.getRanges().getStartRes(), ap.av.getRanges()
1933             .getStartRes(), row, true, true);
1934   }
1935
1936   /**
1937    * scroll to the given column - or nearest visible location
1938    * 
1939    * @param column
1940    */
1941   public void scrollToColumn(int column)
1942   {
1943
1944     column = column < 0 ? ap.av.getRanges().getStartRes() : column;
1945     ap.scrollTo(column, column, ap.av.getRanges().getStartSeq(), true, true);
1946   }
1947
1948   /**
1949    * If this panel is a cdna/protein translation view of the selection source,
1950    * tries to map the source selection to a local one, and returns true. Else
1951    * returns false.
1952    * 
1953    * @param seqsel
1954    * @param colsel
1955    * @param source
1956    */
1957   protected boolean selectionFromTranslation(SequenceGroup seqsel,
1958           ColumnSelection colsel, HiddenColumns hidden,
1959           SelectionSource source)
1960   {
1961     if (!(source instanceof AlignViewportI))
1962     {
1963       return false;
1964     }
1965     final AlignViewportI sourceAv = (AlignViewportI) source;
1966     if (sourceAv.getCodingComplement() != av
1967             && av.getCodingComplement() != sourceAv)
1968     {
1969       return false;
1970     }
1971
1972     /*
1973      * Map sequence selection
1974      */
1975     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
1976     av.setSelectionGroup(sg);
1977     av.isSelectionGroupChanged(true);
1978
1979     /*
1980      * Map column selection
1981      */
1982     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
1983     // av);
1984     ColumnSelection cs = new ColumnSelection();
1985     HiddenColumns hs = new HiddenColumns();
1986     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
1987     av.setColumnSelection(cs);
1988     av.getAlignment().setHiddenColumns(hs);
1989
1990     ap.scalePanelHolder.repaint();
1991     ap.repaint();
1992
1993     return true;
1994   }
1995
1996 }