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