9a67c27b7c4dbf8cd28cce4801f373a581e99192
[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.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.HiddenColumns;
32 import jalview.datamodel.SearchResultMatchI;
33 import jalview.datamodel.SearchResults;
34 import jalview.datamodel.SearchResultsI;
35 import jalview.datamodel.Sequence;
36 import jalview.datamodel.SequenceFeature;
37 import jalview.datamodel.SequenceGroup;
38 import jalview.datamodel.SequenceI;
39 import jalview.io.SequenceAnnotationReport;
40 import jalview.renderer.ResidueShaderI;
41 import jalview.schemes.ResidueProperties;
42 import jalview.structure.SelectionListener;
43 import jalview.structure.SelectionSource;
44 import jalview.structure.SequenceListener;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.structure.VamsasSource;
47 import jalview.util.Comparison;
48 import jalview.util.MappingUtils;
49 import jalview.util.MessageManager;
50 import jalview.util.Platform;
51 import jalview.viewmodel.AlignmentViewport;
52 import jalview.viewmodel.ViewportRanges;
53
54 import java.awt.BorderLayout;
55 import java.awt.Color;
56 import java.awt.Font;
57 import java.awt.FontMetrics;
58 import java.awt.Point;
59 import java.awt.event.ActionEvent;
60 import java.awt.event.ActionListener;
61 import java.awt.event.MouseEvent;
62 import java.awt.event.MouseListener;
63 import java.awt.event.MouseMotionListener;
64 import java.awt.event.MouseWheelEvent;
65 import java.awt.event.MouseWheelListener;
66 import java.util.Collections;
67 import java.util.List;
68
69 import javax.swing.JLabel;
70 import javax.swing.JPanel;
71 import javax.swing.JToolTip;
72 import javax.swing.SwingUtilities;
73 import javax.swing.Timer;
74 import javax.swing.ToolTipManager;
75
76 /**
77  * DOCUMENT ME!
78  * 
79  * @author $author$
80  * @version $Revision: 1.130 $
81  */
82 public class SeqPanel extends JPanel
83         implements MouseListener, MouseMotionListener, MouseWheelListener,
84         SequenceListener, SelectionListener
85 {
86   /*
87    * a class that holds computed mouse position
88    * - column of the alignment (0...)
89    * - sequence offset (0...)
90    * - annotation row offset (0...)
91    * where annotation offset is -1 unless the alignment is shown
92    * in wrapped mode, annotations are shown, and the mouse is
93    * over an annnotation row
94    */
95   static class MousePos
96   {
97     /*
98      * alignment column position of cursor (0...)
99      */
100     final int column;
101
102     /*
103      * index in alignment of sequence under cursor,
104      * or nearest above if cursor is not over a sequence
105      */
106     final int seqIndex;
107
108     /*
109      * index in annotations array of annotation under the cursor
110      * (only possible in wrapped mode with annotations shown),
111      * or -1 if cursor is not over an annotation row
112      */
113     final int annotationIndex;
114
115     MousePos(int col, int seq, int ann)
116     {
117       column = col;
118       seqIndex = seq;
119       annotationIndex = ann;
120     }
121
122     boolean isOverAnnotation()
123     {
124       return annotationIndex != -1;
125     }
126
127     @Override
128     public boolean equals(Object obj)
129     {
130       if (obj == null || !(obj instanceof MousePos))
131       {
132         return false;
133       }
134       MousePos o = (MousePos) obj;
135       boolean b = (column == o.column && seqIndex == o.seqIndex
136               && annotationIndex == o.annotationIndex);
137       // System.out.println(obj + (b ? "= " : "!= ") + this);
138       return b;
139     }
140
141     /**
142      * A simple hashCode that ensures that instances that satisfy equals() have
143      * the same hashCode
144      */
145     @Override
146     public int hashCode()
147     {
148       return column + seqIndex + annotationIndex;
149     }
150
151     /**
152      * toString method for debug output purposes only
153      */
154     @Override
155     public String toString()
156     {
157       return String.format("c%d:s%d:a%d", column, seqIndex,
158               annotationIndex);
159     }
160   }
161
162   private static final int MAX_TOOLTIP_LENGTH = 300;
163
164   public SeqCanvas seqCanvas;
165
166   public AlignmentPanel ap;
167
168   /*
169    * last position for mouseMoved event
170    */
171   private MousePos lastMousePosition;
172
173   protected int editLastRes;
174
175   protected int editStartSeq;
176
177   protected AlignViewport av;
178
179   ScrollThread scrollThread = null;
180
181   boolean mouseDragging = false;
182
183   boolean editingSeqs = false;
184
185   boolean groupEditing = false;
186
187   // ////////////////////////////////////////
188   // ///Everything below this is for defining the boundary of the rubberband
189   // ////////////////////////////////////////
190   int oldSeq = -1;
191
192   boolean changeEndSeq = false;
193
194   boolean changeStartSeq = false;
195
196   boolean changeEndRes = false;
197
198   boolean changeStartRes = false;
199
200   SequenceGroup stretchGroup = null;
201
202   boolean remove = false;
203
204   Point lastMousePress;
205
206   boolean mouseWheelPressed = false;
207
208   StringBuffer keyboardNo1;
209
210   StringBuffer keyboardNo2;
211
212   java.net.URL linkImageURL;
213
214   private final SequenceAnnotationReport seqARep;
215
216   StringBuilder tooltipText = new StringBuilder();
217
218   String tmpString;
219
220   EditCommand editCommand;
221
222   StructureSelectionManager ssm;
223
224   SearchResultsI lastSearchResults;
225
226   /**
227    * Creates a new SeqPanel object
228    * 
229    * @param viewport
230    * @param alignPanel
231    */
232   public SeqPanel(AlignViewport viewport, AlignmentPanel alignPanel)
233   {
234     linkImageURL = getClass().getResource("/images/link.gif");
235     seqARep = new SequenceAnnotationReport(linkImageURL.toString());
236     ToolTipManager.sharedInstance().registerComponent(this);
237     ToolTipManager.sharedInstance().setInitialDelay(0);
238     ToolTipManager.sharedInstance().setDismissDelay(10000);
239     
240     
241     this.av = viewport;
242     setBackground(Color.white);
243
244     seqCanvas = new SeqCanvas(alignPanel);
245     setLayout(new BorderLayout());
246     add(seqCanvas, BorderLayout.CENTER);
247
248     this.ap = alignPanel;
249
250     if (!viewport.isDataset())
251     {
252       addMouseMotionListener(this);
253       addMouseListener(this);
254       addMouseWheelListener(this);
255       ssm = viewport.getStructureSelectionManager();
256       ssm.addStructureViewerListener(this);
257       ssm.addSelectionListener(this);
258     }
259   }
260
261   int startWrapBlock = -1;
262
263   int wrappedBlock = -1;
264
265   /**
266    * Computes the column and sequence row (and possibly annotation row when in
267    * wrapped mode) for the given mouse position
268    * 
269    * @param evt
270    * @return
271    */
272   MousePos findMousePosition(MouseEvent evt)
273   {
274     int col = findColumn(evt);
275     int seqIndex = -1;
276     int annIndex = -1;
277     int y = evt.getY();
278
279     int charHeight = av.getCharHeight();
280     int alignmentHeight = av.getAlignment().getHeight();
281     if (av.getWrapAlignment())
282     {
283       seqCanvas.calculateWrappedGeometry(seqCanvas.getWidth(),
284               seqCanvas.getHeight());
285
286       /*
287        * yPos modulo height of repeating width
288        */
289       int yOffsetPx = y % seqCanvas.wrappedRepeatHeightPx;
290
291       /*
292        * height of sequences plus space / scale above,
293        * plus gap between sequences and annotations
294        */
295       int alignmentHeightPixels = seqCanvas.wrappedSpaceAboveAlignment
296               + alignmentHeight * charHeight
297               + SeqCanvas.SEQS_ANNOTATION_GAP;
298       if (yOffsetPx >= alignmentHeightPixels)
299       {
300         /*
301          * mouse is over annotations; find annotation index, also set
302          * last sequence above (for backwards compatible behaviour)
303          */
304         AlignmentAnnotation[] anns = av.getAlignment()
305                 .getAlignmentAnnotation();
306         int rowOffsetPx = yOffsetPx - alignmentHeightPixels;
307         annIndex = AnnotationPanel.getRowIndex(rowOffsetPx, anns);
308         seqIndex = alignmentHeight - 1;
309       }
310       else
311       {
312         /*
313          * mouse is over sequence (or the space above sequences)
314          */
315         yOffsetPx -= seqCanvas.wrappedSpaceAboveAlignment;
316         if (yOffsetPx >= 0)
317         {
318           seqIndex = Math.min(yOffsetPx / charHeight, alignmentHeight - 1);
319         }
320       }
321     }
322     else
323     {
324       ViewportRanges ranges = av.getRanges();
325       seqIndex = Math.min((y / charHeight) + ranges.getStartSeq(),
326               alignmentHeight - 1);
327       seqIndex = Math.min(seqIndex, ranges.getEndSeq());
328     }
329
330     return new MousePos(col, seqIndex, annIndex);
331   }
332   /**
333    * Returns the aligned sequence position (base 0) at the mouse position, or
334    * the closest visible one
335    * 
336    * @param evt
337    * @return
338    */
339   int findColumn(MouseEvent evt)
340   {
341     int res = 0;
342     int x = evt.getX();
343
344     final int startRes = av.getRanges().getStartRes();
345     final int charWidth = av.getCharWidth();
346
347     if (av.getWrapAlignment())
348     {
349       int hgap = av.getCharHeight();
350       if (av.getScaleAboveWrapped())
351       {
352         hgap += av.getCharHeight();
353       }
354
355       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
356               + hgap + seqCanvas.getAnnotationHeight();
357
358       int y = evt.getY();
359       y = Math.max(0, y - hgap);
360       x -= seqCanvas.getLabelWidthWest();
361       if (x < 0)
362       {
363         // mouse is over left scale
364         return -1;
365       }
366
367       int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
368       if (cwidth < 1)
369       {
370         return 0;
371       }
372       if (x >= cwidth * charWidth)
373       {
374         // mouse is over right scale
375         return -1;
376       }
377
378       wrappedBlock = y / cHeight;
379       wrappedBlock += startRes / cwidth;
380       // allow for wrapped view scrolled right (possible from Overview)
381       int startOffset = startRes % cwidth;
382       res = wrappedBlock * cwidth + startOffset
383               + Math.min(cwidth - 1, x / charWidth);
384     }
385     else
386     {
387       /*
388        * make sure we calculate relative to visible alignment, 
389        * rather than right-hand gutter
390        */
391       x = Math.min(x, seqCanvas.getX() + seqCanvas.getWidth());
392       res = (x / charWidth) + startRes;
393       res = Math.min(res, av.getRanges().getEndRes());
394     }
395
396     if (av.hasHiddenColumns())
397     {
398       res = av.getAlignment().getHiddenColumns()
399               .visibleToAbsoluteColumn(res);
400     }
401
402     return res;
403   }
404
405   /**
406    * When all of a sequence of edits are complete, put the resulting edit list
407    * on the history stack (undo list), and reset flags for editing in progress.
408    */
409   void endEditing()
410   {
411     try
412     {
413       if (editCommand != null && editCommand.getSize() > 0)
414       {
415         ap.alignFrame.addHistoryItem(editCommand);
416         av.firePropertyChange("alignment", null,
417                 av.getAlignment().getSequences());
418       }
419     } finally
420     {
421       /*
422        * Tidy up come what may...
423        */
424       editStartSeq = -1;
425       editLastRes = -1;
426       editingSeqs = false;
427       groupEditing = false;
428       keyboardNo1 = null;
429       keyboardNo2 = null;
430       editCommand = null;
431     }
432   }
433
434   void setCursorRow()
435   {
436     seqCanvas.cursorY = getKeyboardNo1() - 1;
437     scrollToVisible(true);
438   }
439
440   void setCursorColumn()
441   {
442     seqCanvas.cursorX = getKeyboardNo1() - 1;
443     scrollToVisible(true);
444   }
445
446   void setCursorRowAndColumn()
447   {
448     if (keyboardNo2 == null)
449     {
450       keyboardNo2 = new StringBuffer();
451     }
452     else
453     {
454       seqCanvas.cursorX = getKeyboardNo1() - 1;
455       seqCanvas.cursorY = getKeyboardNo2() - 1;
456       scrollToVisible(true);
457     }
458   }
459
460   void setCursorPosition()
461   {
462     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
463
464     seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
465     scrollToVisible(true);
466   }
467
468   void moveCursor(int dx, int dy)
469   {
470     seqCanvas.cursorX += dx;
471     seqCanvas.cursorY += dy;
472
473     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
474
475     if (av.hasHiddenColumns() && !hidden.isVisible(seqCanvas.cursorX))
476     {
477       int original = seqCanvas.cursorX - dx;
478       int maxWidth = av.getAlignment().getWidth();
479
480       if (!hidden.isVisible(seqCanvas.cursorX))
481       {
482         int visx = hidden.absoluteToVisibleColumn(seqCanvas.cursorX - dx);
483         int[] region = hidden.getRegionWithEdgeAtRes(visx);
484
485         if (region != null) // just in case
486         {
487           if (dx == 1)
488           {
489             // moving right
490             seqCanvas.cursorX = region[1] + 1;
491           }
492           else if (dx == -1)
493           {
494             // moving left
495             seqCanvas.cursorX = region[0] - 1;
496           }
497         }
498         seqCanvas.cursorX = (seqCanvas.cursorX < 0) ? 0 : seqCanvas.cursorX;
499       }
500
501       if (seqCanvas.cursorX >= maxWidth
502               || !hidden.isVisible(seqCanvas.cursorX))
503       {
504         seqCanvas.cursorX = original;
505       }
506     }
507
508     scrollToVisible(false);
509   }
510
511   /**
512    * Scroll to make the cursor visible in the viewport.
513    * 
514    * @param jump
515    *          just jump to the location rather than scrolling
516    */
517   void scrollToVisible(boolean jump)
518   {
519     if (seqCanvas.cursorX < 0)
520     {
521       seqCanvas.cursorX = 0;
522     }
523     else if (seqCanvas.cursorX > av.getAlignment().getWidth() - 1)
524     {
525       seqCanvas.cursorX = av.getAlignment().getWidth() - 1;
526     }
527
528     if (seqCanvas.cursorY < 0)
529     {
530       seqCanvas.cursorY = 0;
531     }
532     else if (seqCanvas.cursorY > av.getAlignment().getHeight() - 1)
533     {
534       seqCanvas.cursorY = av.getAlignment().getHeight() - 1;
535     }
536
537     endEditing();
538
539     boolean repaintNeeded = true;
540     if (jump)
541     {
542       // only need to repaint if the viewport did not move, as otherwise it will
543       // get a repaint
544       repaintNeeded = !av.getRanges().setViewportLocation(seqCanvas.cursorX,
545               seqCanvas.cursorY);
546     }
547     else
548     {
549       if (av.getWrapAlignment())
550       {
551         // scrollToWrappedVisible expects x-value to have hidden cols subtracted
552         int x = av.getAlignment().getHiddenColumns()
553                 .absoluteToVisibleColumn(seqCanvas.cursorX);
554         av.getRanges().scrollToWrappedVisible(x);
555       }
556       else
557       {
558         av.getRanges().scrollToVisible(seqCanvas.cursorX,
559                 seqCanvas.cursorY);
560       }
561     }
562
563     if (av.getAlignment().getHiddenColumns().isVisible(seqCanvas.cursorX))
564     {
565       setStatusMessage(av.getAlignment().getSequenceAt(seqCanvas.cursorY),
566             seqCanvas.cursorX, seqCanvas.cursorY);
567     }
568
569     if (repaintNeeded)
570     {
571       seqCanvas.repaint();
572     }
573   }
574
575
576   void setSelectionAreaAtCursor(boolean topLeft)
577   {
578     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
579
580     if (av.getSelectionGroup() != null)
581     {
582       SequenceGroup sg = av.getSelectionGroup();
583       // Find the top and bottom of this group
584       int min = av.getAlignment().getHeight(), max = 0;
585       for (int i = 0; i < sg.getSize(); i++)
586       {
587         int index = av.getAlignment().findIndex(sg.getSequenceAt(i));
588         if (index > max)
589         {
590           max = index;
591         }
592         if (index < min)
593         {
594           min = index;
595         }
596       }
597
598       max++;
599
600       if (topLeft)
601       {
602         sg.setStartRes(seqCanvas.cursorX);
603         if (sg.getEndRes() < seqCanvas.cursorX)
604         {
605           sg.setEndRes(seqCanvas.cursorX);
606         }
607
608         min = seqCanvas.cursorY;
609       }
610       else
611       {
612         sg.setEndRes(seqCanvas.cursorX);
613         if (sg.getStartRes() > seqCanvas.cursorX)
614         {
615           sg.setStartRes(seqCanvas.cursorX);
616         }
617
618         max = seqCanvas.cursorY + 1;
619       }
620
621       if (min > max)
622       {
623         // Only the user can do this
624         av.setSelectionGroup(null);
625       }
626       else
627       {
628         // Now add any sequences between min and max
629         sg.getSequences(null).clear();
630         for (int i = min; i < max; i++)
631         {
632           sg.addSequence(av.getAlignment().getSequenceAt(i), false);
633         }
634       }
635     }
636
637     if (av.getSelectionGroup() == null)
638     {
639       SequenceGroup sg = new SequenceGroup();
640       sg.setStartRes(seqCanvas.cursorX);
641       sg.setEndRes(seqCanvas.cursorX);
642       sg.addSequence(sequence, false);
643       av.setSelectionGroup(sg);
644     }
645
646     ap.paintAlignment(false, false);
647     av.sendSelection();
648   }
649
650   void insertGapAtCursor(boolean group)
651   {
652     groupEditing = group;
653     editStartSeq = seqCanvas.cursorY;
654     editLastRes = seqCanvas.cursorX;
655     editSequence(true, false, seqCanvas.cursorX + getKeyboardNo1());
656     endEditing();
657   }
658
659   void deleteGapAtCursor(boolean group)
660   {
661     groupEditing = group;
662     editStartSeq = seqCanvas.cursorY;
663     editLastRes = seqCanvas.cursorX + getKeyboardNo1();
664     editSequence(false, false, seqCanvas.cursorX);
665     endEditing();
666   }
667
668   void insertNucAtCursor(boolean group, String nuc)
669   {
670     // TODO not called - delete?
671     groupEditing = group;
672     editStartSeq = seqCanvas.cursorY;
673     editLastRes = seqCanvas.cursorX;
674     editSequence(false, true, seqCanvas.cursorX + getKeyboardNo1());
675     endEditing();
676   }
677
678   void numberPressed(char value)
679   {
680     if (keyboardNo1 == null)
681     {
682       keyboardNo1 = new StringBuffer();
683     }
684
685     if (keyboardNo2 != null)
686     {
687       keyboardNo2.append(value);
688     }
689     else
690     {
691       keyboardNo1.append(value);
692     }
693   }
694
695   int getKeyboardNo1()
696   {
697     try
698     {
699       if (keyboardNo1 != null)
700       {
701         int value = Integer.parseInt(keyboardNo1.toString());
702         keyboardNo1 = null;
703         return value;
704       }
705     } catch (Exception x)
706     {
707     }
708     keyboardNo1 = null;
709     return 1;
710   }
711
712   int getKeyboardNo2()
713   {
714     try
715     {
716       if (keyboardNo2 != null)
717       {
718         int value = Integer.parseInt(keyboardNo2.toString());
719         keyboardNo2 = null;
720         return value;
721       }
722     } catch (Exception x)
723     {
724     }
725     keyboardNo2 = null;
726     return 1;
727   }
728
729   /**
730    * DOCUMENT ME!
731    * 
732    * @param evt
733    *          DOCUMENT ME!
734    */
735   @Override
736   public void mouseReleased(MouseEvent evt)
737   {
738     MousePos pos = findMousePosition(evt);
739     if (pos.isOverAnnotation() || pos.seqIndex == -1 || pos.column == -1)
740     {
741       return;
742     }
743
744     boolean didDrag = mouseDragging; // did we come here after a drag
745     mouseDragging = false;
746     mouseWheelPressed = false;
747
748     if (evt.isPopupTrigger()) // Windows: mouseReleased
749     {
750       showPopupMenu(evt, pos);
751       evt.consume();
752       return;
753     }
754
755     if (editingSeqs)
756     {
757       endEditing();
758     }
759     else
760     {
761       doMouseReleasedDefineMode(evt, didDrag);
762     }
763   }
764
765   /**
766    * DOCUMENT ME!
767    * 
768    * @param evt
769    *          DOCUMENT ME!
770    */
771   @Override
772   public void mousePressed(MouseEvent evt)
773   {
774     lastMousePress = evt.getPoint();
775     MousePos pos = findMousePosition(evt);
776     if (pos.isOverAnnotation() || pos.seqIndex == -1 || pos.column == -1)
777     {
778       return;
779     }
780
781     if (SwingUtilities.isMiddleMouseButton(evt))
782     {
783       mouseWheelPressed = true;
784       return;
785     }
786
787     boolean isControlDown = Platform.isControlDown(evt);
788     if (evt.isShiftDown() || isControlDown)
789     {
790       editingSeqs = true;
791       if (isControlDown)
792       {
793         groupEditing = true;
794       }
795     }
796     else
797     {
798       doMousePressedDefineMode(evt, pos);
799       return;
800     }
801
802     int seq = pos.seqIndex;
803     int res = pos.column;
804
805     if ((seq < av.getAlignment().getHeight())
806             && (res < av.getAlignment().getSequenceAt(seq).getLength()))
807     {
808       editStartSeq = seq;
809       editLastRes = res;
810     }
811     else
812     {
813       editStartSeq = -1;
814       editLastRes = -1;
815     }
816
817     return;
818   }
819
820   String lastMessage;
821
822   private String formattedTooltipText;
823
824   @Override
825   public void mouseOverSequence(SequenceI sequence, int index, int pos)
826   {
827     String tmp = sequence.hashCode() + " " + index + " " + pos;
828
829     if (lastMessage == null || !lastMessage.equals(tmp))
830     {
831       // System.err.println("mouseOver Sequence: "+tmp);
832       ssm.mouseOverSequence(sequence, index, pos, av);
833     }
834     lastMessage = tmp;
835   }
836
837   /**
838    * Highlight the mapped region described by the search results object (unless
839    * unchanged). This supports highlight of protein while mousing over linked
840    * cDNA and vice versa. The status bar is also updated to show the location of
841    * the start of the highlighted region.
842    */
843   @Override
844   public void highlightSequence(SearchResultsI results)
845   {
846     if (results == null || results.equals(lastSearchResults))
847     {
848       return;
849     }
850     lastSearchResults = results;
851
852     boolean wasScrolled = false;
853
854     if (av.isFollowHighlight())
855     {
856       // don't allow highlight of protein/cDNA to also scroll a complementary
857       // panel,as this sets up a feedback loop (scrolling panel 1 causes moused
858       // over residue to change abruptly, causing highlighted residue in panel 2
859       // to change, causing a scroll in panel 1 etc)
860       ap.setToScrollComplementPanel(false);
861       wasScrolled = ap.scrollToPosition(results);
862       if (wasScrolled)
863       {
864         seqCanvas.revalidate();
865       }
866       ap.setToScrollComplementPanel(true);
867     }
868
869     boolean fastPaint = !(wasScrolled && av.getWrapAlignment());
870     if (seqCanvas.highlightSearchResults(results, fastPaint))
871     {
872       setStatusMessage(results);
873     }
874   }
875
876   @Override
877   public VamsasSource getVamsasSource()
878   {
879     return this.ap == null ? null : this.ap.av;
880   }
881
882   @Override
883   public void updateColours(SequenceI seq, int index)
884   {
885     System.out.println("update the seqPanel colours");
886     // repaint();
887   }
888
889   /**
890    * Action on mouse movement is to update the status bar to show the current
891    * sequence position, and (if features are shown) to show any features at the
892    * position in a tooltip. Does nothing if the mouse move does not change
893    * residue position.
894    * 
895    * @param evt
896    */
897   @Override
898   public void mouseMoved(MouseEvent evt)
899   {
900     if (editingSeqs)
901     {
902       // This is because MacOSX creates a mouseMoved
903       // If control is down, other platforms will not.
904       mouseDragged(evt);
905     }
906
907     final MousePos mousePos = findMousePosition(evt);
908     if (mousePos.equals(lastMousePosition))
909     {
910       /*
911        * just a pixel move without change of 'cell'
912        */
913       return;
914     }
915     lastMousePosition = mousePos;
916
917     if (mousePos.isOverAnnotation())
918     {
919       mouseMovedOverAnnotation(mousePos);
920       return;
921     }
922     final int seq = mousePos.seqIndex;
923
924     final int column = mousePos.column;
925     if (column < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
926     {
927       lastMousePosition = null;
928       setToolTipText(null);
929       lastTooltip = null;
930       ap.alignFrame.setStatus("");
931       return;
932     }
933
934     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
935
936     if (column >= sequence.getLength())
937     {
938       return;
939     }
940
941     /*
942      * set status bar message, returning residue position in sequence
943      */
944     boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
945     final int pos = setStatusMessage(sequence, column, seq);
946     if (ssm != null && !isGapped)
947     {
948       mouseOverSequence(sequence, column, pos);
949     }
950
951     tooltipText.setLength(6); // "<html>"
952
953     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
954     if (groups != null)
955     {
956       for (int g = 0; g < groups.length; g++)
957       {
958         if (groups[g].getStartRes() <= column
959                 && groups[g].getEndRes() >= column)
960         {
961           if (!groups[g].getName().startsWith("JTreeGroup")
962                   && !groups[g].getName().startsWith("JGroup"))
963           {
964             tooltipText.append(groups[g].getName());
965           }
966
967           if (groups[g].getDescription() != null)
968           {
969             tooltipText.append(": " + groups[g].getDescription());
970           }
971         }
972       }
973     }
974
975     /*
976      * add any features at the position to the tooltip; if over a gap, only
977      * add features that straddle the gap (pos may be the residue before or
978      * after the gap)
979      */
980     if (av.isShowSequenceFeatures())
981     {
982       List<SequenceFeature> features = ap.getFeatureRenderer()
983               .findFeaturesAtColumn(sequence, column + 1);
984       seqARep.appendFeatures(tooltipText, pos, features,
985               this.ap.getSeqPanel().seqCanvas.fr);
986     }
987     if (tooltipText.length() == 6) // <html>
988     {
989       setToolTipText(null);
990       lastTooltip = null;
991     }
992     else
993     {
994       if (tooltipText.length() > MAX_TOOLTIP_LENGTH) // constant
995       {
996         tooltipText.setLength(MAX_TOOLTIP_LENGTH);
997         tooltipText.append("...");
998       }
999       String textString = tooltipText.toString();
1000       if (lastTooltip == null || !lastTooltip.equals(textString))
1001       {
1002         formattedTooltipText = JvSwingUtils.wrapTooltip(true,
1003                 textString);
1004         setToolTipText(formattedTooltipText);        
1005         lastTooltip = textString;
1006       }
1007     }
1008   }
1009
1010   /**
1011    * When the view is in wrapped mode, and the mouse is over an annotation row,
1012    * shows the corresponding tooltip and status message (if any)
1013    * 
1014    * @param pos
1015    * @param column
1016    */
1017   protected void mouseMovedOverAnnotation(MousePos pos)
1018   {
1019     final int column = pos.column;
1020     final int rowIndex = pos.annotationIndex;
1021
1022     if (column < 0 || !av.getWrapAlignment() || !av.isShowAnnotation()
1023             || rowIndex < 0)
1024     {
1025       return;
1026     }
1027     AlignmentAnnotation[] anns = av.getAlignment().getAlignmentAnnotation();
1028
1029     String tooltip = AnnotationPanel.buildToolTip(anns[rowIndex], column,
1030             anns);
1031     setToolTipText(tooltip);
1032     lastTooltip = tooltip;
1033
1034     String msg = AnnotationPanel.getStatusMessage(av.getAlignment(), column,
1035             anns[rowIndex]);
1036     ap.alignFrame.setStatus(msg);
1037   }
1038
1039   private Point lastp = null;
1040
1041   private JToolTip tempTip = new JLabel().createToolTip();
1042
1043   /*
1044    * (non-Javadoc)
1045    * 
1046    * @see javax.swing.JComponent#getToolTipLocation(java.awt.event.MouseEvent)
1047    */
1048   @Override
1049   public Point getToolTipLocation(MouseEvent event)
1050   {
1051     // BH 2018
1052
1053     if (tooltipText == null || tooltipText.length() <= 6)
1054     {
1055       return null;
1056     }
1057
1058     if (lastp != null && event.isShiftDown())
1059     {
1060       return lastp;
1061     }
1062
1063     Point p = lastp;
1064     int x = event.getX();
1065     int y = event.getY();
1066     int w = getWidth();
1067
1068     tempTip.setTipText(formattedTooltipText);
1069     int tipWidth = (int) tempTip.getPreferredSize().getWidth();
1070     
1071     // was      x += (w - x < 200) ? -(w / 2) : 5;
1072     x = (x + tipWidth < w ? x + 10 : w - tipWidth);
1073     p = new Point(x, y + 20); // BH 2018 was - 20?
1074
1075     return lastp = p;
1076   }
1077
1078   String lastTooltip;
1079
1080   /**
1081    * set when the current UI interaction has resulted in a change that requires
1082    * shading in overviews and structures to be recalculated. this could be
1083    * changed to a something more expressive that indicates what actually has
1084    * changed, so selective redraws can be applied (ie. only structures, only
1085    * overview, etc)
1086    */
1087   private boolean updateOverviewAndStructs = false; // TODO: refactor to avcontroller
1088
1089   /**
1090    * set if av.getSelectionGroup() refers to a group that is defined on the
1091    * alignment view, rather than a transient selection
1092    */
1093   // private boolean editingDefinedGroup = false; // TODO: refactor to
1094   // avcontroller or viewModel
1095
1096   /**
1097    * Sets the status message in alignment panel, showing the sequence number
1098    * (index) and id, and residue and residue position if not at a gap, for the
1099    * given sequence and column position. Returns the residue position returned
1100    * by Sequence.findPosition. Note this may be for the nearest adjacent residue
1101    * if at a gapped position.
1102    * 
1103    * @param sequence
1104    *          aligned sequence object
1105    * @param column
1106    *          alignment column
1107    * @param seqIndex
1108    *          index of sequence in alignment
1109    * @return sequence position of residue at column, or adjacent residue if at a
1110    *         gap
1111    */
1112   int setStatusMessage(SequenceI sequence, final int column, int seqIndex)
1113   {
1114     char sequenceChar = sequence.getCharAt(column);
1115     int pos = sequence.findPosition(column);
1116     setStatusMessage(sequence, seqIndex, sequenceChar, pos);
1117
1118     return pos;
1119   }
1120
1121   /**
1122    * Builds the status message for the current cursor location and writes it to
1123    * the status bar, for example
1124    * 
1125    * <pre>
1126    * Sequence 3 ID: FER1_SOLLC
1127    * Sequence 5 ID: FER1_PEA Residue: THR (4)
1128    * Sequence 5 ID: FER1_PEA Residue: B (3)
1129    * Sequence 6 ID: O.niloticus.3 Nucleotide: Uracil (2)
1130    * </pre>
1131    * 
1132    * @param sequence
1133    * @param seqIndex
1134    *          sequence position in the alignment (1..)
1135    * @param sequenceChar
1136    *          the character under the cursor
1137    * @param residuePos
1138    *          the sequence residue position (if not over a gap)
1139    */
1140   protected void setStatusMessage(SequenceI sequence, int seqIndex,
1141           char sequenceChar, int residuePos)
1142   {
1143     StringBuilder text = new StringBuilder(32);
1144
1145     /*
1146      * Sequence number (if known), and sequence name.
1147      */
1148     String seqno = seqIndex == -1 ? "" : " " + (seqIndex + 1);
1149     text.append("Sequence").append(seqno).append(" ID: ")
1150             .append(sequence.getName());
1151
1152     String residue = null;
1153
1154     /*
1155      * Try to translate the display character to residue name (null for gap).
1156      */
1157     boolean isGapped = Comparison.isGap(sequenceChar);
1158
1159     if (!isGapped)
1160     {
1161       boolean nucleotide = av.getAlignment().isNucleotide();
1162       String displayChar = String.valueOf(sequenceChar);
1163       if (nucleotide)
1164       {
1165         residue = ResidueProperties.nucleotideName.get(displayChar);
1166       }
1167       else
1168       {
1169         residue = "X".equalsIgnoreCase(displayChar) ? "X"
1170                 : ("*".equals(displayChar) ? "STOP"
1171                         : ResidueProperties.aa2Triplet.get(displayChar));
1172       }
1173       text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
1174               .append(": ").append(residue == null ? displayChar : residue);
1175
1176       text.append(" (").append(Integer.toString(residuePos)).append(")");
1177     }
1178     ap.alignFrame.setStatus(text.toString());
1179   }
1180
1181   /**
1182    * Set the status bar message to highlight the first matched position in
1183    * search results.
1184    * 
1185    * @param results
1186    */
1187   private void setStatusMessage(SearchResultsI results)
1188   {
1189     AlignmentI al = this.av.getAlignment();
1190     int sequenceIndex = al.findIndex(results);
1191     if (sequenceIndex == -1)
1192     {
1193       return;
1194     }
1195     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
1196     for (SearchResultMatchI m : results.getResults())
1197     {
1198       SequenceI seq = m.getSequence();
1199       if (seq.getDatasetSequence() != null)
1200       {
1201         seq = seq.getDatasetSequence();
1202       }
1203
1204       if (seq == ds)
1205       {
1206         int start = m.getStart();
1207         setStatusMessage(seq, sequenceIndex, seq.getCharAt(start - 1),
1208                 start);
1209         return;
1210       }
1211     }
1212   }
1213
1214   /**
1215    * {@inheritDoc}
1216    */
1217   @Override
1218   public void mouseDragged(MouseEvent evt)
1219   {
1220     MousePos pos = findMousePosition(evt);
1221     if (pos.isOverAnnotation() || pos.column == -1)
1222     {
1223       return;
1224     }
1225
1226     if (mouseWheelPressed)
1227     {
1228       boolean inSplitFrame = ap.av.getCodingComplement() != null;
1229       boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
1230
1231       int oldWidth = av.getCharWidth();
1232
1233       // Which is bigger, left-right or up-down?
1234       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math
1235               .abs(evt.getX() - lastMousePress.getX()))
1236       {
1237         /*
1238          * on drag up or down, decrement or increment font size
1239          */
1240         int fontSize = av.font.getSize();
1241         boolean fontChanged = false;
1242
1243         if (evt.getY() < lastMousePress.getY())
1244         {
1245           fontChanged = true;
1246           fontSize--;
1247         }
1248         else if (evt.getY() > lastMousePress.getY())
1249         {
1250           fontChanged = true;
1251           fontSize++;
1252         }
1253
1254         if (fontSize < 1)
1255         {
1256           fontSize = 1;
1257         }
1258
1259         if (fontChanged)
1260         {
1261           Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1262                   fontSize);
1263           av.setFont(newFont, true);
1264           av.setCharWidth(oldWidth);
1265           ap.fontChanged();
1266           if (copyChanges)
1267           {
1268             ap.av.getCodingComplement().setFont(newFont, true);
1269             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1270                     .getSplitViewContainer();
1271             splitFrame.adjustLayout();
1272             splitFrame.repaint();
1273           }
1274         }
1275       }
1276       else
1277       {
1278         /*
1279          * on drag left or right, decrement or increment character width
1280          */
1281         int newWidth = 0;
1282         if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1283         {
1284           newWidth = av.getCharWidth() - 1;
1285           av.setCharWidth(newWidth);
1286         }
1287         else if (evt.getX() > lastMousePress.getX())
1288         {
1289           newWidth = av.getCharWidth() + 1;
1290           av.setCharWidth(newWidth);
1291         }
1292         if (newWidth > 0)
1293         {
1294           ap.paintAlignment(false, false);
1295           if (copyChanges)
1296           {
1297             /*
1298              * need to ensure newWidth is set on cdna, regardless of which
1299              * panel the mouse drag happened in; protein will compute its 
1300              * character width as 1:1 or 3:1
1301              */
1302             av.getCodingComplement().setCharWidth(newWidth);
1303             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1304                     .getSplitViewContainer();
1305             splitFrame.adjustLayout();
1306             splitFrame.repaint();
1307           }
1308         }
1309       }
1310
1311       FontMetrics fm = getFontMetrics(av.getFont());
1312       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1313
1314       lastMousePress = evt.getPoint();
1315
1316       return;
1317     }
1318
1319     if (!editingSeqs)
1320     {
1321       dragStretchGroup(evt);
1322       return;
1323     }
1324
1325     int res = pos.column;
1326
1327     if (res < 0)
1328     {
1329       res = 0;
1330     }
1331
1332     if ((editLastRes == -1) || (editLastRes == res))
1333     {
1334       return;
1335     }
1336
1337     if ((res < av.getAlignment().getWidth()) && (res < editLastRes))
1338     {
1339       // dragLeft, delete gap
1340       editSequence(false, false, res);
1341     }
1342     else
1343     {
1344       editSequence(true, false, res);
1345     }
1346
1347     mouseDragging = true;
1348     if (scrollThread != null)
1349     {
1350       scrollThread.setMousePosition(evt.getPoint());
1351     }
1352   }
1353
1354   /**
1355    * Edits the sequence to insert or delete one or more gaps, in response to a
1356    * mouse drag or cursor mode command. The number of inserts/deletes may be
1357    * specified with the cursor command, or else depends on the mouse event
1358    * (normally one column, but potentially more for a fast mouse drag).
1359    * <p>
1360    * Delete gaps is limited to the number of gaps left of the cursor position
1361    * (mouse drag), or at or right of the cursor position (cursor mode).
1362    * <p>
1363    * In group editing mode (Ctrl or Cmd down), the edit acts on all sequences in
1364    * the current selection group.
1365    * <p>
1366    * In locked editing mode (with a selection group present), inserts/deletions
1367    * within the selection group are limited to its boundaries (and edits outside
1368    * the group stop at its border).
1369    * 
1370    * @param insertGap
1371    *          true to insert gaps, false to delete gaps
1372    * @param editSeq
1373    *          (unused parameter)
1374    * @param startres
1375    *          the column at which to perform the action; the number of columns
1376    *          affected depends on <code>this.editLastRes</code> (cursor column
1377    *          position)
1378    */
1379   synchronized void editSequence(boolean insertGap, boolean editSeq,
1380           final int startres)
1381   {
1382     int fixedLeft = -1;
1383     int fixedRight = -1;
1384     boolean fixedColumns = false;
1385     SequenceGroup sg = av.getSelectionGroup();
1386
1387     final SequenceI seq = av.getAlignment().getSequenceAt(editStartSeq);
1388
1389     // No group, but the sequence may represent a group
1390     if (!groupEditing && av.hasHiddenRows())
1391     {
1392       if (av.isHiddenRepSequence(seq))
1393       {
1394         sg = av.getRepresentedSequences(seq);
1395         groupEditing = true;
1396       }
1397     }
1398
1399     StringBuilder message = new StringBuilder(64); // for status bar
1400
1401     /*
1402      * make a name for the edit action, for
1403      * status bar message and Undo/Redo menu
1404      */
1405     String label = null;
1406     if (groupEditing)
1407     {
1408         message.append("Edit group:");
1409       label = MessageManager.getString("action.edit_group");
1410     }
1411     else
1412     {
1413         message.append("Edit sequence: " + seq.getName());
1414       label = seq.getName();
1415       if (label.length() > 10)
1416       {
1417         label = label.substring(0, 10);
1418       }
1419       label = MessageManager.formatMessage("label.edit_params",
1420               new String[]
1421               { label });
1422     }
1423
1424     /*
1425      * initialise the edit command if there is not
1426      * already one being extended
1427      */
1428     if (editCommand == null)
1429     {
1430       editCommand = new EditCommand(label);
1431     }
1432
1433     if (insertGap)
1434     {
1435       message.append(" insert ");
1436     }
1437     else
1438     {
1439       message.append(" delete ");
1440     }
1441
1442     message.append(Math.abs(startres - editLastRes) + " gaps.");
1443     ap.alignFrame.setStatus(message.toString());
1444
1445     /*
1446      * is there a selection group containing the sequence being edited?
1447      * if so the boundary of the group is the limit of the edit
1448      * (but the edit may be inside or outside the selection group)
1449      */
1450     boolean inSelectionGroup = sg != null
1451             && sg.getSequences(av.getHiddenRepSequences()).contains(seq);
1452     if (groupEditing || inSelectionGroup)
1453     {
1454       fixedColumns = true;
1455
1456       // sg might be null as the user may only see 1 sequence,
1457       // but the sequence represents a group
1458       if (sg == null)
1459       {
1460         if (!av.isHiddenRepSequence(seq))
1461         {
1462           endEditing();
1463           return;
1464         }
1465         sg = av.getRepresentedSequences(seq);
1466       }
1467
1468       fixedLeft = sg.getStartRes();
1469       fixedRight = sg.getEndRes();
1470
1471       if ((startres < fixedLeft && editLastRes >= fixedLeft)
1472               || (startres >= fixedLeft && editLastRes < fixedLeft)
1473               || (startres > fixedRight && editLastRes <= fixedRight)
1474               || (startres <= fixedRight && editLastRes > fixedRight))
1475       {
1476         endEditing();
1477         return;
1478       }
1479
1480       if (fixedLeft > startres)
1481       {
1482         fixedRight = fixedLeft - 1;
1483         fixedLeft = 0;
1484       }
1485       else if (fixedRight < startres)
1486       {
1487         fixedLeft = fixedRight;
1488         fixedRight = -1;
1489       }
1490     }
1491
1492     if (av.hasHiddenColumns())
1493     {
1494       fixedColumns = true;
1495       int y1 = av.getAlignment().getHiddenColumns()
1496               .getNextHiddenBoundary(true, startres);
1497       int y2 = av.getAlignment().getHiddenColumns()
1498               .getNextHiddenBoundary(false, startres);
1499
1500       if ((insertGap && startres > y1 && editLastRes < y1)
1501               || (!insertGap && startres < y2 && editLastRes > y2))
1502       {
1503         endEditing();
1504         return;
1505       }
1506
1507       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1508       // Selection spans a hidden region
1509       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1510       {
1511         if (startres >= y2)
1512         {
1513           fixedLeft = y2;
1514         }
1515         else
1516         {
1517           fixedRight = y2 - 1;
1518         }
1519       }
1520     }
1521
1522     boolean success = doEditSequence(insertGap, editSeq, startres,
1523             fixedRight, fixedColumns, sg);
1524
1525     /*
1526      * report what actually happened (might be less than
1527      * what was requested), by inspecting the edit commands added
1528      */
1529     String msg = getEditStatusMessage(editCommand);
1530     ap.alignFrame.setStatus(msg == null ? " " : msg);
1531     if (!success)
1532     {
1533       endEditing();
1534     }
1535
1536     editLastRes = startres;
1537     seqCanvas.repaint();
1538   }
1539
1540   /**
1541    * A helper method that performs the requested editing to insert or delete
1542    * gaps (if possible). Answers true if the edit was successful, false if could
1543    * only be performed in part or not at all. Failure may occur in 'locked edit'
1544    * mode, when an insertion requires a matching gapped position (or column) to
1545    * delete, and deletion requires an adjacent gapped position (or column) to
1546    * remove.
1547    * 
1548    * @param insertGap
1549    *          true if inserting gap(s), false if deleting
1550    * @param editSeq
1551    *          (unused parameter, currently always false)
1552    * @param startres
1553    *          the column at which to perform the edit
1554    * @param fixedRight
1555    *          fixed right boundary column of a locked edit (within or to the
1556    *          left of a selection group)
1557    * @param fixedColumns
1558    *          true if this is a locked edit
1559    * @param sg
1560    *          the sequence group (if group edit is being performed)
1561    * @return
1562    */
1563   protected boolean doEditSequence(final boolean insertGap,
1564           final boolean editSeq, final int startres, int fixedRight,
1565           final boolean fixedColumns, final SequenceGroup sg)
1566   {
1567     final SequenceI seq = av.getAlignment().getSequenceAt(editStartSeq);
1568     SequenceI[] seqs = new SequenceI[] { seq };
1569
1570     if (groupEditing)
1571     {
1572       List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1573       int g, groupSize = vseqs.size();
1574       SequenceI[] groupSeqs = new SequenceI[groupSize];
1575       for (g = 0; g < groupSeqs.length; g++)
1576       {
1577         groupSeqs[g] = vseqs.get(g);
1578       }
1579
1580       // drag to right
1581       if (insertGap)
1582       {
1583         // If the user has selected the whole sequence, and is dragging to
1584         // the right, we can still extend the alignment and selectionGroup
1585         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1586                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1587         {
1588           sg.setEndRes(
1589                   av.getAlignment().getWidth() + startres - editLastRes);
1590           fixedRight = sg.getEndRes();
1591         }
1592
1593         // Is it valid with fixed columns??
1594         // Find the next gap before the end
1595         // of the visible region boundary
1596         boolean blank = false;
1597         for (; fixedRight > editLastRes; fixedRight--)
1598         {
1599           blank = true;
1600
1601           for (g = 0; g < groupSize; g++)
1602           {
1603             for (int j = 0; j < startres - editLastRes; j++)
1604             {
1605               if (!Comparison
1606                       .isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1607               {
1608                 blank = false;
1609                 break;
1610               }
1611             }
1612           }
1613           if (blank)
1614           {
1615             break;
1616           }
1617         }
1618
1619         if (!blank)
1620         {
1621           if (sg.getSize() == av.getAlignment().getHeight())
1622           {
1623             if ((av.hasHiddenColumns()
1624                     && startres < av.getAlignment().getHiddenColumns()
1625                             .getNextHiddenBoundary(false, startres)))
1626             {
1627               return false;
1628             }
1629
1630             int alWidth = av.getAlignment().getWidth();
1631             if (av.hasHiddenRows())
1632             {
1633               int hwidth = av.getAlignment().getHiddenSequences()
1634                       .getWidth();
1635               if (hwidth > alWidth)
1636               {
1637                 alWidth = hwidth;
1638               }
1639             }
1640             // We can still insert gaps if the selectionGroup
1641             // contains all the sequences
1642             sg.setEndRes(sg.getEndRes() + startres - editLastRes);
1643             fixedRight = alWidth + startres - editLastRes;
1644           }
1645           else
1646           {
1647             return false;
1648           }
1649         }
1650       }
1651
1652       // drag to left
1653       else if (!insertGap)
1654       {
1655         // / Are we able to delete?
1656         // ie are all columns blank?
1657
1658         for (g = 0; g < groupSize; g++)
1659         {
1660           for (int j = startres; j < editLastRes; j++)
1661           {
1662             if (groupSeqs[g].getLength() <= j)
1663             {
1664               continue;
1665             }
1666
1667             if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1668             {
1669               // Not a gap, block edit not valid
1670               return false;
1671             }
1672           }
1673         }
1674       }
1675
1676       if (insertGap)
1677       {
1678         // dragging to the right
1679         if (fixedColumns && fixedRight != -1)
1680         {
1681           for (int j = editLastRes; j < startres; j++)
1682           {
1683             insertGap(j, groupSeqs, fixedRight);
1684           }
1685         }
1686         else
1687         {
1688           appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1689                   startres - editLastRes, false);
1690         }
1691       }
1692       else
1693       {
1694         // dragging to the left
1695         if (fixedColumns && fixedRight != -1)
1696         {
1697           for (int j = editLastRes; j > startres; j--)
1698           {
1699             deleteChar(startres, groupSeqs, fixedRight);
1700           }
1701         }
1702         else
1703         {
1704           appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1705                   editLastRes - startres, false);
1706         }
1707       }
1708     }
1709     else
1710     {
1711       /*
1712        * editing a single sequence
1713        */
1714       if (insertGap)
1715       {
1716         // dragging to the right
1717         if (fixedColumns && fixedRight != -1)
1718         {
1719           for (int j = editLastRes; j < startres; j++)
1720           {
1721             if (!insertGap(j, seqs, fixedRight))
1722             {
1723               /*
1724                * e.g. cursor mode command specified 
1725                * more inserts than are possible
1726                */
1727               return false;
1728             }
1729           }
1730         }
1731         else
1732         {
1733           appendEdit(Action.INSERT_GAP, seqs, editLastRes,
1734                   startres - editLastRes, false);
1735         }
1736       }
1737       else
1738       {
1739         if (!editSeq)
1740         {
1741           // dragging to the left
1742           if (fixedColumns && fixedRight != -1)
1743           {
1744             for (int j = editLastRes; j > startres; j--)
1745             {
1746               if (!Comparison.isGap(seq.getCharAt(startres)))
1747               {
1748                 return false;
1749               }
1750               deleteChar(startres, seqs, fixedRight);
1751             }
1752           }
1753           else
1754           {
1755             // could be a keyboard edit trying to delete none gaps
1756             int max = 0;
1757             for (int m = startres; m < editLastRes; m++)
1758             {
1759               if (!Comparison.isGap(seq.getCharAt(m)))
1760               {
1761                 break;
1762               }
1763               max++;
1764             }
1765             if (max > 0)
1766             {
1767               appendEdit(Action.DELETE_GAP, seqs, startres, max, false);
1768             }
1769           }
1770         }
1771         else
1772         {// insertGap==false AND editSeq==TRUE;
1773           if (fixedColumns && fixedRight != -1)
1774           {
1775             for (int j = editLastRes; j < startres; j++)
1776             {
1777               insertGap(j, seqs, fixedRight);
1778             }
1779           }
1780           else
1781           {
1782             appendEdit(Action.INSERT_NUC, seqs, editLastRes,
1783                     startres - editLastRes, false);
1784           }
1785         }
1786       }
1787     }
1788
1789     return true;
1790   }
1791
1792   /**
1793    * Constructs an informative status bar message while dragging to insert or
1794    * delete gaps. Answers null if inserts and deletes cancel out.
1795    * 
1796    * @param editCommand
1797    *          a command containing the list of individual edits
1798    * @return
1799    */
1800   protected static String getEditStatusMessage(EditCommand editCommand)
1801   {
1802     if (editCommand == null)
1803     {
1804       return null;
1805     }
1806
1807     /*
1808      * add any inserts, and subtract any deletes,  
1809      * not counting those auto-inserted when doing a 'locked edit'
1810      * (so only counting edits 'under the cursor')
1811      */
1812     int count = 0;
1813     for (Edit cmd : editCommand.getEdits())
1814     {
1815       if (!cmd.isSystemGenerated())
1816       {
1817         count += cmd.getAction() == Action.INSERT_GAP ? cmd.getNumber()
1818                 : -cmd.getNumber();
1819       }
1820     }
1821
1822     if (count == 0)
1823     {
1824       /*
1825        * inserts and deletes cancel out
1826        */
1827       return null;
1828     }
1829
1830     String msgKey = count > 1 ? "label.insert_gaps"
1831             : (count == 1 ? "label.insert_gap"
1832                     : (count == -1 ? "label.delete_gap"
1833                             : "label.delete_gaps"));
1834     count = Math.abs(count);
1835
1836     return MessageManager.formatMessage(msgKey, String.valueOf(count));
1837   }
1838
1839   /**
1840    * Inserts one gap at column j, deleting the right-most gapped column up to
1841    * (and including) fixedColumn. Returns true if the edit is successful, false
1842    * if no blank column is available to allow the insertion to be balanced by a
1843    * deletion.
1844    * 
1845    * @param j
1846    * @param seq
1847    * @param fixedColumn
1848    * @return
1849    */
1850   boolean insertGap(int j, SequenceI[] seq, int fixedColumn)
1851   {
1852     int blankColumn = fixedColumn;
1853     for (int s = 0; s < seq.length; s++)
1854     {
1855       // Find the next gap before the end of the visible region boundary
1856       // If lastCol > j, theres a boundary after the gap insertion
1857
1858       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1859       {
1860         if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1861         {
1862           // Theres a space, so break and insert the gap
1863           break;
1864         }
1865       }
1866
1867       if (blankColumn <= j)
1868       {
1869         blankColumn = fixedColumn;
1870         endEditing();
1871         return false;
1872       }
1873     }
1874
1875     appendEdit(Action.DELETE_GAP, seq, blankColumn, 1, true);
1876
1877     appendEdit(Action.INSERT_GAP, seq, j, 1, false);
1878
1879     return true;
1880   }
1881
1882   /**
1883    * Helper method to add and perform one edit action
1884    * 
1885    * @param action
1886    * @param seq
1887    * @param pos
1888    * @param count
1889    * @param systemGenerated
1890    *          true if the edit is a 'balancing' delete (or insert) to match a
1891    *          user's insert (or delete) in a locked editing region
1892    */
1893   protected void appendEdit(Action action, SequenceI[] seq, int pos,
1894           int count, boolean systemGenerated)
1895   {
1896
1897     final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1898             av.getAlignment().getGapCharacter());
1899     edit.setSystemGenerated(systemGenerated);
1900
1901     editCommand.appendEdit(edit, av.getAlignment(), true, null);
1902   }
1903
1904   /**
1905    * Deletes the character at column j, and inserts a gap at fixedColumn, in
1906    * each of the given sequences. The caller should ensure that all sequences
1907    * are gapped in column j.
1908    * 
1909    * @param j
1910    * @param seqs
1911    * @param fixedColumn
1912    */
1913   void deleteChar(int j, SequenceI[] seqs, int fixedColumn)
1914   {
1915     appendEdit(Action.DELETE_GAP, seqs, j, 1, false);
1916
1917     appendEdit(Action.INSERT_GAP, seqs, fixedColumn, 1, true);
1918   }
1919
1920   /**
1921    * On reentering the panel, stops any scrolling that was started on dragging
1922    * out of the panel
1923    * 
1924    * @param e
1925    */
1926   @Override
1927   public void mouseEntered(MouseEvent e)
1928   {
1929     if (oldSeq < 0)
1930     {
1931       oldSeq = 0;
1932     }
1933     stopScrolling();
1934   }
1935
1936   /**
1937    * On leaving the panel, if the mouse is being dragged, starts a thread to
1938    * scroll it until the mouse is released (in unwrapped mode only)
1939    * 
1940    * @param e
1941    */
1942   @Override
1943   public void mouseExited(MouseEvent e)
1944   {
1945     lastMousePosition = null;
1946     ap.alignFrame.setStatus(" ");
1947     if (av.getWrapAlignment())
1948     {
1949       return;
1950     }
1951
1952     if (mouseDragging && scrollThread == null)
1953     {
1954       startScrolling(e.getPoint());
1955     }
1956   }
1957
1958   /**
1959    * Handler for double-click on a position with one or more sequence features.
1960    * Opens the Amend Features dialog to allow feature details to be amended, or
1961    * the feature deleted.
1962    */
1963   @Override
1964   public void mouseClicked(MouseEvent evt)
1965   {
1966     SequenceGroup sg = null;
1967     MousePos pos = findMousePosition(evt);
1968     if (pos.isOverAnnotation() || pos.seqIndex == -1 || pos.column == -1)
1969     {
1970       return;
1971     }
1972
1973     if (evt.getClickCount() > 1)
1974     {
1975       sg = av.getSelectionGroup();
1976       if (sg != null && sg.getSize() == 1
1977               && sg.getEndRes() - sg.getStartRes() < 2)
1978       {
1979         av.setSelectionGroup(null);
1980       }
1981
1982       int column = pos.column;
1983
1984       /*
1985        * find features at the position (if not gapped), or straddling
1986        * the position (if at a gap)
1987        */
1988       SequenceI sequence = av.getAlignment().getSequenceAt(pos.seqIndex);
1989       List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1990               .findFeaturesAtColumn(sequence, column + 1);
1991
1992       if (!features.isEmpty())
1993       {
1994         /*
1995          * highlight the first feature at the position on the alignment
1996          */
1997         SearchResultsI highlight = new SearchResults();
1998         highlight.addResult(sequence, features.get(0).getBegin(), features
1999                 .get(0).getEnd());
2000         seqCanvas.highlightSearchResults(highlight, true);
2001
2002         /*
2003          * open the Amend Features dialog
2004          */
2005         new FeatureEditor(ap, Collections.singletonList(sequence), features,
2006                 false).showDialog();
2007       }
2008     }
2009   }
2010
2011   @Override
2012   public void mouseWheelMoved(MouseWheelEvent e)
2013   {
2014     e.consume();
2015     double wheelRotation = e.getPreciseWheelRotation();
2016     if (wheelRotation > 0)
2017     {
2018       if (e.isShiftDown())
2019       {
2020         av.getRanges().scrollRight(true);
2021
2022       }
2023       else
2024       {
2025         av.getRanges().scrollUp(false);
2026       }
2027     }
2028     else if (wheelRotation < 0)
2029     {
2030       if (e.isShiftDown())
2031       {
2032         av.getRanges().scrollRight(false);
2033       }
2034       else
2035       {
2036         av.getRanges().scrollUp(true);
2037       }
2038     }
2039
2040     /*
2041      * update status bar and tooltip for new position
2042      * (need to synthesize a mouse movement to refresh tooltip)
2043      */
2044     mouseMoved(e);
2045     ToolTipManager.sharedInstance().mouseMoved(e);
2046   }
2047
2048   /**
2049    * DOCUMENT ME!
2050    * 
2051    * @param pos
2052    *          DOCUMENT ME!
2053    */
2054   protected void doMousePressedDefineMode(MouseEvent evt, MousePos pos)
2055   {
2056     if (pos.isOverAnnotation() || pos.seqIndex == -1 || pos.column == -1)
2057     {
2058       return;
2059     }
2060
2061     final int res = pos.column;
2062     final int seq = pos.seqIndex;
2063     oldSeq = seq;
2064     updateOverviewAndStructs = false;
2065
2066     startWrapBlock = wrappedBlock;
2067
2068     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
2069
2070     if ((sequence == null) || (res > sequence.getLength()))
2071     {
2072       return;
2073     }
2074
2075     stretchGroup = av.getSelectionGroup();
2076
2077     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
2078     {
2079       stretchGroup = av.getAlignment().findGroup(sequence, res);
2080       if (stretchGroup != null)
2081       {
2082         // only update the current selection if the popup menu has a group to
2083         // focus on
2084         av.setSelectionGroup(stretchGroup);
2085       }
2086     }
2087
2088     /*
2089      * defer right-mouse click handling to mouseReleased on Windows
2090      * (where isPopupTrigger() will answer true)
2091      * NB isRightMouseButton is also true for Cmd-click on Mac
2092      */
2093     if (Platform.isWinRightButton(evt))
2094     {
2095       return;
2096     }
2097
2098     if (evt.isPopupTrigger()) // Mac: mousePressed
2099     {
2100       showPopupMenu(evt, pos);
2101       return;
2102     }
2103
2104     if (av.cursorMode)
2105     {
2106       seqCanvas.cursorX = res;
2107       seqCanvas.cursorY = seq;
2108       seqCanvas.repaint();
2109       return;
2110     }
2111
2112     if (stretchGroup == null)
2113     {
2114       createStretchGroup(res, sequence);
2115     }
2116
2117     if (stretchGroup != null)
2118     {
2119       stretchGroup.addPropertyChangeListener(seqCanvas);
2120     }
2121
2122     seqCanvas.repaint();
2123   }
2124
2125   private void createStretchGroup(int res, SequenceI sequence)
2126   {
2127     // Only if left mouse button do we want to change group sizes
2128     // define a new group here
2129     SequenceGroup sg = new SequenceGroup();
2130     sg.setStartRes(res);
2131     sg.setEndRes(res);
2132     sg.addSequence(sequence, false);
2133     av.setSelectionGroup(sg);
2134     stretchGroup = sg;
2135
2136     if (av.getConservationSelected())
2137     {
2138       SliderPanel.setConservationSlider(ap, av.getResidueShading(),
2139               ap.getViewName());
2140     }
2141
2142     if (av.getAbovePIDThreshold())
2143     {
2144       SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
2145               ap.getViewName());
2146     }
2147     // TODO: stretchGroup will always be not null. Is this a merge error ?
2148     // or is there a threading issue here?
2149     if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
2150     {
2151       // Edit end res position of selected group
2152       changeEndRes = true;
2153     }
2154     else if ((stretchGroup != null) && (stretchGroup.getStartRes() == res))
2155     {
2156       // Edit end res position of selected group
2157       changeStartRes = true;
2158     }
2159     stretchGroup.getWidth();
2160
2161   }
2162
2163   /**
2164    * Build and show a pop-up menu at the right-click mouse position
2165    *
2166    * @param evt
2167    * @param pos
2168    */
2169   void showPopupMenu(MouseEvent evt, MousePos pos)
2170   {
2171     final int column = pos.column;
2172     final int seq = pos.seqIndex;
2173     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
2174     List<SequenceFeature> features = ap.getFeatureRenderer()
2175             .findFeaturesAtColumn(sequence, column + 1);
2176
2177     PopupMenu pop = new PopupMenu(ap, null, features);
2178     pop.show(this, evt.getX(), evt.getY());
2179   }
2180
2181   /**
2182    * Update the display after mouse up on a selection or group
2183    * 
2184    * @param evt
2185    *          mouse released event details
2186    * @param afterDrag
2187    *          true if this event is happening after a mouse drag (rather than a
2188    *          mouse down)
2189    */
2190   protected void doMouseReleasedDefineMode(MouseEvent evt,
2191           boolean afterDrag)
2192   {
2193     if (stretchGroup == null)
2194     {
2195       return;
2196     }
2197
2198     stretchGroup.removePropertyChangeListener(seqCanvas);
2199
2200     // always do this - annotation has own state
2201     // but defer colourscheme update until hidden sequences are passed in
2202     boolean vischange = stretchGroup.recalcConservation(true);
2203     updateOverviewAndStructs |= vischange && av.isSelectionDefinedGroup()
2204             && afterDrag;
2205     if (stretchGroup.cs != null)
2206     {
2207       if (afterDrag)
2208       {
2209         stretchGroup.cs.alignmentChanged(stretchGroup,
2210                 av.getHiddenRepSequences());
2211       }
2212
2213       ResidueShaderI groupColourScheme = stretchGroup
2214               .getGroupColourScheme();
2215       String name = stretchGroup.getName();
2216       if (stretchGroup.cs.conservationApplied())
2217       {
2218         SliderPanel.setConservationSlider(ap, groupColourScheme, name);
2219       }
2220       if (stretchGroup.cs.getThreshold() > 0)
2221       {
2222         SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
2223       }
2224     }
2225     PaintRefresher.Refresh(this, av.getSequenceSetId());
2226     // TODO: structure colours only need updating if stretchGroup used to or now
2227     // does contain sequences with structure views
2228     ap.paintAlignment(updateOverviewAndStructs, updateOverviewAndStructs);
2229     updateOverviewAndStructs = false;
2230     changeEndRes = false;
2231     changeStartRes = false;
2232     stretchGroup = null;
2233     av.sendSelection();
2234   }
2235
2236   /**
2237    * Resizes the borders of a selection group depending on the direction of
2238    * mouse drag
2239    * 
2240    * @param evt
2241    */
2242   protected void dragStretchGroup(MouseEvent evt)
2243   {
2244     if (stretchGroup == null)
2245     {
2246       return;
2247     }
2248
2249     MousePos pos = findMousePosition(evt);
2250     if (pos.isOverAnnotation() || pos.column == -1 || pos.seqIndex == -1)
2251     {
2252       return;
2253     }
2254
2255     int res = pos.column;
2256     int y = pos.seqIndex;
2257
2258     if (wrappedBlock != startWrapBlock)
2259     {
2260       return;
2261     }
2262
2263     res = Math.min(res, av.getAlignment().getWidth()-1);
2264
2265     if (stretchGroup.getEndRes() == res)
2266     {
2267       // Edit end res position of selected group
2268       changeEndRes = true;
2269     }
2270     else if (stretchGroup.getStartRes() == res)
2271     {
2272       // Edit start res position of selected group
2273       changeStartRes = true;
2274     }
2275
2276     if (res < av.getRanges().getStartRes())
2277     {
2278       res = av.getRanges().getStartRes();
2279     }
2280
2281     if (changeEndRes)
2282     {
2283       if (res > (stretchGroup.getStartRes() - 1))
2284       {
2285         stretchGroup.setEndRes(res);
2286         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2287       }
2288     }
2289     else if (changeStartRes)
2290     {
2291       if (res < (stretchGroup.getEndRes() + 1))
2292       {
2293         stretchGroup.setStartRes(res);
2294         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2295       }
2296     }
2297
2298     int dragDirection = 0;
2299
2300     if (y > oldSeq)
2301     {
2302       dragDirection = 1;
2303     }
2304     else if (y < oldSeq)
2305     {
2306       dragDirection = -1;
2307     }
2308
2309     while ((y != oldSeq) && (oldSeq > -1)
2310             && (y < av.getAlignment().getHeight()))
2311     {
2312       // This routine ensures we don't skip any sequences, as the
2313       // selection is quite slow.
2314       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
2315
2316       oldSeq += dragDirection;
2317
2318       if (oldSeq < 0)
2319       {
2320         break;
2321       }
2322
2323       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
2324
2325       if (stretchGroup.getSequences(null).contains(nextSeq))
2326       {
2327         stretchGroup.deleteSequence(seq, false);
2328         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2329       }
2330       else
2331       {
2332         if (seq != null)
2333         {
2334           stretchGroup.addSequence(seq, false);
2335         }
2336
2337         stretchGroup.addSequence(nextSeq, false);
2338         updateOverviewAndStructs |= av.isSelectionDefinedGroup();
2339       }
2340     }
2341
2342     if (oldSeq < 0)
2343     {
2344       oldSeq = -1;
2345     }
2346
2347     mouseDragging = true;
2348
2349     if (scrollThread != null)
2350     {
2351       scrollThread.setMousePosition(evt.getPoint());
2352     }
2353
2354     /*
2355      * construct a status message showing the range of the selection
2356      */
2357     StringBuilder status = new StringBuilder(64);
2358     List<SequenceI> seqs = stretchGroup.getSequences();
2359     String name = seqs.get(0).getName();
2360     if (name.length() > 20)
2361     {
2362       name = name.substring(0, 20);
2363     }
2364     status.append(name).append(" - ");
2365     name = seqs.get(seqs.size() - 1).getName();
2366     if (name.length() > 20)
2367     {
2368       name = name.substring(0, 20);
2369     }
2370     status.append(name).append(" ");
2371     int startRes = stretchGroup.getStartRes();
2372     status.append(" cols ").append(String.valueOf(startRes + 1))
2373             .append("-");
2374     int endRes = stretchGroup.getEndRes();
2375     status.append(String.valueOf(endRes + 1));
2376     status.append(" (").append(String.valueOf(seqs.size())).append(" x ")
2377             .append(String.valueOf(endRes - startRes + 1)).append(")");
2378     ap.alignFrame.setStatus(status.toString());
2379   }
2380
2381   /**
2382    * Stops the scroll thread if it is running
2383    */
2384   void stopScrolling()
2385   {
2386     if (scrollThread != null)
2387     {
2388       scrollThread.stopScrolling();
2389       scrollThread = null;
2390     }
2391     mouseDragging = false;
2392   }
2393
2394   /**
2395    * Starts a thread to scroll the alignment, towards a given mouse position
2396    * outside the panel bounds, unless the alignment is in wrapped mode
2397    * 
2398    * @param mousePos
2399    */
2400   void startScrolling(Point mousePos)
2401   {
2402     /*
2403      * set this.mouseDragging in case this was called from 
2404      * a drag in ScalePanel or AnnotationPanel
2405      */
2406     mouseDragging = true;
2407     if (!av.getWrapAlignment() && scrollThread == null)
2408     {
2409       scrollThread = new ScrollThread();
2410       scrollThread.setMousePosition(mousePos);
2411       if (!Platform.isJS())
2412       {
2413         /*
2414          * Java - run in a new thread
2415          */
2416         scrollThread.start();
2417       }
2418       else
2419       {
2420         /*
2421          * Javascript - run every 20ms until scrolling stopped
2422          * or reaches the limit of scrollable alignment
2423          */
2424         Timer t = new Timer(20, new ActionListener()
2425         {
2426           @Override
2427           public void actionPerformed(ActionEvent e)
2428           {
2429             if (scrollThread != null)
2430             {
2431               // if (!scrollOnce() {t.stop();}) gives compiler error :-(
2432               scrollThread.scrollOnce();
2433             }
2434           }
2435         });
2436         t.addActionListener(new ActionListener()
2437         {
2438           @Override
2439           public void actionPerformed(ActionEvent e)
2440           {
2441             if (scrollThread == null)
2442             {
2443               // SeqPanel.stopScrolling called
2444               t.stop();
2445             }
2446           }
2447         });
2448         t.start();
2449       }
2450     }
2451   }
2452
2453   /**
2454    * Performs scrolling of the visible alignment left, right, up or down, until
2455    * scrolling is stopped by calling stopScrolling, mouse drag is ended, or the
2456    * limit of the alignment is reached
2457    */
2458   class ScrollThread extends Thread
2459   {
2460     private Point mousePos;
2461
2462     private volatile boolean keepRunning = true;
2463
2464     /**
2465      * Constructor
2466      */
2467     public ScrollThread()
2468     {
2469       setName("SeqPanel$ScrollThread");
2470     }
2471
2472     /**
2473      * Sets the position of the mouse that determines the direction of the
2474      * scroll to perform. If this is called as the mouse moves, scrolling should
2475      * respond accordingly. For example, if the mouse is dragged right, scroll
2476      * right should start; if the drag continues down, scroll down should also
2477      * happen.
2478      * 
2479      * @param p
2480      */
2481     public void setMousePosition(Point p)
2482     {
2483       mousePos = p;
2484     }
2485
2486     /**
2487      * Sets a flag that will cause the thread to exit
2488      */
2489     public void stopScrolling()
2490     {
2491       keepRunning = false;
2492     }
2493
2494     /**
2495      * Scrolls the alignment left or right, and/or up or down, depending on the
2496      * last notified mouse position, until the limit of the alignment is
2497      * reached, or a flag is set to stop the scroll
2498      */
2499     @Override
2500     public void run()
2501     {
2502       while (keepRunning)
2503       {
2504         if (mousePos != null)
2505         {
2506           keepRunning = scrollOnce();
2507         }
2508         try
2509         {
2510           Thread.sleep(20);
2511         } catch (Exception ex)
2512         {
2513         }
2514       }
2515       SeqPanel.this.scrollThread = null;
2516     }
2517
2518     /**
2519      * Scrolls
2520      * <ul>
2521      * <li>one row up, if the mouse is above the panel</li>
2522      * <li>one row down, if the mouse is below the panel</li>
2523      * <li>one column left, if the mouse is left of the panel</li>
2524      * <li>one column right, if the mouse is right of the panel</li>
2525      * </ul>
2526      * Answers true if a scroll was performed, false if not - meaning either
2527      * that the mouse position is within the panel, or the edge of the alignment
2528      * has been reached.
2529      */
2530     boolean scrollOnce()
2531     {
2532       /*
2533        * quit after mouseUp ensures interrupt in JalviewJS
2534        */
2535       if (!mouseDragging)
2536       {
2537         return false;
2538       }
2539
2540       boolean scrolled = false;
2541       ViewportRanges ranges = SeqPanel.this.av.getRanges();
2542
2543       /*
2544        * scroll up or down
2545        */
2546       if (mousePos.y < 0)
2547       {
2548         // mouse is above this panel - try scroll up
2549         scrolled = ranges.scrollUp(true);
2550       }
2551       else if (mousePos.y >= getHeight())
2552       {
2553         // mouse is below this panel - try scroll down
2554         scrolled = ranges.scrollUp(false);
2555       }
2556
2557       /*
2558        * scroll left or right
2559        */
2560       if (mousePos.x < 0)
2561       {
2562         scrolled |= ranges.scrollRight(false);
2563       }
2564       else if (mousePos.x >= getWidth())
2565       {
2566         scrolled |= ranges.scrollRight(true);
2567       }
2568       return scrolled;
2569     }
2570   }
2571
2572   /**
2573    * modify current selection according to a received message.
2574    */
2575   @Override
2576   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2577           HiddenColumns hidden, SelectionSource source)
2578   {
2579     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2580     // handles selection messages...
2581     // TODO: extend config options to allow user to control if selections may be
2582     // shared between viewports.
2583     boolean iSentTheSelection = (av == source
2584             || (source instanceof AlignViewport
2585                     && ((AlignmentViewport) source).getSequenceSetId()
2586                             .equals(av.getSequenceSetId())));
2587
2588     if (iSentTheSelection)
2589     {
2590       // respond to our own event by updating dependent dialogs
2591       if (ap.getCalculationDialog() != null)
2592       {
2593         ap.getCalculationDialog().validateCalcTypes();
2594       }
2595
2596       return;
2597     }
2598
2599     // process further ?
2600     if (!av.followSelection)
2601     {
2602       return;
2603     }
2604
2605     /*
2606      * Ignore the selection if there is one of our own pending.
2607      */
2608     if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2609     {
2610       return;
2611     }
2612
2613     /*
2614      * Check for selection in a view of which this one is a dna/protein
2615      * complement.
2616      */
2617     if (selectionFromTranslation(seqsel, colsel, hidden, source))
2618     {
2619       return;
2620     }
2621
2622     // do we want to thread this ? (contention with seqsel and colsel locks, I
2623     // suspect)
2624     /*
2625      * only copy colsel if there is a real intersection between
2626      * sequence selection and this panel's alignment
2627      */
2628     boolean repaint = false;
2629     boolean copycolsel = false;
2630
2631     SequenceGroup sgroup = null;
2632     if (seqsel != null && seqsel.getSize() > 0)
2633     {
2634       if (av.getAlignment() == null)
2635       {
2636         Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2637                 + " ViewId=" + av.getViewId()
2638                 + " 's alignment is NULL! returning immediately.");
2639         return;
2640       }
2641       sgroup = seqsel.intersect(av.getAlignment(),
2642               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2643       if ((sgroup != null && sgroup.getSize() > 0))
2644       {
2645         copycolsel = true;
2646       }
2647     }
2648     if (sgroup != null && sgroup.getSize() > 0)
2649     {
2650       av.setSelectionGroup(sgroup);
2651     }
2652     else
2653     {
2654       av.setSelectionGroup(null);
2655     }
2656     av.isSelectionGroupChanged(true);
2657     repaint = true;
2658
2659     if (copycolsel)
2660     {
2661       // the current selection is unset or from a previous message
2662       // so import the new colsel.
2663       if (colsel == null || colsel.isEmpty())
2664       {
2665         if (av.getColumnSelection() != null)
2666         {
2667           av.getColumnSelection().clear();
2668           repaint = true;
2669         }
2670       }
2671       else
2672       {
2673         // TODO: shift colSel according to the intersecting sequences
2674         if (av.getColumnSelection() == null)
2675         {
2676           av.setColumnSelection(new ColumnSelection(colsel));
2677         }
2678         else
2679         {
2680           av.getColumnSelection().setElementsFrom(colsel,
2681                   av.getAlignment().getHiddenColumns());
2682         }
2683       }
2684       av.isColSelChanged(true);
2685       repaint = true;
2686     }
2687
2688     if (copycolsel && av.hasHiddenColumns()
2689             && (av.getAlignment().getHiddenColumns() == null))
2690     {
2691       System.err.println("Bad things");
2692     }
2693     if (repaint) // always true!
2694     {
2695       // probably finessing with multiple redraws here
2696       PaintRefresher.Refresh(this, av.getSequenceSetId());
2697       // ap.paintAlignment(false);
2698     }
2699
2700     // lastly, update dependent dialogs
2701     if (ap.getCalculationDialog() != null)
2702     {
2703       ap.getCalculationDialog().validateCalcTypes();
2704     }
2705
2706   }
2707
2708   /**
2709    * If this panel is a cdna/protein translation view of the selection source,
2710    * tries to map the source selection to a local one, and returns true. Else
2711    * returns false.
2712    * 
2713    * @param seqsel
2714    * @param colsel
2715    * @param source
2716    */
2717   protected boolean selectionFromTranslation(SequenceGroup seqsel,
2718           ColumnSelection colsel, HiddenColumns hidden,
2719           SelectionSource source)
2720   {
2721     if (!(source instanceof AlignViewportI))
2722     {
2723       return false;
2724     }
2725     final AlignViewportI sourceAv = (AlignViewportI) source;
2726     if (sourceAv.getCodingComplement() != av
2727             && av.getCodingComplement() != sourceAv)
2728     {
2729       return false;
2730     }
2731
2732     /*
2733      * Map sequence selection
2734      */
2735     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2736     av.setSelectionGroup(sg);
2737     av.isSelectionGroupChanged(true);
2738
2739     /*
2740      * Map column selection
2741      */
2742     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2743     // av);
2744     ColumnSelection cs = new ColumnSelection();
2745     HiddenColumns hs = new HiddenColumns();
2746     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2747     av.setColumnSelection(cs);
2748     boolean hiddenChanged = av.getAlignment().setHiddenColumns(hs);
2749
2750     // lastly, update any dependent dialogs
2751     if (ap.getCalculationDialog() != null)
2752     {
2753       ap.getCalculationDialog().validateCalcTypes();
2754     }
2755
2756     /*
2757      * repaint alignment, and also Overview or Structure
2758      * if hidden column selection has changed
2759      */
2760     ap.paintAlignment(hiddenChanged, hiddenChanged);
2761
2762     return true;
2763   }
2764
2765   /**
2766    * 
2767    * @return null or last search results handled by this panel
2768    */
2769   public SearchResultsI getLastSearchResults()
2770   {
2771     return lastSearchResults;
2772   }
2773 }