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