cf0991e426dc7c671f360fc4241174f6ba0ccd6b
[jalview.git] / src / jalview / gui / 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.gui;
22
23 import jalview.api.AlignViewportI;
24 import jalview.bin.Cache;
25 import jalview.commands.EditCommand;
26 import jalview.commands.EditCommand.Action;
27 import jalview.commands.EditCommand.Edit;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.SearchResultMatchI;
32 import jalview.datamodel.SearchResults;
33 import jalview.datamodel.SearchResultsI;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceGroup;
37 import jalview.datamodel.SequenceI;
38 import jalview.io.SequenceAnnotationReport;
39 import jalview.renderer.ResidueShaderI;
40 import jalview.schemes.ResidueProperties;
41 import jalview.structure.SelectionListener;
42 import jalview.structure.SelectionSource;
43 import jalview.structure.SequenceListener;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.structure.VamsasSource;
46 import jalview.util.Comparison;
47 import jalview.util.MappingUtils;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
50 import jalview.viewmodel.AlignmentViewport;
51 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
52
53 import java.awt.BorderLayout;
54 import java.awt.Color;
55 import java.awt.Font;
56 import java.awt.FontMetrics;
57 import java.awt.Point;
58 import java.awt.event.MouseEvent;
59 import java.awt.event.MouseListener;
60 import java.awt.event.MouseMotionListener;
61 import java.awt.event.MouseWheelEvent;
62 import java.awt.event.MouseWheelListener;
63 import java.util.Collections;
64 import java.util.List;
65
66 import javax.swing.JPanel;
67 import javax.swing.SwingUtilities;
68 import javax.swing.ToolTipManager;
69
70 /**
71  * DOCUMENT ME!
72  * 
73  * @author $author$
74  * @version $Revision: 1.130 $
75  */
76 public class SeqPanel extends JPanel
77         implements MouseListener, MouseMotionListener, MouseWheelListener,
78         SequenceListener, SelectionListener
79 {
80   private static final int MAX_TOOLTIP_LENGTH = 300;
81
82   public SeqCanvas seqCanvas;
83
84   public AlignmentPanel ap;
85
86   /*
87    * last column position for mouseMoved event
88    */
89   private int lastMouseColumn;
90
91   /*
92    * last sequence offset for mouseMoved event
93    */
94   private int lastMouseSeq;
95
96   protected int lastres;
97
98   protected int startseq;
99
100   protected AlignViewport av;
101
102   ScrollThread scrollThread = null;
103
104   boolean mouseDragging = false;
105
106   boolean editingSeqs = false;
107
108   boolean groupEditing = false;
109
110   // ////////////////////////////////////////
111   // ///Everything below this is for defining the boundary of the rubberband
112   // ////////////////////////////////////////
113   int oldSeq = -1;
114
115   boolean changeEndSeq = false;
116
117   boolean changeStartSeq = false;
118
119   boolean changeEndRes = false;
120
121   boolean changeStartRes = false;
122
123   SequenceGroup stretchGroup = null;
124
125   boolean remove = false;
126
127   Point lastMousePress;
128
129   boolean mouseWheelPressed = false;
130
131   StringBuffer keyboardNo1;
132
133   StringBuffer keyboardNo2;
134
135   java.net.URL linkImageURL;
136
137   private final SequenceAnnotationReport seqARep;
138
139   StringBuilder tooltipText = new StringBuilder();
140
141   String tmpString;
142
143   EditCommand editCommand;
144
145   StructureSelectionManager ssm;
146
147   SearchResultsI lastSearchResults;
148
149   /**
150    * Creates a new SeqPanel object
151    * 
152    * @param viewport
153    * @param alignPanel
154    */
155   public SeqPanel(AlignViewport viewport, AlignmentPanel alignPanel)
156   {
157     linkImageURL = getClass().getResource("/images/link.gif");
158     seqARep = new SequenceAnnotationReport(linkImageURL.toString());
159     ToolTipManager.sharedInstance().registerComponent(this);
160     ToolTipManager.sharedInstance().setInitialDelay(0);
161     ToolTipManager.sharedInstance().setDismissDelay(10000);
162     this.av = viewport;
163     setBackground(Color.white);
164
165     seqCanvas = new SeqCanvas(alignPanel);
166     setLayout(new BorderLayout());
167     add(seqCanvas, BorderLayout.CENTER);
168
169     this.ap = alignPanel;
170
171     if (!viewport.isDataset())
172     {
173       addMouseMotionListener(this);
174       addMouseListener(this);
175       addMouseWheelListener(this);
176       ssm = viewport.getStructureSelectionManager();
177       ssm.addStructureViewerListener(this);
178       ssm.addSelectionListener(this);
179     }
180
181     lastMouseColumn = -1;
182     lastMouseSeq = -1;
183   }
184
185   int startWrapBlock = -1;
186
187   int wrappedBlock = -1;
188
189   /**
190    * Returns the aligned sequence position (base 0) at the mouse position, or
191    * the closest visible one
192    * 
193    * @param evt
194    * @return
195    */
196   int findColumn(MouseEvent evt)
197   {
198     int res = 0;
199     int x = evt.getX();
200
201     int startRes = av.getRanges().getStartRes();
202     if (av.getWrapAlignment())
203     {
204
205       int hgap = av.getCharHeight();
206       if (av.getScaleAboveWrapped())
207       {
208         hgap += av.getCharHeight();
209       }
210
211       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
212               + hgap + seqCanvas.getAnnotationHeight();
213
214       int y = evt.getY();
215       y = Math.max(0, y - hgap);
216       x = Math.max(0, x - seqCanvas.getLabelWidthWest());
217
218       int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
219       if (cwidth < 1)
220       {
221         return 0;
222       }
223
224       wrappedBlock = y / cHeight;
225       wrappedBlock += startRes / cwidth;
226       // allow for wrapped view scrolled right (possible from Overview)
227       int startOffset = startRes % cwidth;
228       res = wrappedBlock * cwidth + startOffset
229               + +Math.min(cwidth - 1, x / av.getCharWidth());
230     }
231     else
232     {
233       if (x > seqCanvas.getX() + seqCanvas.getWidth())
234       {
235         // make sure we calculate relative to visible alignment, rather than
236         // right-hand gutter
237         x = seqCanvas.getX() + seqCanvas.getWidth();
238       }
239       res = (x / av.getCharWidth()) + startRes;
240       if (res > av.getRanges().getEndRes())
241       {
242         // moused off right
243         res = av.getRanges().getEndRes();
244       }
245     }
246
247     if (av.hasHiddenColumns())
248     {
249       res = av.getAlignment().getHiddenColumns()
250               .visibleToAbsoluteColumn(res);
251     }
252
253     return res;
254
255   }
256
257   int findSeq(MouseEvent evt)
258   {
259     int seq = 0;
260     int y = evt.getY();
261
262     if (av.getWrapAlignment())
263     {
264       int hgap = av.getCharHeight();
265       if (av.getScaleAboveWrapped())
266       {
267         hgap += av.getCharHeight();
268       }
269
270       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
271               + hgap + seqCanvas.getAnnotationHeight();
272
273       y -= hgap;
274
275       seq = Math.min((y % cHeight) / av.getCharHeight(),
276               av.getAlignment().getHeight() - 1);
277     }
278     else
279     {
280       seq = Math.min(
281               (y / av.getCharHeight()) + av.getRanges().getStartSeq(),
282               av.getAlignment().getHeight() - 1);
283     }
284
285     return seq;
286   }
287
288   /**
289    * When all of a sequence of edits are complete, put the resulting edit list
290    * on the history stack (undo list), and reset flags for editing in progress.
291    */
292   void endEditing()
293   {
294     try
295     {
296       if (editCommand != null && editCommand.getSize() > 0)
297       {
298         ap.alignFrame.addHistoryItem(editCommand);
299         av.firePropertyChange("alignment", null,
300                 av.getAlignment().getSequences());
301       }
302     } finally
303     {
304       /*
305        * Tidy up come what may...
306        */
307       startseq = -1;
308       lastres = -1;
309       editingSeqs = false;
310       groupEditing = false;
311       keyboardNo1 = null;
312       keyboardNo2 = null;
313       editCommand = null;
314     }
315   }
316
317   void setCursorRow()
318   {
319     seqCanvas.cursorY = getKeyboardNo1() - 1;
320     scrollToVisible(true);
321   }
322
323   void setCursorColumn()
324   {
325     seqCanvas.cursorX = getKeyboardNo1() - 1;
326     scrollToVisible(true);
327   }
328
329   void setCursorRowAndColumn()
330   {
331     if (keyboardNo2 == null)
332     {
333       keyboardNo2 = new StringBuffer();
334     }
335     else
336     {
337       seqCanvas.cursorX = getKeyboardNo1() - 1;
338       seqCanvas.cursorY = getKeyboardNo2() - 1;
339       scrollToVisible(true);
340     }
341   }
342
343   void setCursorPosition()
344   {
345     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
346
347     seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
348     scrollToVisible(true);
349   }
350
351   void moveCursor(int dx, int dy)
352   {
353     seqCanvas.cursorX += dx;
354     seqCanvas.cursorY += dy;
355
356     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
357
358     if (av.hasHiddenColumns() && !hidden.isVisible(seqCanvas.cursorX))
359     {
360       int original = seqCanvas.cursorX - dx;
361       int maxWidth = av.getAlignment().getWidth();
362
363       if (!hidden.isVisible(seqCanvas.cursorX))
364       {
365         int visx = hidden.absoluteToVisibleColumn(seqCanvas.cursorX - dx);
366         int[] region = hidden.getRegionWithEdgeAtRes(visx);
367
368         if (region != null) // just in case
369         {
370           if (dx == 1)
371           {
372             // moving right
373             seqCanvas.cursorX = region[1] + 1;
374           }
375           else if (dx == -1)
376           {
377             // moving left
378             seqCanvas.cursorX = region[0] - 1;
379           }
380         }
381         seqCanvas.cursorX = (seqCanvas.cursorX < 0) ? 0 : seqCanvas.cursorX;
382       }
383
384       if (seqCanvas.cursorX >= maxWidth
385               || !hidden.isVisible(seqCanvas.cursorX))
386       {
387         seqCanvas.cursorX = original;
388       }
389     }
390
391     scrollToVisible(false);
392   }
393
394   /**
395    * Scroll to make the cursor visible in the viewport.
396    * 
397    * @param jump
398    *          just jump to the location rather than scrolling
399    */
400   void scrollToVisible(boolean jump)
401   {
402     if (seqCanvas.cursorX < 0)
403     {
404       seqCanvas.cursorX = 0;
405     }
406     else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
407     {
408       seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
409     }
410
411     if (seqCanvas.cursorY < 0)
412     {
413       seqCanvas.cursorY = 0;
414     }
415     else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
416     {
417       seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
418     }
419
420     endEditing();
421
422     boolean repaintNeeded = true;
423     if (jump)
424     {
425       // only need to repaint if the viewport did not move, as otherwise it will
426       // get a repaint
427       repaintNeeded = !av.getRanges().setViewportLocation(seqCanvas.cursorX,
428               seqCanvas.cursorY);
429     }
430     else
431     {
432       if (av.getWrapAlignment())
433       {
434         // scrollToWrappedVisible expects x-value to have hidden cols subtracted
435         int x = av.getAlignment().getHiddenColumns()
436                 .absoluteToVisibleColumn(seqCanvas.cursorX);
437         av.getRanges().scrollToWrappedVisible(x);
438       }
439       else
440       {
441         av.getRanges().scrollToVisible(seqCanvas.cursorX,
442                 seqCanvas.cursorY);
443       }
444     }
445
446     if (av.getAlignment().getHiddenColumns().isVisible(seqCanvas.cursorX))
447     {
448       setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
449             seqCanvas.cursorX, seqCanvas.cursorY);
450     }
451
452     if (repaintNeeded)
453     {
454       seqCanvas.repaint();
455     }
456   }
457
458
459   void setSelectionAreaAtCursor(boolean topLeft)
460   {
461     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
462
463     if (av.getSelectionGroup() != null)
464     {
465       SequenceGroup sg = av.getSelectionGroup();
466       // Find the top and bottom of this group
467       int min = av.getAlignment().getHeight(), max = 0;
468       for (int i = 0; i < sg.getSize(); i++)
469       {
470         int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
471         if (index > max)
472         {
473           max = index;
474         }
475         if (index < min)
476         {
477           min = index;
478         }
479       }
480
481       max++;
482
483       if (topLeft)
484       {
485         sg.setStartRes(seqCanvas.cursorX);
486         if (sg.getEndRes() < seqCanvas.cursorX)
487         {
488           sg.setEndRes(seqCanvas.cursorX);
489         }
490
491         min = seqCanvas.cursorY;
492       }
493       else
494       {
495         sg.setEndRes(seqCanvas.cursorX);
496         if (sg.getStartRes() > seqCanvas.cursorX)
497         {
498           sg.setStartRes(seqCanvas.cursorX);
499         }
500
501         max = seqCanvas.cursorY + 1;
502       }
503
504       if (min > max)
505       {
506         // Only the user can do this
507         av.setSelectionGroup(null);
508       }
509       else
510       {
511         // Now add any sequences between min and max
512         sg.getSequences(null).clear();
513         for (int i = min; i < max; i++)
514         {
515           sg.addSequence(av.getAlignment().getSequenceAt(i), false);
516         }
517       }
518     }
519
520     if (av.getSelectionGroup() == null)
521     {
522       SequenceGroup sg = new SequenceGroup();
523       sg.setStartRes(seqCanvas.cursorX);
524       sg.setEndRes(seqCanvas.cursorX);
525       sg.addSequence(sequence, false);
526       av.setSelectionGroup(sg);
527     }
528
529     ap.paintAlignment(false, false);
530     av.sendSelection();
531   }
532
533   void insertGapAtCursor(boolean group)
534   {
535     groupEditing = group;
536     startseq = seqCanvas.cursorY;
537     lastres = seqCanvas.cursorX;
538     editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
539     endEditing();
540   }
541
542   void deleteGapAtCursor(boolean group)
543   {
544     groupEditing = group;
545     startseq = seqCanvas.cursorY;
546     lastres = seqCanvas.cursorX + getKeyboardNo1();
547     editSequence(false, false, seqCanvas.cursorX);
548     endEditing();
549   }
550
551   void insertNucAtCursor(boolean group, String nuc)
552   {
553     // TODO not called - delete?
554     groupEditing = group;
555     startseq = seqCanvas.cursorY;
556     lastres = seqCanvas.cursorX;
557     editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
558     endEditing();
559   }
560
561   void numberPressed(char value)
562   {
563     if (keyboardNo1 == null)
564     {
565       keyboardNo1 = new StringBuffer();
566     }
567
568     if (keyboardNo2 != null)
569     {
570       keyboardNo2.append(value);
571     }
572     else
573     {
574       keyboardNo1.append(value);
575     }
576   }
577
578   int getKeyboardNo1()
579   {
580     try
581     {
582       if (keyboardNo1 != null)
583       {
584         int value = Integer.parseInt(keyboardNo1.toString());
585         keyboardNo1 = null;
586         return value;
587       }
588     } catch (Exception x)
589     {
590     }
591     keyboardNo1 = null;
592     return 1;
593   }
594
595   int getKeyboardNo2()
596   {
597     try
598     {
599       if (keyboardNo2 != null)
600       {
601         int value = Integer.parseInt(keyboardNo2.toString());
602         keyboardNo2 = null;
603         return value;
604       }
605     } catch (Exception x)
606     {
607     }
608     keyboardNo2 = null;
609     return 1;
610   }
611
612   /**
613    * DOCUMENT ME!
614    * 
615    * @param evt
616    *          DOCUMENT ME!
617    */
618   @Override
619   public void mouseReleased(MouseEvent evt)
620   {
621     boolean didDrag = mouseDragging; // did we come here after a drag
622     mouseDragging = false;
623     mouseWheelPressed = false;
624
625     if (evt.isPopupTrigger()) // Windows: mouseReleased
626     {
627       showPopupMenu(evt);
628       evt.consume();
629       return;
630     }
631
632     if (!editingSeqs)
633     {
634       doMouseReleasedDefineMode(evt, didDrag);
635       return;
636     }
637
638     endEditing();
639   }
640
641   /**
642    * DOCUMENT ME!
643    * 
644    * @param evt
645    *          DOCUMENT ME!
646    */
647   @Override
648   public void mousePressed(MouseEvent evt)
649   {
650     lastMousePress = evt.getPoint();
651
652     if (SwingUtilities.isMiddleMouseButton(evt))
653     {
654       mouseWheelPressed = true;
655       return;
656     }
657
658     boolean isControlDown = Platform.isControlDown(evt);
659     if (evt.isShiftDown() || isControlDown)
660     {
661       editingSeqs = true;
662       if (isControlDown)
663       {
664         groupEditing = true;
665       }
666     }
667     else
668     {
669       doMousePressedDefineMode(evt);
670       return;
671     }
672
673     int seq = findSeq(evt);
674     int res = findColumn(evt);
675
676     if (seq < 0 || res < 0)
677     {
678       return;
679     }
680
681     if ((seq < av.getAlignment().getHeight())
682             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
683     {
684       startseq = seq;
685       lastres = res;
686     }
687     else
688     {
689       startseq = -1;
690       lastres = -1;
691     }
692
693     return;
694   }
695
696   String lastMessage;
697
698   @Override
699   public void mouseOverSequence(SequenceI sequence, int index, int pos)
700   {
701     String tmp = sequence.hashCode() + " " + index + " " + pos;
702
703     if (lastMessage == null || !lastMessage.equals(tmp))
704     {
705       // System.err.println("mouseOver Sequence: "+tmp);
706       ssm.mouseOverSequence(sequence, index, pos, av);
707     }
708     lastMessage = tmp;
709   }
710
711   /**
712    * Highlight the mapped region described by the search results object (unless
713    * unchanged). This supports highlight of protein while mousing over linked
714    * cDNA and vice versa. The status bar is also updated to show the location of
715    * the start of the highlighted region.
716    */
717   @Override
718   public void highlightSequence(SearchResultsI results)
719   {
720     if (results == null || results.equals(lastSearchResults))
721     {
722       return;
723     }
724     lastSearchResults = results;
725
726     boolean wasScrolled = false;
727
728     if (av.isFollowHighlight())
729     {
730       // don't allow highlight of protein/cDNA to also scroll a complementary
731       // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
732       // over residue to change abruptly, causing highlighted residue in panel 2
733       // to change, causing a scroll in panel 1 etc)
734       ap.setToScrollComplementPanel(false);
735       wasScrolled = ap.scrollToPosition(results, false);
736       if (wasScrolled)
737       {
738         seqCanvas.revalidate();
739       }
740       ap.setToScrollComplementPanel(true);
741     }
742
743     boolean noFastPaint = wasScrolled && av.getWrapAlignment();
744     if (seqCanvas.highlightSearchResults(results, noFastPaint))
745     {
746       setStatusMessage(results);
747     }
748   }
749
750   @Override
751   public VamsasSource getVamsasSource()
752   {
753     return this.ap == null ? null : this.ap.av;
754   }
755
756   @Override
757   public void updateColours(SequenceI seq, int index)
758   {
759     System.out.println("update the seqPanel colours");
760     // repaint();
761   }
762
763   /**
764    * Action on mouse movement is to update the status bar to show the current
765    * sequence position, and (if features are shown) to show any features at the
766    * position in a tooltip. Does nothing if the mouse move does not change
767    * residue position.
768    * 
769    * @param evt
770    */
771   @Override
772   public void mouseMoved(MouseEvent evt)
773   {
774     if (editingSeqs)
775     {
776       // This is because MacOSX creates a mouseMoved
777       // If control is down, other platforms will not.
778       mouseDragged(evt);
779     }
780
781     final int column = findColumn(evt);
782     final int seq = findSeq(evt);
783
784     if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
785     {
786       lastMouseSeq = -1;
787       return;
788     }
789     if (column == lastMouseColumn && seq == lastMouseSeq)
790     {
791       /*
792        * just a pixel move without change of residue
793        */
794       return;
795     }
796     lastMouseColumn = column;
797     lastMouseSeq = seq;
798
799     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
800
801     if (column >= sequence.getLength())
802     {
803       return;
804     }
805
806     /*
807      * set status bar message, returning residue position in sequence
808      */
809     boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
810     final int pos = setStatusMessage(sequence, column, seq);
811     if (ssm != null && !isGapped)
812     {
813       mouseOverSequence(sequence, column, pos);
814     }
815
816     tooltipText.setLength(6); // Cuts the buffer back to <html>
817
818     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
819     if (groups != null)
820     {
821       for (int g = 0; g < groups.length; g++)
822       {
823         if (groups[g].getStartRes() <= column
824                 && groups[g].getEndRes() >= column)
825         {
826           if (!groups[g].getName().startsWith("JTreeGroup")
827                   && !groups[g].getName().startsWith("JGroup"))
828           {
829             tooltipText.append(groups[g].getName());
830           }
831
832           if (groups[g].getDescription() != null)
833           {
834             tooltipText.append(": " + groups[g].getDescription());
835           }
836         }
837       }
838     }
839
840     /*
841      * add any features at the position to the tooltip; if over a gap, only
842      * add features that straddle the gap (pos may be the residue before or
843      * after the gap)
844      */
845     if (av.isShowSequenceFeatures())
846     {
847       List<SequenceFeature> features = ap.getFeatureRenderer()
848               .findFeaturesAtColumn(sequence, column + 1);
849       seqARep.appendFeatures(tooltipText, pos, features,
850               this.ap.getSeqPanel().seqCanvas.fr);
851
852       /*
853        * add features in CDS/protein complement at the corresponding
854        * position if configured to do so
855        */
856       if (av.isShowComplementFeatures())
857       {
858         if (!Comparison.isGap(sequence.getCharAt(column)))
859         {
860           AlignViewportI complement = ap.getAlignViewport()
861                   .getCodingComplement();
862           AlignFrame af = Desktop.getAlignFrameFor(complement);
863           FeatureRendererModel fr2 = af.getFeatureRenderer();
864           features = fr2.findComplementFeaturesAtResidue(sequence, pos);
865           seqARep.appendFeatures(tooltipText, pos, features, fr2);
866         }
867       }
868     }
869     if (tooltipText.length() == 6) // <html>
870     {
871       setToolTipText(null);
872       lastTooltip = null;
873     }
874     else
875     {
876       if (tooltipText.length() > MAX_TOOLTIP_LENGTH) // constant
877       {
878         tooltipText.setLength(MAX_TOOLTIP_LENGTH);
879         tooltipText.append("...");
880       }
881       String textString = tooltipText.toString();
882       if (lastTooltip == null || !lastTooltip.equals(textString))
883       {
884         String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
885                 textString);
886         setToolTipText(formattedTooltipText);
887         lastTooltip = textString;
888       }
889     }
890   }
891
892   private Point lastp = null;
893
894   /*
895    * (non-Javadoc)
896    * 
897    * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
898    */
899   @Override
900   public Point getToolTipLocation(MouseEvent event)
901   {
902     int x = event.getX(), w = getWidth();
903     int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
904     // close to edge
905     Point p = lastp;
906     if (!event.isShiftDown() || p == null)
907     {
908       p = (tooltipText != null && tooltipText.length() > 6)
909               ? new Point(event.getX() + wdth, event.getY() - 20)
910               : null;
911     }
912     /*
913      * TODO: try to modify position region is not obcured by tooltip
914      */
915     return lastp = p;
916   }
917
918   String lastTooltip;
919
920   /**
921    * set when the current UI interaction has resulted in a change that requires
922    * shading in overviews and structures to be recalculated. this could be
923    * changed to a something more expressive that indicates what actually has
924    * changed, so selective redraws can be applied (ie. only structures, only
925    * overview, etc)
926    */
927   private boolean updateOverviewAndStructs = false; // TODO: refactor to avcontroller
928
929   /**
930    * set if av.getSelectionGroup() refers to a group that is defined on the
931    * alignment view, rather than a transient selection
932    */
933   // private boolean editingDefinedGroup = false; // TODO: refactor to
934   // avcontroller or viewModel
935
936   /**
937    * Sets the status message in alignment panel, showing the sequence number
938    * (index) and id, and residue and residue position if not at a gap, for the
939    * given sequence and column position. Returns the residue position returned
940    * by Sequence.findPosition. Note this may be for the nearest adjacent residue
941    * if at a gapped position.
942    * 
943    * @param sequence
944    *          aligned sequence object
945    * @param column
946    *          alignment column
947    * @param seqIndex
948    *          index of sequence in alignment
949    * @return sequence position of residue at column, or adjacent residue if at a
950    *         gap
951    */
952   int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
953   {
954     char sequenceChar = sequence.getCharAt(column);
955     int pos = sequence.findPosition(column);
956     setStatusMessage(sequence, seqIndex, sequenceChar, pos);
957
958     return pos;
959   }
960
961   /**
962    * Builds the status message for the current cursor location and writes it to
963    * the status bar, for example
964    * 
965    * <pre>
966    * Sequence 3 ID: FER1_SOLLC
967    * Sequence 5 ID: FER1_PEA Residue: THR (4)
968    * Sequence 5 ID: FER1_PEA Residue: B (3)
969    * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
970    * </pre>
971    * 
972    * @param sequence
973    * @param seqIndex
974    *          sequence position in the alignment (1..)
975    * @param sequenceChar
976    *          the character under the cursor
977    * @param residuePos
978    *          the sequence residue position (if not over a gap)
979    */
980   protected void setStatusMessage(SequenceI sequence, int seqIndex,
981           char sequenceChar, int residuePos)
982   {
983     StringBuilder text = new StringBuilder(32);
984
985     /*
986      * Sequence number (if known), and sequence name.
987      */
988     String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
989     text.append("Sequence").append(seqno).append(" ID: ")
990             .append(sequence.getName());
991
992     String residue = null;
993
994     /*
995      * Try to translate the display character to residue name (null for gap).
996      */
997     boolean isGapped = Comparison.isGap(sequenceChar);
998
999     if (!isGapped)
1000     {
1001       boolean nucleotide = av.getAlignment().isNucleotide();
1002       String displayChar = String.valueOf(sequenceChar);
1003       if (nucleotide)
1004       {
1005         residue = ResidueProperties.nucleotideName.get(displayChar);
1006       }
1007       else
1008       {
1009         residue = "X".equalsIgnoreCase(displayChar) ? "X"
1010                 : ("*".equals(displayChar) ? "STOP"
1011                         : ResidueProperties.aa2Triplet.get(displayChar));
1012       }
1013       text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
1014               .append(": ").append(residue == null ? displayChar : residue);
1015
1016       text.append(" (").append(Integer.toString(residuePos)).append(")");
1017     }
1018     ap.alignFrame.statusBar.setText(text.toString());
1019   }
1020
1021   /**
1022    * Set the status bar message to highlight the first matched position in
1023    * search results.
1024    * 
1025    * @param results
1026    */
1027   private void setStatusMessage(SearchResultsI results)
1028   {
1029     AlignmentI al = this.av.getAlignment();
1030     int sequenceIndex = al.findIndex(results);
1031     if (sequenceIndex == -1)
1032     {
1033       return;
1034     }
1035     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
1036     for (SearchResultMatchI m : results.getResults())
1037     {
1038       SequenceI seq = m.getSequence();
1039       if (seq.getDatasetSequence() != null)
1040       {
1041         seq = seq.getDatasetSequence();
1042       }
1043
1044       if (seq == ds)
1045       {
1046         int start = m.getStart();
1047         setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
1048                 start);
1049         return;
1050       }
1051     }
1052   }
1053
1054   /**
1055    * {@inheritDoc}
1056    */
1057   @Override
1058   public void mouseDragged(MouseEvent evt)
1059   {
1060     if (mouseWheelPressed)
1061     {
1062       boolean inSplitFrame = ap.av.getCodingComplement() != null;
1063       boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
1064
1065       int oldWidth = av.getCharWidth();
1066
1067       // Which is bigger, left-right or up-down?
1068       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math
1069               .abs(evt.getX() - lastMousePress.getX()))
1070       {
1071         /*
1072          * on drag up or down, decrement or increment font size
1073          */
1074         int fontSize = av.font.getSize();
1075         boolean fontChanged = false;
1076
1077         if (evt.getY() < lastMousePress.getY())
1078         {
1079           fontChanged = true;
1080           fontSize--;
1081         }
1082         else if (evt.getY() > lastMousePress.getY())
1083         {
1084           fontChanged = true;
1085           fontSize++;
1086         }
1087
1088         if (fontSize < 1)
1089         {
1090           fontSize = 1;
1091         }
1092
1093         if (fontChanged)
1094         {
1095           Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1096                   fontSize);
1097           av.setFont(newFont, true);
1098           av.setCharWidth(oldWidth);
1099           ap.fontChanged();
1100           if (copyChanges)
1101           {
1102             ap.av.getCodingComplement().setFont(newFont, true);
1103             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1104                     .getSplitViewContainer();
1105             splitFrame.adjustLayout();
1106             splitFrame.repaint();
1107           }
1108         }
1109       }
1110       else
1111       {
1112         /*
1113          * on drag left or right, decrement or increment character width
1114          */
1115         int newWidth = 0;
1116         if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1117         {
1118           newWidth = av.getCharWidth() - 1;
1119           av.setCharWidth(newWidth);
1120         }
1121         else if (evt.getX() > lastMousePress.getX())
1122         {
1123           newWidth = av.getCharWidth() + 1;
1124           av.setCharWidth(newWidth);
1125         }
1126         if (newWidth > 0)
1127         {
1128           ap.paintAlignment(false, false);
1129           if (copyChanges)
1130           {
1131             /*
1132              * need to ensure newWidth is set on cdna, regardless of which
1133              * panel the mouse drag happened in; protein will compute its 
1134              * character width as 1:1 or 3:1
1135              */
1136             av.getCodingComplement().setCharWidth(newWidth);
1137             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1138                     .getSplitViewContainer();
1139             splitFrame.adjustLayout();
1140             splitFrame.repaint();
1141           }
1142         }
1143       }
1144
1145       FontMetrics fm = getFontMetrics(av.getFont());
1146       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1147
1148       lastMousePress = evt.getPoint();
1149
1150       return;
1151     }
1152
1153     if (!editingSeqs)
1154     {
1155       doMouseDraggedDefineMode(evt);
1156       return;
1157     }
1158
1159     int res = findColumn(evt);
1160
1161     if (res < 0)
1162     {
1163       res = 0;
1164     }
1165
1166     if ((lastres == -1) || (lastres == res))
1167     {
1168       return;
1169     }
1170
1171     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1172     {
1173       // dragLeft, delete gap
1174       editSequence(false, false, res);
1175     }
1176     else
1177     {
1178       editSequence(true, false, res);
1179     }
1180
1181     mouseDragging = true;
1182     if ((scrollThread != null) && (scrollThread.isRunning()))
1183     {
1184       scrollThread.setEvent(evt);
1185     }
1186   }
1187
1188   // TODO: Make it more clever than many booleans
1189   synchronized void editSequence(boolean insertGap, boolean editSeq,
1190           int startres)
1191   {
1192     int fixedLeft = -1;
1193     int fixedRight = -1;
1194     boolean fixedColumns = false;
1195     SequenceGroup sg = av.getSelectionGroup();
1196
1197     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1198
1199     // No group, but the sequence may represent a group
1200     if (!groupEditing && av.hasHiddenRows())
1201     {
1202       if (av.isHiddenRepSequence(seq))
1203       {
1204         sg = av.getRepresentedSequences(seq);
1205         groupEditing = true;
1206       }
1207     }
1208
1209     StringBuilder message = new StringBuilder(64);
1210     if (groupEditing)
1211     {
1212       message.append("Edit group:");
1213       if (editCommand == null)
1214       {
1215         editCommand = new EditCommand(
1216                 MessageManager.getString("action.edit_group"));
1217       }
1218     }
1219     else
1220     {
1221       message.append("Edit sequence: " + seq.getName());
1222       String label = seq.getName();
1223       if (label.length() > 10)
1224       {
1225         label = label.substring(0, 10);
1226       }
1227       if (editCommand == null)
1228       {
1229         editCommand = new EditCommand(MessageManager
1230                 .formatMessage("label.edit_params", new String[]
1231                 { label }));
1232       }
1233     }
1234
1235     if (insertGap)
1236     {
1237       message.append(" insert ");
1238     }
1239     else
1240     {
1241       message.append(" delete ");
1242     }
1243
1244     message.append(Math.abs(startres - lastres) + " gaps.");
1245     ap.alignFrame.statusBar.setText(message.toString());
1246
1247     // Are we editing within a selection group?
1248     if (groupEditing || (sg != null
1249             && sg.getSequences(av.getHiddenRepSequences()).contains(seq)))
1250     {
1251       fixedColumns = true;
1252
1253       // sg might be null as the user may only see 1 sequence,
1254       // but the sequence represents a group
1255       if (sg == null)
1256       {
1257         if (!av.isHiddenRepSequence(seq))
1258         {
1259           endEditing();
1260           return;
1261         }
1262         sg = av.getRepresentedSequences(seq);
1263       }
1264
1265       fixedLeft = sg.getStartRes();
1266       fixedRight = sg.getEndRes();
1267
1268       if ((startres < fixedLeft && lastres >= fixedLeft)
1269               || (startres >= fixedLeft && lastres < fixedLeft)
1270               || (startres > fixedRight && lastres <= fixedRight)
1271               || (startres <= fixedRight && lastres > fixedRight))
1272       {
1273         endEditing();
1274         return;
1275       }
1276
1277       if (fixedLeft > startres)
1278       {
1279         fixedRight = fixedLeft - 1;
1280         fixedLeft = 0;
1281       }
1282       else if (fixedRight < startres)
1283       {
1284         fixedLeft = fixedRight;
1285         fixedRight = -1;
1286       }
1287     }
1288
1289     if (av.hasHiddenColumns())
1290     {
1291       fixedColumns = true;
1292       int y1 = av.getAlignment().getHiddenColumns()
1293               .getNextHiddenBoundary(true, startres);
1294       int y2 = av.getAlignment().getHiddenColumns()
1295               .getNextHiddenBoundary(false, startres);
1296
1297       if ((insertGap && startres > y1 && lastres < y1)
1298               || (!insertGap && startres < y2 && lastres > y2))
1299       {
1300         endEditing();
1301         return;
1302       }
1303
1304       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1305       // Selection spans a hidden region
1306       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1307       {
1308         if (startres >= y2)
1309         {
1310           fixedLeft = y2;
1311         }
1312         else
1313         {
1314           fixedRight = y2 - 1;
1315         }
1316       }
1317     }
1318
1319     if (groupEditing)
1320     {
1321       List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1322       int g, groupSize = vseqs.size();
1323       SequenceI[] groupSeqs = new SequenceI[groupSize];
1324       for (g = 0; g < groupSeqs.length; g++)
1325       {
1326         groupSeqs[g] = vseqs.get(g);
1327       }
1328
1329       // drag to right
1330       if (insertGap)
1331       {
1332         // If the user has selected the whole sequence, and is dragging to
1333         // the right, we can still extend the alignment and selectionGroup
1334         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1335                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1336         {
1337           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1338           fixedRight = sg.getEndRes();
1339         }
1340
1341         // Is it valid with fixed columns??
1342         // Find the next gap before the end
1343         // of the visible region boundary
1344         boolean blank = false;
1345         for (; fixedRight > lastres; fixedRight--)
1346         {
1347           blank = true;
1348
1349           for (g = 0; g < groupSize; g++)
1350           {
1351             for (int j = 0; j < startres - lastres; j++)
1352             {
1353               if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1354               {
1355                 blank = false;
1356                 break;
1357               }
1358             }
1359           }
1360           if (blank)
1361           {
1362             break;
1363           }
1364         }
1365
1366         if (!blank)
1367         {
1368           if (sg.getSize() == av.getAlignment().getHeight())
1369           {
1370             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1371                     .getHiddenColumns()
1372                     .getNextHiddenBoundary(false, startres)))
1373             {
1374               endEditing();
1375               return;
1376             }
1377
1378             int alWidth = av.getAlignment().getWidth();
1379             if (av.hasHiddenRows())
1380             {
1381               int hwidth = av.getAlignment().getHiddenSequences()
1382                       .getWidth();
1383               if (hwidth > alWidth)
1384               {
1385                 alWidth = hwidth;
1386               }
1387             }
1388             // We can still insert gaps if the selectionGroup
1389             // contains all the sequences
1390             sg.setEndRes(sg.getEndRes() + startres - lastres);
1391             fixedRight = alWidth + startres - lastres;
1392           }
1393           else
1394           {
1395             endEditing();
1396             return;
1397           }
1398         }
1399       }
1400
1401       // drag to left
1402       else if (!insertGap)
1403       {
1404         // / Are we able to delete?
1405         // ie are all columns blank?
1406
1407         for (g = 0; g < groupSize; g++)
1408         {
1409           for (int j = startres; j < lastres; j++)
1410           {
1411             if (groupSeqs[g].getLength() <= j)
1412             {
1413               continue;
1414             }
1415
1416             if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1417             {
1418               // Not a gap, block edit not valid
1419               endEditing();
1420               return;
1421             }
1422           }
1423         }
1424       }
1425
1426       if (insertGap)
1427       {
1428         // dragging to the right
1429         if (fixedColumns && fixedRight != -1)
1430         {
1431           for (int j = lastres; j < startres; j++)
1432           {
1433             insertChar(j, groupSeqs, fixedRight);
1434           }
1435         }
1436         else
1437         {
1438           appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1439                   startres - lastres);
1440         }
1441       }
1442       else
1443       {
1444         // dragging to the left
1445         if (fixedColumns && fixedRight != -1)
1446         {
1447           for (int j = lastres; j > startres; j--)
1448           {
1449             deleteChar(startres, groupSeqs, fixedRight);
1450           }
1451         }
1452         else
1453         {
1454           appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1455                   lastres - startres);
1456         }
1457
1458       }
1459     }
1460     else
1461     // ///Editing a single sequence///////////
1462     {
1463       if (insertGap)
1464       {
1465         // dragging to the right
1466         if (fixedColumns && fixedRight != -1)
1467         {
1468           for (int j = lastres; j < startres; j++)
1469           {
1470             insertChar(j, new SequenceI[] { seq }, fixedRight);
1471           }
1472         }
1473         else
1474         {
1475           appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1476                   startres - lastres);
1477         }
1478       }
1479       else
1480       {
1481         if (!editSeq)
1482         {
1483           // dragging to the left
1484           if (fixedColumns && fixedRight != -1)
1485           {
1486             for (int j = lastres; j > startres; j--)
1487             {
1488               if (!Comparison.isGap(seq.getCharAt(startres)))
1489               {
1490                 endEditing();
1491                 break;
1492               }
1493               deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1494             }
1495           }
1496           else
1497           {
1498             // could be a keyboard edit trying to delete none gaps
1499             int max = 0;
1500             for (int m = startres; m < lastres; m++)
1501             {
1502               if (!Comparison.isGap(seq.getCharAt(m)))
1503               {
1504                 break;
1505               }
1506               max++;
1507             }
1508
1509             if (max > 0)
1510             {
1511               appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1512                       startres, max);
1513             }
1514           }
1515         }
1516         else
1517         {// insertGap==false AND editSeq==TRUE;
1518           if (fixedColumns && fixedRight != -1)
1519           {
1520             for (int j = lastres; j < startres; j++)
1521             {
1522               insertChar(j, new SequenceI[] { seq }, fixedRight);
1523             }
1524           }
1525           else
1526           {
1527             appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1528                     startres - lastres);
1529           }
1530         }
1531       }
1532     }
1533
1534     lastres = startres;
1535     seqCanvas.repaint();
1536   }
1537
1538   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1539   {
1540     int blankColumn = fixedColumn;
1541     for (int s = 0; s < seq.length; s++)
1542     {
1543       // Find the next gap before the end of the visible region boundary
1544       // If lastCol > j, theres a boundary after the gap insertion
1545
1546       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1547       {
1548         if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1549         {
1550           // Theres a space, so break and insert the gap
1551           break;
1552         }
1553       }
1554
1555       if (blankColumn <= j)
1556       {
1557         blankColumn = fixedColumn;
1558         endEditing();
1559         return;
1560       }
1561     }
1562
1563     appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1564
1565     appendEdit(Action.INSERT_GAP, seq, j, 1);
1566
1567   }
1568
1569   /**
1570    * Helper method to add and perform one edit action.
1571    * 
1572    * @param action
1573    * @param seq
1574    * @param pos
1575    * @param count
1576    */
1577   protected void appendEdit(Action action, SequenceI[] seq, int pos,
1578           int count)
1579   {
1580
1581     final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1582             av.getAlignment().getGapCharacter());
1583
1584     editCommand.appendEdit(edit, av.getAlignment(), true, null);
1585   }
1586
1587   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1588   {
1589
1590     appendEdit(Action.DELETE_GAP, seq, j, 1);
1591
1592     appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1593   }
1594
1595   /**
1596    * DOCUMENT ME!
1597    * 
1598    * @param e
1599    *          DOCUMENT ME!
1600    */
1601   @Override
1602   public void mouseEntered(MouseEvent e)
1603   {
1604     if (oldSeq < 0)
1605     {
1606       oldSeq = 0;
1607     }
1608
1609     if ((scrollThread != null) && (scrollThread.isRunning()))
1610     {
1611       scrollThread.stopScrolling();
1612       scrollThread = null;
1613     }
1614   }
1615
1616   /**
1617    * DOCUMENT ME!
1618    * 
1619    * @param e
1620    *          DOCUMENT ME!
1621    */
1622   @Override
1623   public void mouseExited(MouseEvent e)
1624   {
1625     if (av.getWrapAlignment())
1626     {
1627       return;
1628     }
1629
1630     if (mouseDragging && scrollThread == null)
1631     {
1632       scrollThread = new ScrollThread();
1633     }
1634   }
1635
1636   /**
1637    * Handler for double-click on a position with one or more sequence features.
1638    * Opens the Amend Features dialog to allow feature details to be amended, or
1639    * the feature deleted.
1640    */
1641   @Override
1642   public void mouseClicked(MouseEvent evt)
1643   {
1644     SequenceGroup sg = null;
1645     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1646     if (evt.getClickCount() > 1)
1647     {
1648       sg = av.getSelectionGroup();
1649       if (sg != null && sg.getSize() == 1
1650               && sg.getEndRes() - sg.getStartRes() < 2)
1651       {
1652         av.setSelectionGroup(null);
1653       }
1654
1655       int column = findColumn(evt);
1656
1657       /*
1658        * find features at the position (if not gapped), or straddling
1659        * the position (if at a gap)
1660        */
1661       List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1662               .findFeaturesAtColumn(sequence, column + 1);
1663
1664       if (!features.isEmpty())
1665       {
1666         /*
1667          * highlight the first feature at the position on the alignment
1668          */
1669         SearchResultsI highlight = new SearchResults();
1670         highlight.addResult(sequence, features.get(0).getBegin(), features
1671                 .get(0).getEnd());
1672         seqCanvas.highlightSearchResults(highlight, false);
1673
1674         /*
1675          * open the Amend Features dialog; clear highlighting afterwards,
1676          * whether changes were made or not
1677          */
1678         List<SequenceI> seqs = Collections.singletonList(sequence);
1679         seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1680                 ap);
1681         av.setSearchResults(null); // clear highlighting
1682         seqCanvas.repaint(); // draw new/amended features
1683       }
1684     }
1685   }
1686
1687   @Override
1688   public void mouseWheelMoved(MouseWheelEvent e)
1689   {
1690     e.consume();
1691     double wheelRotation = e.getPreciseWheelRotation();
1692     if (wheelRotation > 0)
1693     {
1694       if (e.isShiftDown())
1695       {
1696         av.getRanges().scrollRight(true);
1697
1698       }
1699       else
1700       {
1701         av.getRanges().scrollUp(false);
1702       }
1703     }
1704     else if (wheelRotation < 0)
1705     {
1706       if (e.isShiftDown())
1707       {
1708         av.getRanges().scrollRight(false);
1709       }
1710       else
1711       {
1712         av.getRanges().scrollUp(true);
1713       }
1714     }
1715
1716     /*
1717      * update status bar and tooltip for new position
1718      * (need to synthesize a mouse movement to refresh tooltip)
1719      */
1720     mouseMoved(e);
1721     ToolTipManager.sharedInstance().mouseMoved(e);
1722   }
1723
1724   /**
1725    * DOCUMENT ME!
1726    * 
1727    * @param evt
1728    *          DOCUMENT ME!
1729    */
1730   public void doMousePressedDefineMode(MouseEvent evt)
1731   {
1732     final int res = findColumn(evt);
1733     final int seq = findSeq(evt);
1734     oldSeq = seq;
1735     updateOverviewAndStructs = false;
1736
1737     startWrapBlock = wrappedBlock;
1738
1739     if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1740     {
1741       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1742               MessageManager.getString(
1743                       "label.cannot_edit_annotations_in_wrapped_view"),
1744               MessageManager.getString("label.wrapped_view_no_edit"),
1745               JvOptionPane.WARNING_MESSAGE);
1746       return;
1747     }
1748
1749     if (seq < 0 || res < 0)
1750     {
1751       return;
1752     }
1753
1754     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1755
1756     if ((sequence == null) || (res > sequence.getLength()))
1757     {
1758       return;
1759     }
1760
1761     stretchGroup = av.getSelectionGroup();
1762
1763     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1764     {
1765       stretchGroup = av.getAlignment().findGroup(sequence, res);
1766       if (stretchGroup != null)
1767       {
1768         // only update the current selection if the popup menu has a group to
1769         // focus on
1770         av.setSelectionGroup(stretchGroup);
1771       }
1772     }
1773
1774     if (evt.isPopupTrigger()) // Mac: mousePressed
1775     {
1776       showPopupMenu(evt);
1777       return;
1778     }
1779
1780     /*
1781      * defer right-mouse click handling to mouseReleased on Windows
1782      * (where isPopupTrigger() will answer true)
1783      * NB isRightMouseButton is also true for Cmd-click on Mac
1784      */
1785     if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1786     {
1787       return;
1788     }
1789
1790     if (av.cursorMode)
1791     {
1792       seqCanvas.cursorX = findColumn(evt);
1793       seqCanvas.cursorY = findSeq(evt);
1794       seqCanvas.repaint();
1795       return;
1796     }
1797
1798     if (stretchGroup == null)
1799     {
1800       createStretchGroup(res, sequence);
1801     }
1802
1803     if (stretchGroup != null)
1804     {
1805       stretchGroup.addPropertyChangeListener(seqCanvas);
1806     }
1807
1808     seqCanvas.repaint();
1809   }
1810
1811   private void createStretchGroup(int res, SequenceI sequence)
1812   {
1813     // Only if left mouse button do we want to change group sizes
1814     // define a new group here
1815     SequenceGroup sg = new SequenceGroup();
1816     sg.setStartRes(res);
1817     sg.setEndRes(res);
1818     sg.addSequence(sequence, false);
1819     av.setSelectionGroup(sg);
1820     stretchGroup = sg;
1821
1822     if (av.getConservationSelected())
1823     {
1824       SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1825               ap.getViewName());
1826     }
1827
1828     if (av.getAbovePIDThreshold())
1829     {
1830       SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1831               ap.getViewName());
1832     }
1833     // TODO: stretchGroup will always be not null. Is this a merge error ?
1834     // or is there a threading issue here?
1835     if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1836     {
1837       // Edit end res position of selected group
1838       changeEndRes = true;
1839     }
1840     else if ((stretchGroup != null) && (stretchGroup.getStartRes() == res))
1841     {
1842       // Edit end res position of selected group
1843       changeStartRes = true;
1844     }
1845     stretchGroup.getWidth();
1846
1847   }
1848
1849   /**
1850    * Build and show a pop-up menu at the right-click mouse position
1851    * 
1852    * @param evt
1853    * @param res
1854    * @param sequences
1855    */
1856   void showPopupMenu(MouseEvent evt)
1857   {
1858     final int column = findColumn(evt);
1859     final int seq = findSeq(evt);
1860     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1861     List<SequenceFeature> features = ap.getFeatureRenderer()
1862             .findFeaturesAtColumn(sequence, column + 1);
1863
1864     PopupMenu pop = new PopupMenu(ap, null, features);
1865     pop.show(this, evt.getX(), evt.getY());
1866   }
1867
1868   /**
1869    * Update the display after mouse up on a selection or group
1870    * 
1871    * @param evt
1872    *          mouse released event details
1873    * @param afterDrag
1874    *          true if this event is happening after a mouse drag (rather than a
1875    *          mouse down)
1876    */
1877   public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1878   {
1879     if (stretchGroup == null)
1880     {
1881       return;
1882     }
1883
1884     stretchGroup.removePropertyChangeListener(seqCanvas);
1885
1886     // always do this - annotation has own state
1887     // but defer colourscheme update until hidden sequences are passed in
1888     boolean vischange = stretchGroup.recalcConservation(true);
1889     updateOverviewAndStructs |= vischange && av.isSelectionDefinedGroup()
1890             && afterDrag;
1891     if (stretchGroup.cs != null)
1892     {
1893       stretchGroup.cs.alignmentChanged(stretchGroup,
1894               av.getHiddenRepSequences());
1895
1896       ResidueShaderI groupColourScheme = stretchGroup
1897               .getGroupColourScheme();
1898       String name = stretchGroup.getName();
1899       if (stretchGroup.cs.conservationApplied())
1900       {
1901         SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1902       }
1903       if (stretchGroup.cs.getThreshold() > 0)
1904       {
1905         SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1906       }
1907     }
1908     PaintRefresher.Refresh(this, av.getSequenceSetId());
1909     // TODO: structure colours only need updating if stretchGroup used to or now
1910     // does contain sequences with structure views
1911     ap.paintAlignment(updateOverviewAndStructs, updateOverviewAndStructs);
1912     updateOverviewAndStructs = false;
1913     changeEndRes = false;
1914     changeStartRes = false;
1915     stretchGroup = null;
1916     av.sendSelection();
1917   }
1918
1919   /**
1920    * DOCUMENT ME!
1921    * 
1922    * @param evt
1923    *          DOCUMENT ME!
1924    */
1925   public void doMouseDraggedDefineMode(MouseEvent evt)
1926   {
1927     int res = findColumn(evt);
1928     int y = findSeq(evt);
1929
1930     if (wrappedBlock != startWrapBlock)
1931     {
1932       return;
1933     }
1934
1935     if (stretchGroup == null)
1936     {
1937       return;
1938     }
1939
1940     if (res >= av.getAlignment().getWidth())
1941     {
1942       res = av.getAlignment().getWidth() - 1;
1943     }
1944
1945     if (stretchGroup.getEndRes() == res)
1946     {
1947       // Edit end res position of selected group
1948       changeEndRes = true;
1949     }
1950     else if (stretchGroup.getStartRes() == res)
1951     {
1952       // Edit start res position of selected group
1953       changeStartRes = true;
1954     }
1955
1956     if (res < av.getRanges().getStartRes())
1957     {
1958       res = av.getRanges().getStartRes();
1959     }
1960
1961     if (changeEndRes)
1962     {
1963       if (res > (stretchGroup.getStartRes() - 1))
1964       {
1965         stretchGroup.setEndRes(res);
1966         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1967       }
1968     }
1969     else if (changeStartRes)
1970     {
1971       if (res < (stretchGroup.getEndRes() + 1))
1972       {
1973         stretchGroup.setStartRes(res);
1974         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1975       }
1976     }
1977
1978     int dragDirection = 0;
1979
1980     if (y > oldSeq)
1981     {
1982       dragDirection = 1;
1983     }
1984     else if (y < oldSeq)
1985     {
1986       dragDirection = -1;
1987     }
1988
1989     while ((y != oldSeq) && (oldSeq > -1)
1990             && (y < av.getAlignment().getHeight()))
1991     {
1992       // This routine ensures we don't skip any sequences, as the
1993       // selection is quite slow.
1994       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1995
1996       oldSeq += dragDirection;
1997
1998       if (oldSeq < 0)
1999       {
2000         break;
2001       }
2002
2003       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
2004
2005       if (stretchGroup.getSequences(null).contains(nextSeq))
2006       {
2007         stretchGroup.deleteSequence(seq, false);
2008         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2009       }
2010       else
2011       {
2012         if (seq != null)
2013         {
2014           stretchGroup.addSequence(seq, false);
2015         }
2016
2017         stretchGroup.addSequence(nextSeq, false);
2018         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2019       }
2020     }
2021
2022     if (oldSeq < 0)
2023     {
2024       oldSeq = -1;
2025     }
2026
2027     mouseDragging = true;
2028
2029     if ((scrollThread != null) && (scrollThread.isRunning()))
2030     {
2031       scrollThread.setEvent(evt);
2032     }
2033   }
2034
2035   void scrollCanvas(MouseEvent evt)
2036   {
2037     if (evt == null)
2038     {
2039       if ((scrollThread != null) && (scrollThread.isRunning()))
2040       {
2041         scrollThread.stopScrolling();
2042         scrollThread = null;
2043       }
2044       mouseDragging = false;
2045     }
2046     else
2047     {
2048       if (scrollThread == null)
2049       {
2050         scrollThread = new ScrollThread();
2051       }
2052
2053       mouseDragging = true;
2054       scrollThread.setEvent(evt);
2055     }
2056
2057   }
2058
2059   // this class allows scrolling off the bottom of the visible alignment
2060   class ScrollThread extends Thread
2061   {
2062     MouseEvent evt;
2063
2064     private volatile boolean threadRunning = true;
2065
2066     public ScrollThread()
2067     {
2068       start();
2069     }
2070
2071     public void setEvent(MouseEvent e)
2072     {
2073       evt = e;
2074     }
2075
2076     public void stopScrolling()
2077     {
2078       threadRunning = false;
2079     }
2080
2081     public boolean isRunning()
2082     {
2083       return threadRunning;
2084     }
2085
2086     @Override
2087     public void run()
2088     {
2089       while (threadRunning)
2090       {
2091         if (evt != null)
2092         {
2093           if (mouseDragging && (evt.getY() < 0)
2094                   && (av.getRanges().getStartSeq() > 0))
2095           {
2096             av.getRanges().scrollUp(true);
2097           }
2098
2099           if (mouseDragging && (evt.getY() >= getHeight()) && (av
2100                   .getAlignment().getHeight() > av.getRanges().getEndSeq()))
2101           {
2102             av.getRanges().scrollUp(false);
2103           }
2104
2105           if (mouseDragging && (evt.getX() < 0))
2106           {
2107             av.getRanges().scrollRight(false);
2108           }
2109           else if (mouseDragging && (evt.getX() >= getWidth()))
2110           {
2111             av.getRanges().scrollRight(true);
2112           }
2113         }
2114
2115         try
2116         {
2117           Thread.sleep(20);
2118         } catch (Exception ex)
2119         {
2120         }
2121       }
2122     }
2123   }
2124
2125   /**
2126    * modify current selection according to a received message.
2127    */
2128   @Override
2129   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2130           HiddenColumns hidden, SelectionSource source)
2131   {
2132     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2133     // handles selection messages...
2134     // TODO: extend config options to allow user to control if selections may be
2135     // shared between viewports.
2136     boolean iSentTheSelection = (av == source
2137             || (source instanceof AlignViewport
2138                     && ((AlignmentViewport) source).getSequenceSetId()
2139                             .equals(av.getSequenceSetId())));
2140
2141     if (iSentTheSelection)
2142     {
2143       // respond to our own event by updating dependent dialogs
2144       if (ap.getCalculationDialog() != null)
2145       {
2146         ap.getCalculationDialog().validateCalcTypes();
2147       }
2148
2149       return;
2150     }
2151
2152     // process further ?
2153     if (!av.followSelection)
2154     {
2155       return;
2156     }
2157
2158     /*
2159      * Ignore the selection if there is one of our own pending.
2160      */
2161     if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2162     {
2163       return;
2164     }
2165
2166     /*
2167      * Check for selection in a view of which this one is a dna/protein
2168      * complement.
2169      */
2170     if (selectionFromTranslation(seqsel, colsel, hidden, source))
2171     {
2172       return;
2173     }
2174
2175     // do we want to thread this ? (contention with seqsel and colsel locks, I
2176     // suspect)
2177     /*
2178      * only copy colsel if there is a real intersection between
2179      * sequence selection and this panel's alignment
2180      */
2181     boolean repaint = false;
2182     boolean copycolsel = false;
2183
2184     SequenceGroup sgroup = null;
2185     if (seqsel != null && seqsel.getSize() > 0)
2186     {
2187       if (av.getAlignment() == null)
2188       {
2189         Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2190                 + " ViewId=" + av.getViewId()
2191                 + " 's alignment is NULL! returning immediately.");
2192         return;
2193       }
2194       sgroup = seqsel.intersect(av.getAlignment(),
2195               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2196       if ((sgroup != null && sgroup.getSize() > 0))
2197       {
2198         copycolsel = true;
2199       }
2200     }
2201     if (sgroup != null && sgroup.getSize() > 0)
2202     {
2203       av.setSelectionGroup(sgroup);
2204     }
2205     else
2206     {
2207       av.setSelectionGroup(null);
2208     }
2209     av.isSelectionGroupChanged(true);
2210     repaint = true;
2211
2212     if (copycolsel)
2213     {
2214       // the current selection is unset or from a previous message
2215       // so import the new colsel.
2216       if (colsel == null || colsel.isEmpty())
2217       {
2218         if (av.getColumnSelection() != null)
2219         {
2220           av.getColumnSelection().clear();
2221           repaint = true;
2222         }
2223       }
2224       else
2225       {
2226         // TODO: shift colSel according to the intersecting sequences
2227         if (av.getColumnSelection() == null)
2228         {
2229           av.setColumnSelection(new ColumnSelection(colsel));
2230         }
2231         else
2232         {
2233           av.getColumnSelection().setElementsFrom(colsel,
2234                   av.getAlignment().getHiddenColumns());
2235         }
2236       }
2237       av.isColSelChanged(true);
2238       repaint = true;
2239     }
2240
2241     if (copycolsel && av.hasHiddenColumns()
2242             && (av.getAlignment().getHiddenColumns() == null))
2243     {
2244       System.err.println("Bad things");
2245     }
2246     if (repaint) // always true!
2247     {
2248       // probably finessing with multiple redraws here
2249       PaintRefresher.Refresh(this, av.getSequenceSetId());
2250       // ap.paintAlignment(false);
2251     }
2252
2253     // lastly, update dependent dialogs
2254     if (ap.getCalculationDialog() != null)
2255     {
2256       ap.getCalculationDialog().validateCalcTypes();
2257     }
2258
2259   }
2260
2261   /**
2262    * If this panel is a cdna/protein translation view of the selection source,
2263    * tries to map the source selection to a local one, and returns true. Else
2264    * returns false.
2265    * 
2266    * @param seqsel
2267    * @param colsel
2268    * @param source
2269    */
2270   protected boolean selectionFromTranslation(SequenceGroup seqsel,
2271           ColumnSelection colsel, HiddenColumns hidden,
2272           SelectionSource source)
2273   {
2274     if (!(source instanceof AlignViewportI))
2275     {
2276       return false;
2277     }
2278     final AlignViewportI sourceAv = (AlignViewportI) source;
2279     if (sourceAv.getCodingComplement() != av
2280             && av.getCodingComplement() != sourceAv)
2281     {
2282       return false;
2283     }
2284
2285     /*
2286      * Map sequence selection
2287      */
2288     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2289     av.setSelectionGroup(sg);
2290     av.isSelectionGroupChanged(true);
2291
2292     /*
2293      * Map column selection
2294      */
2295     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2296     // av);
2297     ColumnSelection cs = new ColumnSelection();
2298     HiddenColumns hs = new HiddenColumns();
2299     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2300     av.setColumnSelection(cs);
2301     av.getAlignment().setHiddenColumns(hs);
2302
2303     // lastly, update any dependent dialogs
2304     if (ap.getCalculationDialog() != null)
2305     {
2306       ap.getCalculationDialog().validateCalcTypes();
2307     }
2308
2309     PaintRefresher.Refresh(this, av.getSequenceSetId());
2310
2311     return true;
2312   }
2313
2314   /**
2315    * 
2316    * @return null or last search results handled by this panel
2317    */
2318   public SearchResultsI getLastSearchResults()
2319   {
2320     return lastSearchResults;
2321   }
2322 }