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