328dfdc0671f601eeb4592aec47f1e9ca9795b75
[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
78         implements MouseListener, MouseMotionListener, MouseWheelListener,
79         SequenceListener, 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     int startRes = av.getRanges().getStartRes();
193     if (av.getWrapAlignment())
194     {
195
196       int hgap = av.getCharHeight();
197       if (av.getScaleAboveWrapped())
198       {
199         hgap += av.getCharHeight();
200       }
201
202       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
203               + hgap + seqCanvas.getAnnotationHeight();
204
205       int y = evt.getY();
206       y -= hgap;
207       x = Math.max(0, x - seqCanvas.LABEL_WEST);
208
209       int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
210       if (cwidth < 1)
211       {
212         return 0;
213       }
214
215       wrappedBlock = y / cHeight;
216       wrappedBlock += startRes / cwidth;
217       // allow for wrapped view scrolled right (possible from Overview)
218       int startOffset = startRes % cwidth;
219       res = wrappedBlock * cwidth + startOffset
220               + +Math.min(cwidth - 1, x / av.getCharWidth());
221     }
222     else
223     {
224       if (x > seqCanvas.getX() + seqCanvas.getWidth())
225       {
226         // make sure we calculate relative to visible alignment, rather than
227         // right-hand gutter
228         x = seqCanvas.getX() + seqCanvas.getWidth();
229       }
230       res = (x / av.getCharWidth()) + startRes;
231       if (res > av.getRanges().getEndRes())
232       {
233         // moused off right
234         res = av.getRanges().getEndRes();
235       }
236     }
237
238     if (av.hasHiddenColumns())
239     {
240       res = av.getAlignment().getHiddenColumns()
241               .adjustForHiddenColumns(res);
242     }
243
244     return res;
245
246   }
247
248   int findSeq(MouseEvent evt)
249   {
250     int seq = 0;
251     int y = evt.getY();
252
253     if (av.getWrapAlignment())
254     {
255       int hgap = av.getCharHeight();
256       if (av.getScaleAboveWrapped())
257       {
258         hgap += av.getCharHeight();
259       }
260
261       int cHeight = av.getAlignment().getHeight() * av.getCharHeight()
262               + hgap + seqCanvas.getAnnotationHeight();
263
264       y -= hgap;
265
266       seq = Math.min((y % cHeight) / av.getCharHeight(),
267               av.getAlignment().getHeight() - 1);
268     }
269     else
270     {
271       seq = Math.min(
272               (y / av.getCharHeight()) + av.getRanges().getStartSeq(),
273               av.getAlignment().getHeight() - 1);
274     }
275
276     return seq;
277   }
278
279   /**
280    * When all of a sequence of edits are complete, put the resulting edit list
281    * on the history stack (undo list), and reset flags for editing in progress.
282    */
283   void endEditing()
284   {
285     try
286     {
287       if (editCommand != null && editCommand.getSize() > 0)
288       {
289         ap.alignFrame.addHistoryItem(editCommand);
290         av.firePropertyChange("alignment", null,
291                 av.getAlignment().getSequences());
292       }
293     } finally
294     {
295       /*
296        * Tidy up come what may...
297        */
298       startseq = -1;
299       lastres = -1;
300       editingSeqs = false;
301       groupEditing = false;
302       keyboardNo1 = null;
303       keyboardNo2 = null;
304       editCommand = null;
305     }
306   }
307
308   void setCursorRow()
309   {
310     seqCanvas.cursorY = getKeyboardNo1() - 1;
311     scrollToVisible();
312   }
313
314   void setCursorColumn()
315   {
316     seqCanvas.cursorX = getKeyboardNo1() - 1;
317     scrollToVisible();
318   }
319
320   void setCursorRowAndColumn()
321   {
322     if (keyboardNo2 == null)
323     {
324       keyboardNo2 = new StringBuffer();
325     }
326     else
327     {
328       seqCanvas.cursorX = getKeyboardNo1() - 1;
329       seqCanvas.cursorY = getKeyboardNo2() - 1;
330       scrollToVisible();
331     }
332   }
333
334   void setCursorPosition()
335   {
336     SequenceI sequence = av.getAlignment().getSequenceAt(seqCanvas.cursorY);
337
338     seqCanvas.cursorX = sequence.findIndex(getKeyboardNo1()) - 1;
339     scrollToVisible();
340   }
341
342   void moveCursor(int dx, int dy)
343   {
344     seqCanvas.cursorX += dx;
345     seqCanvas.cursorY += dy;
346
347     HiddenColumns hidden = av.getAlignment().getHiddenColumns();
348
349     if (av.hasHiddenColumns() && !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)
849               ? new Point(event.getX() + wdth, event.getY() - 20)
850               : null;
851     }
852     /*
853      * TODO: try to modify position region is not obcured by tooltip
854      */
855     return lastp = p;
856   }
857
858   String lastTooltip;
859
860   /**
861    * set when the current UI interaction has resulted in a change that requires
862    * overview shading to be recalculated. this could be changed to something
863    * more expressive that indicates what actually has changed, so selective
864    * redraws can be applied
865    */
866   private boolean needOverviewUpdate = false; // TODO: refactor to avcontroller
867
868   /**
869    * set if av.getSelectionGroup() refers to a group that is defined on the
870    * alignment view, rather than a transient selection
871    */
872   // private boolean editingDefinedGroup = false; // TODO: refactor to
873   // avcontroller or viewModel
874
875   /**
876    * Sets the status message in alignment panel, showing the sequence number
877    * (index) and id, and residue and residue position if not at a gap, for the
878    * given sequence and column position. Returns the residue position returned
879    * by Sequence.findPosition. Note this may be for the nearest adjacent residue
880    * if at a gapped position.
881    * 
882    * @param sequence
883    *          aligned sequence object
884    * @param column
885    *          alignment column
886    * @param seq
887    *          index of sequence in alignment
888    * @return sequence position of residue at column, or adjacent residue if at a
889    *         gap
890    */
891   int setStatusMessage(SequenceI sequence, final int column, int seq)
892   {
893     StringBuilder text = new StringBuilder(32);
894
895     /*
896      * Sequence number (if known), and sequence name.
897      */
898     String seqno = seq == -1 ? "" : " " + (seq + 1);
899     text.append("Sequence").append(seqno).append(" ID: ")
900             .append(sequence.getName());
901
902     String residue = null;
903
904     /*
905      * Try to translate the display character to residue name (null for gap).
906      */
907     final String displayChar = String.valueOf(sequence.getCharAt(column));
908     boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
909     int pos = sequence.findPosition(column);
910
911     if (!isGapped)
912     {
913       boolean nucleotide = av.getAlignment().isNucleotide();
914       if (nucleotide)
915       {
916         residue = ResidueProperties.nucleotideName.get(displayChar);
917       }
918       else
919       {
920         residue = "X".equalsIgnoreCase(displayChar) ? "X"
921                 : ("*".equals(displayChar) ? "STOP"
922                         : ResidueProperties.aa2Triplet.get(displayChar));
923       }
924       text.append(" ").append(nucleotide ? "Nucleotide" : "Residue")
925               .append(": ").append(residue == null ? displayChar : residue);
926
927       text.append(" (").append(Integer.toString(pos)).append(")");
928     }
929     ap.alignFrame.statusBar.setText(text.toString());
930
931     return pos;
932   }
933
934   /**
935    * Set the status bar message to highlight the first matched position in
936    * search results.
937    * 
938    * @param results
939    */
940   private void setStatusMessage(SearchResultsI results)
941   {
942     AlignmentI al = this.av.getAlignment();
943     int sequenceIndex = al.findIndex(results);
944     if (sequenceIndex == -1)
945     {
946       return;
947     }
948     SequenceI ds = al.getSequenceAt(sequenceIndex).getDatasetSequence();
949     for (SearchResultMatchI m : results.getResults())
950     {
951       SequenceI seq = m.getSequence();
952       if (seq.getDatasetSequence() != null)
953       {
954         seq = seq.getDatasetSequence();
955       }
956
957       if (seq == ds)
958       {
959         /*
960          * Convert position in sequence (base 1) to sequence character array
961          * index (base 0)
962          */
963         int start = m.getStart() - m.getSequence().getStart();
964         setStatusMessage(seq, start, sequenceIndex);
965         return;
966       }
967     }
968   }
969
970   /**
971    * {@inheritDoc}
972    */
973   @Override
974   public void mouseDragged(MouseEvent evt)
975   {
976     if (mouseWheelPressed)
977     {
978       boolean inSplitFrame = ap.av.getCodingComplement() != null;
979       boolean copyChanges = inSplitFrame && av.isProteinFontAsCdna();
980
981       int oldWidth = av.getCharWidth();
982
983       // Which is bigger, left-right or up-down?
984       if (Math.abs(evt.getY() - lastMousePress.getY()) > Math
985               .abs(evt.getX() - lastMousePress.getX()))
986       {
987         /*
988          * on drag up or down, decrement or increment font size
989          */
990         int fontSize = av.font.getSize();
991         boolean fontChanged = false;
992
993         if (evt.getY() < lastMousePress.getY())
994         {
995           fontChanged = true;
996           fontSize--;
997         }
998         else if (evt.getY() > lastMousePress.getY())
999         {
1000           fontChanged = true;
1001           fontSize++;
1002         }
1003
1004         if (fontSize < 1)
1005         {
1006           fontSize = 1;
1007         }
1008
1009         if (fontChanged)
1010         {
1011           Font newFont = new Font(av.font.getName(), av.font.getStyle(),
1012                   fontSize);
1013           av.setFont(newFont, true);
1014           av.setCharWidth(oldWidth);
1015           ap.fontChanged();
1016           if (copyChanges)
1017           {
1018             ap.av.getCodingComplement().setFont(newFont, true);
1019             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1020                     .getSplitViewContainer();
1021             splitFrame.adjustLayout();
1022             splitFrame.repaint();
1023           }
1024         }
1025       }
1026       else
1027       {
1028         /*
1029          * on drag left or right, decrement or increment character width
1030          */
1031         int newWidth = 0;
1032         if (evt.getX() < lastMousePress.getX() && av.getCharWidth() > 1)
1033         {
1034           newWidth = av.getCharWidth() - 1;
1035           av.setCharWidth(newWidth);
1036         }
1037         else if (evt.getX() > lastMousePress.getX())
1038         {
1039           newWidth = av.getCharWidth() + 1;
1040           av.setCharWidth(newWidth);
1041         }
1042         if (newWidth > 0)
1043         {
1044           ap.paintAlignment(false);
1045           if (copyChanges)
1046           {
1047             /*
1048              * need to ensure newWidth is set on cdna, regardless of which
1049              * panel the mouse drag happened in; protein will compute its 
1050              * character width as 1:1 or 3:1
1051              */
1052             av.getCodingComplement().setCharWidth(newWidth);
1053             SplitFrame splitFrame = (SplitFrame) ap.alignFrame
1054                     .getSplitViewContainer();
1055             splitFrame.adjustLayout();
1056             splitFrame.repaint();
1057           }
1058         }
1059       }
1060
1061       FontMetrics fm = getFontMetrics(av.getFont());
1062       av.validCharWidth = fm.charWidth('M') <= av.getCharWidth();
1063
1064       lastMousePress = evt.getPoint();
1065
1066       return;
1067     }
1068
1069     if (!editingSeqs)
1070     {
1071       doMouseDraggedDefineMode(evt);
1072       return;
1073     }
1074
1075     int res = findColumn(evt);
1076
1077     if (res < 0)
1078     {
1079       res = 0;
1080     }
1081
1082     if ((lastres == -1) || (lastres == res))
1083     {
1084       return;
1085     }
1086
1087     if ((res < av.getAlignment().getWidth()) && (res < lastres))
1088     {
1089       // dragLeft, delete gap
1090       editSequence(false, false, res);
1091     }
1092     else
1093     {
1094       editSequence(true, false, res);
1095     }
1096
1097     mouseDragging = true;
1098     if (scrollThread != null)
1099     {
1100       scrollThread.setEvent(evt);
1101     }
1102   }
1103
1104   // TODO: Make it more clever than many booleans
1105   synchronized void editSequence(boolean insertGap, boolean editSeq,
1106           int startres)
1107   {
1108     int fixedLeft = -1;
1109     int fixedRight = -1;
1110     boolean fixedColumns = false;
1111     SequenceGroup sg = av.getSelectionGroup();
1112
1113     SequenceI seq = av.getAlignment().getSequenceAt(startseq);
1114
1115     // No group, but the sequence may represent a group
1116     if (!groupEditing && av.hasHiddenRows())
1117     {
1118       if (av.isHiddenRepSequence(seq))
1119       {
1120         sg = av.getRepresentedSequences(seq);
1121         groupEditing = true;
1122       }
1123     }
1124
1125     StringBuilder message = new StringBuilder(64);
1126     if (groupEditing)
1127     {
1128       message.append("Edit group:");
1129       if (editCommand == null)
1130       {
1131         editCommand = new EditCommand(
1132                 MessageManager.getString("action.edit_group"));
1133       }
1134     }
1135     else
1136     {
1137       message.append("Edit sequence: " + seq.getName());
1138       String label = seq.getName();
1139       if (label.length() > 10)
1140       {
1141         label = label.substring(0, 10);
1142       }
1143       if (editCommand == null)
1144       {
1145         editCommand = new EditCommand(MessageManager
1146                 .formatMessage("label.edit_params", new String[]
1147                 { label }));
1148       }
1149     }
1150
1151     if (insertGap)
1152     {
1153       message.append(" insert ");
1154     }
1155     else
1156     {
1157       message.append(" delete ");
1158     }
1159
1160     message.append(Math.abs(startres - lastres) + " gaps.");
1161     ap.alignFrame.statusBar.setText(message.toString());
1162
1163     // Are we editing within a selection group?
1164     if (groupEditing || (sg != null
1165             && sg.getSequences(av.getHiddenRepSequences()).contains(seq)))
1166     {
1167       fixedColumns = true;
1168
1169       // sg might be null as the user may only see 1 sequence,
1170       // but the sequence represents a group
1171       if (sg == null)
1172       {
1173         if (!av.isHiddenRepSequence(seq))
1174         {
1175           endEditing();
1176           return;
1177         }
1178         sg = av.getRepresentedSequences(seq);
1179       }
1180
1181       fixedLeft = sg.getStartRes();
1182       fixedRight = sg.getEndRes();
1183
1184       if ((startres < fixedLeft && lastres >= fixedLeft)
1185               || (startres >= fixedLeft && lastres < fixedLeft)
1186               || (startres > fixedRight && lastres <= fixedRight)
1187               || (startres <= fixedRight && lastres > fixedRight))
1188       {
1189         endEditing();
1190         return;
1191       }
1192
1193       if (fixedLeft > startres)
1194       {
1195         fixedRight = fixedLeft - 1;
1196         fixedLeft = 0;
1197       }
1198       else if (fixedRight < startres)
1199       {
1200         fixedLeft = fixedRight;
1201         fixedRight = -1;
1202       }
1203     }
1204
1205     if (av.hasHiddenColumns())
1206     {
1207       fixedColumns = true;
1208       int y1 = av.getAlignment().getHiddenColumns()
1209               .getHiddenBoundaryLeft(startres);
1210       int y2 = av.getAlignment().getHiddenColumns()
1211               .getHiddenBoundaryRight(startres);
1212
1213       if ((insertGap && startres > y1 && lastres < y1)
1214               || (!insertGap && startres < y2 && lastres > y2))
1215       {
1216         endEditing();
1217         return;
1218       }
1219
1220       // System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1221       // Selection spans a hidden region
1222       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1223       {
1224         if (startres >= y2)
1225         {
1226           fixedLeft = y2;
1227         }
1228         else
1229         {
1230           fixedRight = y2 - 1;
1231         }
1232       }
1233     }
1234
1235     if (groupEditing)
1236     {
1237       List<SequenceI> vseqs = sg.getSequences(av.getHiddenRepSequences());
1238       int g, groupSize = vseqs.size();
1239       SequenceI[] groupSeqs = new SequenceI[groupSize];
1240       for (g = 0; g < groupSeqs.length; g++)
1241       {
1242         groupSeqs[g] = vseqs.get(g);
1243       }
1244
1245       // drag to right
1246       if (insertGap)
1247       {
1248         // If the user has selected the whole sequence, and is dragging to
1249         // the right, we can still extend the alignment and selectionGroup
1250         if (sg.getStartRes() == 0 && sg.getEndRes() == fixedRight
1251                 && sg.getEndRes() == av.getAlignment().getWidth() - 1)
1252         {
1253           sg.setEndRes(av.getAlignment().getWidth() + startres - lastres);
1254           fixedRight = sg.getEndRes();
1255         }
1256
1257         // Is it valid with fixed columns??
1258         // Find the next gap before the end
1259         // of the visible region boundary
1260         boolean blank = false;
1261         for (fixedRight = fixedRight; fixedRight > lastres; fixedRight--)
1262         {
1263           blank = true;
1264
1265           for (g = 0; g < groupSize; g++)
1266           {
1267             for (int j = 0; j < startres - lastres; j++)
1268             {
1269               if (!Comparison.isGap(groupSeqs[g].getCharAt(fixedRight - j)))
1270               {
1271                 blank = false;
1272                 break;
1273               }
1274             }
1275           }
1276           if (blank)
1277           {
1278             break;
1279           }
1280         }
1281
1282         if (!blank)
1283         {
1284           if (sg.getSize() == av.getAlignment().getHeight())
1285           {
1286             if ((av.hasHiddenColumns() && startres < av.getAlignment()
1287                     .getHiddenColumns().getHiddenBoundaryRight(startres)))
1288             {
1289               endEditing();
1290               return;
1291             }
1292
1293             int alWidth = av.getAlignment().getWidth();
1294             if (av.hasHiddenRows())
1295             {
1296               int hwidth = av.getAlignment().getHiddenSequences()
1297                       .getWidth();
1298               if (hwidth > alWidth)
1299               {
1300                 alWidth = hwidth;
1301               }
1302             }
1303             // We can still insert gaps if the selectionGroup
1304             // contains all the sequences
1305             sg.setEndRes(sg.getEndRes() + startres - lastres);
1306             fixedRight = alWidth + startres - lastres;
1307           }
1308           else
1309           {
1310             endEditing();
1311             return;
1312           }
1313         }
1314       }
1315
1316       // drag to left
1317       else if (!insertGap)
1318       {
1319         // / Are we able to delete?
1320         // ie are all columns blank?
1321
1322         for (g = 0; g < groupSize; g++)
1323         {
1324           for (int j = startres; j < lastres; j++)
1325           {
1326             if (groupSeqs[g].getLength() <= j)
1327             {
1328               continue;
1329             }
1330
1331             if (!Comparison.isGap(groupSeqs[g].getCharAt(j)))
1332             {
1333               // Not a gap, block edit not valid
1334               endEditing();
1335               return;
1336             }
1337           }
1338         }
1339       }
1340
1341       if (insertGap)
1342       {
1343         // dragging to the right
1344         if (fixedColumns && fixedRight != -1)
1345         {
1346           for (int j = lastres; j < startres; j++)
1347           {
1348             insertChar(j, groupSeqs, fixedRight);
1349           }
1350         }
1351         else
1352         {
1353           appendEdit(Action.INSERT_GAP, groupSeqs, startres,
1354                   startres - lastres);
1355         }
1356       }
1357       else
1358       {
1359         // dragging to the left
1360         if (fixedColumns && fixedRight != -1)
1361         {
1362           for (int j = lastres; j > startres; j--)
1363           {
1364             deleteChar(startres, groupSeqs, fixedRight);
1365           }
1366         }
1367         else
1368         {
1369           appendEdit(Action.DELETE_GAP, groupSeqs, startres,
1370                   lastres - startres);
1371         }
1372
1373       }
1374     }
1375     else
1376     // ///Editing a single sequence///////////
1377     {
1378       if (insertGap)
1379       {
1380         // dragging to the right
1381         if (fixedColumns && fixedRight != -1)
1382         {
1383           for (int j = lastres; j < startres; j++)
1384           {
1385             insertChar(j, new SequenceI[] { seq }, fixedRight);
1386           }
1387         }
1388         else
1389         {
1390           appendEdit(Action.INSERT_GAP, new SequenceI[] { seq }, lastres,
1391                   startres - lastres);
1392         }
1393       }
1394       else
1395       {
1396         if (!editSeq)
1397         {
1398           // dragging to the left
1399           if (fixedColumns && fixedRight != -1)
1400           {
1401             for (int j = lastres; j > startres; j--)
1402             {
1403               if (!Comparison.isGap(seq.getCharAt(startres)))
1404               {
1405                 endEditing();
1406                 break;
1407               }
1408               deleteChar(startres, new SequenceI[] { seq }, fixedRight);
1409             }
1410           }
1411           else
1412           {
1413             // could be a keyboard edit trying to delete none gaps
1414             int max = 0;
1415             for (int m = startres; m < lastres; m++)
1416             {
1417               if (!Comparison.isGap(seq.getCharAt(m)))
1418               {
1419                 break;
1420               }
1421               max++;
1422             }
1423
1424             if (max > 0)
1425             {
1426               appendEdit(Action.DELETE_GAP, new SequenceI[] { seq },
1427                       startres, max);
1428             }
1429           }
1430         }
1431         else
1432         {// insertGap==false AND editSeq==TRUE;
1433           if (fixedColumns && fixedRight != -1)
1434           {
1435             for (int j = lastres; j < startres; j++)
1436             {
1437               insertChar(j, new SequenceI[] { seq }, fixedRight);
1438             }
1439           }
1440           else
1441           {
1442             appendEdit(Action.INSERT_NUC, new SequenceI[] { seq }, lastres,
1443                     startres - lastres);
1444           }
1445         }
1446       }
1447     }
1448
1449     lastres = startres;
1450     seqCanvas.repaint();
1451   }
1452
1453   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1454   {
1455     int blankColumn = fixedColumn;
1456     for (int s = 0; s < seq.length; s++)
1457     {
1458       // Find the next gap before the end of the visible region boundary
1459       // If lastCol > j, theres a boundary after the gap insertion
1460
1461       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1462       {
1463         if (Comparison.isGap(seq[s].getCharAt(blankColumn)))
1464         {
1465           // Theres a space, so break and insert the gap
1466           break;
1467         }
1468       }
1469
1470       if (blankColumn <= j)
1471       {
1472         blankColumn = fixedColumn;
1473         endEditing();
1474         return;
1475       }
1476     }
1477
1478     appendEdit(Action.DELETE_GAP, seq, blankColumn, 1);
1479
1480     appendEdit(Action.INSERT_GAP, seq, j, 1);
1481
1482   }
1483
1484   /**
1485    * Helper method to add and perform one edit action.
1486    * 
1487    * @param action
1488    * @param seq
1489    * @param pos
1490    * @param count
1491    */
1492   protected void appendEdit(Action action, SequenceI[] seq, int pos,
1493           int count)
1494   {
1495
1496     final Edit edit = new EditCommand().new Edit(action, seq, pos, count,
1497             av.getAlignment().getGapCharacter());
1498
1499     editCommand.appendEdit(edit, av.getAlignment(), true, null);
1500   }
1501
1502   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1503   {
1504
1505     appendEdit(Action.DELETE_GAP, seq, j, 1);
1506
1507     appendEdit(Action.INSERT_GAP, seq, fixedColumn, 1);
1508   }
1509
1510   /**
1511    * DOCUMENT ME!
1512    * 
1513    * @param e
1514    *          DOCUMENT ME!
1515    */
1516   @Override
1517   public void mouseEntered(MouseEvent e)
1518   {
1519     if (oldSeq < 0)
1520     {
1521       oldSeq = 0;
1522     }
1523
1524     if (scrollThread != null)
1525     {
1526       scrollThread.running = false;
1527       scrollThread = null;
1528     }
1529   }
1530
1531   /**
1532    * DOCUMENT ME!
1533    * 
1534    * @param e
1535    *          DOCUMENT ME!
1536    */
1537   @Override
1538   public void mouseExited(MouseEvent e)
1539   {
1540     if (av.getWrapAlignment())
1541     {
1542       return;
1543     }
1544
1545     if (mouseDragging)
1546     {
1547       scrollThread = new ScrollThread();
1548     }
1549   }
1550
1551   /**
1552    * Handler for double-click on a position with one or more sequence features.
1553    * Opens the Amend Features dialog to allow feature details to be amended, or
1554    * the feature deleted.
1555    */
1556   @Override
1557   public void mouseClicked(MouseEvent evt)
1558   {
1559     SequenceGroup sg = null;
1560     SequenceI sequence = av.getAlignment().getSequenceAt(findSeq(evt));
1561     if (evt.getClickCount() > 1)
1562     {
1563       sg = av.getSelectionGroup();
1564       if (sg != null && sg.getSize() == 1
1565               && sg.getEndRes() - sg.getStartRes() < 2)
1566       {
1567         av.setSelectionGroup(null);
1568       }
1569
1570       int column = findColumn(evt);
1571       boolean isGapped = Comparison.isGap(sequence.getCharAt(column));
1572
1573       /*
1574        * find features at the position (if not gapped), or straddling
1575        * the position (if at a gap)
1576        */
1577       List<SequenceFeature> features = seqCanvas.getFeatureRenderer()
1578               .findFeaturesAtRes(sequence.getDatasetSequence(),
1579                       sequence.findPosition(column));
1580       if (isGapped)
1581       {
1582         removeAdjacentFeatures(features, column, sequence);
1583       }
1584
1585       if (!features.isEmpty())
1586       {
1587         /*
1588          * highlight the first feature at the position on the alignment
1589          */
1590         SearchResultsI highlight = new SearchResults();
1591         highlight.addResult(sequence, features.get(0).getBegin(),
1592                 features.get(0).getEnd());
1593         seqCanvas.highlightSearchResults(highlight);
1594
1595         /*
1596          * open the Amend Features dialog; clear highlighting afterwards,
1597          * whether changes were made or not
1598          */
1599         List<SequenceI> seqs = Collections.singletonList(sequence);
1600         seqCanvas.getFeatureRenderer().amendFeatures(seqs, features, false,
1601                 ap);
1602         seqCanvas.highlightSearchResults(null);
1603       }
1604     }
1605   }
1606
1607   @Override
1608   public void mouseWheelMoved(MouseWheelEvent e)
1609   {
1610     e.consume();
1611     if (e.getWheelRotation() > 0)
1612     {
1613       if (e.isShiftDown())
1614       {
1615         av.getRanges().scrollRight(true);
1616
1617       }
1618       else if (!av.getWrapAlignment())
1619       {
1620         av.getRanges().scrollUp(false);
1621       }
1622     }
1623     else
1624     {
1625       if (e.isShiftDown())
1626       {
1627         av.getRanges().scrollRight(false);
1628       }
1629       else if (!av.getWrapAlignment())
1630       {
1631         av.getRanges().scrollUp(true);
1632       }
1633     }
1634     // TODO Update tooltip for new position.
1635   }
1636
1637   /**
1638    * DOCUMENT ME!
1639    * 
1640    * @param evt
1641    *          DOCUMENT ME!
1642    */
1643   public void doMousePressedDefineMode(MouseEvent evt)
1644   {
1645     final int res = findColumn(evt);
1646     final int seq = findSeq(evt);
1647     oldSeq = seq;
1648     needOverviewUpdate = false;
1649
1650     startWrapBlock = wrappedBlock;
1651
1652     if (av.getWrapAlignment() && seq > av.getAlignment().getHeight())
1653     {
1654       JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1655               MessageManager.getString(
1656                       "label.cannot_edit_annotations_in_wrapped_view"),
1657               MessageManager.getString("label.wrapped_view_no_edit"),
1658               JvOptionPane.WARNING_MESSAGE);
1659       return;
1660     }
1661
1662     if (seq < 0 || res < 0)
1663     {
1664       return;
1665     }
1666
1667     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1668
1669     if ((sequence == null) || (res > sequence.getLength()))
1670     {
1671       return;
1672     }
1673
1674     stretchGroup = av.getSelectionGroup();
1675
1676     if (stretchGroup == null || !stretchGroup.contains(sequence, res))
1677     {
1678       stretchGroup = av.getAlignment().findGroup(sequence, res);
1679       if (stretchGroup != null)
1680       {
1681         // only update the current selection if the popup menu has a group to
1682         // focus on
1683         av.setSelectionGroup(stretchGroup);
1684       }
1685     }
1686
1687     if (evt.isPopupTrigger()) // Mac: mousePressed
1688     {
1689       showPopupMenu(evt);
1690       return;
1691     }
1692
1693     /*
1694      * defer right-mouse click handling to mouseReleased on Windows
1695      * (where isPopupTrigger() will answer true)
1696      * NB isRightMouseButton is also true for Cmd-click on Mac
1697      */
1698     if (SwingUtilities.isRightMouseButton(evt) && !Platform.isAMac())
1699     {
1700       return;
1701     }
1702
1703     if (av.cursorMode)
1704     {
1705       seqCanvas.cursorX = findColumn(evt);
1706       seqCanvas.cursorY = findSeq(evt);
1707       seqCanvas.repaint();
1708       return;
1709     }
1710
1711     if (stretchGroup == null)
1712     {
1713       createStretchGroup(res, sequence);
1714     }
1715
1716     if (stretchGroup != null)
1717     {
1718       stretchGroup.addPropertyChangeListener(seqCanvas);
1719     }
1720
1721     seqCanvas.repaint();
1722   }
1723
1724   private void createStretchGroup(int res, SequenceI sequence)
1725   {
1726     // Only if left mouse button do we want to change group sizes
1727     // define a new group here
1728     SequenceGroup sg = new SequenceGroup();
1729     sg.setStartRes(res);
1730     sg.setEndRes(res);
1731     sg.addSequence(sequence, false);
1732     av.setSelectionGroup(sg);
1733     stretchGroup = sg;
1734
1735     if (av.getConservationSelected())
1736     {
1737       SliderPanel.setConservationSlider(ap, av.getResidueShading(),
1738               ap.getViewName());
1739     }
1740
1741     if (av.getAbovePIDThreshold())
1742     {
1743       SliderPanel.setPIDSliderSource(ap, av.getResidueShading(),
1744               ap.getViewName());
1745     }
1746     // TODO: stretchGroup will always be not null. Is this a merge error ?
1747     // or is there a threading issue here?
1748     if ((stretchGroup != null) && (stretchGroup.getEndRes() == res))
1749     {
1750       // Edit end res position of selected group
1751       changeEndRes = true;
1752     }
1753     else if ((stretchGroup != null) && (stretchGroup.getStartRes() == res))
1754     {
1755       // Edit end res position of selected group
1756       changeStartRes = true;
1757     }
1758     stretchGroup.getWidth();
1759
1760   }
1761
1762   /**
1763    * Build and show a pop-up menu at the right-click mouse position
1764    * 
1765    * @param evt
1766    * @param res
1767    * @param sequences
1768    */
1769   void showPopupMenu(MouseEvent evt)
1770   {
1771     final int res = findColumn(evt);
1772     final int seq = findSeq(evt);
1773     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
1774     List<SequenceFeature> allFeatures = ap.getFeatureRenderer()
1775             .findFeaturesAtRes(sequence.getDatasetSequence(),
1776                     sequence.findPosition(res));
1777     List<String> links = new ArrayList<>();
1778     for (SequenceFeature sf : allFeatures)
1779     {
1780       if (sf.links != null)
1781       {
1782         for (String link : sf.links)
1783         {
1784           links.add(link);
1785         }
1786       }
1787     }
1788
1789     PopupMenu pop = new PopupMenu(ap, null, links);
1790     pop.show(this, evt.getX(), evt.getY());
1791   }
1792
1793   /**
1794    * Update the display after mouse up on a selection or group
1795    * 
1796    * @param evt
1797    *          mouse released event details
1798    * @param afterDrag
1799    *          true if this event is happening after a mouse drag (rather than a
1800    *          mouse down)
1801    */
1802   public void doMouseReleasedDefineMode(MouseEvent evt, boolean afterDrag)
1803   {
1804     if (stretchGroup == null)
1805     {
1806       return;
1807     }
1808
1809     stretchGroup.removePropertyChangeListener(seqCanvas);
1810
1811     // always do this - annotation has own state
1812     // but defer colourscheme update until hidden sequences are passed in
1813     boolean vischange = stretchGroup.recalcConservation(true);
1814     needOverviewUpdate |= vischange && av.isSelectionDefinedGroup()
1815             && afterDrag;
1816     if (stretchGroup.cs != null)
1817     {
1818       stretchGroup.cs.alignmentChanged(stretchGroup,
1819               av.getHiddenRepSequences());
1820
1821       ResidueShaderI groupColourScheme = stretchGroup
1822               .getGroupColourScheme();
1823       String name = stretchGroup.getName();
1824       if (stretchGroup.cs.conservationApplied())
1825       {
1826         SliderPanel.setConservationSlider(ap, groupColourScheme, name);
1827       }
1828       if (stretchGroup.cs.getThreshold() > 0)
1829       {
1830         SliderPanel.setPIDSliderSource(ap, groupColourScheme, name);
1831       }
1832     }
1833     PaintRefresher.Refresh(this, av.getSequenceSetId());
1834     ap.paintAlignment(needOverviewUpdate);
1835     needOverviewUpdate = false;
1836     changeEndRes = false;
1837     changeStartRes = false;
1838     stretchGroup = null;
1839     av.sendSelection();
1840   }
1841
1842   /**
1843    * DOCUMENT ME!
1844    * 
1845    * @param evt
1846    *          DOCUMENT ME!
1847    */
1848   public void doMouseDraggedDefineMode(MouseEvent evt)
1849   {
1850     int res = findColumn(evt);
1851     int y = findSeq(evt);
1852
1853     if (wrappedBlock != startWrapBlock)
1854     {
1855       return;
1856     }
1857
1858     if (stretchGroup == null)
1859     {
1860       return;
1861     }
1862
1863     if (res >= av.getAlignment().getWidth())
1864     {
1865       res = av.getAlignment().getWidth() - 1;
1866     }
1867
1868     if (stretchGroup.getEndRes() == res)
1869     {
1870       // Edit end res position of selected group
1871       changeEndRes = true;
1872     }
1873     else if (stretchGroup.getStartRes() == res)
1874     {
1875       // Edit start res position of selected group
1876       changeStartRes = true;
1877     }
1878
1879     if (res < av.getRanges().getStartRes())
1880     {
1881       res = av.getRanges().getStartRes();
1882     }
1883
1884     if (changeEndRes)
1885     {
1886       if (res > (stretchGroup.getStartRes() - 1))
1887       {
1888         stretchGroup.setEndRes(res);
1889         needOverviewUpdate |= av.isSelectionDefinedGroup();
1890       }
1891     }
1892     else if (changeStartRes)
1893     {
1894       if (res < (stretchGroup.getEndRes() + 1))
1895       {
1896         stretchGroup.setStartRes(res);
1897         needOverviewUpdate |= av.isSelectionDefinedGroup();
1898       }
1899     }
1900
1901     int dragDirection = 0;
1902
1903     if (y > oldSeq)
1904     {
1905       dragDirection = 1;
1906     }
1907     else if (y < oldSeq)
1908     {
1909       dragDirection = -1;
1910     }
1911
1912     while ((y != oldSeq) && (oldSeq > -1)
1913             && (y < av.getAlignment().getHeight()))
1914     {
1915       // This routine ensures we don't skip any sequences, as the
1916       // selection is quite slow.
1917       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1918
1919       oldSeq += dragDirection;
1920
1921       if (oldSeq < 0)
1922       {
1923         break;
1924       }
1925
1926       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1927
1928       if (stretchGroup.getSequences(null).contains(nextSeq))
1929       {
1930         stretchGroup.deleteSequence(seq, false);
1931         needOverviewUpdate |= av.isSelectionDefinedGroup();
1932       }
1933       else
1934       {
1935         if (seq != null)
1936         {
1937           stretchGroup.addSequence(seq, false);
1938         }
1939
1940         stretchGroup.addSequence(nextSeq, false);
1941         needOverviewUpdate |= av.isSelectionDefinedGroup();
1942       }
1943     }
1944
1945     if (oldSeq < 0)
1946     {
1947       oldSeq = -1;
1948     }
1949
1950     mouseDragging = true;
1951
1952     if (scrollThread != null)
1953     {
1954       scrollThread.setEvent(evt);
1955     }
1956   }
1957
1958   void scrollCanvas(MouseEvent evt)
1959   {
1960     if (evt == null)
1961     {
1962       if (scrollThread != null)
1963       {
1964         scrollThread.running = false;
1965         scrollThread = null;
1966       }
1967       mouseDragging = false;
1968     }
1969     else
1970     {
1971       if (scrollThread == null)
1972       {
1973         scrollThread = new ScrollThread();
1974       }
1975
1976       mouseDragging = true;
1977       scrollThread.setEvent(evt);
1978     }
1979
1980   }
1981
1982   // this class allows scrolling off the bottom of the visible alignment
1983   class ScrollThread extends Thread
1984   {
1985     MouseEvent evt;
1986
1987     boolean running = false;
1988
1989     public ScrollThread()
1990     {
1991       start();
1992     }
1993
1994     public void setEvent(MouseEvent e)
1995     {
1996       evt = e;
1997     }
1998
1999     public void stopScrolling()
2000     {
2001       running = false;
2002     }
2003
2004     @Override
2005     public void run()
2006     {
2007       running = true;
2008
2009       while (running)
2010       {
2011         if (evt != null)
2012         {
2013           if (mouseDragging && (evt.getY() < 0)
2014                   && (av.getRanges().getStartSeq() > 0))
2015           {
2016             running = av.getRanges().scrollUp(true);
2017           }
2018
2019           if (mouseDragging && (evt.getY() >= getHeight()) && (av
2020                   .getAlignment().getHeight() > av.getRanges().getEndSeq()))
2021           {
2022             running = av.getRanges().scrollUp(false);
2023           }
2024
2025           if (mouseDragging && (evt.getX() < 0))
2026           {
2027             running = av.getRanges().scrollRight(false);
2028           }
2029           else if (mouseDragging && (evt.getX() >= getWidth()))
2030           {
2031             running = av.getRanges().scrollRight(true);
2032           }
2033         }
2034
2035         try
2036         {
2037           Thread.sleep(20);
2038         } catch (Exception ex)
2039         {
2040         }
2041       }
2042     }
2043   }
2044
2045   /**
2046    * modify current selection according to a received message.
2047    */
2048   @Override
2049   public void selection(SequenceGroup seqsel, ColumnSelection colsel,
2050           HiddenColumns hidden, SelectionSource source)
2051   {
2052     // TODO: fix this hack - source of messages is align viewport, but SeqPanel
2053     // handles selection messages...
2054     // TODO: extend config options to allow user to control if selections may be
2055     // shared between viewports.
2056     boolean iSentTheSelection = (av == source
2057             || (source instanceof AlignViewport
2058                     && ((AlignmentViewport) source).getSequenceSetId()
2059                             .equals(av.getSequenceSetId())));
2060
2061     if (iSentTheSelection)
2062     {
2063       // respond to our own event by updating dependent dialogs
2064       if (ap.getCalculationDialog() != null)
2065       {
2066         ap.getCalculationDialog().validateCalcTypes();
2067       }
2068
2069       return;
2070     }
2071
2072     // process further ?
2073     if (!av.followSelection)
2074     {
2075       return;
2076     }
2077
2078     /*
2079      * Ignore the selection if there is one of our own pending.
2080      */
2081     if (av.isSelectionGroupChanged(false) || av.isColSelChanged(false))
2082     {
2083       return;
2084     }
2085
2086     /*
2087      * Check for selection in a view of which this one is a dna/protein
2088      * complement.
2089      */
2090     if (selectionFromTranslation(seqsel, colsel, hidden, source))
2091     {
2092       return;
2093     }
2094
2095     // do we want to thread this ? (contention with seqsel and colsel locks, I
2096     // suspect)
2097     /*
2098      * only copy colsel if there is a real intersection between
2099      * sequence selection and this panel's alignment
2100      */
2101     boolean repaint = false;
2102     boolean copycolsel = false;
2103
2104     SequenceGroup sgroup = null;
2105     if (seqsel != null && seqsel.getSize() > 0)
2106     {
2107       if (av.getAlignment() == null)
2108       {
2109         Cache.log.warn("alignviewport av SeqSetId=" + av.getSequenceSetId()
2110                 + " ViewId=" + av.getViewId()
2111                 + " 's alignment is NULL! returning immediately.");
2112         return;
2113       }
2114       sgroup = seqsel.intersect(av.getAlignment(),
2115               (av.hasHiddenRows()) ? av.getHiddenRepSequences() : null);
2116       if ((sgroup != null && sgroup.getSize() > 0))
2117       {
2118         copycolsel = true;
2119       }
2120     }
2121     if (sgroup != null && sgroup.getSize() > 0)
2122     {
2123       av.setSelectionGroup(sgroup);
2124     }
2125     else
2126     {
2127       av.setSelectionGroup(null);
2128     }
2129     av.isSelectionGroupChanged(true);
2130     repaint = true;
2131
2132     if (copycolsel)
2133     {
2134       // the current selection is unset or from a previous message
2135       // so import the new colsel.
2136       if (colsel == null || colsel.isEmpty())
2137       {
2138         if (av.getColumnSelection() != null)
2139         {
2140           av.getColumnSelection().clear();
2141           repaint = true;
2142         }
2143       }
2144       else
2145       {
2146         // TODO: shift colSel according to the intersecting sequences
2147         if (av.getColumnSelection() == null)
2148         {
2149           av.setColumnSelection(new ColumnSelection(colsel));
2150         }
2151         else
2152         {
2153           av.getColumnSelection().setElementsFrom(colsel,
2154                   av.getAlignment().getHiddenColumns());
2155         }
2156       }
2157       av.isColSelChanged(true);
2158       repaint = true;
2159     }
2160
2161     if (copycolsel && av.hasHiddenColumns()
2162             && (av.getAlignment().getHiddenColumns() == null))
2163     {
2164       System.err.println("Bad things");
2165     }
2166     if (repaint) // always true!
2167     {
2168       // probably finessing with multiple redraws here
2169       PaintRefresher.Refresh(this, av.getSequenceSetId());
2170       // ap.paintAlignment(false);
2171     }
2172
2173     // lastly, update dependent dialogs
2174     if (ap.getCalculationDialog() != null)
2175     {
2176       ap.getCalculationDialog().validateCalcTypes();
2177     }
2178
2179   }
2180
2181   /**
2182    * If this panel is a cdna/protein translation view of the selection source,
2183    * tries to map the source selection to a local one, and returns true. Else
2184    * returns false.
2185    * 
2186    * @param seqsel
2187    * @param colsel
2188    * @param source
2189    */
2190   protected boolean selectionFromTranslation(SequenceGroup seqsel,
2191           ColumnSelection colsel, HiddenColumns hidden,
2192           SelectionSource source)
2193   {
2194     if (!(source instanceof AlignViewportI))
2195     {
2196       return false;
2197     }
2198     final AlignViewportI sourceAv = (AlignViewportI) source;
2199     if (sourceAv.getCodingComplement() != av
2200             && av.getCodingComplement() != sourceAv)
2201     {
2202       return false;
2203     }
2204
2205     /*
2206      * Map sequence selection
2207      */
2208     SequenceGroup sg = MappingUtils.mapSequenceGroup(seqsel, sourceAv, av);
2209     av.setSelectionGroup(sg);
2210     av.isSelectionGroupChanged(true);
2211
2212     /*
2213      * Map column selection
2214      */
2215     // ColumnSelection cs = MappingUtils.mapColumnSelection(colsel, sourceAv,
2216     // av);
2217     ColumnSelection cs = new ColumnSelection();
2218     HiddenColumns hs = new HiddenColumns();
2219     MappingUtils.mapColumnSelection(colsel, hidden, sourceAv, av, cs, hs);
2220     av.setColumnSelection(cs);
2221     av.getAlignment().setHiddenColumns(hs);
2222
2223     // lastly, update any dependent dialogs
2224     if (ap.getCalculationDialog() != null)
2225     {
2226       ap.getCalculationDialog().validateCalcTypes();
2227     }
2228
2229     PaintRefresher.Refresh(this, av.getSequenceSetId());
2230
2231     return true;
2232   }
2233 }