Merge remote-tracking branch 'origin/develop' into bug/JAL-2491
[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 findRes(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 = findRes(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     int res = findRes(evt);
718     int seq = findSeq(evt);
719     int pos;
720     if (res < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
721     {
722       return;
723     }
724
725     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
726
727     if (res >= sequence.getLength())
728     {
729       return;
730     }
731
732     pos = setStatusMessage(sequence, res, seq);
733     if (ssm != null && pos > -1)
734     {
735       mouseOverSequence(sequence, res, pos);
736     }
737
738     tooltipText.setLength(6); // Cuts the buffer back to <html>
739
740     SequenceGroup[] groups = av.getAlignment().findAllGroups(sequence);
741     if (groups != null)
742     {
743       for (int g = 0; g < groups.length; g++)
744       {
745         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
746         {
747           if (!groups[g].getName().startsWith("JTreeGroup")
748                   && !groups[g].getName().startsWith("JGroup"))
749           {
750             tooltipText.append(groups[g].getName());
751           }
752
753           if (groups[g].getDescription() != null)
754           {
755             tooltipText.append(": " + groups[g].getDescription());
756           }
757         }
758       }
759     }
760
761     // use aa to see if the mouse pointer is on a
762     if (av.isShowSequenceFeatures())
763     {
764       int rpos;
765       List<SequenceFeature> features = ap.getFeatureRenderer()
766               .findFeaturesAtRes(sequence.getDatasetSequence(),
767                       rpos = sequence.findPosition(res));
768       seqARep.appendFeatures(tooltipText, rpos, 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    * Set status message in alignment panel
836    * 
837    * @param sequence
838    *          aligned sequence object
839    * @param res
840    *          alignment column
841    * @param seq
842    *          index of sequence in alignment
843    * @return position of res in sequence
844    */
845   int setStatusMessage(SequenceI sequence, int res, int seq)
846   {
847     StringBuilder text = new StringBuilder(32);
848
849     /*
850      * Sequence number (if known), and sequence name.
851      */
852     String seqno = seq == -1 ? "" : " " + (seq + 1);
853     text.append("Sequence").append(seqno).append(" ID: ")
854             .append(sequence.getName());
855
856     String residue = null;
857     /*
858      * Try to translate the display character to residue name (null for gap).
859      */
860     final String displayChar = String.valueOf(sequence.getCharAt(res));
861     if (av.getAlignment().isNucleotide())
862     {
863       residue = ResidueProperties.nucleotideName.get(displayChar);
864       if (residue != null)
865       {
866         text.append(" Nucleotide: ").append(residue);
867       }
868     }
869     else
870     {
871       residue = "X".equalsIgnoreCase(displayChar) ? "X" : ("*"
872               .equals(displayChar) ? "STOP" : ResidueProperties.aa2Triplet
873               .get(displayChar));
874       if (residue != null)
875       {
876         text.append(" Residue: ").append(residue);
877       }
878     }
879
880     int pos = -1;
881     if (residue != null)
882     {
883       pos = sequence.findPosition(res);
884       text.append(" (").append(Integer.toString(pos)).append(")");
885     }
886     ap.alignFrame.statusBar.setText(text.toString());
887     return pos;
888   }
889
890   /**
891    * Set the status bar message to highlight the first matched position in
892    * search results.
893    * 
894    * @param results
895    */
896   private void setStatusMessage(SearchResultsI results)
897   {
898     AlignmentI al = this.av.getAlignment();
899     int sequenceIndex = al.findIndex(results);
900     if (sequenceIndex == -1)
901     {
902       return;
903     }
904     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
905     for (SearchResultMatchI m : results.getResults())
906     {
907       SequenceI seq = m.getSequence();
908       if (seq.getDatasetSequence() != null)
909       {
910         seq = seq.getDatasetSequence();
911       }
912
913       if (seq == ds)
914       {
915         /*
916          * Convert position in sequence (base 1) to sequence character array
917          * index (base 0)
918          */
919         int start = m.getStart() - m.getSequence().getStart();
920         setStatusMessage(seq, start, sequenceIndex);
921         return;
922       }
923     }
924   }
925
926   /**
927    * {@inheritDoc}
928    */
929   @Override
930   public void mouseDragged(MouseEvent evt)
931   {
932     if (mouseWheelPressed)
933     {
934       boolean inSplitFrame = ap.av.getCodingComplement() != null;
935       boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
936
937       int oldWidth = av.getCharWidth();
938
939       // Which is bigger, left-right or up-down?
940       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math.abs(evt
941               .getX() - lastMousePress.getX()))
942       {
943         /*
944          * on drag up or down, decrement or increment font size
945          */
946         int fontSize = av.font.getSize();
947         boolean fontChanged = false;
948
949         if (evt.getY() < lastMousePress.getY())
950         {
951           fontChanged = true;
952           fontSize--;
953         }
954         else if (evt.getY() > lastMousePress.getY())
955         {
956           fontChanged = true;
957           fontSize++;
958         }
959
960         if (fontSize < 1)
961         {
962           fontSize = 1;
963         }
964
965         if (fontChanged)
966         {
967           Font newFont = new Font(av.font.getName(), av.font.getStyle(),
968                   fontSize);
969           av.setFont(newFont, true);
970           av.setCharWidth(oldWidth);
971           ap.fontChanged();
972           if (copyChanges)
973           {
974             ap.av.getCodingComplement().setFont(newFont, true);
975             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
976                     .getSplitViewContainer();
977             splitFrame.adjustLayout();
978             splitFrame.repaint();
979           }
980         }
981       }
982       else
983       {
984         /*
985          * on drag left or right, decrement or increment character width
986          */
987         int newWidth = 0;
988         if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
989         {
990           newWidth = av.getCharWidth() - 1;
991           av.setCharWidth(newWidth);
992         }
993         else if (evt.getX() > lastMousePress.getX())
994         {
995           newWidth = av.getCharWidth() + 1;
996           av.setCharWidth(newWidth);
997         }
998         if (newWidth > 0)
999         {
1000           ap.paintAlignment(false);
1001           if (copyChanges)
1002           {
1003             /*
1004              * need to ensure newWidth is set on cdna, regardless of which
1005              * panel the mouse drag happened in; protein will compute its 
1006              * character width as 1:1 or 3:1
1007              */
1008             av.getCodingComplement().setCharWidth(newWidth);
1009             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1010                     .getSplitViewContainer();
1011             splitFrame.adjustLayout();
1012             splitFrame.repaint();
1013           }
1014         }
1015       }
1016
1017       FontMetrics fm = getFontMetrics(av.getFont());
1018       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1019
1020       lastMousePress = evt.getPoint();
1021
1022       return;
1023     }
1024
1025     if (!editingSeqs)
1026     {
1027       doMouseDraggedDefineMode(evt);
1028       return;
1029     }
1030
1031     int res = findRes(evt);
1032
1033     if (res < 0)
1034     {
1035       res = 0;
1036     }
1037
1038     if ((lastres == -1) || (lastres == res))
1039     {
1040       return;
1041     }
1042
1043     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1044     {
1045       // dragLeft, delete gap
1046       editSequence(false, false, res);
1047     }
1048     else
1049     {
1050       editSequence(true, false, res);
1051     }
1052
1053     mouseDragging = true;
1054     if (scrollThread != null)
1055     {
1056       scrollThread.setEvent(evt);
1057     }
1058   }
1059
1060   // TODO: Make it more clever than many booleans
1061   synchronized void editSequence(boolean insertGap, boolean editSeq,
1062           int startres)
1063   {
1064     int fixedLeft = -1;
1065     int fixedRight = -1;
1066     boolean fixedColumns = false;
1067     SequenceGroup sg = av.getSelectionGroup();
1068
1069     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1070
1071     // No group, but the sequence may represent a group
1072     if (!groupEditing && av.hasHiddenRows())
1073     {
1074       if (av.isHiddenRepSequence(seq))
1075       {
1076         sg = av.getRepresentedSequences(seq);
1077         groupEditing = true;
1078       }
1079     }
1080
1081     StringBuilder message = new StringBuilder(64);
1082     if (groupEditing)
1083     {
1084       message.append("Edit group:");
1085       if (editCommand == null)
1086       {
1087         editCommand = new EditCommand(
1088                 MessageManager.getString("action.edit_group"));
1089       }
1090     }
1091     else
1092     {
1093       message.append("Edit sequence: " + seq.getName());
1094       String label = seq.getName();
1095       if (label.length() > 10)
1096       {
1097         label = label.substring(0, 10);
1098       }
1099       if (editCommand == null)
1100       {
1101         editCommand = new EditCommand(MessageManager.formatMessage(
1102                 "label.edit_params", new String[] { label }));
1103       }
1104     }
1105
1106     if (insertGap)
1107     {
1108       message.append(" insert ");
1109     }
1110     else
1111     {
1112       message.append(" delete ");
1113     }
1114
1115     message.append(Math.abs(startres - lastres) + " gaps.");
1116     ap.alignFrame.statusBar.setText(message.toString());
1117
1118     // Are we editing within a selection group?
1119     if (groupEditing
1120             || (sg != null && sg.getSequences(av.getHiddenRepSequences())
1121                     .contains(seq)))
1122     {
1123       fixedColumns = true;
1124
1125       // sg might be null as the user may only see 1 sequence,
1126       // but the sequence represents a group
1127       if (sg == null)
1128       {
1129         if (!av.isHiddenRepSequence(seq))
1130         {
1131           endEditing();
1132           return;
1133         }
1134         sg = av.getRepresentedSequences(seq);
1135       }
1136
1137       fixedLeft = sg.getStartRes();
1138       fixedRight = sg.getEndRes();
1139
1140       if ((startres < fixedLeft && lastres >= fixedLeft)
1141               || (startres >= fixedLeft && lastres < fixedLeft)
1142               || (startres > fixedRight && lastres <= fixedRight)
1143               || (startres <= fixedRight && lastres > fixedRight))
1144       {
1145         endEditing();
1146         return;
1147       }
1148
1149       if (fixedLeft > startres)
1150       {
1151         fixedRight = fixedLeft - 1;
1152         fixedLeft = 0;
1153       }
1154       else if (fixedRight < startres)
1155       {
1156         fixedLeft = fixedRight;
1157         fixedRight = -1;
1158       }
1159     }
1160
1161     if (av.hasHiddenColumns())
1162     {
1163       fixedColumns = true;
1164       int y1 = av.getAlignment().getHiddenColumns()
1165               .getHiddenBoundaryLeft(startres);
1166       int y2 = av.getAlignment().getHiddenColumns()
1167               .getHiddenBoundaryRight(startres);
1168
1169       if ((insertGap && startres > y1 && lastres < y1)
1170               || (!insertGap && startres < y2 && lastres > y2))
1171       {
1172         endEditing();
1173         return;
1174       }
1175
1176       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1177       // Selection spans a hidden region
1178       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1179       {
1180         if (startres >= y2)
1181         {
1182           fixedLeft = y2;
1183         }
1184         else
1185         {
1186           fixedRight = y2 - 1;
1187         }
1188       }
1189     }
1190
1191     if (groupEditing)
1192     {
1193       List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1194       int g, groupSize = vseqs.size();
1195       SequenceI[] groupSeqs = new SequenceI[groupSize];
1196       for (g = 0; g < groupSeqs.length; g++)
1197       {
1198         groupSeqs[g] = vseqs.get(g);
1199       }
1200
1201       // drag to right
1202       if (insertGap)
1203       {
1204         // If the user has selected the whole sequence, and is dragging to
1205         // the right, we can still extend the alignment and selectionGroup
1206         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1207                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1208         {
1209           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1210           fixedRight = sg.getEndRes();
1211         }
1212
1213         // Is it valid with fixed columns??
1214         // Find the next gap before the end
1215         // of the visible region boundary
1216         boolean blank = false;
1217         for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1218         {
1219           blank = true;
1220
1221           for (g = 0; g < groupSize; g++)
1222           {
1223             for (int j = 0; j < startres - lastres; j++)
1224             {
1225               if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1226               {
1227                 blank = false;
1228                 break;
1229               }
1230             }
1231           }
1232           if (blank)
1233           {
1234             break;
1235           }
1236         }
1237
1238         if (!blank)
1239         {
1240           if (sg.getSize() == av.getAlignment().getHeight())
1241           {
1242             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1243                     .getHiddenColumns().getHiddenBoundaryRight(startres)))
1244             {
1245               endEditing();
1246               return;
1247             }
1248
1249             int alWidth = av.getAlignment().getWidth();
1250             if (av.hasHiddenRows())
1251             {
1252               int hwidth = av.getAlignment().getHiddenSequences()
1253                       .getWidth();
1254               if (hwidth > alWidth)
1255               {
1256                 alWidth = hwidth;
1257               }
1258             }
1259             // We can still insert gaps if the selectionGroup
1260             // contains all the sequences
1261             sg.setEndRes(sg.getEndRes() + startres - lastres);
1262             fixedRight = alWidth + startres - lastres;
1263           }
1264           else
1265           {
1266             endEditing();
1267             return;
1268           }
1269         }
1270       }
1271
1272       // drag to left
1273       else if (!insertGap)
1274       {
1275         // / Are we able to delete?
1276         // ie are all columns blank?
1277
1278         for (g = 0; g < groupSize; g++)
1279         {
1280           for (int j = startres; j < lastres; j++)
1281           {
1282             if (groupSeqs[g].getLength() <= j)
1283             {
1284               continue;
1285             }
1286
1287             if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1288             {
1289               // Not a gap, block edit not valid
1290               endEditing();
1291               return;
1292             }
1293           }
1294         }
1295       }
1296
1297       if (insertGap)
1298       {
1299         // dragging to the right
1300         if (fixedColumns && fixedRight != -1)
1301         {
1302           for (int j = lastres; j < startres; j++)
1303           {
1304             insertChar(j, groupSeqs, fixedRight);
1305           }
1306         }
1307         else
1308         {
1309           appendEdit(Action.INSERT_GAP, groupSeqs, startres, startres
1310                   - lastres);
1311         }
1312       }
1313       else
1314       {
1315         // dragging to the left
1316         if (fixedColumns && fixedRight != -1)
1317         {
1318           for (int j = lastres; j > startres; j--)
1319           {
1320             deleteChar(startres, groupSeqs, fixedRight);
1321           }
1322         }
1323         else
1324         {
1325           appendEdit(Action.DELETE_GAP, groupSeqs, startres, lastres
1326                   - startres);
1327         }
1328
1329       }
1330     }
1331     else
1332     // ///Editing a single sequence///////////
1333     {
1334       if (insertGap)
1335       {
1336         // dragging to the right
1337         if (fixedColumns && fixedRight != -1)
1338         {
1339           for (int j = lastres; j < startres; j++)
1340           {
1341             insertChar(j, new SequenceI[] { seq }, fixedRight);
1342           }
1343         }
1344         else
1345         {
1346           appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1347                   startres - lastres);
1348         }
1349       }
1350       else
1351       {
1352         if (!editSeq)
1353         {
1354           // dragging to the left
1355           if (fixedColumns && fixedRight != -1)
1356           {
1357             for (int j = lastres; j > startres; j--)
1358             {
1359               if (!Comparison.isGap(seq.getCharAt(startres)))
1360               {
1361                 endEditing();
1362                 break;
1363               }
1364               deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1365             }
1366           }
1367           else
1368           {
1369             // could be a keyboard edit trying to delete none gaps
1370             int max = 0;
1371             for (int m = startres; m < lastres; m++)
1372             {
1373               if (!Comparison.isGap(seq.getCharAt(m)))
1374               {
1375                 break;
1376               }
1377               max++;
1378             }
1379
1380             if (max > 0)
1381             {
1382               appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1383                       startres, max);
1384             }
1385           }
1386         }
1387         else
1388         {// insertGap==false AND editSeq==TRUE;
1389           if (fixedColumns && fixedRight != -1)
1390           {
1391             for (int j = lastres; j < startres; j++)
1392             {
1393               insertChar(j, new SequenceI[] { seq }, fixedRight);
1394             }
1395           }
1396           else
1397           {
1398             appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1399                     startres - lastres);
1400           }
1401         }
1402       }
1403     }
1404
1405     lastres = startres;
1406     seqCanvas.repaint();
1407   }
1408
1409   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1410   {
1411     int blankColumn = fixedColumn;
1412     for (int s = 0; s < seq.length; s++)
1413     {
1414       // Find the next gap before the end of the visible region boundary
1415       // If lastCol > j, theres a boundary after the gap insertion
1416
1417       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1418       {
1419         if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1420         {
1421           // Theres a space, so break and insert the gap
1422           break;
1423         }
1424       }
1425
1426       if (blankColumn <= j)
1427       {
1428         blankColumn = fixedColumn;
1429         endEditing();
1430         return;
1431       }
1432     }
1433
1434     appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1435
1436     appendEdit(Action.INSERT_GAP, seq, j, 1);
1437
1438   }
1439
1440   /**
1441    * Helper method to add and perform one edit action.
1442    * 
1443    * @param action
1444    * @param seq
1445    * @param pos
1446    * @param count
1447    */
1448   protected void appendEdit(Action action, SequenceI[] seq, int pos,
1449           int count)
1450   {
1451
1452     final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1453             av.getAlignment().getGapCharacter());
1454
1455     editCommand.appendEdit(edit, av.getAlignment(), true, null);
1456   }
1457
1458   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1459   {
1460
1461     appendEdit(Action.DELETE_GAP, seq, j, 1);
1462
1463     appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1464   }
1465
1466   /**
1467    * DOCUMENT ME!
1468    * 
1469    * @param e
1470    *          DOCUMENT ME!
1471    */
1472   @Override
1473   public void mouseEntered(MouseEvent e)
1474   {
1475     if (oldSeq < 0)
1476     {
1477       oldSeq = 0;
1478     }
1479
1480     if (scrollThread != null)
1481     {
1482       scrollThread.running = false;
1483       scrollThread = null;
1484     }
1485   }
1486
1487   /**
1488    * DOCUMENT ME!
1489    * 
1490    * @param e
1491    *          DOCUMENT ME!
1492    */
1493   @Override
1494   public void mouseExited(MouseEvent e)
1495   {
1496     if (av.getWrapAlignment())
1497     {
1498       return;
1499     }
1500
1501     if (mouseDragging)
1502     {
1503       scrollThread = new ScrollThread();
1504     }
1505   }
1506
1507   /**
1508    * Handler for double-click on a position with one or more sequence features.
1509    * Opens the Amend Features dialog to allow feature details to be amended, or
1510    * the feature deleted.
1511    */
1512   @Override
1513   public void mouseClicked(MouseEvent evt)
1514   {
1515     SequenceGroup sg = null;
1516     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1517     if (evt.getClickCount() > 1)
1518     {
1519       sg = av.getSelectionGroup();
1520       if (sg != null && sg.getSize() == 1
1521               && sg.getEndRes() - sg.getStartRes() < 2)
1522       {
1523         av.setSelectionGroup(null);
1524       }
1525
1526       List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1527               .findFeaturesAtRes(sequence.getDatasetSequence(),
1528                       sequence.findPosition(findRes(evt)));
1529
1530       if (!features.isEmpty())
1531       {
1532         /*
1533          * highlight the first feature at the position on the alignment
1534          */
1535         SearchResultsI highlight = new SearchResults();
1536         highlight.addResult(sequence, features.get(0).getBegin(), features
1537                 .get(0).getEnd());
1538         seqCanvas.highlightSearchResults(highlight);
1539
1540         /*
1541          * open the Amend Features dialog; clear highlighting afterwards,
1542          * whether changes were made or not
1543          */
1544         List<SequenceI> seqs = Collections.singletonList(sequence);
1545         seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1546                 ap, null);
1547         seqCanvas.highlightSearchResults(null);
1548       }
1549     }
1550   }
1551
1552   @Override
1553   public void mouseWheelMoved(MouseWheelEvent e)
1554   {
1555     e.consume();
1556     if (e.getWheelRotation() > 0)
1557     {
1558       if (e.isShiftDown())
1559       {
1560         av.getRanges().scrollRight(true);
1561
1562       }
1563       else
1564       {
1565         av.getRanges().scrollUp(false);
1566       }
1567     }
1568     else
1569     {
1570       if (e.isShiftDown())
1571       {
1572         av.getRanges().scrollRight(false);
1573       }
1574       else
1575       {
1576         av.getRanges().scrollUp(true);
1577       }
1578     }
1579     // TODO Update tooltip for new position.
1580   }
1581
1582   /**
1583    * DOCUMENT ME!
1584    * 
1585    * @param evt
1586    *          DOCUMENT ME!
1587    */
1588   public void doMousePressedDefineMode(MouseEvent evt)
1589   {
1590     final int res = findRes(evt);
1591     final int seq = findSeq(evt);
1592     oldSeq = seq;
1593     needOverviewUpdate = false;
1594
1595     startWrapBlock = wrappedBlock;
1596
1597     if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1598     {
1599       JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
1600               .getString("label.cannot_edit_annotations_in_wrapped_view"),
1601               MessageManager.getString("label.wrapped_view_no_edit"),
1602               JvOptionPane.WARNING_MESSAGE);
1603       return;
1604     }
1605
1606     if (seq < 0 || res < 0)
1607     {
1608       return;
1609     }
1610
1611     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1612
1613     if ((sequence == null) || (res > sequence.getLength()))
1614     {
1615       return;
1616     }
1617
1618     stretchGroup = av.getSelectionGroup();
1619
1620     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1621     {
1622       stretchGroup = av.getAlignment().findGroup(sequence, res);
1623       if (stretchGroup != null)
1624       {
1625         // only update the current selection if the popup menu has a group to
1626         // focus on
1627         av.setSelectionGroup(stretchGroup);
1628       }
1629     }
1630
1631     if (evt.isPopupTrigger()) // Mac: mousePressed
1632     {
1633       showPopupMenu(evt);
1634       return;
1635     }
1636
1637     /*
1638      * defer right-mouse click handling to mouseReleased on Windows
1639      * (where isPopupTrigger() will answer true)
1640      * NB isRightMouseButton is also true for Cmd-click on Mac
1641      */
1642     if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1643     {
1644       return;
1645     }
1646
1647     if (av.cursorMode)
1648     {
1649       seqCanvas.cursorX = findRes(evt);
1650       seqCanvas.cursorY = findSeq(evt);
1651       seqCanvas.repaint();
1652       return;
1653     }
1654
1655     if (stretchGroup == null)
1656     {
1657       // Only if left mouse button do we want to change group sizes
1658
1659       // define a new group here
1660       SequenceGroup sg = new SequenceGroup();
1661       sg.setStartRes(res);
1662       sg.setEndRes(res);
1663       sg.addSequence(sequence, false);
1664       av.setSelectionGroup(sg);
1665       stretchGroup = sg;
1666
1667       if (av.getConservationSelected())
1668       {
1669         SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1670                 ap.getViewName());
1671       }
1672
1673       if (av.getAbovePIDThreshold())
1674       {
1675         SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1676                 ap.getViewName());
1677       }
1678       // TODO: stretchGroup will always be not null. Is this a merge error ?
1679       if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1680       {
1681         // Edit end res position of selected group
1682         changeEndRes = true;
1683       }
1684       else if ((stretchGroup != null)
1685               && (stretchGroup.getStartRes() == res))
1686       {
1687         // Edit end res position of selected group
1688         changeStartRes = true;
1689       }
1690       stretchGroup.getWidth();
1691     }
1692
1693     seqCanvas.repaint();
1694   }
1695
1696   /**
1697    * Build and show a pop-up menu at the right-click mouse position
1698    * 
1699    * @param evt
1700    * @param res
1701    * @param sequences
1702    */
1703   void showPopupMenu(MouseEvent evt)
1704   {
1705     final int res = findRes(evt);
1706     final int seq = findSeq(evt);
1707     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1708     List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1709             .findFeaturesAtRes(sequence.getDatasetSequence(),
1710                     sequence.findPosition(res));
1711     List<String> links = new ArrayList<String>();
1712     for (SequenceFeature sf : allFeatures)
1713     {
1714       if (sf.links != null)
1715       {
1716         for (String link : sf.links)
1717         {
1718           links.add(link);
1719         }
1720       }
1721     }
1722
1723     PopupMenu pop = new PopupMenu(ap, null, links);
1724     pop.show(this, evt.getX(), evt.getY());
1725   }
1726
1727   /**
1728    * DOCUMENT ME!
1729    * 
1730    * @param evt
1731    *          DOCUMENT ME!
1732    */
1733   public void doMouseReleasedDefineMode(MouseEvent evt)
1734   {
1735     if (stretchGroup == null)
1736     {
1737       return;
1738     }
1739     // always do this - annotation has own state
1740     // but defer colourscheme update until hidden sequences are passed in
1741     boolean vischange = stretchGroup.recalcConservation(true);
1742     needOverviewUpdate |= vischange && av.isSelectionDefinedGroup();
1743     if (stretchGroup.cs != null)
1744     {
1745       stretchGroup.cs.alignmentChanged(stretchGroup,
1746               av.getHiddenRepSequences());
1747
1748       ResidueShaderI groupColourScheme = stretchGroup.getGroupColourScheme();
1749       String name = stretchGroup.getName();
1750       if (stretchGroup.cs.conservationApplied())
1751       {
1752         SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1753       }
1754       if (stretchGroup.cs.getThreshold() > 0)
1755       {
1756         SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1757       }
1758     }
1759     PaintRefresher.Refresh(this, av.getSequenceSetId());
1760     ap.paintAlignment(needOverviewUpdate);
1761     needOverviewUpdate = false;
1762     changeEndRes = false;
1763     changeStartRes = false;
1764     stretchGroup = null;
1765     av.sendSelection();
1766   }
1767
1768   /**
1769    * DOCUMENT ME!
1770    * 
1771    * @param evt
1772    *          DOCUMENT ME!
1773    */
1774   public void doMouseDraggedDefineMode(MouseEvent evt)
1775   {
1776     int res = findRes(evt);
1777     int y = findSeq(evt);
1778
1779     if (wrappedBlock != startWrapBlock)
1780     {
1781       return;
1782     }
1783
1784     if (stretchGroup == null)
1785     {
1786       return;
1787     }
1788
1789     if (res >= av.getAlignment().getWidth())
1790     {
1791       res = av.getAlignment().getWidth() - 1;
1792     }
1793
1794     if (stretchGroup.getEndRes() == res)
1795     {
1796       // Edit end res position of selected group
1797       changeEndRes = true;
1798     }
1799     else if (stretchGroup.getStartRes() == res)
1800     {
1801       // Edit start res position of selected group
1802       changeStartRes = true;
1803     }
1804
1805     if (res < av.getRanges().getStartRes())
1806     {
1807       res = av.getRanges().getStartRes();
1808     }
1809
1810     if (changeEndRes)
1811     {
1812       if (res > (stretchGroup.getStartRes() - 1))
1813       {
1814         stretchGroup.setEndRes(res);
1815         needOverviewUpdate |= av.isSelectionDefinedGroup();
1816       }
1817     }
1818     else if (changeStartRes)
1819     {
1820       if (res < (stretchGroup.getEndRes() + 1))
1821       {
1822         stretchGroup.setStartRes(res);
1823         needOverviewUpdate |= av.isSelectionDefinedGroup();
1824       }
1825     }
1826
1827     int dragDirection = 0;
1828
1829     if (y > oldSeq)
1830     {
1831       dragDirection = 1;
1832     }
1833     else if (y < oldSeq)
1834     {
1835       dragDirection = -1;
1836     }
1837
1838     while ((y != oldSeq) && (oldSeq > -1)
1839             && (y < av.getAlignment().getHeight()))
1840     {
1841       // This routine ensures we don't skip any sequences, as the
1842       // selection is quite slow.
1843       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1844
1845       oldSeq += dragDirection;
1846
1847       if (oldSeq < 0)
1848       {
1849         break;
1850       }
1851
1852       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1853
1854       if (stretchGroup.getSequences(null).contains(nextSeq))
1855       {
1856         stretchGroup.deleteSequence(seq, false);
1857         needOverviewUpdate |= av.isSelectionDefinedGroup();
1858       }
1859       else
1860       {
1861         if (seq != null)
1862         {
1863           stretchGroup.addSequence(seq, false);
1864         }
1865
1866         stretchGroup.addSequence(nextSeq, false);
1867         needOverviewUpdate |= av.isSelectionDefinedGroup();
1868       }
1869     }
1870
1871     if (oldSeq < 0)
1872     {
1873       oldSeq = -1;
1874     }
1875
1876     mouseDragging = true;
1877
1878     if (scrollThread != null)
1879     {
1880       scrollThread.setEvent(evt);
1881     }
1882
1883     seqCanvas.repaint();
1884   }
1885
1886   void scrollCanvas(MouseEvent evt)
1887   {
1888     if (evt == null)
1889     {
1890       if (scrollThread != null)
1891       {
1892         scrollThread.running = false;
1893         scrollThread = null;
1894       }
1895       mouseDragging = false;
1896     }
1897     else
1898     {
1899       if (scrollThread == null)
1900       {
1901         scrollThread = new ScrollThread();
1902       }
1903
1904       mouseDragging = true;
1905       scrollThread.setEvent(evt);
1906     }
1907
1908   }
1909
1910   // this class allows scrolling off the bottom of the visible alignment
1911   class ScrollThread extends Thread
1912   {
1913     MouseEvent evt;
1914
1915     boolean running = false;
1916
1917     public ScrollThread()
1918     {
1919       start();
1920     }
1921
1922     public void setEvent(MouseEvent e)
1923     {
1924       evt = e;
1925     }
1926
1927     public void stopScrolling()
1928     {
1929       running = false;
1930     }
1931
1932     @Override
1933     public void run()
1934     {
1935       running = true;
1936
1937       while (running)
1938       {
1939         if (evt != null)
1940         {
1941           if (mouseDragging && (evt.getY() < 0)
1942                   && (av.getRanges().getStartSeq() > 0))
1943           {
1944             running = av.getRanges().scrollUp(true);
1945           }
1946
1947           if (mouseDragging && (evt.getY() >= getHeight())
1948                   && (av.getAlignment().getHeight() > av.getRanges()
1949                           .getEndSeq()))
1950           {
1951             running = av.getRanges().scrollUp(false);
1952           }
1953
1954           if (mouseDragging && (evt.getX() < 0))
1955           {
1956             running = av.getRanges().scrollRight(false);
1957           }
1958           else if (mouseDragging && (evt.getX() >= getWidth()))
1959           {
1960             running = av.getRanges().scrollRight(true);
1961           }
1962         }
1963
1964         try
1965         {
1966           Thread.sleep(20);
1967         } catch (Exception ex)
1968         {
1969         }
1970       }
1971     }
1972   }
1973
1974   /**
1975    * modify current selection according to a received message.
1976    */
1977   @Override
1978   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
1979           HiddenColumns hidden, SelectionSource source)
1980   {
1981     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
1982     // handles selection messages...
1983     // TODO: extend config options to allow user to control if selections may be
1984     // shared between viewports.
1985     boolean iSentTheSelection = (av == source || (source instanceof AlignViewport && ((AlignmentViewport) source)
1986             .getSequenceSetId().equals(av.getSequenceSetId())));
1987
1988     if (iSentTheSelection)
1989     {
1990       // respond to our own event by updating dependent dialogs
1991       if (ap.getCalculationDialog() != null)
1992       {
1993         ap.getCalculationDialog().validateCalcTypes();
1994       }
1995
1996       // process further ?
1997       if (!av.followSelection)
1998       {
1999         return;
2000       }
2001     }
2002
2003     /*
2004      * Ignore the selection if there is one of our own pending.
2005      */
2006     if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2007     {
2008       return;
2009     }
2010
2011     /*
2012      * Check for selection in a view of which this one is a dna/protein
2013      * complement.
2014      */
2015     if (selectionFromTranslation(seqsel, colsel, hidden, source))
2016     {
2017       return;
2018     }
2019
2020     // do we want to thread this ? (contention with seqsel and colsel locks, I
2021     // suspect)
2022     /*
2023      * only copy colsel if there is a real intersection between
2024      * sequence selection and this panel's alignment
2025      */
2026     boolean repaint = false;
2027     boolean copycolsel = false;
2028
2029     SequenceGroup sgroup = null;
2030     if (seqsel != null && seqsel.getSize() > 0)
2031     {
2032       if (av.getAlignment() == null)
2033       {
2034         Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2035                 + " ViewId=" + av.getViewId()
2036                 + " 's alignment is NULL! returning immediately.");
2037         return;
2038       }
2039       sgroup = seqsel.intersect(av.getAlignment(),
2040               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2041       if ((sgroup != null && sgroup.getSize() > 0))
2042       {
2043         copycolsel = true;
2044       }
2045     }
2046     if (sgroup != null && sgroup.getSize() > 0)
2047     {
2048       av.setSelectionGroup(sgroup);
2049     }
2050     else
2051     {
2052       av.setSelectionGroup(null);
2053     }
2054     av.isSelectionGroupChanged(true);
2055     repaint = true;
2056
2057     if (copycolsel)
2058     {
2059       // the current selection is unset or from a previous message
2060       // so import the new colsel.
2061       if (colsel == null || colsel.isEmpty())
2062       {
2063         if (av.getColumnSelection() != null)
2064         {
2065           av.getColumnSelection().clear();
2066           repaint = true;
2067         }
2068       }
2069       else
2070       {
2071         // TODO: shift colSel according to the intersecting sequences
2072         if (av.getColumnSelection() == null)
2073         {
2074           av.setColumnSelection(new ColumnSelection(colsel));
2075         }
2076         else
2077         {
2078           av.getColumnSelection().setElementsFrom(colsel,
2079                   av.getAlignment().getHiddenColumns());
2080         }
2081       }
2082       av.isColSelChanged(true);
2083       repaint = true;
2084     }
2085
2086     if (copycolsel
2087             && av.hasHiddenColumns()
2088             && (av.getAlignment().getHiddenColumns() == null || av
2089                     .getAlignment().getHiddenColumns().getHiddenRegions() == null))
2090     {
2091       System.err.println("Bad things");
2092     }
2093     if (repaint) // always true!
2094     {
2095       // probably finessing with multiple redraws here
2096       PaintRefresher.Refresh(this, av.getSequenceSetId());
2097       // ap.paintAlignment(false);
2098     }
2099
2100     // lastly, update dependent dialogs
2101     if (ap.getCalculationDialog() != null)
2102     {
2103       ap.getCalculationDialog().validateCalcTypes();
2104     }
2105
2106   }
2107
2108   /**
2109    * If this panel is a cdna/protein translation view of the selection source,
2110    * tries to map the source selection to a local one, and returns true. Else
2111    * returns false.
2112    * 
2113    * @param seqsel
2114    * @param colsel
2115    * @param source
2116    */
2117   protected boolean selectionFromTranslation(SequenceGroup seqsel,
2118           ColumnSelection colsel, HiddenColumns hidden,
2119           SelectionSource source)
2120   {
2121     if (!(source instanceof AlignViewportI))
2122     {
2123       return false;
2124     }
2125     final AlignViewportI sourceAv = (AlignViewportI) source;
2126     if (sourceAv.getCodingComplement() != av
2127             && av.getCodingComplement() != sourceAv)
2128     {
2129       return false;
2130     }
2131
2132     /*
2133      * Map sequence selection
2134      */
2135     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2136     av.setSelectionGroup(sg);
2137     av.isSelectionGroupChanged(true);
2138
2139     /*
2140      * Map column selection
2141      */
2142     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2143     // av);
2144     ColumnSelection cs = new ColumnSelection();
2145     HiddenColumns hs = new HiddenColumns();
2146     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2147     av.setColumnSelection(cs);
2148     av.getAlignment().setHiddenColumns(hs);
2149
2150     // lastly, update any dependent dialogs
2151     if (ap.getCalculationDialog() != null)
2152     {
2153       ap.getCalculationDialog().validateCalcTypes();
2154     }
2155
2156     PaintRefresher.Refresh(this, av.getSequenceSetId());
2157
2158     return true;
2159   }
2160 }