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