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