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