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