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