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