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