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