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