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