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