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