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