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