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