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