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