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