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