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