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