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