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