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