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