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