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