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