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