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