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