JAL-2773 add new flag to paintAlignment(updateOverview,updateStructures) and first...
[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,
136               av.getAlignment().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() && !av.getAlignment().getHiddenColumns()
187             .isVisible(seqCanvas.cursorX))
188     {
189       int original = seqCanvas.cursorX - dx;
190       int maxWidth = av.getAlignment().getWidth();
191
192       while (!av.getAlignment().getHiddenColumns()
193               .isVisible(seqCanvas.cursorX) && seqCanvas.cursorX < maxWidth
194               && seqCanvas.cursorX > 0)
195       {
196         seqCanvas.cursorX += dx;
197       }
198
199       if (seqCanvas.cursorX >= maxWidth || !av.getAlignment()
200               .getHiddenColumns().isVisible(seqCanvas.cursorX))
201       {
202         seqCanvas.cursorX = original;
203       }
204     }
205     scrollToVisible();
206   }
207
208   void scrollToVisible()
209   {
210     if (seqCanvas.cursorX < 0)
211     {
212       seqCanvas.cursorX = 0;
213     }
214     else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
215     {
216       seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
217     }
218
219     if (seqCanvas.cursorY < 0)
220     {
221       seqCanvas.cursorY = 0;
222     }
223     else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
224     {
225       seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
226     }
227
228     endEditing();
229     if (av.getWrapAlignment())
230     {
231       av.getRanges().scrollToWrappedVisible(seqCanvas.cursorX);
232     }
233     else
234     {
235       ViewportRanges ranges = av.getRanges();
236       HiddenColumns hidden = av.getAlignment().getHiddenColumns();
237       while (seqCanvas.cursorY < ranges.getStartSeq())
238       {
239         ranges.scrollUp(true);
240       }
241       while (seqCanvas.cursorY > ranges.getEndSeq())
242       {
243         ranges.scrollUp(false);
244       }
245       while (seqCanvas.cursorX < hidden
246               .adjustForHiddenColumns(ranges.getStartRes()))
247       {
248
249         if (!ranges.scrollRight(false))
250         {
251           break;
252         }
253       }
254       while (seqCanvas.cursorX > hidden
255               .adjustForHiddenColumns(ranges.getEndRes()))
256       {
257         if (!ranges.scrollRight(true))
258         {
259           break;
260         }
261       }
262     }
263     setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
264             seqCanvas.cursorX, seqCanvas.cursorY);
265
266     seqCanvas.repaint();
267   }
268
269   void setSelectionAreaAtCursor(boolean topLeft)
270   {
271     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
272
273     if (av.getSelectionGroup() != null)
274     {
275       SequenceGroup sg = av.getSelectionGroup();
276       // Find the top and bottom of this group
277       int min = av.getAlignment().getHeight(), max = 0;
278       for (int i = 0; i < sg.getSize(); i++)
279       {
280         int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
281         if (index > max)
282         {
283           max = index;
284         }
285         if (index < min)
286         {
287           min = index;
288         }
289       }
290
291       max++;
292
293       if (topLeft)
294       {
295         sg.setStartRes(seqCanvas.cursorX);
296         if (sg.getEndRes() < seqCanvas.cursorX)
297         {
298           sg.setEndRes(seqCanvas.cursorX);
299         }
300
301         min = seqCanvas.cursorY;
302       }
303       else
304       {
305         sg.setEndRes(seqCanvas.cursorX);
306         if (sg.getStartRes() > seqCanvas.cursorX)
307         {
308           sg.setStartRes(seqCanvas.cursorX);
309         }
310
311         max = seqCanvas.cursorY + 1;
312       }
313
314       if (min > max)
315       {
316         // Only the user can do this
317         av.setSelectionGroup(null);
318       }
319       else
320       {
321         // Now add any sequences between min and max
322         sg.clear();
323         for (int i = min; i < max; i++)
324         {
325           sg.addSequence(av.getAlignment().getSequenceAt(i), false);
326         }
327       }
328     }
329
330     if (av.getSelectionGroup() == null)
331     {
332       SequenceGroup sg = new SequenceGroup();
333       sg.setStartRes(seqCanvas.cursorX);
334       sg.setEndRes(seqCanvas.cursorX);
335       sg.addSequence(sequence, false);
336       av.setSelectionGroup(sg);
337     }
338     ap.paintAlignment(false, false);
339     av.sendSelection();
340   }
341
342   void insertGapAtCursor(boolean group)
343   {
344     groupEditing = group;
345     startseq = seqCanvas.cursorY;
346     lastres = seqCanvas.cursorX;
347     editSequence(true, seqCanvas.cursorX + getKeyboardNo1());
348     endEditing();
349   }
350
351   void deleteGapAtCursor(boolean group)
352   {
353     groupEditing = group;
354     startseq = seqCanvas.cursorY;
355     lastres = seqCanvas.cursorX + getKeyboardNo1();
356     editSequence(false, seqCanvas.cursorX);
357     endEditing();
358   }
359
360   void numberPressed(char value)
361   {
362     if (keyboardNo1 == null)
363     {
364       keyboardNo1 = new StringBuffer();
365     }
366
367     if (keyboardNo2 != null)
368     {
369       keyboardNo2.append(value);
370     }
371     else
372     {
373       keyboardNo1.append(value);
374     }
375   }
376
377   int getKeyboardNo1()
378   {
379     try
380     {
381       if (keyboardNo1 != null)
382       {
383         int value = Integer.parseInt(keyboardNo1.toString());
384         keyboardNo1 = null;
385         return value;
386       }
387     } catch (Exception x)
388     {
389     }
390     keyboardNo1 = null;
391     return 1;
392   }
393
394   int getKeyboardNo2()
395   {
396     try
397     {
398       if (keyboardNo2 != null)
399       {
400         int value = Integer.parseInt(keyboardNo2.toString());
401         keyboardNo2 = null;
402         return value;
403       }
404     } catch (Exception x)
405     {
406     }
407     keyboardNo2 = null;
408     return 1;
409   }
410
411   /**
412    * Set status message in alignment panel
413    * 
414    * @param sequence
415    *          aligned sequence object
416    * @param column
417    *          alignment column
418    * @param seq
419    *          index of sequence in alignment
420    * @return position of column in sequence or -1 if at gap
421    */
422   void setStatusMessage(SequenceI sequence, int column, int seq)
423   {
424     // TODO remove duplication of identical gui method
425     StringBuilder text = new StringBuilder(32);
426     String seqno = seq == -1 ? "" : " " + (seq + 1);
427     text.append("Sequence" + seqno + " ID: " + sequence.getName());
428
429     String residue = null;
430     /*
431      * Try to translate the display character to residue name (null for gap).
432      */
433     final String displayChar = String.valueOf(sequence.getCharAt(column));
434     if (av.getAlignment().isNucleotide())
435     {
436       residue = ResidueProperties.nucleotideName.get(displayChar);
437       if (residue != null)
438       {
439         text.append(" Nucleotide: ").append(residue);
440       }
441     }
442     else
443     {
444       residue = "X".equalsIgnoreCase(displayChar) ? "X"
445               : ("*".equals(displayChar) ? "STOP"
446                       : ResidueProperties.aa2Triplet.get(displayChar));
447       if (residue != null)
448       {
449         text.append(" Residue: ").append(residue);
450       }
451     }
452
453     int pos = -1;
454     if (residue != null)
455     {
456       pos = sequence.findPosition(column);
457       text.append(" (").append(Integer.toString(pos)).append(")");
458     }
459
460     ap.alignFrame.statusBar.setText(text.toString());
461   }
462
463   /**
464    * Set the status bar message to highlight the first matched position in
465    * search results.
466    * 
467    * @param results
468    * @return true if results were matched, false if not
469    */
470   private boolean setStatusMessage(SearchResultsI results)
471   {
472     AlignmentI al = this.av.getAlignment();
473     int sequenceIndex = al.findIndex(results);
474     if (sequenceIndex == -1)
475     {
476       return false;
477     }
478     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
479     for (SearchResultMatchI m : results.getResults())
480     {
481       SequenceI seq = m.getSequence();
482       if (seq.getDatasetSequence() != null)
483       {
484         seq = seq.getDatasetSequence();
485       }
486
487       if (seq == ds)
488       {
489         /*
490          * Convert position in sequence (base 1) to sequence character array
491          * index (base 0)
492          */
493         int start = m.getStart() - m.getSequence().getStart();
494         setStatusMessage(seq, start, sequenceIndex);
495         return true;
496       }
497     }
498     return false;
499   }
500
501   @Override
502   public void mousePressed(MouseEvent evt)
503   {
504     lastMousePress = evt.getPoint();
505
506     // For now, ignore the mouseWheel font resizing on Macs
507     // As the Button2_mask always seems to be true
508     if ((evt.getModifiers()
509             & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK
510             && !av.MAC)
511     {
512       mouseWheelPressed = true;
513       return;
514     }
515
516     if (evt.isShiftDown() || evt.isControlDown() || evt.isAltDown())
517     {
518       if (evt.isControlDown() || evt.isAltDown())
519       {
520         groupEditing = true;
521       }
522       editingSeqs = true;
523     }
524     else
525     {
526       doMousePressedDefineMode(evt);
527       return;
528     }
529
530     int seq = findSeq(evt);
531     int res = findColumn(evt);
532
533     if (seq < 0 || res < 0)
534     {
535       return;
536     }
537
538     if ((seq < av.getAlignment().getHeight())
539             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
540     {
541       startseq = seq;
542       lastres = res;
543     }
544     else
545     {
546       startseq = -1;
547       lastres = -1;
548     }
549
550     return;
551   }
552
553   @Override
554   public void mouseClicked(MouseEvent evt)
555   {
556     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
557     if (evt.getClickCount() > 1)
558     {
559       if (av.getSelectionGroup() != null
560               && av.getSelectionGroup().getSize() == 1
561               && av.getSelectionGroup().getEndRes()
562                       - av.getSelectionGroup().getStartRes() < 2)
563       {
564         av.setSelectionGroup(null);
565       }
566
567       int column = findColumn(evt);
568       List<SequenceFeature> features = findFeaturesAtColumn(sequence,
569               column + 1);
570
571       if (!features.isEmpty())
572       {
573         SearchResultsI highlight = new SearchResults();
574         highlight.addResult(sequence, features.get(0).getBegin(),
575                 features.get(0).getEnd());
576         seqCanvas.highlightSearchResults(highlight);
577         seqCanvas.getFeatureRenderer().amendFeatures(
578                 Collections.singletonList(sequence), features, false, ap);
579         av.setSearchResults(null); // clear highlighting
580         seqCanvas.repaint(); // draw new/amended features
581       }
582     }
583   }
584
585   @Override
586   public void mouseReleased(MouseEvent evt)
587   {
588     boolean didDrag = mouseDragging; // did we come here after a drag
589     mouseDragging = false;
590     mouseWheelPressed = false;
591
592     if (!editingSeqs)
593     {
594       doMouseReleasedDefineMode(evt, didDrag);
595       return;
596     }
597
598     endEditing();
599
600   }
601
602   int startWrapBlock = -1;
603
604   int wrappedBlock = -1;
605
606   /**
607    * Returns the aligned sequence position (base 0) at the mouse position, or
608    * the closest visible one
609    * 
610    * @param evt
611    * @return
612    */
613   int findColumn(MouseEvent evt)
614   {
615     int res = 0;
616     int x = evt.getX();
617
618     int startRes = av.getRanges().getStartRes();
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 = Math.max(0, 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 += startRes / cwidth;
643       int startOffset = startRes % cwidth; // in case start is scrolled right
644                                            // from 0
645       res = wrappedBlock * cwidth + startOffset
646               + +Math.min(cwidth - 1, x / av.getCharWidth());
647     }
648     else
649     {
650       res = (x / av.getCharWidth()) + startRes;
651     }
652
653     if (av.hasHiddenColumns())
654     {
655       res = av.getAlignment().getHiddenColumns()
656               .adjustForHiddenColumns(res);
657     }
658
659     return res;
660
661   }
662
663   int findSeq(MouseEvent evt)
664   {
665     final int sqnum = findAlRow(evt);
666     return (sqnum < 0) ? 0 : sqnum;
667   }
668
669   /**
670    * 
671    * @param evt
672    * @return row in alignment that was selected (or -1 for column selection)
673    */
674   private int findAlRow(MouseEvent evt)
675   {
676     int seq = 0;
677     int y = evt.getY();
678
679     if (av.getWrapAlignment())
680     {
681       int hgap = av.getCharHeight();
682       if (av.getScaleAboveWrapped())
683       {
684         hgap += av.getCharHeight();
685       }
686
687       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
688               + hgap + seqCanvas.getAnnotationHeight();
689
690       y -= hgap;
691
692       seq = Math.min((y % cHeight) / av.getCharHeight(),
693               av.getAlignment().getHeight() - 1);
694       if (seq < 0)
695       {
696         seq = -1;
697       }
698     }
699     else
700     {
701       seq = Math.min(
702               (y / av.getCharHeight()) + av.getRanges().getStartSeq(),
703               av.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.get(String.valueOf(ch));
836         text.append(" Residue: ").append(residue == null ? ch : residue);
837       }
838       text.append(" (").append(Integer.toString(respos)).append(")");
839     }
840
841     ap.alignFrame.statusBar.setText(text.toString());
842
843     StringBuilder tooltipText = new StringBuilder();
844     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
845     if (groups != null)
846     {
847       for (int g = 0; g < groups.length; g++)
848       {
849         if (groups[g].getStartRes() <= column
850                 && 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
939               .abs(evt.getX() - 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, 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"))
1049               .append(":");
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
1068                 .formatMessage("label.edit_params", new String[]
1069                 { label }));
1070       }
1071     }
1072
1073     if (insertGap)
1074     {
1075       message.append(" insert ");
1076     }
1077     else
1078     {
1079       message.append(" delete ");
1080     }
1081
1082     message.append(Math.abs(startres - lastres) + " gaps.");
1083     ap.alignFrame.statusBar.setText(message.toString());
1084
1085     // Are we editing within a selection group?
1086     if (groupEditing || (sg != null
1087             && sg.getSequences(av.getHiddenRepSequences()).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
1188                       .isGap(gs.getCharAt(fixedRight - 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, new SequenceI[] { seq },
1310                   lastres, startres - lastres, av.getAlignment(), true);
1311         }
1312       }
1313       else
1314       {
1315         // dragging to the left
1316         if (fixedColumns && fixedRight != -1)
1317         {
1318           for (int j = lastres; j > startres; j--)
1319           {
1320             if (!jalview.util.Comparison.isGap(seq.getCharAt(startres)))
1321             {
1322               endEditing();
1323               break;
1324             }
1325             deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1326           }
1327         }
1328         else
1329         {
1330           // could be a keyboard edit trying to delete none gaps
1331           int max = 0;
1332           for (int m = startres; m < lastres; m++)
1333           {
1334             if (!jalview.util.Comparison.isGap(seq.getCharAt(m)))
1335             {
1336               break;
1337             }
1338             max++;
1339           }
1340
1341           if (max > 0)
1342           {
1343             editCommand.appendEdit(Action.DELETE_GAP,
1344                     new SequenceI[]
1345                     { seq }, startres, max, av.getAlignment(), true);
1346           }
1347         }
1348       }
1349     }
1350
1351     lastres = startres;
1352     seqCanvas.repaint();
1353   }
1354
1355   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1356   {
1357     int blankColumn = fixedColumn;
1358     for (int s = 0; s < seq.length; s++)
1359     {
1360       // Find the next gap before the end of the visible region boundary
1361       // If lastCol > j, theres a boundary after the gap insertion
1362
1363       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1364       {
1365         if (jalview.util.Comparison.isGap(seq[s].getCharAt(blankColumn)))
1366         {
1367           // Theres a space, so break and insert the gap
1368           break;
1369         }
1370       }
1371
1372       if (blankColumn <= j)
1373       {
1374         blankColumn = fixedColumn;
1375         endEditing();
1376         return;
1377       }
1378     }
1379
1380     editCommand.appendEdit(Action.DELETE_GAP, seq, blankColumn, 1,
1381             av.getAlignment(), true);
1382
1383     editCommand.appendEdit(Action.INSERT_GAP, seq, j, 1, av.getAlignment(),
1384             true);
1385
1386   }
1387
1388   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1389   {
1390
1391     editCommand.appendEdit(Action.DELETE_GAP, seq, j, 1, av.getAlignment(),
1392             true);
1393
1394     editCommand.appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1,
1395             av.getAlignment(), true);
1396   }
1397
1398   // ////////////////////////////////////////
1399   // ///Everything below this is for defining the boundary of the rubberband
1400   // ////////////////////////////////////////
1401   public void doMousePressedDefineMode(MouseEvent evt)
1402   {
1403     if (scrollThread != null)
1404     {
1405       scrollThread.threadRunning = false;
1406       scrollThread = null;
1407     }
1408
1409     int column = findColumn(evt);
1410     int seq = findSeq(evt);
1411     oldSeq = seq;
1412     startWrapBlock = wrappedBlock;
1413
1414     if (seq == -1)
1415     {
1416       return;
1417     }
1418
1419     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1420
1421     if (sequence == null || column > sequence.getLength())
1422     {
1423       return;
1424     }
1425
1426     stretchGroup = av.getSelectionGroup();
1427
1428     if (stretchGroup == null || !stretchGroup.contains(sequence, column))
1429     {
1430       stretchGroup = av.getAlignment().findGroup(sequence, column);
1431       if (stretchGroup != null)
1432       {
1433         // only update the current selection if the popup menu has a group to
1434         // focus on
1435         av.setSelectionGroup(stretchGroup);
1436       }
1437     }
1438
1439     // DETECT RIGHT MOUSE BUTTON IN AWT
1440     if ((evt.getModifiers()
1441             & 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<>();
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, 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) && (scrollThread.isRunning()))
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) && (scrollThread.isRunning()))
1669     {
1670       scrollThread.stopScrolling();
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) && (scrollThread.isRunning()))
1694       {
1695         scrollThread.stopScrolling();
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     private volatile boolean threadRunning = true;
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       threadRunning = false;
1733     }
1734
1735     public boolean isRunning()
1736     {
1737       return threadRunning;
1738     }
1739
1740     @Override
1741     public void run()
1742     {
1743       while (threadRunning)
1744       {
1745
1746         if (evt != null)
1747         {
1748
1749           if (mouseDragging && evt.getY() < 0
1750                   && av.getRanges().getStartSeq() > 0)
1751           {
1752             av.getRanges().scrollUp(true);
1753           }
1754
1755           if (mouseDragging && evt.getY() >= getSize().height && av
1756                   .getAlignment().getHeight() > av.getRanges().getEndSeq())
1757           {
1758             av.getRanges().scrollUp(false);
1759           }
1760
1761           if (mouseDragging && evt.getX() < 0)
1762           {
1763             av.getRanges().scrollRight(false);
1764           }
1765
1766           else if (mouseDragging && evt.getX() >= getSize().width)
1767           {
1768             av.getRanges().scrollRight(true);
1769           }
1770         }
1771
1772         try
1773         {
1774           Thread.sleep(75);
1775         } catch (Exception ex)
1776         {
1777         }
1778       }
1779     }
1780   }
1781
1782   /**
1783    * modify current selection according to a received message.
1784    */
1785   @Override
1786   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1787           HiddenColumns hidden, SelectionSource source)
1788   {
1789     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1790     // handles selection messages...
1791     // TODO: extend config options to allow user to control if selections may be
1792     // shared between viewports.
1793     if (av != null && (av == source || !av.followSelection
1794             || (source instanceof AlignViewport
1795                     && ((AlignmentViewport) source).getSequenceSetId()
1796                             .equals(av.getSequenceSetId()))))
1797     {
1798       return;
1799     }
1800
1801     /*
1802      * Check for selection in a view of which this one is a dna/protein
1803      * complement.
1804      */
1805     if (selectionFromTranslation(seqsel, colsel, hidden, source))
1806     {
1807       return;
1808     }
1809
1810     // do we want to thread this ? (contention with seqsel and colsel locks, I
1811     // suspect)
1812     /*
1813      * only copy colsel if there is a real intersection between
1814      * sequence selection and this panel's alignment
1815      */
1816     boolean repaint = false;
1817     boolean copycolsel = false;
1818     if (av.getSelectionGroup() == null || !av.isSelectionGroupChanged(true))
1819     {
1820       SequenceGroup sgroup = null;
1821       if (seqsel != null && seqsel.getSize() > 0)
1822       {
1823         if (av.getAlignment() == null)
1824         {
1825           System.out.println("Selection message: alignviewport av SeqSetId="
1826                   + av.getSequenceSetId() + " ViewId=" + av.getViewId()
1827                   + " 's alignment is NULL! returning immediatly.");
1828           return;
1829         }
1830         sgroup = seqsel.intersect(av.getAlignment(),
1831                 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
1832         if ((sgroup != null && sgroup.getSize() > 0))
1833         {
1834           copycolsel = true;
1835         }
1836       }
1837       if (sgroup != null && sgroup.getSize() > 0)
1838       {
1839         av.setSelectionGroup(sgroup);
1840       }
1841       else
1842       {
1843         av.setSelectionGroup(null);
1844       }
1845       repaint = av.isSelectionGroupChanged(true);
1846     }
1847     if (copycolsel && (av.getColumnSelection() == null
1848             || !av.isColSelChanged(true)))
1849     {
1850       // the current selection is unset or from a previous message
1851       // so import the new colsel.
1852       if (colsel == null || colsel.isEmpty())
1853       {
1854         if (av.getColumnSelection() != null)
1855         {
1856           av.getColumnSelection().clear();
1857         }
1858       }
1859       else
1860       {
1861         // TODO: shift colSel according to the intersecting sequences
1862         if (av.getColumnSelection() == null)
1863         {
1864           av.setColumnSelection(new ColumnSelection(colsel));
1865         }
1866         else
1867         {
1868           av.getColumnSelection().setElementsFrom(colsel,
1869                   av.getAlignment().getHiddenColumns());
1870         }
1871       }
1872       repaint |= av.isColSelChanged(true);
1873     }
1874     if (copycolsel && 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(),
1910             ap.av.getRanges().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,
1923             true);
1924   }
1925
1926   /**
1927    * If this panel is a cdna/protein translation view of the selection source,
1928    * tries to map the source selection to a local one, and returns true. Else
1929    * returns false.
1930    * 
1931    * @param seqsel
1932    * @param colsel
1933    * @param source
1934    */
1935   protected boolean selectionFromTranslation(SequenceGroup seqsel,
1936           ColumnSelection colsel, HiddenColumns hidden,
1937           SelectionSource source)
1938   {
1939     if (!(source instanceof AlignViewportI))
1940     {
1941       return false;
1942     }
1943     final AlignViewportI sourceAv = (AlignViewportI) source;
1944     if (sourceAv.getCodingComplement() != av
1945             && av.getCodingComplement() != sourceAv)
1946     {
1947       return false;
1948     }
1949
1950     /*
1951      * Map sequence selection
1952      */
1953     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
1954     av.setSelectionGroup(sg);
1955     av.isSelectionGroupChanged(true);
1956
1957     /*
1958      * Map column selection
1959      */
1960     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
1961     // av);
1962     ColumnSelection cs = new ColumnSelection();
1963     HiddenColumns hs = new HiddenColumns();
1964     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
1965     av.setColumnSelection(cs);
1966     av.getAlignment().setHiddenColumns(hs);
1967
1968     ap.scalePanelHolder.repaint();
1969     ap.repaint();
1970
1971     return true;
1972   }
1973
1974 }