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