2958f9de6ae80679c8a9fe801605724ff8821c72
[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().getHiddenSequences().isHidden(seqCanvas.cursorY)
432             && av.getAlignment().getHiddenColumns()
433                     .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.getMinMax());
838     }
839     if (tooltipText.length() == 6) // <html>
840     {
841       setToolTipText(null);
842       lastTooltip = null;
843     }
844     else
845     {
846       String textString = tooltipText.toString();
847       if (lastTooltip == null || !lastTooltip.equals(textString))
848       {
849         String formattedTooltipText = JvSwingUtils.wrapTooltip(true,
850                 textString);
851         setToolTipText(formattedTooltipText);
852         lastTooltip = textString;
853       }
854     }
855   }
856
857   private Point lastp = null;
858
859   /*
860    * (non-Javadoc)
861    * 
862    * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
863    */
864   @Override
865   public Point getToolTipLocation(MouseEvent event)
866   {
867     int x = event.getX(), w = getWidth();
868     int wdth = (w - x < 200) ? -(w / 2) : 5; // switch sides when tooltip is too
869     // close to edge
870     Point p = lastp;
871     if (!event.isShiftDown() || p == null)
872     {
873       p = (tooltipText != null && tooltipText.length() > 6)
874               ? new Point(event.getX() + wdth, event.getY() - 20)
875               : null;
876     }
877     /*
878      * TODO: try to modify position region is not obcured by tooltip
879      */
880     return lastp = p;
881   }
882
883   String lastTooltip;
884
885   /**
886    * set when the current UI interaction has resulted in a change that requires
887    * shading in overviews and structures to be recalculated. this could be
888    * changed to a something more expressive that indicates what actually has
889    * changed, so selective redraws can be applied (ie. only structures, only
890    * overview, etc)
891    */
892   private boolean updateOverviewAndStructs = false; // TODO: refactor to avcontroller
893
894   /**
895    * set if av.getSelectionGroup() refers to a group that is defined on the
896    * alignment view, rather than a transient selection
897    */
898   // private boolean editingDefinedGroup = false; // TODO: refactor to
899   // avcontroller or viewModel
900
901   /**
902    * Sets the status message in alignment panel, showing the sequence number
903    * (index) and id, and residue and residue position if not at a gap, for the
904    * given sequence and column position. Returns the residue position returned
905    * by Sequence.findPosition. Note this may be for the nearest adjacent residue
906    * if at a gapped position.
907    * 
908    * @param sequence
909    *          aligned sequence object
910    * @param column
911    *          alignment column
912    * @param seqIndex
913    *          index of sequence in alignment
914    * @return sequence position of residue at column, or adjacent residue if at a
915    *         gap
916    */
917   int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
918   {
919     char sequenceChar = sequence.getCharAt(column);
920     int pos = sequence.findPosition(column);
921     setStatusMessage(sequence, seqIndex, sequenceChar, pos);
922
923     return pos;
924   }
925
926   /**
927    * Builds the status message for the current cursor location and writes it to
928    * the status bar, for example
929    * 
930    * <pre>
931    * Sequence 3 ID: FER1_SOLLC
932    * Sequence 5 ID: FER1_PEA Residue: THR (4)
933    * Sequence 5 ID: FER1_PEA Residue: B (3)
934    * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
935    * </pre>
936    * 
937    * @param sequence
938    * @param seqIndex
939    *          sequence position in the alignment (1..)
940    * @param sequenceChar
941    *          the character under the cursor
942    * @param residuePos
943    *          the sequence residue position (if not over a gap)
944    */
945   protected void setStatusMessage(SequenceI sequence, int seqIndex,
946           char sequenceChar, int residuePos)
947   {
948     StringBuilder text = new StringBuilder(32);
949
950     /*
951      * Sequence number (if known), and sequence name.
952      */
953     String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
954     text.append("Sequence").append(seqno).append(" ID: ")
955             .append(sequence.getName());
956
957     String residue = null;
958
959     /*
960      * Try to translate the display character to residue name (null for gap).
961      */
962     boolean isGapped = Comparison.isGap(sequenceChar);
963
964     if (!isGapped)
965     {
966       boolean nucleotide = av.getAlignment().isNucleotide();
967       String displayChar = String.valueOf(sequenceChar);
968       if (nucleotide)
969       {
970         residue = ResidueProperties.nucleotideName.get(displayChar);
971       }
972       else
973       {
974         residue = "X".equalsIgnoreCase(displayChar) ? "X"
975                 : ("*".equals(displayChar) ? "STOP"
976                         : ResidueProperties.aa2Triplet.get(displayChar));
977       }
978       text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
979               .append(": ").append(residue == null ? displayChar : residue);
980
981       text.append(" (").append(Integer.toString(residuePos)).append(")");
982     }
983     ap.alignFrame.statusBar.setText(text.toString());
984   }
985
986   /**
987    * Set the status bar message to highlight the first matched position in
988    * search results.
989    * 
990    * @param results
991    */
992   private void setStatusMessage(SearchResultsI results)
993   {
994     AlignmentI al = this.av.getAlignment();
995     int sequenceIndex = al.findIndex(results);
996     if (sequenceIndex == -1)
997     {
998       return;
999     }
1000     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
1001     for (SearchResultMatchI m : results.getResults())
1002     {
1003       SequenceI seq = m.getSequence();
1004       if (seq.getDatasetSequence() != null)
1005       {
1006         seq = seq.getDatasetSequence();
1007       }
1008
1009       if (seq == ds)
1010       {
1011         int start = m.getStart();
1012         setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
1013                 start);
1014         return;
1015       }
1016     }
1017   }
1018
1019   /**
1020    * {@inheritDoc}
1021    */
1022   @Override
1023   public void mouseDragged(MouseEvent evt)
1024   {
1025     if (mouseWheelPressed)
1026     {
1027       boolean inSplitFrame = ap.av.getCodingComplement() != null;
1028       boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
1029
1030       int oldWidth = av.getCharWidth();
1031
1032       // Which is bigger, left-right or up-down?
1033       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math
1034               .abs(evt.getX() - lastMousePress.getX()))
1035       {
1036         /*
1037          * on drag up or down, decrement or increment font size
1038          */
1039         int fontSize = av.font.getSize();
1040         boolean fontChanged = false;
1041
1042         if (evt.getY() < lastMousePress.getY())
1043         {
1044           fontChanged = true;
1045           fontSize--;
1046         }
1047         else if (evt.getY() > lastMousePress.getY())
1048         {
1049           fontChanged = true;
1050           fontSize++;
1051         }
1052
1053         if (fontSize < 1)
1054         {
1055           fontSize = 1;
1056         }
1057
1058         if (fontChanged)
1059         {
1060           Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1061                   fontSize);
1062           av.setFont(newFont, true);
1063           av.setCharWidth(oldWidth);
1064           ap.fontChanged();
1065           if (copyChanges)
1066           {
1067             ap.av.getCodingComplement().setFont(newFont, true);
1068             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1069                     .getSplitViewContainer();
1070             splitFrame.adjustLayout();
1071             splitFrame.repaint();
1072           }
1073         }
1074       }
1075       else
1076       {
1077         /*
1078          * on drag left or right, decrement or increment character width
1079          */
1080         int newWidth = 0;
1081         if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1082         {
1083           newWidth = av.getCharWidth() - 1;
1084           av.setCharWidth(newWidth);
1085         }
1086         else if (evt.getX() > lastMousePress.getX())
1087         {
1088           newWidth = av.getCharWidth() + 1;
1089           av.setCharWidth(newWidth);
1090         }
1091         if (newWidth > 0)
1092         {
1093           ap.paintAlignment(false, false);
1094           if (copyChanges)
1095           {
1096             /*
1097              * need to ensure newWidth is set on cdna, regardless of which
1098              * panel the mouse drag happened in; protein will compute its 
1099              * character width as 1:1 or 3:1
1100              */
1101             av.getCodingComplement().setCharWidth(newWidth);
1102             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1103                     .getSplitViewContainer();
1104             splitFrame.adjustLayout();
1105             splitFrame.repaint();
1106           }
1107         }
1108       }
1109
1110       FontMetrics fm = getFontMetrics(av.getFont());
1111       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1112
1113       lastMousePress = evt.getPoint();
1114
1115       return;
1116     }
1117
1118     if (!editingSeqs)
1119     {
1120       doMouseDraggedDefineMode(evt);
1121       return;
1122     }
1123
1124     int res = findColumn(evt);
1125
1126     if (res < 0)
1127     {
1128       res = 0;
1129     }
1130
1131     if ((lastres == -1) || (lastres == res))
1132     {
1133       return;
1134     }
1135
1136     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1137     {
1138       // dragLeft, delete gap
1139       editSequence(false, false, res);
1140     }
1141     else
1142     {
1143       editSequence(true, false, res);
1144     }
1145
1146     mouseDragging = true;
1147     if ((scrollThread != null) && (scrollThread.isRunning()))
1148     {
1149       scrollThread.setEvent(evt);
1150     }
1151   }
1152
1153   // TODO: Make it more clever than many booleans
1154   synchronized void editSequence(boolean insertGap, boolean editSeq,
1155           int startres)
1156   {
1157     int fixedLeft = -1;
1158     int fixedRight = -1;
1159     boolean fixedColumns = false;
1160     SequenceGroup sg = av.getSelectionGroup();
1161
1162     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1163
1164     // No group, but the sequence may represent a group
1165     if (!groupEditing && av.hasHiddenRows())
1166     {
1167       if (av.isHiddenRepSequence(seq))
1168       {
1169         sg = av.getRepresentedSequences(seq);
1170         groupEditing = true;
1171       }
1172     }
1173
1174     StringBuilder message = new StringBuilder(64);
1175     if (groupEditing)
1176     {
1177       message.append("Edit group:");
1178       if (editCommand == null)
1179       {
1180         editCommand = new EditCommand(
1181                 MessageManager.getString("action.edit_group"));
1182       }
1183     }
1184     else
1185     {
1186       message.append("Edit sequence: " + seq.getName());
1187       String label = seq.getName();
1188       if (label.length() > 10)
1189       {
1190         label = label.substring(0, 10);
1191       }
1192       if (editCommand == null)
1193       {
1194         editCommand = new EditCommand(MessageManager
1195                 .formatMessage("label.edit_params", new String[]
1196                 { label }));
1197       }
1198     }
1199
1200     if (insertGap)
1201     {
1202       message.append(" insert ");
1203     }
1204     else
1205     {
1206       message.append(" delete ");
1207     }
1208
1209     message.append(Math.abs(startres - lastres) + " gaps.");
1210     ap.alignFrame.statusBar.setText(message.toString());
1211
1212     // Are we editing within a selection group?
1213     if (groupEditing || (sg != null
1214             && sg.getSequences(av.getHiddenRepSequences()).contains(seq)))
1215     {
1216       fixedColumns = true;
1217
1218       // sg might be null as the user may only see 1 sequence,
1219       // but the sequence represents a group
1220       if (sg == null)
1221       {
1222         if (!av.isHiddenRepSequence(seq))
1223         {
1224           endEditing();
1225           return;
1226         }
1227         sg = av.getRepresentedSequences(seq);
1228       }
1229
1230       fixedLeft = sg.getStartRes();
1231       fixedRight = sg.getEndRes();
1232
1233       if ((startres < fixedLeft && lastres >= fixedLeft)
1234               || (startres >= fixedLeft && lastres < fixedLeft)
1235               || (startres > fixedRight && lastres <= fixedRight)
1236               || (startres <= fixedRight && lastres > fixedRight))
1237       {
1238         endEditing();
1239         return;
1240       }
1241
1242       if (fixedLeft > startres)
1243       {
1244         fixedRight = fixedLeft - 1;
1245         fixedLeft = 0;
1246       }
1247       else if (fixedRight < startres)
1248       {
1249         fixedLeft = fixedRight;
1250         fixedRight = -1;
1251       }
1252     }
1253
1254     if (av.hasHiddenColumns())
1255     {
1256       fixedColumns = true;
1257       int y1 = av.getAlignment().getHiddenColumns()
1258               .getHiddenBoundaryLeft(startres);
1259       int y2 = av.getAlignment().getHiddenColumns()
1260               .getHiddenBoundaryRight(startres);
1261
1262       if ((insertGap && startres > y1 && lastres < y1)
1263               || (!insertGap && startres < y2 && lastres > y2))
1264       {
1265         endEditing();
1266         return;
1267       }
1268
1269       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1270       // Selection spans a hidden region
1271       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1272       {
1273         if (startres >= y2)
1274         {
1275           fixedLeft = y2;
1276         }
1277         else
1278         {
1279           fixedRight = y2 - 1;
1280         }
1281       }
1282     }
1283
1284     if (groupEditing)
1285     {
1286       List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1287       int g, groupSize = vseqs.size();
1288       SequenceI[] groupSeqs = new SequenceI[groupSize];
1289       for (g = 0; g < groupSeqs.length; g++)
1290       {
1291         groupSeqs[g] = vseqs.get(g);
1292       }
1293
1294       // drag to right
1295       if (insertGap)
1296       {
1297         // If the user has selected the whole sequence, and is dragging to
1298         // the right, we can still extend the alignment and selectionGroup
1299         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1300                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1301         {
1302           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1303           fixedRight = sg.getEndRes();
1304         }
1305
1306         // Is it valid with fixed columns??
1307         // Find the next gap before the end
1308         // of the visible region boundary
1309         boolean blank = false;
1310         for (; fixedRight > lastres; fixedRight--)
1311         {
1312           blank = true;
1313
1314           for (g = 0; g < groupSize; g++)
1315           {
1316             for (int j = 0; j < startres - lastres; j++)
1317             {
1318               if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1319               {
1320                 blank = false;
1321                 break;
1322               }
1323             }
1324           }
1325           if (blank)
1326           {
1327             break;
1328           }
1329         }
1330
1331         if (!blank)
1332         {
1333           if (sg.getSize() == av.getAlignment().getHeight())
1334           {
1335             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1336                     .getHiddenColumns().getHiddenBoundaryRight(startres)))
1337             {
1338               endEditing();
1339               return;
1340             }
1341
1342             int alWidth = av.getAlignment().getWidth();
1343             if (av.hasHiddenRows())
1344             {
1345               int hwidth = av.getAlignment().getHiddenSequences()
1346                       .getWidth();
1347               if (hwidth > alWidth)
1348               {
1349                 alWidth = hwidth;
1350               }
1351             }
1352             // We can still insert gaps if the selectionGroup
1353             // contains all the sequences
1354             sg.setEndRes(sg.getEndRes() + startres - lastres);
1355             fixedRight = alWidth + startres - lastres;
1356           }
1357           else
1358           {
1359             endEditing();
1360             return;
1361           }
1362         }
1363       }
1364
1365       // drag to left
1366       else if (!insertGap)
1367       {
1368         // / Are we able to delete?
1369         // ie are all columns blank?
1370
1371         for (g = 0; g < groupSize; g++)
1372         {
1373           for (int j = startres; j < lastres; j++)
1374           {
1375             if (groupSeqs[g].getLength() <= j)
1376             {
1377               continue;
1378             }
1379
1380             if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1381             {
1382               // Not a gap, block edit not valid
1383               endEditing();
1384               return;
1385             }
1386           }
1387         }
1388       }
1389
1390       if (insertGap)
1391       {
1392         // dragging to the right
1393         if (fixedColumns && fixedRight != -1)
1394         {
1395           for (int j = lastres; j < startres; j++)
1396           {
1397             insertChar(j, groupSeqs, fixedRight);
1398           }
1399         }
1400         else
1401         {
1402           appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1403                   startres - lastres);
1404         }
1405       }
1406       else
1407       {
1408         // dragging to the left
1409         if (fixedColumns && fixedRight != -1)
1410         {
1411           for (int j = lastres; j > startres; j--)
1412           {
1413             deleteChar(startres, groupSeqs, fixedRight);
1414           }
1415         }
1416         else
1417         {
1418           appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1419                   lastres - startres);
1420         }
1421
1422       }
1423     }
1424     else
1425     // ///Editing a single sequence///////////
1426     {
1427       if (insertGap)
1428       {
1429         // dragging to the right
1430         if (fixedColumns && fixedRight != -1)
1431         {
1432           for (int j = lastres; j < startres; j++)
1433           {
1434             insertChar(j, new SequenceI[] { seq }, fixedRight);
1435           }
1436         }
1437         else
1438         {
1439           appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1440                   startres - lastres);
1441         }
1442       }
1443       else
1444       {
1445         if (!editSeq)
1446         {
1447           // dragging to the left
1448           if (fixedColumns && fixedRight != -1)
1449           {
1450             for (int j = lastres; j > startres; j--)
1451             {
1452               if (!Comparison.isGap(seq.getCharAt(startres)))
1453               {
1454                 endEditing();
1455                 break;
1456               }
1457               deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1458             }
1459           }
1460           else
1461           {
1462             // could be a keyboard edit trying to delete none gaps
1463             int max = 0;
1464             for (int m = startres; m < lastres; m++)
1465             {
1466               if (!Comparison.isGap(seq.getCharAt(m)))
1467               {
1468                 break;
1469               }
1470               max++;
1471             }
1472
1473             if (max > 0)
1474             {
1475               appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1476                       startres, max);
1477             }
1478           }
1479         }
1480         else
1481         {// insertGap==false AND editSeq==TRUE;
1482           if (fixedColumns && fixedRight != -1)
1483           {
1484             for (int j = lastres; j < startres; j++)
1485             {
1486               insertChar(j, new SequenceI[] { seq }, fixedRight);
1487             }
1488           }
1489           else
1490           {
1491             appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1492                     startres - lastres);
1493           }
1494         }
1495       }
1496     }
1497
1498     lastres = startres;
1499     seqCanvas.repaint();
1500   }
1501
1502   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1503   {
1504     int blankColumn = fixedColumn;
1505     for (int s = 0; s < seq.length; s++)
1506     {
1507       // Find the next gap before the end of the visible region boundary
1508       // If lastCol > j, theres a boundary after the gap insertion
1509
1510       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1511       {
1512         if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1513         {
1514           // Theres a space, so break and insert the gap
1515           break;
1516         }
1517       }
1518
1519       if (blankColumn <= j)
1520       {
1521         blankColumn = fixedColumn;
1522         endEditing();
1523         return;
1524       }
1525     }
1526
1527     appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1528
1529     appendEdit(Action.INSERT_GAP, seq, j, 1);
1530
1531   }
1532
1533   /**
1534    * Helper method to add and perform one edit action.
1535    * 
1536    * @param action
1537    * @param seq
1538    * @param pos
1539    * @param count
1540    */
1541   protected void appendEdit(Action action, SequenceI[] seq, int pos,
1542           int count)
1543   {
1544
1545     final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1546             av.getAlignment().getGapCharacter());
1547
1548     editCommand.appendEdit(edit, av.getAlignment(), true, null);
1549   }
1550
1551   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1552   {
1553
1554     appendEdit(Action.DELETE_GAP, seq, j, 1);
1555
1556     appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1557   }
1558
1559   /**
1560    * DOCUMENT ME!
1561    * 
1562    * @param e
1563    *          DOCUMENT ME!
1564    */
1565   @Override
1566   public void mouseEntered(MouseEvent e)
1567   {
1568     if (oldSeq < 0)
1569     {
1570       oldSeq = 0;
1571     }
1572
1573     if ((scrollThread != null) && (scrollThread.isRunning()))
1574     {
1575       scrollThread.stopScrolling();
1576       scrollThread = null;
1577     }
1578   }
1579
1580   /**
1581    * DOCUMENT ME!
1582    * 
1583    * @param e
1584    *          DOCUMENT ME!
1585    */
1586   @Override
1587   public void mouseExited(MouseEvent e)
1588   {
1589     if (av.getWrapAlignment())
1590     {
1591       return;
1592     }
1593
1594     if (mouseDragging && scrollThread == null)
1595     {
1596       scrollThread = new ScrollThread();
1597     }
1598   }
1599
1600   /**
1601    * Handler for double-click on a position with one or more sequence features.
1602    * Opens the Amend Features dialog to allow feature details to be amended, or
1603    * the feature deleted.
1604    */
1605   @Override
1606   public void mouseClicked(MouseEvent evt)
1607   {
1608     SequenceGroup sg = null;
1609     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1610     if (evt.getClickCount() > 1)
1611     {
1612       sg = av.getSelectionGroup();
1613       if (sg != null && sg.getSize() == 1
1614               && sg.getEndRes() - sg.getStartRes() < 2)
1615       {
1616         av.setSelectionGroup(null);
1617       }
1618
1619       int column = findColumn(evt);
1620
1621       /*
1622        * find features at the position (if not gapped), or straddling
1623        * the position (if at a gap)
1624        */
1625       List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1626               .findFeaturesAtColumn(sequence, column + 1);
1627
1628       if (!features.isEmpty())
1629       {
1630         /*
1631          * highlight the first feature at the position on the alignment
1632          */
1633         SearchResultsI highlight = new SearchResults();
1634         highlight.addResult(sequence, features.get(0).getBegin(), features
1635                 .get(0).getEnd());
1636         seqCanvas.highlightSearchResults(highlight, false);
1637
1638         /*
1639          * open the Amend Features dialog; clear highlighting afterwards,
1640          * whether changes were made or not
1641          */
1642         List<SequenceI> seqs = Collections.singletonList(sequence);
1643         seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1644                 ap);
1645         av.setSearchResults(null); // clear highlighting
1646         seqCanvas.repaint(); // draw new/amended features
1647       }
1648     }
1649   }
1650
1651   @Override
1652   public void mouseWheelMoved(MouseWheelEvent e)
1653   {
1654     e.consume();
1655     if (e.getWheelRotation() > 0)
1656     {
1657       if (e.isShiftDown())
1658       {
1659         av.getRanges().scrollRight(true);
1660
1661       }
1662       else
1663       {
1664         av.getRanges().scrollUp(false);
1665       }
1666     }
1667     else
1668     {
1669       if (e.isShiftDown())
1670       {
1671         av.getRanges().scrollRight(false);
1672       }
1673       else
1674       {
1675         av.getRanges().scrollUp(true);
1676       }
1677     }
1678
1679     /*
1680      * update status bar and tooltip for new position
1681      * (need to synthesize a mouse movement to refresh tooltip)
1682      */
1683     mouseMoved(e);
1684     ToolTipManager.sharedInstance().mouseMoved(e);
1685   }
1686
1687   /**
1688    * DOCUMENT ME!
1689    * 
1690    * @param evt
1691    *          DOCUMENT ME!
1692    */
1693   public void doMousePressedDefineMode(MouseEvent evt)
1694   {
1695     final int res = findColumn(evt);
1696     final int seq = findSeq(evt);
1697     oldSeq = seq;
1698     updateOverviewAndStructs = false;
1699
1700     startWrapBlock = wrappedBlock;
1701
1702     if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1703     {
1704       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1705               MessageManager.getString(
1706                       "label.cannot_edit_annotations_in_wrapped_view"),
1707               MessageManager.getString("label.wrapped_view_no_edit"),
1708               JvOptionPane.WARNING_MESSAGE);
1709       return;
1710     }
1711
1712     if (seq < 0 || res < 0)
1713     {
1714       return;
1715     }
1716
1717     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1718
1719     if ((sequence == null) || (res > sequence.getLength()))
1720     {
1721       return;
1722     }
1723
1724     stretchGroup = av.getSelectionGroup();
1725
1726     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1727     {
1728       stretchGroup = av.getAlignment().findGroup(sequence, res);
1729       if (stretchGroup != null)
1730       {
1731         // only update the current selection if the popup menu has a group to
1732         // focus on
1733         av.setSelectionGroup(stretchGroup);
1734       }
1735     }
1736
1737     if (evt.isPopupTrigger()) // Mac: mousePressed
1738     {
1739       showPopupMenu(evt);
1740       return;
1741     }
1742
1743     /*
1744      * defer right-mouse click handling to mouseReleased on Windows
1745      * (where isPopupTrigger() will answer true)
1746      * NB isRightMouseButton is also true for Cmd-click on Mac
1747      */
1748     if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1749     {
1750       return;
1751     }
1752
1753     if (av.cursorMode)
1754     {
1755       seqCanvas.cursorX = findColumn(evt);
1756       seqCanvas.cursorY = findSeq(evt);
1757       seqCanvas.repaint();
1758       return;
1759     }
1760
1761     if (stretchGroup == null)
1762     {
1763       createStretchGroup(res, sequence);
1764     }
1765
1766     if (stretchGroup != null)
1767     {
1768       stretchGroup.addPropertyChangeListener(seqCanvas);
1769     }
1770
1771     seqCanvas.repaint();
1772   }
1773
1774   private void createStretchGroup(int res, SequenceI sequence)
1775   {
1776     // Only if left mouse button do we want to change group sizes
1777     // define a new group here
1778     SequenceGroup sg = new SequenceGroup();
1779     sg.setStartRes(res);
1780     sg.setEndRes(res);
1781     sg.addSequence(sequence, false);
1782     av.setSelectionGroup(sg);
1783     stretchGroup = sg;
1784
1785     if (av.getConservationSelected())
1786     {
1787       SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1788               ap.getViewName());
1789     }
1790
1791     if (av.getAbovePIDThreshold())
1792     {
1793       SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1794               ap.getViewName());
1795     }
1796     // TODO: stretchGroup will always be not null. Is this a merge error ?
1797     // or is there a threading issue here?
1798     if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1799     {
1800       // Edit end res position of selected group
1801       changeEndRes = true;
1802     }
1803     else if ((stretchGroup != null) && (stretchGroup.getStartRes() == res))
1804     {
1805       // Edit end res position of selected group
1806       changeStartRes = true;
1807     }
1808     stretchGroup.getWidth();
1809
1810   }
1811
1812   /**
1813    * Build and show a pop-up menu at the right-click mouse position
1814    * 
1815    * @param evt
1816    * @param res
1817    * @param sequences
1818    */
1819   void showPopupMenu(MouseEvent evt)
1820   {
1821     final int column = findColumn(evt);
1822     final int seq = findSeq(evt);
1823     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1824     List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1825             .findFeaturesAtColumn(sequence, column + 1);
1826     List<String> links = new ArrayList<>();
1827     for (SequenceFeature sf : allFeatures)
1828     {
1829       if (sf.links != null)
1830       {
1831         for (String link : sf.links)
1832         {
1833           links.add(link);
1834         }
1835       }
1836     }
1837
1838     PopupMenu pop = new PopupMenu(ap, null, links);
1839     pop.show(this, evt.getX(), evt.getY());
1840   }
1841
1842   /**
1843    * Update the display after mouse up on a selection or group
1844    * 
1845    * @param evt
1846    *          mouse released event details
1847    * @param afterDrag
1848    *          true if this event is happening after a mouse drag (rather than a
1849    *          mouse down)
1850    */
1851   public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1852   {
1853     if (stretchGroup == null)
1854     {
1855       return;
1856     }
1857
1858     stretchGroup.removePropertyChangeListener(seqCanvas);
1859
1860     // always do this - annotation has own state
1861     // but defer colourscheme update until hidden sequences are passed in
1862     boolean vischange = stretchGroup.recalcConservation(true);
1863     updateOverviewAndStructs |= vischange && av.isSelectionDefinedGroup()
1864             && afterDrag;
1865     if (stretchGroup.cs != null)
1866     {
1867       stretchGroup.cs.alignmentChanged(stretchGroup,
1868               av.getHiddenRepSequences());
1869
1870       ResidueShaderI groupColourScheme = stretchGroup
1871               .getGroupColourScheme();
1872       String name = stretchGroup.getName();
1873       if (stretchGroup.cs.conservationApplied())
1874       {
1875         SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1876       }
1877       if (stretchGroup.cs.getThreshold() > 0)
1878       {
1879         SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1880       }
1881     }
1882     PaintRefresher.Refresh(this, av.getSequenceSetId());
1883     // TODO: structure colours only need updating if stretchGroup used to or now
1884     // does contain sequences with structure views
1885     ap.paintAlignment(updateOverviewAndStructs, updateOverviewAndStructs);
1886     updateOverviewAndStructs = false;
1887     changeEndRes = false;
1888     changeStartRes = false;
1889     stretchGroup = null;
1890     av.sendSelection();
1891   }
1892
1893   /**
1894    * DOCUMENT ME!
1895    * 
1896    * @param evt
1897    *          DOCUMENT ME!
1898    */
1899   public void doMouseDraggedDefineMode(MouseEvent evt)
1900   {
1901     int res = findColumn(evt);
1902     int y = findSeq(evt);
1903
1904     if (wrappedBlock != startWrapBlock)
1905     {
1906       return;
1907     }
1908
1909     if (stretchGroup == null)
1910     {
1911       return;
1912     }
1913
1914     if (res >= av.getAlignment().getWidth())
1915     {
1916       res = av.getAlignment().getWidth() - 1;
1917     }
1918
1919     if (stretchGroup.getEndRes() == res)
1920     {
1921       // Edit end res position of selected group
1922       changeEndRes = true;
1923     }
1924     else if (stretchGroup.getStartRes() == res)
1925     {
1926       // Edit start res position of selected group
1927       changeStartRes = true;
1928     }
1929
1930     if (res < av.getRanges().getStartRes())
1931     {
1932       res = av.getRanges().getStartRes();
1933     }
1934
1935     if (changeEndRes)
1936     {
1937       if (res > (stretchGroup.getStartRes() - 1))
1938       {
1939         stretchGroup.setEndRes(res);
1940         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1941       }
1942     }
1943     else if (changeStartRes)
1944     {
1945       if (res < (stretchGroup.getEndRes() + 1))
1946       {
1947         stretchGroup.setStartRes(res);
1948         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1949       }
1950     }
1951
1952     int dragDirection = 0;
1953
1954     if (y > oldSeq)
1955     {
1956       dragDirection = 1;
1957     }
1958     else if (y < oldSeq)
1959     {
1960       dragDirection = -1;
1961     }
1962
1963     while ((y != oldSeq) && (oldSeq > -1)
1964             && (y < av.getAlignment().getHeight()))
1965     {
1966       // This routine ensures we don't skip any sequences, as the
1967       // selection is quite slow.
1968       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1969
1970       oldSeq += dragDirection;
1971
1972       if (oldSeq < 0)
1973       {
1974         break;
1975       }
1976
1977       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1978
1979       if (stretchGroup.getSequences(null).contains(nextSeq))
1980       {
1981         stretchGroup.deleteSequence(seq, false);
1982         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1983       }
1984       else
1985       {
1986         if (seq != null)
1987         {
1988           stretchGroup.addSequence(seq, false);
1989         }
1990
1991         stretchGroup.addSequence(nextSeq, false);
1992         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
1993       }
1994     }
1995
1996     if (oldSeq < 0)
1997     {
1998       oldSeq = -1;
1999     }
2000
2001     mouseDragging = true;
2002
2003     if ((scrollThread != null) && (scrollThread.isRunning()))
2004     {
2005       scrollThread.setEvent(evt);
2006     }
2007   }
2008
2009   void scrollCanvas(MouseEvent evt)
2010   {
2011     if (evt == null)
2012     {
2013       if ((scrollThread != null) && (scrollThread.isRunning()))
2014       {
2015         scrollThread.stopScrolling();
2016         scrollThread = null;
2017       }
2018       mouseDragging = false;
2019     }
2020     else
2021     {
2022       if (scrollThread == null)
2023       {
2024         scrollThread = new ScrollThread();
2025       }
2026
2027       mouseDragging = true;
2028       scrollThread.setEvent(evt);
2029     }
2030
2031   }
2032
2033   // this class allows scrolling off the bottom of the visible alignment
2034   class ScrollThread extends Thread
2035   {
2036     MouseEvent evt;
2037
2038     private volatile boolean threadRunning = true;
2039
2040     public ScrollThread()
2041     {
2042       start();
2043     }
2044
2045     public void setEvent(MouseEvent e)
2046     {
2047       evt = e;
2048     }
2049
2050     public void stopScrolling()
2051     {
2052       threadRunning = false;
2053     }
2054
2055     public boolean isRunning()
2056     {
2057       return threadRunning;
2058     }
2059
2060     @Override
2061     public void run()
2062     {
2063       while (threadRunning)
2064       {
2065         if (evt != null)
2066         {
2067           if (mouseDragging && (evt.getY() < 0)
2068                   && (av.getRanges().getStartSeq() > 0))
2069           {
2070             av.getRanges().scrollUp(true);
2071           }
2072
2073           if (mouseDragging && (evt.getY() >= getHeight()) && (av
2074                   .getAlignment().getHeight() > av.getRanges().getEndSeq()))
2075           {
2076             av.getRanges().scrollUp(false);
2077           }
2078
2079           if (mouseDragging && (evt.getX() < 0))
2080           {
2081             av.getRanges().scrollRight(false);
2082           }
2083           else if (mouseDragging && (evt.getX() >= getWidth()))
2084           {
2085             av.getRanges().scrollRight(true);
2086           }
2087         }
2088
2089         try
2090         {
2091           Thread.sleep(20);
2092         } catch (Exception ex)
2093         {
2094         }
2095       }
2096     }
2097   }
2098
2099   /**
2100    * modify current selection according to a received message.
2101    */
2102   @Override
2103   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2104           HiddenColumns hidden, SelectionSource source)
2105   {
2106     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2107     // handles selection messages...
2108     // TODO: extend config options to allow user to control if selections may be
2109     // shared between viewports.
2110     boolean iSentTheSelection = (av == source
2111             || (source instanceof AlignViewport
2112                     && ((AlignmentViewport) source).getSequenceSetId()
2113                             .equals(av.getSequenceSetId())));
2114
2115     if (iSentTheSelection)
2116     {
2117       // respond to our own event by updating dependent dialogs
2118       if (ap.getCalculationDialog() != null)
2119       {
2120         ap.getCalculationDialog().validateCalcTypes();
2121       }
2122
2123       return;
2124     }
2125
2126     // process further ?
2127     if (!av.followSelection)
2128     {
2129       return;
2130     }
2131
2132     /*
2133      * Ignore the selection if there is one of our own pending.
2134      */
2135     if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2136     {
2137       return;
2138     }
2139
2140     /*
2141      * Check for selection in a view of which this one is a dna/protein
2142      * complement.
2143      */
2144     if (selectionFromTranslation(seqsel, colsel, hidden, source))
2145     {
2146       return;
2147     }
2148
2149     // do we want to thread this ? (contention with seqsel and colsel locks, I
2150     // suspect)
2151     /*
2152      * only copy colsel if there is a real intersection between
2153      * sequence selection and this panel's alignment
2154      */
2155     boolean repaint = false;
2156     boolean copycolsel = false;
2157
2158     SequenceGroup sgroup = null;
2159     if (seqsel != null && seqsel.getSize() > 0)
2160     {
2161       if (av.getAlignment() == null)
2162       {
2163         Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2164                 + " ViewId=" + av.getViewId()
2165                 + " 's alignment is NULL! returning immediately.");
2166         return;
2167       }
2168       sgroup = seqsel.intersect(av.getAlignment(),
2169               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2170       if ((sgroup != null && sgroup.getSize() > 0))
2171       {
2172         copycolsel = true;
2173       }
2174     }
2175     if (sgroup != null && sgroup.getSize() > 0)
2176     {
2177       av.setSelectionGroup(sgroup);
2178     }
2179     else
2180     {
2181       av.setSelectionGroup(null);
2182     }
2183     av.isSelectionGroupChanged(true);
2184     repaint = true;
2185
2186     if (copycolsel)
2187     {
2188       // the current selection is unset or from a previous message
2189       // so import the new colsel.
2190       if (colsel == null || colsel.isEmpty())
2191       {
2192         if (av.getColumnSelection() != null)
2193         {
2194           av.getColumnSelection().clear();
2195           repaint = true;
2196         }
2197       }
2198       else
2199       {
2200         // TODO: shift colSel according to the intersecting sequences
2201         if (av.getColumnSelection() == null)
2202         {
2203           av.setColumnSelection(new ColumnSelection(colsel));
2204         }
2205         else
2206         {
2207           av.getColumnSelection().setElementsFrom(colsel,
2208                   av.getAlignment().getHiddenColumns());
2209         }
2210       }
2211       av.isColSelChanged(true);
2212       repaint = true;
2213     }
2214
2215     if (copycolsel && av.hasHiddenColumns()
2216             && (av.getAlignment().getHiddenColumns() == null))
2217     {
2218       System.err.println("Bad things");
2219     }
2220     if (repaint) // always true!
2221     {
2222       // probably finessing with multiple redraws here
2223       PaintRefresher.Refresh(this, av.getSequenceSetId());
2224       // ap.paintAlignment(false);
2225     }
2226
2227     // lastly, update dependent dialogs
2228     if (ap.getCalculationDialog() != null)
2229     {
2230       ap.getCalculationDialog().validateCalcTypes();
2231     }
2232
2233   }
2234
2235   /**
2236    * If this panel is a cdna/protein translation view of the selection source,
2237    * tries to map the source selection to a local one, and returns true. Else
2238    * returns false.
2239    * 
2240    * @param seqsel
2241    * @param colsel
2242    * @param source
2243    */
2244   protected boolean selectionFromTranslation(SequenceGroup seqsel,
2245           ColumnSelection colsel, HiddenColumns hidden,
2246           SelectionSource source)
2247   {
2248     if (!(source instanceof AlignViewportI))
2249     {
2250       return false;
2251     }
2252     final AlignViewportI sourceAv = (AlignViewportI) source;
2253     if (sourceAv.getCodingComplement() != av
2254             && av.getCodingComplement() != sourceAv)
2255     {
2256       return false;
2257     }
2258
2259     /*
2260      * Map sequence selection
2261      */
2262     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2263     av.setSelectionGroup(sg);
2264     av.isSelectionGroupChanged(true);
2265
2266     /*
2267      * Map column selection
2268      */
2269     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2270     // av);
2271     ColumnSelection cs = new ColumnSelection();
2272     HiddenColumns hs = new HiddenColumns();
2273     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2274     av.setColumnSelection(cs);
2275     av.getAlignment().setHiddenColumns(hs);
2276
2277     // lastly, update any dependent dialogs
2278     if (ap.getCalculationDialog() != null)
2279     {
2280       ap.getCalculationDialog().validateCalcTypes();
2281     }
2282
2283     PaintRefresher.Refresh(this, av.getSequenceSetId());
2284
2285     return true;
2286   }
2287 }