4dd131ad1bf9583e495b2361ac83e9db2f29e2fc
[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() - 1;
485         setStatusMessage(seq, start, sequenceIndex);
486         return true;
487       }
488     }
489     return false;
490   }
491
492   public void mousePressed(MouseEvent evt)
493   {
494     lastMousePress = evt.getPoint();
495
496     // For now, ignore the mouseWheel font resizing on Macs
497     // As the Button2_mask always seems to be true
498     if ((evt.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK
499             && !av.MAC)
500     {
501       mouseWheelPressed = true;
502       return;
503     }
504
505     if (evt.isShiftDown() || evt.isControlDown() || evt.isAltDown())
506     {
507       if (evt.isControlDown() || evt.isAltDown())
508       {
509         groupEditing = true;
510       }
511       editingSeqs = true;
512     }
513     else
514     {
515       doMousePressedDefineMode(evt);
516       return;
517     }
518
519     int seq = findSeq(evt);
520     int res = findRes(evt);
521
522     if (seq < 0 || res < 0)
523     {
524       return;
525     }
526
527     if ((seq < av.getAlignment().getHeight())
528             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
529     {
530       startseq = seq;
531       lastres = res;
532     }
533     else
534     {
535       startseq = -1;
536       lastres = -1;
537     }
538
539     return;
540   }
541
542   public void mouseClicked(MouseEvent evt)
543   {
544     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
545     if (evt.getClickCount() > 1)
546     {
547       if (av.getSelectionGroup() != null
548               && av.getSelectionGroup().getSize() == 1
549               && av.getSelectionGroup().getEndRes()
550                       - av.getSelectionGroup().getStartRes() < 2)
551       {
552         av.setSelectionGroup(null);
553       }
554
555       SequenceFeature[] features = findFeaturesAtRes(sequence,
556               sequence.findPosition(findRes(evt)));
557
558       if (features != null && features.length > 0)
559       {
560         SearchResults highlight = new SearchResults();
561         highlight.addResult(sequence, features[0].getBegin(),
562                 features[0].getEnd());
563         seqCanvas.highlightSearchResults(highlight);
564       }
565       if (features != null && features.length > 0)
566       {
567         seqCanvas.getFeatureRenderer().amendFeatures(new SequenceI[]
568         { sequence }, features, false, ap);
569
570         seqCanvas.highlightSearchResults(null);
571       }
572     }
573   }
574
575   public void mouseReleased(MouseEvent evt)
576   {
577     mouseDragging = false;
578     mouseWheelPressed = false;
579     ap.paintAlignment(true);
580
581     if (!editingSeqs)
582     {
583       doMouseReleasedDefineMode(evt);
584       return;
585     }
586
587     endEditing();
588
589   }
590
591   int startWrapBlock = -1;
592
593   int wrappedBlock = -1;
594
595   int findRes(MouseEvent evt)
596   {
597     int res = 0;
598     int x = evt.getX();
599
600     if (av.getWrapAlignment())
601     {
602
603       int hgap = av.getCharHeight();
604       if (av.getScaleAboveWrapped())
605       {
606         hgap += av.getCharHeight();
607       }
608
609       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
610               + hgap
611               + seqCanvas.getAnnotationHeight();
612
613       int y = evt.getY();
614       y -= hgap;
615       x -= seqCanvas.LABEL_WEST;
616
617       int cwidth = seqCanvas.getWrappedCanvasWidth(getSize().width);
618       if (cwidth < 1)
619       {
620         return 0;
621       }
622
623       wrappedBlock = y / cHeight;
624       wrappedBlock += av.getStartRes() / cwidth;
625
626       res = wrappedBlock * cwidth + x / av.getCharWidth();
627
628     }
629     else
630     {
631       res = (x / av.getCharWidth()) + av.getStartRes();
632     }
633
634     if (av.hasHiddenColumns())
635     {
636       res = av.getColumnSelection().adjustForHiddenColumns(res);
637     }
638
639     return res;
640
641   }
642
643   int findSeq(MouseEvent evt)
644   {
645     final int sqnum = findAlRow(evt);
646     return (sqnum < 0) ? 0 : sqnum;
647   }
648
649   /**
650    * 
651    * @param evt
652    * @return row in alignment that was selected (or -1 for column selection)
653    */
654   private int findAlRow(MouseEvent evt)
655   {
656     int seq = 0;
657     int y = evt.getY();
658
659     if (av.getWrapAlignment())
660     {
661       int hgap = av.getCharHeight();
662       if (av.getScaleAboveWrapped())
663       {
664         hgap += av.getCharHeight();
665       }
666
667       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
668               + hgap
669               + seqCanvas.getAnnotationHeight();
670
671       y -= hgap;
672
673       seq = Math.min((y % cHeight) / av.getCharHeight(), av.getAlignment()
674               .getHeight() - 1);
675       if (seq < 0)
676       {
677         seq = -1;
678       }
679     }
680     else
681     {
682       seq = Math.min((y / av.getCharHeight()) + av.getStartSeq(), av
683               .getAlignment().getHeight() - 1);
684       if (seq < 0)
685       {
686         seq = -1;
687       }
688     }
689
690     return seq;
691   }
692
693   public void doMousePressed(MouseEvent evt)
694   {
695
696     int seq = findSeq(evt);
697     int res = findRes(evt);
698
699     if (seq < av.getAlignment().getHeight()
700             && res < av.getAlignment().getSequenceAt(seq).getLength())
701     {
702       // char resstr = align.getSequenceAt(seq).getSequence().charAt(res);
703       // Find the residue's position in the sequence (res is the position
704       // in the alignment
705
706       startseq = seq;
707       lastres = res;
708     }
709     else
710     {
711       startseq = -1;
712       lastres = -1;
713     }
714
715     return;
716   }
717
718   String lastMessage;
719
720   public void mouseOverSequence(SequenceI sequence, int index, int pos)
721   {
722     String tmp = sequence.hashCode() + index + "";
723     if (lastMessage == null || !lastMessage.equals(tmp))
724     {
725       ssm.mouseOverSequence(sequence, index, pos, av);
726     }
727
728     lastMessage = tmp;
729   }
730
731   public void highlightSequence(SearchResults results)
732   {
733     if (av.isFollowHighlight())
734     {
735       if (ap.scrollToPosition(results, true))
736       {
737         ap.alignFrame.repaint();
738       }
739     }
740     setStatusMessage(results);
741     seqCanvas.highlightSearchResults(results);
742
743   }
744
745   @Override
746   public VamsasSource getVamsasSource()
747   {
748     return this.ap == null ? null : this.ap.av;
749   }
750
751   public void updateColours(SequenceI seq, int index)
752   {
753     System.out.println("update the seqPanel colours");
754     // repaint();
755   }
756
757   public void mouseMoved(MouseEvent evt)
758   {
759     int res = findRes(evt);
760     int seq = findSeq(evt);
761
762     if (seq >= av.getAlignment().getHeight() || seq < 0 || res < 0)
763     {
764       if (tooltip != null)
765       {
766         tooltip.setTip("");
767       }
768       return;
769     }
770
771     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
772     if (res > sequence.getLength())
773     {
774       if (tooltip != null)
775       {
776         tooltip.setTip("");
777       }
778       return;
779     }
780
781     int respos = sequence.findPosition(res);
782     if (ssm != null)
783     {
784       mouseOverSequence(sequence, res, respos);
785     }
786
787     StringBuilder text = new StringBuilder();
788     text.append("Sequence ").append(Integer.toString(seq + 1))
789             .append(" ID: ").append(sequence.getName());
790
791     String obj = null;
792     final String ch = String.valueOf(sequence.getCharAt(res));
793     if (av.getAlignment().isNucleotide())
794     {
795       obj = ResidueProperties.nucleotideName.get(ch);
796       if (obj != null)
797       {
798         text.append(" Nucleotide: ").append(obj);
799       }
800     }
801     else
802     {
803       obj = "X".equalsIgnoreCase(ch) ? "X"
804               : ResidueProperties.aa2Triplet.get(ch);
805       if (obj != null)
806       {
807         text.append(" Residue: ").append(obj);
808       }
809     }
810
811     if (obj != null)
812     {
813       text.append(" (").append(Integer.toString(respos)).append(")");
814     }
815
816     ap.alignFrame.statusBar.setText(text.toString());
817
818     StringBuilder tooltipText = new StringBuilder();
819     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
820     if (groups != null)
821     {
822       for (int g = 0; g < groups.length; g++)
823       {
824         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
825         {
826           if (!groups[g].getName().startsWith("JTreeGroup")
827                   && !groups[g].getName().startsWith("JGroup"))
828           {
829             tooltipText.append(groups[g].getName()).append(" ");
830           }
831           if (groups[g].getDescription() != null)
832           {
833             tooltipText.append(groups[g].getDescription());
834           }
835           tooltipText.append("\n");
836         }
837       }
838     }
839
840     // use aa to see if the mouse pointer is on a
841     SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
842             sequence.findPosition(res));
843
844     int index = 0;
845     while (index < allFeatures.length)
846     {
847       SequenceFeature sf = allFeatures[index];
848
849       tooltipText.append(sf.getType() + " " + sf.begin + ":" + sf.end);
850
851       if (sf.getDescription() != null)
852       {
853         tooltipText.append(" " + sf.getDescription());
854       }
855
856       if (sf.getValue("status") != null)
857       {
858         String status = sf.getValue("status").toString();
859         if (status.length() > 0)
860         {
861           tooltipText.append(" (" + sf.getValue("status") + ")");
862         }
863       }
864       tooltipText.append("\n");
865
866       index++;
867     }
868
869     if (tooltip == null)
870     {
871       tooltip = new Tooltip(tooltipText.toString(), seqCanvas);
872     }
873     else
874     {
875       tooltip.setTip(tooltipText.toString());
876     }
877   }
878
879   SequenceFeature[] findFeaturesAtRes(SequenceI sequence, int res)
880   {
881     Vector tmp = new Vector();
882     SequenceFeature[] features = sequence.getSequenceFeatures();
883     if (features != null)
884     {
885       for (int i = 0; i < features.length; i++)
886       {
887         if (av.getFeaturesDisplayed() == null
888                 || !av.getFeaturesDisplayed().isVisible(features[i].getType()))
889         {
890           continue;
891         }
892
893         if (features[i].featureGroup != null
894                 && !seqCanvas.fr.checkGroupVisibility(features[i].featureGroup,false))
895         {
896           continue;
897         }
898
899         if ((features[i].getBegin() <= res)
900                 && (features[i].getEnd() >= res))
901         {
902           tmp.addElement(features[i]);
903         }
904       }
905     }
906
907     features = new SequenceFeature[tmp.size()];
908     tmp.copyInto(features);
909
910     return features;
911   }
912
913   Tooltip tooltip;
914
915   public void mouseDragged(MouseEvent evt)
916   {
917     if (mouseWheelPressed)
918     {
919       int oldWidth = av.getCharWidth();
920
921       // Which is bigger, left-right or up-down?
922       if (Math.abs(evt.getY() - lastMousePress.y) > Math.abs(evt.getX()
923               - lastMousePress.x))
924       {
925         int fontSize = av.font.getSize();
926
927         if (evt.getY() < lastMousePress.y && av.getCharHeight() > 1)
928         {
929           fontSize--;
930         }
931         else if (evt.getY() > lastMousePress.y)
932         {
933           fontSize++;
934         }
935
936         if (fontSize < 1)
937         {
938           fontSize = 1;
939         }
940
941         av.setFont(new Font(av.font.getName(), av.font.getStyle(), fontSize));
942         av.setCharWidth(oldWidth);
943       }
944       else
945       {
946         if (evt.getX() < lastMousePress.x && av.getCharWidth() > 1)
947         {
948           av.setCharWidth(av.getCharWidth() - 1);
949         }
950         else if (evt.getX() > lastMousePress.x)
951         {
952           av.setCharWidth(av.getCharWidth() + 1);
953         }
954
955         if (av.getCharWidth() < 1)
956         {
957           av.setCharWidth(1);
958         }
959       }
960
961       ap.fontChanged();
962
963       FontMetrics fm = getFontMetrics(av.getFont());
964       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
965
966       lastMousePress = evt.getPoint();
967
968       ap.paintAlignment(false);
969       ap.annotationPanel.image = null;
970       return;
971     }
972
973     if (!editingSeqs)
974     {
975       doMouseDraggedDefineMode(evt);
976       return;
977     }
978
979     int res = findRes(evt);
980
981     if (res < 0)
982     {
983       res = 0;
984     }
985
986     if ((lastres == -1) || (lastres == res))
987     {
988       return;
989     }
990
991     if ((res < av.getAlignment().getWidth()) && (res < lastres))
992     {
993       // dragLeft, delete gap
994       editSequence(false, res);
995     }
996     else
997     {
998       editSequence(true, res);
999     }
1000
1001     mouseDragging = true;
1002     if (scrollThread != null)
1003     {
1004       scrollThread.setEvent(evt);
1005     }
1006
1007   }
1008
1009   synchronized void editSequence(boolean insertGap, int startres)
1010   {
1011     int fixedLeft = -1;
1012     int fixedRight = -1;
1013     boolean fixedColumns = false;
1014     SequenceGroup sg = av.getSelectionGroup();
1015
1016     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1017
1018     if (!groupEditing && av.hasHiddenRows())
1019     {
1020       if (av.isHiddenRepSequence(seq))
1021       {
1022         sg = av.getRepresentedSequences(seq);
1023         groupEditing = true;
1024       }
1025     }
1026
1027     StringBuffer message = new StringBuffer();
1028     if (groupEditing)
1029     {
1030       message.append(MessageManager.getString("action.edit_group")).append(
1031               ":");
1032       if (editCommand == null)
1033       {
1034         editCommand = new EditCommand(
1035                 MessageManager.getString("action.edit_group"));
1036       }
1037     }
1038     else
1039     {
1040       message.append(MessageManager.getString("label.edit_sequence"))
1041               .append(" " + seq.getName());
1042       String label = seq.getName();
1043       if (label.length() > 10)
1044       {
1045         label = label.substring(0, 10);
1046       }
1047       if (editCommand == null)
1048       {
1049         editCommand = new EditCommand(MessageManager.formatMessage(
1050                 "label.edit_params", new String[]
1051                 { label }));
1052       }
1053     }
1054
1055     if (insertGap)
1056     {
1057       message.append(" insert ");
1058     }
1059     else
1060     {
1061       message.append(" delete ");
1062     }
1063
1064     message.append(Math.abs(startres - lastres) + " gaps.");
1065     ap.alignFrame.statusBar.setText(message.toString());
1066
1067     // Are we editing within a selection group?
1068     if (groupEditing
1069             || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1070                     .contains(seq)))
1071     {
1072       fixedColumns = true;
1073
1074       // sg might be null as the user may only see 1 sequence,
1075       // but the sequence represents a group
1076       if (sg == null)
1077       {
1078         if (!av.isHiddenRepSequence(seq))
1079         {
1080           endEditing();
1081           return;
1082         }
1083
1084         sg = av.getRepresentedSequences(seq);
1085       }
1086
1087       fixedLeft = sg.getStartRes();
1088       fixedRight = sg.getEndRes();
1089
1090       if ((startres < fixedLeft && lastres >= fixedLeft)
1091               || (startres >= fixedLeft && lastres < fixedLeft)
1092               || (startres > fixedRight && lastres <= fixedRight)
1093               || (startres <= fixedRight && lastres > fixedRight))
1094       {
1095         endEditing();
1096         return;
1097       }
1098
1099       if (fixedLeft > startres)
1100       {
1101         fixedRight = fixedLeft - 1;
1102         fixedLeft = 0;
1103       }
1104       else if (fixedRight < startres)
1105       {
1106         fixedLeft = fixedRight;
1107         fixedRight = -1;
1108       }
1109     }
1110
1111     if (av.hasHiddenColumns())
1112     {
1113       fixedColumns = true;
1114       int y1 = av.getColumnSelection().getHiddenBoundaryLeft(startres);
1115       int y2 = av.getColumnSelection().getHiddenBoundaryRight(startres);
1116
1117       if ((insertGap && startres > y1 && lastres < y1)
1118               || (!insertGap && startres < y2 && lastres > y2))
1119       {
1120         endEditing();
1121         return;
1122       }
1123
1124       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1125       // Selection spans a hidden region
1126       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1127       {
1128         if (startres >= y2)
1129         {
1130           fixedLeft = y2;
1131         }
1132         else
1133         {
1134           fixedRight = y2 - 1;
1135         }
1136       }
1137     }
1138
1139     if (groupEditing)
1140     {
1141       SequenceI[] groupSeqs = sg.getSequences(av.getHiddenRepSequences())
1142               .toArray(new SequenceI[0]);
1143
1144       // drag to right
1145       if (insertGap)
1146       {
1147         // If the user has selected the whole sequence, and is dragging to
1148         // the right, we can still extend the alignment and selectionGroup
1149         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1150                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1151         {
1152           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1153           fixedRight = sg.getEndRes();
1154         }
1155
1156         // Is it valid with fixed columns??
1157         // Find the next gap before the end
1158         // of the visible region boundary
1159         boolean blank = false;
1160         for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1161         {
1162           blank = true;
1163
1164           for (SequenceI gs : groupSeqs)
1165           {
1166             for (int j = 0; j < startres - lastres; j++)
1167             {
1168               if (!jalview.util.Comparison.isGap(gs.getCharAt(fixedRight
1169                       - j)))
1170               {
1171                 blank = false;
1172                 break;
1173               }
1174             }
1175           }
1176           if (blank)
1177           {
1178             break;
1179           }
1180         }
1181
1182         if (!blank)
1183         {
1184           if (sg.getSize() == av.getAlignment().getHeight())
1185           {
1186             if ((av.hasHiddenColumns() && startres < av
1187                     .getColumnSelection().getHiddenBoundaryRight(startres)))
1188             {
1189               endEditing();
1190               return;
1191             }
1192
1193             int alWidth = av.getAlignment().getWidth();
1194             if (av.hasHiddenRows())
1195             {
1196               int hwidth = av.getAlignment().getHiddenSequences()
1197                       .getWidth();
1198               if (hwidth > alWidth)
1199               {
1200                 alWidth = hwidth;
1201               }
1202             }
1203             // We can still insert gaps if the selectionGroup
1204             // contains all the sequences
1205             sg.setEndRes(sg.getEndRes() + startres - lastres);
1206             fixedRight = alWidth + startres - lastres;
1207           }
1208           else
1209           {
1210             endEditing();
1211             return;
1212           }
1213         }
1214       }
1215
1216       // drag to left
1217       else if (!insertGap)
1218       {
1219         // / Are we able to delete?
1220         // ie are all columns blank?
1221
1222         for (SequenceI gs : groupSeqs)
1223         {
1224           for (int j = startres; j < lastres; j++)
1225           {
1226             if (gs.getLength() <= j)
1227             {
1228               continue;
1229             }
1230
1231             if (!jalview.util.Comparison.isGap(gs.getCharAt(j)))
1232             {
1233               // Not a gap, block edit not valid
1234               endEditing();
1235               return;
1236             }
1237           }
1238         }
1239       }
1240
1241       if (insertGap)
1242       {
1243         // dragging to the right
1244         if (fixedColumns && fixedRight != -1)
1245         {
1246           for (int j = lastres; j < startres; j++)
1247           {
1248             insertChar(j, groupSeqs, fixedRight);
1249           }
1250         }
1251         else
1252         {
1253           editCommand.appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1254                   startres - lastres, av.getAlignment(), true);
1255         }
1256       }
1257       else
1258       {
1259         // dragging to the left
1260         if (fixedColumns && fixedRight != -1)
1261         {
1262           for (int j = lastres; j > startres; j--)
1263           {
1264             deleteChar(startres, groupSeqs, fixedRight);
1265           }
1266         }
1267         else
1268         {
1269           editCommand.appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1270                   lastres - startres, av.getAlignment(), true);
1271         }
1272
1273       }
1274     }
1275     else
1276     // ///Editing a single sequence///////////
1277     {
1278       if (insertGap)
1279       {
1280         // dragging to the right
1281         if (fixedColumns && fixedRight != -1)
1282         {
1283           for (int j = lastres; j < startres; j++)
1284           {
1285             insertChar(j, new SequenceI[]
1286             { seq }, fixedRight);
1287           }
1288         }
1289         else
1290         {
1291           editCommand.appendEdit(Action.INSERT_GAP, new SequenceI[]
1292           { seq }, lastres, startres - lastres, av.getAlignment(), true);
1293         }
1294       }
1295       else
1296       {
1297         // dragging to the left
1298         if (fixedColumns && fixedRight != -1)
1299         {
1300           for (int j = lastres; j > startres; j--)
1301           {
1302             if (!jalview.util.Comparison.isGap(seq.getCharAt(startres)))
1303             {
1304               endEditing();
1305               break;
1306             }
1307             deleteChar(startres, new SequenceI[]
1308             { seq }, fixedRight);
1309           }
1310         }
1311         else
1312         {
1313           // could be a keyboard edit trying to delete none gaps
1314           int max = 0;
1315           for (int m = startres; m < lastres; m++)
1316           {
1317             if (!jalview.util.Comparison.isGap(seq.getCharAt(m)))
1318             {
1319               break;
1320             }
1321             max++;
1322           }
1323
1324           if (max > 0)
1325           {
1326             editCommand.appendEdit(Action.DELETE_GAP, new SequenceI[]
1327             { seq }, startres, max, av.getAlignment(), true);
1328           }
1329         }
1330       }
1331     }
1332
1333     lastres = startres;
1334     seqCanvas.repaint();
1335   }
1336
1337   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1338   {
1339     int blankColumn = fixedColumn;
1340     for (int s = 0; s < seq.length; s++)
1341     {
1342       // Find the next gap before the end of the visible region boundary
1343       // If lastCol > j, theres a boundary after the gap insertion
1344
1345       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1346       {
1347         if (jalview.util.Comparison.isGap(seq[s].getCharAt(blankColumn)))
1348         {
1349           // Theres a space, so break and insert the gap
1350           break;
1351         }
1352       }
1353
1354       if (blankColumn <= j)
1355       {
1356         blankColumn = fixedColumn;
1357         endEditing();
1358         return;
1359       }
1360     }
1361
1362     editCommand.appendEdit(Action.DELETE_GAP, seq, blankColumn, 1,
1363             av.getAlignment(), true);
1364
1365     editCommand.appendEdit(Action.INSERT_GAP, seq, j, 1, av.getAlignment(),
1366             true);
1367
1368   }
1369
1370   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1371   {
1372
1373     editCommand.appendEdit(Action.DELETE_GAP, seq, j, 1, av.getAlignment(),
1374             true);
1375
1376     editCommand.appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1,
1377             av.getAlignment(), true);
1378   }
1379
1380   // ////////////////////////////////////////
1381   // ///Everything below this is for defining the boundary of the rubberband
1382   // ////////////////////////////////////////
1383   public void doMousePressedDefineMode(MouseEvent evt)
1384   {
1385     if (scrollThread != null)
1386     {
1387       scrollThread.running = false;
1388       scrollThread = null;
1389     }
1390
1391     int res = findRes(evt);
1392     int seq = findSeq(evt);
1393     oldSeq = seq;
1394     startWrapBlock = wrappedBlock;
1395
1396     if (seq == -1)
1397     {
1398       return;
1399     }
1400
1401     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1402
1403     if (sequence == null || res > sequence.getLength())
1404     {
1405       return;
1406     }
1407
1408     stretchGroup = av.getSelectionGroup();
1409
1410     if (stretchGroup == null)
1411     {
1412       stretchGroup = av.getAlignment().findGroup(sequence);
1413       if (stretchGroup != null && res > stretchGroup.getStartRes()
1414               && res < stretchGroup.getEndRes())
1415       {
1416         av.setSelectionGroup(stretchGroup);
1417       }
1418       else
1419       {
1420         stretchGroup = null;
1421       }
1422     }
1423
1424     else if (!stretchGroup.getSequences(null).contains(sequence)
1425             || stretchGroup.getStartRes() > res
1426             || stretchGroup.getEndRes() < res)
1427     {
1428       stretchGroup = null;
1429
1430       SequenceGroup[] allGroups = av.getAlignment().findAllGroups(sequence);
1431
1432       if (allGroups != null)
1433       {
1434         for (int i = 0; i < allGroups.length; i++)
1435         {
1436           if (allGroups[i].getStartRes() <= res
1437                   && allGroups[i].getEndRes() >= res)
1438           {
1439             stretchGroup = allGroups[i];
1440             break;
1441           }
1442         }
1443       }
1444       av.setSelectionGroup(stretchGroup);
1445     }
1446
1447     // DETECT RIGHT MOUSE BUTTON IN AWT
1448     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK)
1449     {
1450       SequenceFeature[] allFeatures = findFeaturesAtRes(sequence,
1451               sequence.findPosition(res));
1452
1453       Vector<String> links = null;
1454       if (allFeatures != null)
1455       {
1456         for (int i = 0; i < allFeatures.length; i++)
1457         {
1458           if (allFeatures[i].links != null)
1459           {
1460             if (links == null)
1461             {
1462               links = new Vector<String>();
1463             }
1464             for (int j = 0; j < allFeatures[i].links.size(); j++)
1465             {
1466               links.addElement(allFeatures[i].links.elementAt(j));
1467             }
1468           }
1469         }
1470       }
1471       APopupMenu popup = new APopupMenu(ap, null, links);
1472       this.add(popup);
1473       popup.show(this, evt.getX(), evt.getY());
1474       return;
1475     }
1476
1477     if (av.cursorMode)
1478     {
1479       seqCanvas.cursorX = findRes(evt);
1480       seqCanvas.cursorY = findSeq(evt);
1481       seqCanvas.repaint();
1482       return;
1483     }
1484
1485     // Only if left mouse button do we want to change group sizes
1486
1487     if (stretchGroup == null)
1488     {
1489       // define a new group here
1490       SequenceGroup sg = new SequenceGroup();
1491       sg.setStartRes(res);
1492       sg.setEndRes(res);
1493       sg.addSequence(sequence, false);
1494       av.setSelectionGroup(sg);
1495       stretchGroup = sg;
1496
1497       if (av.getConservationSelected())
1498       {
1499         SliderPanel.setConservationSlider(ap, av.getGlobalColourScheme(),
1500                 "Background");
1501       }
1502       if (av.getAbovePIDThreshold())
1503       {
1504         SliderPanel.setPIDSliderSource(ap, av.getGlobalColourScheme(),
1505                 "Background");
1506       }
1507
1508     }
1509   }
1510
1511   public void doMouseReleasedDefineMode(MouseEvent evt)
1512   {
1513     if (stretchGroup == null)
1514     {
1515       return;
1516     }
1517
1518     stretchGroup.recalcConservation(); // always do this - annotation has own
1519                                        // state
1520     if (stretchGroup.cs != null)
1521     {
1522       stretchGroup.cs.alignmentChanged(stretchGroup,
1523               av.getHiddenRepSequences());
1524
1525       if (stretchGroup.cs.conservationApplied())
1526       {
1527         SliderPanel.setConservationSlider(ap, stretchGroup.cs,
1528                 stretchGroup.getName());
1529       }
1530       else
1531       {
1532         SliderPanel.setPIDSliderSource(ap, stretchGroup.cs,
1533                 stretchGroup.getName());
1534       }
1535     }
1536     changeEndRes = false;
1537     changeStartRes = false;
1538     stretchGroup = null;
1539     PaintRefresher.Refresh(ap, av.getSequenceSetId());
1540     ap.paintAlignment(true);
1541     av.sendSelection();
1542   }
1543
1544   public void doMouseDraggedDefineMode(MouseEvent evt)
1545   {
1546     int res = findRes(evt);
1547     int y = findSeq(evt);
1548
1549     if (wrappedBlock != startWrapBlock)
1550     {
1551       return;
1552     }
1553
1554     if (stretchGroup == null)
1555     {
1556       return;
1557     }
1558
1559     mouseDragging = true;
1560
1561     if (y > av.getAlignment().getHeight())
1562     {
1563       y = av.getAlignment().getHeight() - 1;
1564     }
1565
1566     if (res >= av.getAlignment().getWidth())
1567     {
1568       res = av.getAlignment().getWidth() - 1;
1569     }
1570
1571     if (stretchGroup.getEndRes() == res)
1572     {
1573       // Edit end res position of selected group
1574       changeEndRes = true;
1575     }
1576     else if (stretchGroup.getStartRes() == res)
1577     {
1578       // Edit start res position of selected group
1579       changeStartRes = true;
1580     }
1581
1582     if (res < 0)
1583     {
1584       res = 0;
1585     }
1586
1587     if (changeEndRes)
1588     {
1589       if (res > (stretchGroup.getStartRes() - 1))
1590       {
1591         stretchGroup.setEndRes(res);
1592       }
1593     }
1594     else if (changeStartRes)
1595     {
1596       if (res < (stretchGroup.getEndRes() + 1))
1597       {
1598         stretchGroup.setStartRes(res);
1599       }
1600     }
1601
1602     int dragDirection = 0;
1603
1604     if (y > oldSeq)
1605     {
1606       dragDirection = 1;
1607     }
1608     else if (y < oldSeq)
1609     {
1610       dragDirection = -1;
1611     }
1612
1613     while ((y != oldSeq) && (oldSeq > -1)
1614             && (y < av.getAlignment().getHeight()))
1615     {
1616       // This routine ensures we don't skip any sequences, as the
1617       // selection is quite slow.
1618       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1619
1620       oldSeq += dragDirection;
1621
1622       if (oldSeq < 0)
1623       {
1624         break;
1625       }
1626
1627       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1628
1629       if (stretchGroup.getSequences(null).contains(nextSeq))
1630       {
1631         stretchGroup.deleteSequence(seq, false);
1632       }
1633       else
1634       {
1635         if (seq != null)
1636         {
1637           stretchGroup.addSequence(seq, false);
1638         }
1639
1640         stretchGroup.addSequence(nextSeq, false);
1641       }
1642     }
1643
1644     if (oldSeq < 0)
1645     {
1646       oldSeq = -1;
1647     }
1648
1649     if (res > av.endRes || res < av.startRes || y < av.startSeq
1650             || y > av.endSeq)
1651     {
1652       mouseExited(evt);
1653     }
1654
1655     if (scrollThread != null)
1656     {
1657       scrollThread.setEvent(evt);
1658     }
1659
1660     seqCanvas.repaint();
1661   }
1662
1663   public void mouseEntered(MouseEvent e)
1664   {
1665     if (oldSeq < 0)
1666     {
1667       oldSeq = 0;
1668     }
1669
1670     if (scrollThread != null)
1671     {
1672       scrollThread.running = false;
1673       scrollThread = null;
1674     }
1675   }
1676
1677   public void mouseExited(MouseEvent e)
1678   {
1679     if (av.getWrapAlignment())
1680     {
1681       return;
1682     }
1683
1684     if (mouseDragging && scrollThread == null)
1685     {
1686       scrollThread = new ScrollThread();
1687     }
1688   }
1689
1690   void scrollCanvas(MouseEvent evt)
1691   {
1692     if (evt == null)
1693     {
1694       if (scrollThread != null)
1695       {
1696         scrollThread.running = false;
1697         scrollThread = null;
1698       }
1699       mouseDragging = false;
1700     }
1701     else
1702     {
1703       if (scrollThread == null)
1704       {
1705         scrollThread = new ScrollThread();
1706       }
1707
1708       mouseDragging = true;
1709       scrollThread.setEvent(evt);
1710     }
1711
1712   }
1713
1714   // this class allows scrolling off the bottom of the visible alignment
1715   class ScrollThread extends Thread
1716   {
1717     MouseEvent evt;
1718
1719     boolean running = false;
1720
1721     public ScrollThread()
1722     {
1723       start();
1724     }
1725
1726     public void setEvent(MouseEvent e)
1727     {
1728       evt = e;
1729     }
1730
1731     public void stopScrolling()
1732     {
1733       running = false;
1734     }
1735
1736     public void run()
1737     {
1738       running = true;
1739       while (running)
1740       {
1741
1742         if (evt != null)
1743         {
1744
1745           if (mouseDragging && evt.getY() < 0 && av.getStartSeq() > 0)
1746           {
1747             running = ap.scrollUp(true);
1748           }
1749
1750           if (mouseDragging && evt.getY() >= getSize().height
1751                   && av.getAlignment().getHeight() > av.getEndSeq())
1752           {
1753             running = ap.scrollUp(false);
1754           }
1755
1756           if (mouseDragging && evt.getX() < 0)
1757           {
1758             running = ap.scrollRight(false);
1759           }
1760
1761           else if (mouseDragging && evt.getX() >= getSize().width)
1762           {
1763             running = ap.scrollRight(true);
1764           }
1765         }
1766
1767         try
1768         {
1769           Thread.sleep(75);
1770         } catch (Exception ex)
1771         {
1772         }
1773       }
1774     }
1775   }
1776
1777   /**
1778    * modify current selection according to a received message.
1779    */
1780   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1781           SelectionSource source)
1782   {
1783     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1784     // handles selection messages...
1785     // TODO: extend config options to allow user to control if selections may be
1786     // shared between viewports.
1787     if (av != null
1788             && (av == source || !av.followSelection || (source instanceof AlignViewport && ((AlignmentViewport) source)
1789                     .getSequenceSetId().equals(av.getSequenceSetId()))))
1790     {
1791       return;
1792     }
1793
1794     /*
1795      * Check for selection in a view of which this one is a dna/protein
1796      * complement.
1797      */
1798     if (selectionFromTranslation(seqsel, colsel, source))
1799     {
1800       return;
1801     }
1802
1803     // do we want to thread this ? (contention with seqsel and colsel locks, I
1804     // suspect)
1805     // rules are: colsel is copied if there is a real intersection between
1806     // sequence selection
1807     boolean repaint = false, copycolsel = true;
1808     if (av.getSelectionGroup() == null || !av.isSelectionGroupChanged(true))
1809     {
1810       SequenceGroup sgroup = null;
1811       if (seqsel != null && seqsel.getSize() > 0)
1812       {
1813         if (av.getAlignment() == null)
1814         {
1815           System.out
1816                   .println("Selection message: alignviewport av SeqSetId="
1817                           + av.getSequenceSetId() + " ViewId="
1818                           + av.getViewId()
1819                           + " 's alignment is NULL! returning immediatly.");
1820           return;
1821         }
1822         sgroup = seqsel.intersect(av.getAlignment(),
1823                 (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
1824         if ((sgroup == null || sgroup.getSize() == 0)
1825                 && (colsel == null || colsel.size() == 0))
1826         {
1827           // don't copy columns if the region didn't intersect.
1828           copycolsel = false;
1829         }
1830       }
1831       if (sgroup != null && sgroup.getSize() > 0)
1832       {
1833         av.setSelectionGroup(sgroup);
1834       }
1835       else
1836       {
1837         av.setSelectionGroup(null);
1838       }
1839       repaint = av.isSelectionGroupChanged(true);
1840     }
1841     if (copycolsel
1842             && (av.getColumnSelection() == null || !av
1843                     .isColSelChanged(true)))
1844     {
1845       // the current selection is unset or from a previous message
1846       // so import the new colsel.
1847       if (colsel == null || colsel.size() == 0)
1848       {
1849         if (av.getColumnSelection() != null)
1850         {
1851           av.getColumnSelection().clear();
1852         }
1853       }
1854       else
1855       {
1856         // TODO: shift colSel according to the intersecting sequences
1857         if (av.getColumnSelection() == null)
1858         {
1859           av.setColumnSelection(new ColumnSelection(colsel));
1860         }
1861         else
1862         {
1863           av.getColumnSelection().setElementsFrom(colsel);
1864         }
1865       }
1866       repaint |= av.isColSelChanged(true);
1867     }
1868     if (copycolsel
1869             && av.hasHiddenColumns()
1870             && (av.getColumnSelection() == null || av.getColumnSelection()
1871                     .getHiddenColumns() == null))
1872     {
1873       System.err.println("Bad things");
1874     }
1875     if (repaint)
1876     {
1877       ap.scalePanelHolder.repaint();
1878       ap.repaint();
1879     }
1880   }
1881
1882   /**
1883    * scroll to the given row/column - or nearest visible location
1884    * 
1885    * @param row
1886    * @param column
1887    */
1888   public void scrollTo(int row, int column)
1889   {
1890
1891     row = row < 0 ? ap.av.startSeq : row;
1892     column = column < 0 ? ap.av.startRes : column;
1893     ap.scrollTo(column, column, row, true, true);
1894   }
1895
1896   /**
1897    * scroll to the given row - or nearest visible location
1898    * 
1899    * @param row
1900    */
1901   public void scrollToRow(int row)
1902   {
1903
1904     row = row < 0 ? ap.av.startSeq : row;
1905     ap.scrollTo(ap.av.startRes, ap.av.startRes, row, true, true);
1906   }
1907
1908   /**
1909    * scroll to the given column - or nearest visible location
1910    * 
1911    * @param column
1912    */
1913   public void scrollToColumn(int column)
1914   {
1915
1916     column = column < 0 ? ap.av.startRes : column;
1917     ap.scrollTo(column, column, ap.av.startSeq, true, true);
1918   }
1919
1920   /**
1921    * If this panel is a cdna/protein translation view of the selection source,
1922    * tries to map the source selection to a local one, and returns true. Else
1923    * returns false.
1924    * 
1925    * @param seqsel
1926    * @param colsel
1927    * @param source
1928    */
1929   protected boolean selectionFromTranslation(SequenceGroup seqsel,
1930           ColumnSelection colsel, SelectionSource source)
1931   {
1932     if (!(source instanceof AlignViewportI)) {
1933       return false;
1934     }
1935     final AlignViewportI sourceAv = (AlignViewportI) source;
1936     if (sourceAv.getCodingComplement() != av && av.getCodingComplement() != sourceAv)
1937     {
1938       return false;
1939     }
1940   
1941     /*
1942      * Map sequence selection
1943      */
1944     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
1945     av.setSelectionGroup(sg);
1946     av.isSelectionGroupChanged(true);
1947   
1948     /*
1949      * Map column selection
1950      */
1951     ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
1952             av);
1953     av.setColumnSelection(cs);
1954     av.isColSelChanged(true);
1955   
1956     ap.scalePanelHolder.repaint();
1957     ap.repaint();
1958   
1959     return true;
1960   }
1961
1962 }