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