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