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