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