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