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