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