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