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