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