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