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