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