pickmanager on sequence and alignment position, vamsas pick broadcast and refactor...
[jalview.git] / src / jalview / gui / SeqPanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25 import javax.swing.*;
26
27 import jalview.commands.*;
28 import jalview.datamodel.*;
29 import jalview.schemes.*;
30 import jalview.structure.*;
31
32 /**
33  * DOCUMENT ME!
34  *
35  * @author $author$
36  * @version $Revision$
37  */
38 public class SeqPanel
39     extends JPanel implements MouseListener,
40     MouseMotionListener, MouseWheelListener, SequenceListener
41
42 {
43   /** DOCUMENT ME!! */
44   public SeqCanvas seqCanvas;
45
46   /** DOCUMENT ME!! */
47   public AlignmentPanel ap;
48   protected int lastres;
49   protected int startseq;
50   protected AlignViewport av;
51
52   ScrollThread scrollThread = null;
53   boolean mouseDragging = false;
54   boolean editingSeqs = false;
55   boolean groupEditing = false;
56
57   //////////////////////////////////////////
58   /////Everything below this is for defining the boundary of the rubberband
59   //////////////////////////////////////////
60   int oldSeq = -1;
61   boolean changeEndSeq = false;
62   boolean changeStartSeq = false;
63   boolean changeEndRes = false;
64   boolean changeStartRes = false;
65   SequenceGroup stretchGroup = null;
66   boolean remove = false;
67
68   Point lastMousePress;
69   boolean mouseWheelPressed = false;
70   StringBuffer keyboardNo1;
71   StringBuffer keyboardNo2;
72
73   java.net.URL linkImageURL;
74
75   StringBuffer tooltipText = new StringBuffer("<html>");
76   String tmpString;
77
78   EditCommand editCommand;
79
80   StructureSelectionManager ssm;
81
82
83   /**
84    * Creates a new SeqPanel object.
85    *
86    * @param avp DOCUMENT ME!
87    * @param p DOCUMENT ME!
88    */
89   public SeqPanel(AlignViewport av, AlignmentPanel ap)
90   {
91     linkImageURL = getClass().getResource("/images/link.gif");
92     ToolTipManager.sharedInstance().registerComponent(this);
93     ToolTipManager.sharedInstance().setInitialDelay(0);
94     ToolTipManager.sharedInstance().setDismissDelay(10000);
95     this.av = av;
96     setBackground(Color.white);
97
98     seqCanvas = new SeqCanvas(ap);
99     setLayout(new BorderLayout());
100     add(seqCanvas, BorderLayout.CENTER);
101
102     this.ap = ap;
103
104     if (!av.isDataset())
105     {
106       addMouseMotionListener(this);
107       addMouseListener(this);
108       addMouseWheelListener(this);
109       ssm = StructureSelectionManager.getStructureSelectionManager();
110       ssm.addStructureViewerListener(this);
111     }
112   }
113
114   int startWrapBlock = -1;
115   int wrappedBlock = -1;
116   int findRes(MouseEvent evt)
117   {
118     int res = 0;
119     int x = evt.getX();
120
121     if (av.wrapAlignment)
122     {
123
124       int hgap = av.charHeight;
125       if (av.scaleAboveWrapped)
126       {
127         hgap += av.charHeight;
128       }
129
130       int cHeight = av.getAlignment().getHeight() * av.charHeight
131           + hgap + seqCanvas.getAnnotationHeight();
132
133       int y = evt.getY();
134       y -= hgap;
135       x -= seqCanvas.LABEL_WEST;
136
137       int cwidth = seqCanvas.getWrappedCanvasWidth(this.getWidth());
138       if (cwidth < 1)
139       {
140         return 0;
141       }
142
143       wrappedBlock = y / cHeight;
144       wrappedBlock += av.getStartRes() / cwidth;
145
146       res = wrappedBlock * cwidth + x / av.getCharWidth();
147
148     }
149     else
150     {
151       res = (x / av.getCharWidth()) + av.getStartRes();
152     }
153
154     if (av.hasHiddenColumns)
155     {
156       res = av.getColumnSelection().adjustForHiddenColumns(res);
157     }
158
159     return res;
160
161   }
162
163   int findSeq(MouseEvent evt)
164   {
165     int seq = 0;
166     int y = evt.getY();
167
168     if (av.wrapAlignment)
169     {
170       int hgap = av.charHeight;
171       if (av.scaleAboveWrapped)
172       {
173         hgap += av.charHeight;
174       }
175
176       int cHeight = av.getAlignment().getHeight() * av.charHeight
177           + hgap + seqCanvas.getAnnotationHeight();
178
179       y -= hgap;
180
181       seq = Math.min( (y % cHeight) / av.getCharHeight(),
182                      av.alignment.getHeight() - 1);
183     }
184     else
185     {
186       seq = Math.min( (y / av.getCharHeight()) + av.getStartSeq(),
187                      av.alignment.getHeight() - 1);
188     }
189
190     return seq;
191   }
192
193   SequenceFeature[] findFeaturesAtRes(SequenceI sequence, int res)
194   {
195     Vector tmp = new Vector();
196     SequenceFeature[] features = sequence.getSequenceFeatures();
197     if (features != null)
198     {
199       for (int i = 0; i < features.length; i++)
200       {
201         if (av.featuresDisplayed == null
202             || !av.featuresDisplayed.containsKey(features[i].getType()))
203         {
204           continue;
205         }
206
207         if (features[i].featureGroup != null
208            && seqCanvas.fr.featureGroups!=null
209             && seqCanvas.fr.featureGroups.containsKey(features[i].featureGroup)
210             && !((Boolean)seqCanvas.fr.featureGroups.get(features[i].featureGroup)).booleanValue())
211           continue;
212
213
214         if ( (features[i].getBegin() <= res) &&
215             (features[i].getEnd() >= res))
216         {
217           tmp.addElement(features[i]);
218         }
219       }
220     }
221
222     features = new SequenceFeature[tmp.size()];
223     tmp.copyInto(features);
224
225     return features;
226   }
227
228
229   void endEditing()
230   {
231     if (editCommand != null && editCommand.getSize() > 0)
232     {
233       ap.alignFrame.addHistoryItem(editCommand);
234       av.firePropertyChange("alignment", null,
235                             av.getAlignment().getSequences());
236     }
237
238     startseq = -1;
239     lastres = -1;
240     editingSeqs = false;
241     groupEditing = false;
242     keyboardNo1 = null;
243     keyboardNo2 = null;
244     editCommand = null;
245   }
246
247   void setCursorRow()
248   {
249     seqCanvas.cursorY = getKeyboardNo1() - 1;
250     scrollToVisible();
251   }
252
253   void setCursorColumn()
254   {
255     seqCanvas.cursorX = getKeyboardNo1() - 1;
256     scrollToVisible();
257   }
258
259   void setCursorRowAndColumn()
260   {
261     if (keyboardNo2 == null)
262     {
263       keyboardNo2 = new StringBuffer();
264     }
265     else
266     {
267       seqCanvas.cursorX = getKeyboardNo1() - 1;
268       seqCanvas.cursorY = getKeyboardNo2() - 1;
269       scrollToVisible();
270     }
271   }
272
273   void setCursorPosition()
274   {
275     SequenceI sequence =
276         (Sequence) av.getAlignment().getSequenceAt(seqCanvas.cursorY);
277
278     seqCanvas.cursorX = sequence.findIndex(
279         getKeyboardNo1() - 1
280         );
281     scrollToVisible();
282   }
283
284   void moveCursor(int dx, int dy)
285   {
286     seqCanvas.cursorX += dx;
287     seqCanvas.cursorY += dy;
288     if (av.hasHiddenColumns && !av.colSel.isVisible(seqCanvas.cursorX))
289     {
290       int original = seqCanvas.cursorX - dx;
291       int maxWidth = av.alignment.getWidth();
292
293       while (!av.colSel.isVisible(seqCanvas.cursorX)
294              && seqCanvas.cursorX < maxWidth
295              && seqCanvas.cursorX > 0)
296       {
297         seqCanvas.cursorX += dx;
298       }
299
300       if (seqCanvas.cursorX >= maxWidth
301           || !av.colSel.isVisible(seqCanvas.cursorX))
302       {
303         seqCanvas.cursorX = original;
304       }
305     }
306
307     scrollToVisible();
308   }
309
310   void scrollToVisible()
311   {
312     if (seqCanvas.cursorX < 0)
313     {
314       seqCanvas.cursorX = 0;
315     }
316     else if (seqCanvas.cursorX > av.alignment.getWidth() - 1)
317     {
318       seqCanvas.cursorX = av.alignment.getWidth() - 1;
319     }
320
321     if (seqCanvas.cursorY < 0)
322     {
323       seqCanvas.cursorY = 0;
324     }
325     else if (seqCanvas.cursorY > av.alignment.getHeight() - 1)
326     {
327       seqCanvas.cursorY = av.alignment.getHeight() - 1;
328     }
329
330     endEditing();
331     if (av.wrapAlignment)
332     {
333       ap.scrollToWrappedVisible(seqCanvas.cursorX);
334     }
335     else
336     {
337       while (seqCanvas.cursorY < av.startSeq)
338       {
339         ap.scrollUp(true);
340       }
341       while (seqCanvas.cursorY + 1 > av.endSeq)
342       {
343         ap.scrollUp(false);
344       }
345       if (!av.wrapAlignment)
346       {
347         while (seqCanvas.cursorX < av.colSel.adjustForHiddenColumns(av.startRes))
348         {
349           if (!ap.scrollRight(false))
350           {
351             break;
352           }
353         }
354         while (seqCanvas.cursorX > av.colSel.adjustForHiddenColumns(av.endRes))
355         {
356           if (!ap.scrollRight(true))
357           {
358             break;
359           }
360         }
361       }
362     }
363     setStatusMessage(av.alignment.getSequenceAt(seqCanvas.cursorY),
364                      seqCanvas.cursorX, seqCanvas.cursorY);
365
366     seqCanvas.repaint();
367   }
368
369   void setSelectionAreaAtCursor(boolean topLeft)
370   {
371     SequenceI sequence =
372         (Sequence) av.getAlignment().getSequenceAt(seqCanvas.cursorY);
373
374     if (av.getSelectionGroup() != null)
375     {
376       SequenceGroup sg = av.selectionGroup;
377       //Find the top and bottom of this group
378       int min = av.alignment.getHeight(), max = 0;
379       for (int i = 0; i < sg.getSize(); i++)
380       {
381         int index = av.alignment.findIndex(sg.getSequenceAt(i));
382         if (index > max)
383         {
384           max = index;
385         }
386         if (index < min)
387         {
388           min = index;
389         }
390       }
391
392       max++;
393
394       if (topLeft)
395       {
396         sg.setStartRes(seqCanvas.cursorX);
397         if (sg.getEndRes() < seqCanvas.cursorX)
398         {
399           sg.setEndRes(seqCanvas.cursorX);
400         }
401
402         min = seqCanvas.cursorY;
403       }
404       else
405       {
406         sg.setEndRes(seqCanvas.cursorX);
407         if (sg.getStartRes() > seqCanvas.cursorX)
408         {
409           sg.setStartRes(seqCanvas.cursorX);
410         }
411
412         max = seqCanvas.cursorY + 1;
413       }
414
415       if (min > max)
416       {
417         // Only the user can do this
418         av.setSelectionGroup(null);
419       }
420       else
421       {
422         // Now add any sequences between min and max
423         sg.getSequences(null).clear();
424         for (int i = min; i < max; i++)
425         {
426           sg.addSequence(av.alignment.getSequenceAt(i), false);
427         }
428       }
429     }
430
431     if (av.getSelectionGroup() == null)
432     {
433       SequenceGroup sg = new SequenceGroup();
434       sg.setStartRes(seqCanvas.cursorX);
435       sg.setEndRes(seqCanvas.cursorX);
436       sg.addSequence(sequence, false);
437       av.setSelectionGroup(sg);
438     }
439
440     ap.paintAlignment(false);
441   }
442
443   void insertGapAtCursor(boolean group)
444   {
445     groupEditing = group;
446     startseq = seqCanvas.cursorY;
447     lastres = seqCanvas.cursorX;
448     editSequence(true, seqCanvas.cursorX + getKeyboardNo1());
449     endEditing();
450   }
451
452   void deleteGapAtCursor(boolean group)
453   {
454     groupEditing = group;
455     startseq = seqCanvas.cursorY;
456     lastres = seqCanvas.cursorX + getKeyboardNo1();
457     editSequence(false, seqCanvas.cursorX);
458     endEditing();
459   }
460
461   void numberPressed(char value)
462   {
463     if (keyboardNo1 == null)
464     {
465       keyboardNo1 = new StringBuffer();
466     }
467
468     if (keyboardNo2 != null)
469     {
470       keyboardNo2.append(value);
471     }
472     else
473     {
474       keyboardNo1.append(value);
475     }
476   }
477
478   int getKeyboardNo1()
479   {
480     if (keyboardNo1 == null)
481       return 1;
482     else
483     {
484       int value = Integer.parseInt(keyboardNo1.toString());
485       keyboardNo1 = null;
486       return value;
487     }
488   }
489
490   int getKeyboardNo2()
491   {
492     if (keyboardNo2 == null)
493       return 1;
494     else
495     {
496       int value = Integer.parseInt(keyboardNo2.toString());
497       keyboardNo2 = null;
498       return value;
499     }
500   }
501
502   /**
503    * DOCUMENT ME!
504    *
505    * @param evt DOCUMENT ME!
506    */
507   public void mouseReleased(MouseEvent evt)
508   {
509     mouseDragging = false;
510     mouseWheelPressed = false;
511
512     if (!editingSeqs)
513     {
514       doMouseReleasedDefineMode(evt);
515       return;
516     }
517
518     endEditing();
519   }
520
521   /**
522    * DOCUMENT ME!
523    *
524    * @param evt DOCUMENT ME!
525    */
526   public void mousePressed(MouseEvent evt)
527   {
528     lastMousePress = evt.getPoint();
529
530     if (javax.swing.SwingUtilities.isMiddleMouseButton(evt))
531     {
532       mouseWheelPressed = true;
533       return;
534     }
535
536     if (evt.isShiftDown() || evt.isAltDown() ||
537         evt.isControlDown())
538     {
539       if (evt.isAltDown() || evt.isControlDown())
540       {
541         groupEditing = true;
542       }
543       editingSeqs = true;
544     }
545     else
546     {
547       doMousePressedDefineMode(evt);
548       return;
549     }
550
551     int seq = findSeq(evt);
552     int res = findRes(evt);
553
554     if (seq < 0 || res < 0)
555     {
556       return;
557     }
558
559     if ( (seq < av.getAlignment().getHeight()) &&
560         (res < av.getAlignment().getSequenceAt(seq).getLength()))
561     {
562       startseq = seq;
563       lastres = res;
564     }
565     else
566     {
567       startseq = -1;
568       lastres = -1;
569     }
570
571     return;
572   }
573
574   String lastMessage;
575   public void mouseOverSequence(SequenceI sequence, int index, int pos)
576   {
577     String tmp = sequence.hashCode()+" "+index+" "+pos;
578     
579     if (lastMessage == null || !lastMessage.equals(tmp))
580     {
581       // System.err.println("mouseOver Sequence: "+tmp);
582       ssm.mouseOverSequence(sequence, index, pos);
583     }
584     lastMessage = tmp;
585   }
586
587
588   public void highlightSequence(SearchResults results)
589   {
590       seqCanvas.highlightSearchResults(results);
591   }
592
593   public void updateColours(SequenceI seq, int index)
594   {
595     System.out.println("update the seqPanel colours");
596     //repaint();
597   }
598
599   /**
600    * DOCUMENT ME!
601    *
602    * @param evt DOCUMENT ME!
603    */
604   public void mouseMoved(MouseEvent evt)
605   {
606     if (editingSeqs)
607     {
608       // This is because MacOSX creates a mouseMoved
609       // If control is down, other platforms will not.
610       mouseDragged(evt);
611     }
612
613     int res = findRes(evt);
614     int seq = findSeq(evt);
615     int pos;
616     if (res < 0 || seq < 0 || seq >= av.getAlignment().getHeight())
617     {
618       return;
619     }
620
621     SequenceI sequence = av.getAlignment().getSequenceAt(seq);
622
623     if (res >= sequence.getLength())
624     {
625       return;
626     }
627
628     pos = setStatusMessage(sequence, res, seq);
629     if (ssm != null && pos>-1)
630       mouseOverSequence(sequence, res, pos);
631
632
633     tooltipText.setLength(6); // Cuts the buffer back to <html>
634
635     SequenceGroup[] groups = av.alignment.findAllGroups(sequence);
636     if (groups != null)
637     {
638       for (int g = 0; g < groups.length; g++)
639       {
640         if (groups[g].getStartRes() <= res && groups[g].getEndRes() >= res)
641         {
642           if (tooltipText.length() > 6)
643           {
644             tooltipText.append("<br>");
645           }
646
647           if (!groups[g].getName().startsWith("JTreeGroup") &&
648               !groups[g].getName().startsWith("JGroup"))
649           {
650             tooltipText.append(groups[g].getName());
651           }
652
653           if (groups[g].getDescription() != null)
654           {
655             tooltipText.append(": " + groups[g].getDescription());
656           }
657         }
658       }
659     }
660
661     // use aa to see if the mouse pointer is on a
662     if (av.showSequenceFeatures)
663     {
664       SequenceFeature[] features = findFeaturesAtRes(
665           sequence.getDatasetSequence(), sequence.findPosition(res));
666
667       if (features != null)
668       {
669         for (int i = 0; i < features.length; i++)
670         {
671           if (features[i].getType().equals("disulfide bond"))
672           {
673             if (features[i].getBegin() == sequence.findPosition(res)
674                 || features[i].getEnd() == sequence.findPosition(res))
675             {
676               if (tooltipText.length() > 6)
677               {
678                 tooltipText.append("<br>");
679               }
680               tooltipText.append("disulfide bond " + features[i].getBegin() +
681                                  ":" +
682                                  features[i].getEnd());
683               if (features[i].links != null)
684               {
685                 tooltipText.append(" <img src=\"" + linkImageURL + "\">");
686               }
687             }
688           }
689           else
690           {
691             if (tooltipText.length() > 6)
692             {
693               tooltipText.append("<br>");
694             }
695
696             tooltipText.append(features[i].getType() + " " +
697                                features[i].begin);
698             if (features[i].begin != features[i].end)
699             {
700               tooltipText.append(" " + features[i].end);
701             }
702
703             if (features[i].getDescription() != null
704                 && !features[i].description.equals(features[i].getType()))
705             {
706               tmpString = features[i].getDescription();
707               int startTag = tmpString.toUpperCase().indexOf("<HTML>");
708               if (startTag > -1)
709               {
710                 tmpString = tmpString.substring(startTag + 6);
711               }
712               int endTag = tmpString.toUpperCase().indexOf("</BODY>");
713               if (endTag > -1)
714               {
715                 tmpString = tmpString.substring(0, endTag);
716               }
717               endTag = tmpString.toUpperCase().indexOf("</HTML>");
718               if (endTag > -1)
719               {
720                 tmpString = tmpString.substring(0, endTag);
721               }
722
723               if (startTag > -1)
724               {
725                 tooltipText.append("; " + tmpString);
726               }
727               else
728               {
729                 if (tmpString.indexOf("<") > -1 || tmpString.indexOf(">") > -1)
730                 {
731                   //The description does not specify html is to
732                   //be used, so we must remove < > symbols
733                   tmpString = tmpString.replaceAll("<", "&lt;");
734                   tmpString = tmpString.replaceAll(">", "&gt;");
735
736                   tooltipText.append("; ");
737                   tooltipText.append(tmpString);
738
739                 }
740                 else
741                 {
742                   tooltipText.append("; " + tmpString);
743                 }
744               }
745             }
746             if (features[i].getValue("status") != null)
747             {
748               String status = features[i].getValue("status").toString();
749               if (status.length() > 0)
750               {
751                 tooltipText.append("; (" + features[i].getValue("status") + ")");
752               }
753             }
754
755             if (features[i].links != null)
756             {
757               tooltipText.append(" <img src=\"" + linkImageURL + "\">");
758             }
759
760           }
761         }
762       }
763     }
764
765     if (tooltipText.length() == 6) // <html></html>
766     {
767       setToolTipText(null);
768     }
769     else
770     {
771       tooltipText.append("</html>");
772       if (lastTooltip == null || !lastTooltip.equals(tooltipText.toString()))
773         setToolTipText(tooltipText.toString());
774
775       lastTooltip = tooltipText.toString();
776     }
777
778   }
779   String lastTooltip;
780
781   /**
782    * Set status message in alignment panel
783    * @param sequence aligned sequence object
784    * @param res alignment column
785    * @param seq index of sequence in alignment
786    * @return position of res in sequence
787    */
788   int setStatusMessage(SequenceI sequence, int res, int seq)
789   {
790     int pos=-1;
791     StringBuffer text = new StringBuffer("Sequence " + (seq + 1) + " ID: " +
792                                          sequence.getName());
793
794     Object obj = null;
795     if (av.alignment.isNucleotide())
796     {
797       obj = ResidueProperties.nucleotideName.get(sequence.getCharAt(res) +
798                                                  "");
799       if (obj != null)
800       {
801         text.append(" Nucleotide: ");
802       }
803     }
804     else
805     {
806       obj = ResidueProperties.aa2Triplet.get(sequence.getCharAt(res) + "");
807       if (obj != null)
808       {
809         text.append("  Residue: ");
810       }
811     }
812
813     if (obj != null)
814     {
815       pos=sequence.findPosition(res);
816       if (obj != "")
817       {
818         text.append(obj + " (" + pos +
819                     ")");
820       }
821     }
822     ap.alignFrame.statusBar.setText(text.toString());
823     return pos;
824   }
825
826   /**
827    * DOCUMENT ME!
828    *
829    * @param evt DOCUMENT ME!
830    */
831   public void mouseDragged(MouseEvent evt)
832   {
833     if (mouseWheelPressed)
834     {
835       int oldWidth = av.charWidth;
836
837       //Which is bigger, left-right or up-down?
838       if (Math.abs(evt.getY() - lastMousePress.getY())
839           > Math.abs(evt.getX() - lastMousePress.getX()))
840       {
841         int fontSize = av.font.getSize();
842
843         if (evt.getY() < lastMousePress.getY())
844         {
845           fontSize--;
846         }
847         else if (evt.getY() > lastMousePress.getY())
848         {
849           fontSize++;
850         }
851
852         if (fontSize < 1)
853         {
854           fontSize = 1;
855         }
856
857         av.setFont(new Font(av.font.getName(), av.font.getStyle(), fontSize));
858         av.charWidth = oldWidth;
859         ap.fontChanged();
860       }
861       else
862       {
863         if (evt.getX() < lastMousePress.getX() && av.charWidth > 1)
864         {
865           av.charWidth--;
866         }
867         else if (evt.getX() > lastMousePress.getX())
868         {
869           av.charWidth++;
870         }
871
872         ap.paintAlignment(false);
873       }
874
875       FontMetrics fm = getFontMetrics(av.getFont());
876       av.validCharWidth = fm.charWidth('M') <= av.charWidth;
877
878       lastMousePress = evt.getPoint();
879
880       return;
881     }
882
883     if (!editingSeqs)
884     {
885       doMouseDraggedDefineMode(evt);
886       return;
887     }
888
889     int res = findRes(evt);
890
891     if (res < 0)
892     {
893       res = 0;
894     }
895
896     if ( (lastres == -1) || (lastres == res))
897     {
898       return;
899     }
900
901     if ( (res < av.getAlignment().getWidth()) && (res < lastres))
902     {
903       // dragLeft, delete gap
904       editSequence(false, res);
905     }
906     else
907     {
908       editSequence(true, res);
909     }
910
911     mouseDragging = true;
912     if (scrollThread != null)
913     {
914       scrollThread.setEvent(evt);
915     }
916   }
917
918
919
920   synchronized void editSequence(boolean insertGap, int startres)
921   {
922     int fixedLeft = -1;
923     int fixedRight = -1;
924     boolean fixedColumns = false;
925     SequenceGroup sg = av.getSelectionGroup();
926
927     SequenceI seq = av.alignment.getSequenceAt(startseq);
928
929     //No group, but the sequence may represent a group
930     if (!groupEditing && av.hasHiddenRows)
931     {
932       if (av.hiddenRepSequences != null
933           && av.hiddenRepSequences.containsKey(seq))
934       {
935         sg = (SequenceGroup) av.hiddenRepSequences.get(seq);
936         groupEditing = true;
937       }
938     }
939
940     StringBuffer message = new StringBuffer();
941     if (groupEditing)
942     {
943       message.append("Edit group:");
944       if (editCommand == null)
945       {
946         editCommand = new EditCommand("Edit Group");
947       }
948     }
949     else
950     {
951       message.append("Edit sequence: " + seq.getName());
952       String label = seq.getName();
953       if (label.length() > 10)
954       {
955         label = label.substring(0, 10);
956       }
957       if (editCommand == null)
958       {
959         editCommand = new EditCommand("Edit " + label);
960       }
961     }
962
963     if (insertGap)
964     {
965       message.append(" insert ");
966     }
967     else
968     {
969       message.append(" delete ");
970     }
971
972     message.append(Math.abs(startres - lastres) + " gaps.");
973     ap.alignFrame.statusBar.setText(message.toString());
974
975     //Are we editing within a selection group?
976     if (groupEditing
977         || (sg != null && sg.getSequences(av.hiddenRepSequences).contains(seq)))
978     {
979       fixedColumns = true;
980
981       //sg might be null as the user may only see 1 sequence,
982       //but the sequence represents a group
983       if (sg == null)
984       {
985         if (av.hiddenRepSequences == null
986             || !av.hiddenRepSequences.containsKey(seq))
987         {
988           endEditing();
989           return;
990         }
991         sg = (SequenceGroup) av.hiddenRepSequences.get(seq);
992       }
993
994       fixedLeft = sg.getStartRes();
995       fixedRight = sg.getEndRes();
996
997       if ( (startres < fixedLeft && lastres >= fixedLeft)
998           || (startres >= fixedLeft && lastres < fixedLeft)
999           || (startres > fixedRight && lastres <= fixedRight)
1000           || (startres <= fixedRight && lastres > fixedRight))
1001       {
1002         endEditing();
1003         return;
1004       }
1005
1006       if (fixedLeft > startres)
1007       {
1008         fixedRight = fixedLeft - 1;
1009         fixedLeft = 0;
1010       }
1011       else if (fixedRight < startres)
1012       {
1013         fixedLeft = fixedRight;
1014         fixedRight = -1;
1015       }
1016     }
1017
1018     if (av.hasHiddenColumns)
1019     {
1020       fixedColumns = true;
1021       int y1 = av.getColumnSelection().getHiddenBoundaryLeft(startres);
1022       int y2 = av.getColumnSelection().getHiddenBoundaryRight(startres);
1023
1024       if ( (insertGap && startres > y1 && lastres < y1)
1025           || (!insertGap && startres < y2 && lastres > y2))
1026       {
1027         endEditing();
1028         return;
1029       }
1030
1031       //System.out.print(y1+" "+y2+" "+fixedLeft+" "+fixedRight+"~~");
1032       //Selection spans a hidden region
1033       if (fixedLeft < y1 && (fixedRight > y2 || fixedRight == -1))
1034       {
1035         if (startres >= y2)
1036         {
1037           fixedLeft = y2;
1038         }
1039         else
1040         {
1041           fixedRight = y2 - 1;
1042         }
1043       }
1044     }
1045
1046     if (groupEditing)
1047     {
1048       Vector vseqs = sg.getSequences(av.hiddenRepSequences);
1049       int g, groupSize = vseqs.size();
1050       SequenceI[] groupSeqs = new SequenceI[groupSize];
1051       for (g = 0; g < groupSeqs.length; g++)
1052       {
1053         groupSeqs[g] = (SequenceI) vseqs.elementAt(g);
1054       }
1055
1056       // drag to right
1057       if (insertGap)
1058       {
1059         //If the user has selected the whole sequence, and is dragging to
1060         // the right, we can still extend the alignment and selectionGroup
1061         if (sg.getStartRes() == 0
1062             && sg.getEndRes() == fixedRight
1063             && sg.getEndRes() == av.alignment.getWidth() - 1
1064             )
1065         {
1066           sg.setEndRes(av.alignment.getWidth() + startres - lastres);
1067           fixedRight = sg.getEndRes();
1068         }
1069
1070         // Is it valid with fixed columns??
1071         // Find the next gap before the end
1072         // of the visible region boundary
1073         boolean blank = false;
1074         for (fixedRight = fixedRight;
1075              fixedRight > lastres;
1076              fixedRight--)
1077         {
1078           blank = true;
1079
1080           for (g = 0; g < groupSize; g++)
1081           {
1082             for (int j = 0; j < startres - lastres; j++)
1083             {
1084               if (!jalview.util.Comparison.isGap(
1085                   groupSeqs[g].getCharAt(fixedRight - j)))
1086               {
1087                 blank = false;
1088                 break;
1089               }
1090             }
1091           }
1092           if (blank)
1093           {
1094             break;
1095           }
1096         }
1097
1098         if (!blank)
1099         {
1100           if (sg.getSize() == av.alignment.getHeight())
1101           {
1102             if ( (av.hasHiddenColumns
1103                   &&
1104                   startres < av.getColumnSelection().getHiddenBoundaryRight(startres)))
1105             {
1106               endEditing();
1107               return;
1108             }
1109
1110             int alWidth = av.alignment.getWidth();
1111             if (av.hasHiddenRows)
1112             {
1113               int hwidth = av.alignment.getHiddenSequences().getWidth();
1114               if (hwidth > alWidth)
1115               {
1116                 alWidth = hwidth;
1117               }
1118             }
1119             //We can still insert gaps if the selectionGroup
1120             //contains all the sequences
1121             sg.setEndRes(sg.getEndRes() + startres - lastres);
1122             fixedRight = alWidth + startres - lastres;
1123           }
1124           else
1125           {
1126             endEditing();
1127             return;
1128           }
1129         }
1130       }
1131
1132       // drag to left
1133       else if (!insertGap)
1134       {
1135         /// Are we able to delete?
1136         // ie are all columns blank?
1137
1138         for (g = 0; g < groupSize; g++)
1139         {
1140           for (int j = startres; j < lastres; j++)
1141           {
1142             if (groupSeqs[g].getLength() <= j)
1143             {
1144               continue;
1145             }
1146
1147             if (!jalview.util.Comparison.isGap(
1148                 groupSeqs[g].getCharAt(j)))
1149             {
1150               // Not a gap, block edit not valid
1151               endEditing();
1152               return;
1153             }
1154           }
1155         }
1156       }
1157
1158       if (insertGap)
1159       {
1160         // dragging to the right
1161         if (fixedColumns && fixedRight != -1)
1162         {
1163           for (int j = lastres; j < startres; j++)
1164           {
1165             insertChar(j, groupSeqs, fixedRight);
1166           }
1167         }
1168         else
1169         {
1170           editCommand.appendEdit(EditCommand.INSERT_GAP,
1171                                  groupSeqs,
1172                                  startres, startres - lastres,
1173                                  av.alignment,
1174                                  true);
1175         }
1176       }
1177       else
1178       {
1179         // dragging to the left
1180         if (fixedColumns && fixedRight != -1)
1181         {
1182           for (int j = lastres; j > startres; j--)
1183           {
1184             deleteChar(startres, groupSeqs, fixedRight);
1185           }
1186         }
1187         else
1188         {
1189           editCommand.appendEdit(EditCommand.DELETE_GAP,
1190                                  groupSeqs,
1191                                  startres, lastres - startres,
1192                                  av.alignment,
1193                                  true);
1194         }
1195
1196       }
1197     }
1198     else /////Editing a single sequence///////////
1199     {
1200       if (insertGap)
1201       {
1202         // dragging to the right
1203         if (fixedColumns && fixedRight != -1)
1204         {
1205           for (int j = lastres; j < startres; j++)
1206           {
1207             insertChar(j, new SequenceI[]
1208                        {seq}, fixedRight);
1209           }
1210         }
1211         else
1212         {
1213           editCommand.appendEdit(EditCommand.INSERT_GAP,
1214                                  new SequenceI[]
1215                                  {seq},
1216                                  lastres, startres - lastres,
1217                                  av.alignment,
1218                                  true);
1219         }
1220       }
1221       else
1222       {
1223         // dragging to the left
1224         if (fixedColumns && fixedRight != -1)
1225         {
1226           for (int j = lastres; j > startres; j--)
1227           {
1228             if (!jalview.util.Comparison.isGap(seq.getCharAt(startres)))
1229             {
1230               endEditing();
1231               break;
1232             }
1233             deleteChar(startres, new SequenceI[]
1234                        {seq}, fixedRight);
1235           }
1236         }
1237         else
1238         {
1239           //could be a keyboard edit trying to delete none gaps
1240           int max = 0;
1241           for (int m = startres; m < lastres; m++)
1242           {
1243             if (!jalview.util.Comparison.isGap(seq.getCharAt(m)))
1244             {
1245               break;
1246             }
1247             max++;
1248           }
1249
1250           if (max > 0)
1251           {
1252             editCommand.appendEdit(EditCommand.DELETE_GAP,
1253                                    new SequenceI[]
1254                                    {seq},
1255                                    startres, max,
1256                                    av.alignment,
1257                                    true);
1258           }
1259         }
1260       }
1261     }
1262
1263     lastres = startres;
1264     seqCanvas.repaint();
1265   }
1266
1267   void insertChar(int j, SequenceI[] seq, int fixedColumn)
1268   {
1269     int blankColumn = fixedColumn;
1270     for (int s = 0; s < seq.length; s++)
1271     {
1272       //Find the next gap before the end of the visible region boundary
1273       //If lastCol > j, theres a boundary after the gap insertion
1274
1275       for (blankColumn = fixedColumn; blankColumn > j; blankColumn--)
1276       {
1277         if (jalview.util.Comparison.isGap(seq[s].getCharAt(blankColumn)))
1278         {
1279           //Theres a space, so break and insert the gap
1280           break;
1281         }
1282       }
1283
1284       if (blankColumn <= j)
1285       {
1286         blankColumn = fixedColumn;
1287         endEditing();
1288         return;
1289       }
1290     }
1291
1292     editCommand.appendEdit(EditCommand.DELETE_GAP,
1293                            seq,
1294                            blankColumn, 1, av.alignment, true);
1295
1296     editCommand.appendEdit(EditCommand.INSERT_GAP,
1297                            seq,
1298                            j, 1, av.alignment,
1299                            true);
1300
1301   }
1302
1303   void deleteChar(int j, SequenceI[] seq, int fixedColumn)
1304   {
1305
1306     editCommand.appendEdit(EditCommand.DELETE_GAP,
1307                            seq,
1308                            j, 1, av.alignment, true);
1309
1310     editCommand.appendEdit(EditCommand.INSERT_GAP,
1311                            seq,
1312                            fixedColumn, 1, av.alignment, true);
1313   }
1314
1315   /**
1316    * DOCUMENT ME!
1317    *
1318    * @param e DOCUMENT ME!
1319    */
1320   public void mouseEntered(MouseEvent e)
1321   {
1322     if (oldSeq < 0)
1323     {
1324       oldSeq = 0;
1325     }
1326
1327     if (scrollThread != null)
1328     {
1329       scrollThread.running = false;
1330       scrollThread = null;
1331     }
1332   }
1333
1334   /**
1335    * DOCUMENT ME!
1336    *
1337    * @param e DOCUMENT ME!
1338    */
1339   public void mouseExited(MouseEvent e)
1340   {
1341     if (av.getWrapAlignment())
1342     {
1343       return;
1344     }
1345
1346     if (mouseDragging)
1347     {
1348       scrollThread = new ScrollThread();
1349     }
1350   }
1351
1352   public void mouseClicked(MouseEvent evt)
1353   {
1354     SequenceI sequence = av.alignment.getSequenceAt(findSeq(evt));
1355     if (evt.getClickCount() > 1)
1356     {
1357       if (av.getSelectionGroup().getSize() == 1
1358           && av.getSelectionGroup().getEndRes()
1359           - av.getSelectionGroup().getStartRes() < 2)
1360       {
1361         av.setSelectionGroup(null);
1362       }
1363
1364       SequenceFeature[] features = findFeaturesAtRes(
1365           sequence.getDatasetSequence(),
1366           sequence.findPosition(findRes(evt))
1367           );
1368
1369       if (features != null && features.length > 0)
1370       {
1371         SearchResults highlight = new SearchResults();
1372         highlight.addResult(sequence,
1373                             features[0].getBegin(),
1374                             features[0].getEnd());
1375         seqCanvas.highlightSearchResults(highlight);
1376       }
1377       if (features != null && features.length > 0)
1378       {
1379         seqCanvas.getFeatureRenderer().amendFeatures(
1380             new SequenceI[]
1381             {sequence}, features, false, ap);
1382
1383         seqCanvas.highlightSearchResults(null);
1384       }
1385     }
1386   }
1387
1388   public void mouseWheelMoved(MouseWheelEvent e)
1389   {
1390     e.consume();
1391       if (e.getWheelRotation() > 0)
1392       {
1393         ap.scrollUp(false);
1394       }
1395       else
1396       {
1397         ap.scrollUp(true);
1398       }
1399   }
1400
1401   /**
1402    * DOCUMENT ME!
1403    *
1404    * @param evt DOCUMENT ME!
1405    */
1406   public void doMousePressedDefineMode(MouseEvent evt)
1407   {
1408     int res = findRes(evt);
1409     int seq = findSeq(evt);
1410     oldSeq = seq;
1411
1412     startWrapBlock = wrappedBlock;
1413
1414     if (av.wrapAlignment && seq > av.alignment.getHeight())
1415     {
1416       JOptionPane.showInternalMessageDialog(Desktop.desktop,
1417                                             "Cannot edit annotations in wrapped view.",
1418                                             "Wrapped view - no edit",
1419                                             JOptionPane.WARNING_MESSAGE);
1420       return;
1421     }
1422
1423     if (seq < 0 || res < 0)
1424     {
1425       return;
1426     }
1427
1428     SequenceI sequence = (Sequence) av.getAlignment().getSequenceAt(seq);
1429
1430     if ( (sequence == null) || (res > sequence.getLength()))
1431     {
1432       return;
1433     }
1434
1435     stretchGroup = av.getSelectionGroup();
1436
1437     if (stretchGroup == null)
1438     {
1439       stretchGroup = av.alignment.findGroup(sequence);
1440
1441       if ( (stretchGroup != null) && (res > stretchGroup.getStartRes()) &&
1442           (res < stretchGroup.getEndRes()))
1443       {
1444         av.setSelectionGroup(stretchGroup);
1445       }
1446       else
1447       {
1448         stretchGroup = null;
1449       }
1450     }
1451     else if (!stretchGroup.getSequences(null).contains(sequence) ||
1452              (stretchGroup.getStartRes() > res) ||
1453              (stretchGroup.getEndRes() < res))
1454     {
1455       stretchGroup = null;
1456
1457       SequenceGroup[] allGroups = av.alignment.findAllGroups(sequence);
1458
1459       if (allGroups != null)
1460       {
1461         for (int i = 0; i < allGroups.length; i++)
1462         {
1463           if ( (allGroups[i].getStartRes() <= res) &&
1464               (allGroups[i].getEndRes() >= res))
1465           {
1466             stretchGroup = allGroups[i];
1467             break;
1468           }
1469         }
1470       }
1471
1472       av.setSelectionGroup(stretchGroup);
1473
1474     }
1475
1476     if (javax.swing.SwingUtilities.isRightMouseButton(evt))
1477     {
1478       SequenceFeature [] allFeatures = findFeaturesAtRes(sequence.getDatasetSequence(),
1479                                                sequence.findPosition(res));
1480       Vector links = new Vector();
1481       for (int i = 0; i < allFeatures.length; i++)
1482       {
1483         if (allFeatures[i].links != null)
1484         {
1485           for (int j = 0; j < allFeatures[i].links.size(); j++)
1486           {
1487             links.addElement(allFeatures[i].links.elementAt(j));
1488           }
1489         }
1490       }
1491
1492       jalview.gui.PopupMenu pop = new jalview.gui.PopupMenu(ap, null, links);
1493       pop.show(this, evt.getX(), evt.getY());
1494       return;
1495     }
1496
1497     if (av.cursorMode)
1498     {
1499       seqCanvas.cursorX = findRes(evt);
1500       seqCanvas.cursorY = findSeq(evt);
1501       seqCanvas.repaint();
1502       return;
1503     }
1504
1505     if (stretchGroup == null)
1506     {
1507       //Only if left mouse button do we want to change group sizes
1508
1509       // define a new group here
1510       SequenceGroup sg = new SequenceGroup();
1511       sg.setStartRes(res);
1512       sg.setEndRes(res);
1513       sg.addSequence(sequence, false);
1514       av.setSelectionGroup(sg);
1515       stretchGroup = sg;
1516
1517       if (av.getConservationSelected())
1518       {
1519         SliderPanel.setConservationSlider(ap,
1520                                           av.getGlobalColourScheme(),
1521                                           "Background");
1522       }
1523
1524       if (av.getAbovePIDThreshold())
1525       {
1526         SliderPanel.setPIDSliderSource(ap, av.getGlobalColourScheme(),
1527                                        "Background");
1528       }
1529       if ( (stretchGroup != null) && (stretchGroup.getEndRes() == res))
1530       {
1531         // Edit end res position of selected group
1532         changeEndRes = true;
1533       }
1534       else if ( (stretchGroup != null) &&
1535                (stretchGroup.getStartRes() == res))
1536       {
1537         // Edit end res position of selected group
1538         changeStartRes = true;
1539       }
1540       stretchGroup.getWidth();
1541     }
1542
1543     seqCanvas.repaint();
1544   }
1545
1546   /**
1547    * DOCUMENT ME!
1548    *
1549    * @param evt DOCUMENT ME!
1550    */
1551   public void doMouseReleasedDefineMode(MouseEvent evt)
1552   {
1553     if (stretchGroup == null)
1554     {
1555       return;
1556     }
1557
1558     if (stretchGroup.cs != null)
1559     {
1560       if (stretchGroup.cs instanceof ClustalxColourScheme)
1561       {
1562         ( (ClustalxColourScheme) stretchGroup.cs).resetClustalX(
1563             stretchGroup.getSequences(av.hiddenRepSequences),
1564             stretchGroup.getWidth());
1565       }
1566
1567       if (stretchGroup.cs instanceof Blosum62ColourScheme
1568           || stretchGroup.cs instanceof PIDColourScheme
1569           || stretchGroup.cs.conservationApplied()
1570           || stretchGroup.cs.getThreshold() > 0)
1571       {
1572         stretchGroup.recalcConservation();
1573       }
1574
1575       if (stretchGroup.cs.conservationApplied())
1576       {
1577         SliderPanel.setConservationSlider(ap, stretchGroup.cs,
1578                                           stretchGroup.getName());
1579       }
1580       else
1581       {
1582         SliderPanel.setPIDSliderSource(ap, stretchGroup.cs,
1583                                        stretchGroup.getName());
1584       }
1585       PaintRefresher.Refresh(this, av.getSequenceSetId());
1586       ap.paintAlignment(true);
1587     }
1588
1589     changeEndRes = false;
1590     changeStartRes = false;
1591     stretchGroup = null;
1592
1593   }
1594
1595   /**
1596    * DOCUMENT ME!
1597    *
1598    * @param evt DOCUMENT ME!
1599    */
1600   public void doMouseDraggedDefineMode(MouseEvent evt)
1601   {
1602     int res = findRes(evt);
1603     int y = findSeq(evt);
1604
1605     if (wrappedBlock != startWrapBlock)
1606     {
1607       return;
1608     }
1609
1610     if (stretchGroup == null)
1611     {
1612       return;
1613     }
1614
1615     if (res >= av.alignment.getWidth())
1616     {
1617       res = av.alignment.getWidth() - 1;
1618     }
1619
1620     if (stretchGroup.getEndRes() == res)
1621     {
1622       // Edit end res position of selected group
1623       changeEndRes = true;
1624     }
1625     else if (stretchGroup.getStartRes() == res)
1626     {
1627       // Edit start res position of selected group
1628       changeStartRes = true;
1629     }
1630
1631     if (res < av.getStartRes())
1632     {
1633       res = av.getStartRes();
1634     }
1635
1636     if (changeEndRes)
1637     {
1638       if (res > (stretchGroup.getStartRes() - 1))
1639       {
1640         stretchGroup.setEndRes(res);
1641       }
1642     }
1643     else if (changeStartRes)
1644     {
1645       if (res < (stretchGroup.getEndRes() + 1))
1646       {
1647         stretchGroup.setStartRes(res);
1648       }
1649     }
1650
1651     int dragDirection = 0;
1652
1653     if (y > oldSeq)
1654     {
1655       dragDirection = 1;
1656     }
1657     else if (y < oldSeq)
1658     {
1659       dragDirection = -1;
1660     }
1661
1662     while ( (y != oldSeq) && (oldSeq > -1) && (y < av.alignment.getHeight()))
1663     {
1664       // This routine ensures we don't skip any sequences, as the
1665       // selection is quite slow.
1666       Sequence seq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1667
1668       oldSeq += dragDirection;
1669
1670       if (oldSeq < 0)
1671       {
1672         break;
1673       }
1674
1675       Sequence nextSeq = (Sequence) av.getAlignment().getSequenceAt(oldSeq);
1676
1677       if (stretchGroup.getSequences(null).contains(nextSeq))
1678       {
1679         stretchGroup.deleteSequence(seq, false);
1680       }
1681       else
1682       {
1683         if (seq != null)
1684         {
1685           stretchGroup.addSequence(seq, false);
1686         }
1687
1688         stretchGroup.addSequence(nextSeq, false);
1689       }
1690     }
1691
1692     if (oldSeq < 0)
1693     {
1694       oldSeq = -1;
1695     }
1696
1697     mouseDragging = true;
1698
1699     if (scrollThread != null)
1700     {
1701       scrollThread.setEvent(evt);
1702     }
1703
1704     seqCanvas.repaint();
1705   }
1706
1707   void scrollCanvas(MouseEvent evt)
1708   {
1709     if (evt == null)
1710     {
1711       if (scrollThread != null)
1712       {
1713         scrollThread.running = false;
1714         scrollThread = null;
1715       }
1716       mouseDragging = false;
1717     }
1718     else
1719     {
1720       if (scrollThread == null)
1721       {
1722         scrollThread = new ScrollThread();
1723       }
1724
1725       mouseDragging = true;
1726       scrollThread.setEvent(evt);
1727     }
1728
1729   }
1730
1731   // this class allows scrolling off the bottom of the visible alignment
1732   class ScrollThread
1733       extends Thread
1734   {
1735     MouseEvent evt;
1736     boolean running = false;
1737
1738     public ScrollThread()
1739     {
1740       start();
1741     }
1742
1743     public void setEvent(MouseEvent e)
1744     {
1745       evt = e;
1746     }
1747
1748     public void stopScrolling()
1749     {
1750       running = false;
1751     }
1752
1753     public void run()
1754     {
1755       running = true;
1756
1757       while (running)
1758       {
1759         if (evt != null)
1760         {
1761           if (mouseDragging && (evt.getY() < 0) &&
1762               (av.getStartSeq() > 0))
1763           {
1764             running = ap.scrollUp(true);
1765           }
1766
1767           if (mouseDragging && (evt.getY() >= getHeight()) &&
1768               (av.alignment.getHeight() > av.getEndSeq()))
1769           {
1770             running = ap.scrollUp(false);
1771           }
1772
1773           if (mouseDragging && (evt.getX() < 0))
1774           {
1775             running = ap.scrollRight(false);
1776           }
1777           else if (mouseDragging && (evt.getX() >= getWidth()))
1778           {
1779             running = ap.scrollRight(true);
1780           }
1781         }
1782
1783         try
1784         {
1785           Thread.sleep(20);
1786         }
1787         catch (Exception ex)
1788         {
1789         }
1790       }
1791     }
1792   }
1793 }