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