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