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