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