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