refactored do and undo() method to take array of alignments for operations that resul...
[jalview.git] / src / jalview / commands / EditCommand.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.commands;
20
21 import java.util.*;
22
23 import jalview.datamodel.*;
24
25 /**
26  *
27  * <p>Title: EditCommmand</p>
28  *
29  * <p>Description: Essential information for performing
30  * undo and redo for cut/paste insert/delete gap
31  * which can be stored in the HistoryList </p>
32  *
33  * <p>Copyright: Copyright (c) 2006</p>
34  *
35  * <p>Company: Dundee University</p>
36  *
37  * @author not attributable
38  * @version 1.0
39  */
40 public class EditCommand
41     implements CommandI
42 {
43   public static final int INSERT_GAP = 0;
44   public static final int DELETE_GAP = 1;
45   public static final int CUT = 2;
46   public static final int PASTE = 3;
47   public static final int REPLACE = 4;
48
49   Edit[] edits;
50
51   String description;
52
53   public EditCommand()
54   {}
55
56   public EditCommand(String description)
57   {
58     this.description = description;
59   }
60
61   public EditCommand(String description,
62                      int command,
63                      SequenceI[] seqs,
64                      int position,
65                      int number,
66                      AlignmentI al)
67   {
68     this.description = description;
69     if (command == CUT || command == PASTE)
70     {
71       edits = new Edit[]
72           {
73           new Edit(command, seqs, position, number, al)};
74     }
75
76     performEdit(0, null);
77   }
78
79   public EditCommand(String description,
80                      int command,
81                      String replace,
82                      SequenceI[] seqs,
83                      int position,
84                      int number,
85                      AlignmentI al)
86   {
87     this.description = description;
88     if (command == REPLACE)
89     {
90       edits = new Edit[]
91           { new Edit(command, seqs, position, number, al, replace)};
92     }
93
94     performEdit(0, null);
95   }
96
97   final public String getDescription()
98   {
99     return description;
100   }
101
102   public int getSize()
103   {
104     return edits == null ? 0 : edits.length;
105   }
106
107   final public AlignmentI getAlignment()
108   {
109     return edits[0].al;
110   }
111
112   /**
113    * append a new editCommand
114    * Note. this shouldn't be called if the edit is an operation affects more alignment objects than the one referenced
115    * in al (for example, cut or pasting whole sequences). Use the form with an additional AlignmentI[] views parameter. 
116    * @param command
117    * @param seqs
118    * @param position
119    * @param number
120    * @param al
121    * @param performEdit
122    */
123   final public void appendEdit(int command,
124           SequenceI[] seqs,
125           int position,
126           int number,
127           AlignmentI al,
128           boolean performEdit)
129   {
130     appendEdit(command, seqs, position, number, al, performEdit, null);
131   }
132   /**
133    * append a new edit command with a set of alignment views that may be operated on
134    * @param command
135    * @param seqs
136    * @param position
137    * @param number
138    * @param al
139    * @param performEdit
140    * @param views
141    */
142   final public void appendEdit(int command,
143                                SequenceI[] seqs,
144                                int position,
145                                int number,
146                                AlignmentI al,
147                                boolean performEdit, AlignmentI[] views)
148   {
149     Edit edit = new Edit(command, seqs, position, number, al.getGapCharacter());
150     if (al.getHeight() == seqs.length)
151     {
152       edit.al = al;
153       edit.fullAlignmentHeight = true;
154     }
155
156     if (edits != null)
157     {
158       Edit[] temp = new Edit[edits.length + 1];
159       System.arraycopy(edits, 0, temp, 0, edits.length);
160       edits = temp;
161       edits[edits.length - 1] = edit;
162     }
163     else
164     {
165       edits = new Edit[]
166           {
167           edit};
168     }
169
170     if (performEdit)
171     {
172       performEdit(edits.length - 1, views);
173     }
174   }
175
176   final void performEdit(int commandIndex, AlignmentI[] views)
177   {
178     int eSize = edits.length;
179     for (int e = commandIndex; e < eSize; e++)
180     {
181       switch(edits[e].command)
182       {
183         case INSERT_GAP:
184         insertGap(edits[e]);
185           break;
186         case DELETE_GAP:
187         deleteGap(edits[e]);
188           break;
189         case CUT:
190         cut(edits[e], views);
191           break;
192         case PASTE:
193         paste(edits[e], views);
194           break;
195         case REPLACE:
196           replace(edits[e]);
197           break;
198       }
199     }
200   }
201
202   final public void doCommand(AlignmentI[] views)
203   {
204     performEdit(0,views);
205   }
206
207   final public void undoCommand(AlignmentI[] views)
208   {
209     int e = 0, eSize = edits.length;
210     for (e = eSize - 1; e > -1; e--)
211     {
212       switch (edits[e].command)
213       {
214         case INSERT_GAP:
215         deleteGap(edits[e]);
216           break;
217         case DELETE_GAP:
218         insertGap(edits[e]);
219           break;
220         case CUT:
221         paste(edits[e], views);
222           break;
223         case PASTE:
224         cut(edits[e], views);
225           break;
226         case REPLACE:
227           replace(edits[e]);
228           break;
229       }
230     }
231   }
232
233   final void insertGap(Edit command)
234   {
235     for (int s = 0; s < command.seqs.length; s++)
236     {
237       command.seqs[s].insertCharAt(command.position,
238                                    command.number,
239                                    command.gapChar);
240     }
241
242     adjustAnnotations(command, true, false, null);
243   }
244
245   final void deleteGap(Edit command)
246   {
247     for (int s = 0; s < command.seqs.length; s++)
248     {
249       command.seqs[s].deleteChars(command.position,
250                                   command.position + command.number);
251     }
252
253     adjustAnnotations(command, false, false, null);
254   }
255
256   void cut(Edit command, AlignmentI[] views)
257   {
258     boolean seqDeleted=false;
259     command.string = new char[command.seqs.length][];
260
261     for (int i = 0; i < command.seqs.length; i++)
262     {
263       if (command.seqs[i].getLength() > command.position)
264       {
265         command.string[i] = command.seqs[i].getSequence(command.position,
266             command.position + command.number);
267
268         if (command.seqs[i].getDatasetSequence() != null
269             || command.seqs[i].getSequenceFeatures() != null)
270         {
271           for (int s = command.position; s < command.position + command.number;
272                s++)
273           {
274             if (jalview.schemes.ResidueProperties
275                 .aaIndex[command.seqs[i].getCharAt(s)] != 23)
276             {
277               adjustFeatures(command, i,
278                              command.seqs[i].findPosition(command.position),
279                              command.seqs[i].findPosition(command.position +
280                   command.number),
281                              false);
282               break;
283             }
284           }
285         }
286         command.seqs[i].deleteChars(command.position,
287                                     command.position + command.number);
288       }
289
290       if (command.seqs[i].getLength() < 1)
291       {
292         command.al.deleteSequence(command.seqs[i]);
293         seqDeleted=true;
294       }
295     }
296
297     adjustAnnotations(command, false, seqDeleted, views);
298   }
299
300   void paste(Edit command, AlignmentI[] views)
301   {
302     StringBuffer tmp;
303     boolean newDSNeeded;
304     boolean seqWasDeleted=false;
305     int start = 0, end = 0;
306
307     for (int i = 0; i < command.seqs.length; i++)
308     {
309       newDSNeeded = false;
310       if (command.seqs[i].getLength() < 1)
311       {
312         // ie this sequence was deleted, we need to
313         // read it to the alignment
314         if (command.alIndex[i] < command.al.getHeight())
315         {
316           command.al.getSequences().insertElementAt(command.seqs[i],
317               command.alIndex[i]);
318         }
319         else
320         {
321           command.al.addSequence(command.seqs[i]);
322         }
323         seqWasDeleted=true;
324       }
325       tmp = new StringBuffer();
326       tmp.append(command.seqs[i].getSequence());
327
328       if (command.string != null && command.string[i] != null)
329       {
330         if (command.position >= tmp.length())
331         {
332           //This occurs if padding is on, and residues
333           //are removed from end of alignment
334           int length = command.position - tmp.length();
335           while (length > 0)
336           {
337             tmp.append(command.gapChar);
338             length--;
339           }
340         }
341         tmp.insert(command.position, command.string[i]);
342
343         for (int s = 0; s < command.string[i].length; s++)
344         {
345           if (jalview.schemes.ResidueProperties.aaIndex[command.string[i][s]] !=
346               23)
347           {
348             newDSNeeded = true;
349             start = command.seqs[i].findPosition(command.position);
350             end = command.seqs[i].findPosition(command.position +
351                                                command.number);
352             break;
353           }
354         }
355         command.string[i] = null;
356       }
357
358       command.seqs[i].setSequence(tmp.toString());
359
360       if (newDSNeeded)
361       {
362         if (command.seqs[i].getDatasetSequence() != null)
363         { // use new ds mechanism here
364           Sequence ds = new Sequence(command.seqs[i].getName(),
365                                      jalview.analysis.AlignSeq.extractGaps(
366                                          jalview.util.Comparison.GapChars,
367                                          command.seqs[i].getSequenceAsString()
368                                      ),
369                                      command.seqs[i].getStart(),
370                                      command.seqs[i].getEnd());
371           ds.setDescription(command.seqs[i].getDescription());
372           command.seqs[i].setDatasetSequence(ds);
373         }
374
375         adjustFeatures(command, i, start, end, true);
376       }
377     }
378     adjustAnnotations(command, true, seqWasDeleted, views);
379
380     command.string = null;
381   }
382
383   void replace(Edit command)
384   {
385     StringBuffer tmp;
386     String oldstring;
387     int start = command.position;
388     int end = command.number;
389
390     command.number = start + command.string[0].length;
391     for (int i = 0; i < command.seqs.length; i++)
392     {
393       oldstring = command.seqs[i].getSequenceAsString();
394       tmp = new StringBuffer(oldstring.substring(0, start));
395       tmp.append(command.string[i]);
396       tmp.append(oldstring.substring(end));
397       command.seqs[i].setSequence(tmp.toString());
398       command.string[i] = oldstring.substring(start, end).toCharArray();
399       tmp = null;
400       oldstring = null;
401     }
402   }
403
404   final void adjustAnnotations(Edit command, boolean insert, boolean modifyVisibility, AlignmentI[] views)
405   {
406
407     AlignmentAnnotation[] annotations = null;
408
409     if (modifyVisibility && !insert)
410     {
411       // only occurs if a sequence was added or deleted.
412       command.deletedAnnotationRows = new Hashtable();
413     }
414     if (command.fullAlignmentHeight)
415     {
416       annotations = command.al.getAlignmentAnnotation();
417     }
418     else
419     {
420       int aSize = 0;
421       AlignmentAnnotation[] tmp;
422       for (int s = 0; s < command.seqs.length; s++)
423       {
424         if (modifyVisibility)
425         {
426           // Rows are only removed or added to sequence object.
427           if (!insert) {
428             // remove rows
429             tmp = command.seqs[s].getAnnotation();
430             if (tmp!=null) {
431               int alen=tmp.length;
432               for (int aa =0; aa<tmp.length; aa++)
433               {
434                 if (!command.al.deleteAnnotation(tmp[aa]))
435                 {
436                   // strip out annotation not in the current al (will be put back on insert in all views)
437                   tmp[aa] = null;
438                   alen--;
439                 }
440               }
441               command.seqs[s].setAlignmentAnnotation(null);
442               if (alen!=tmp.length)
443               { 
444                 // save the non-null annotation references only
445                 AlignmentAnnotation[] saved = new AlignmentAnnotation[alen];
446                 for (int aa=0,aapos=0;aa<tmp.length;aa++)
447                 {
448                   if (tmp[aa]!=null)
449                   {
450                     saved[aapos++] = tmp[aa];
451                     tmp[aa] = null;
452                   }
453                 }
454                 tmp = saved;
455                 command.deletedAnnotationRows.put(command.seqs[s], saved);
456                 // and then remove any annotation in the other views
457                 for (int alview=0; views!=null && alview<views.length; alview++)
458                 {
459                   if (views[alview]!=command.al)
460                   {
461                     AlignmentAnnotation[] toremove = views[alview].getAlignmentAnnotation();
462                     if (toremove==null || toremove.length==0)
463                     {
464                       continue;
465                     }
466                     // remove any alignment annotation on this sequence that's on that alignment view.
467                     for (int aa = 0; aa<toremove.length; aa++)
468                     {
469                       if (toremove[aa].sequenceRef==command.seqs[s])
470                       {
471                         views[alview].deleteAnnotation(toremove[aa]);
472                       }
473                     }
474                   }
475                 }
476               } else {
477                 // save all the annotation
478                 command.deletedAnnotationRows.put(command.seqs[s], tmp);
479               }
480             }
481           } else {
482             // recover rows
483             if (command.deletedAnnotationRows!=null && command.deletedAnnotationRows.containsKey(command.seqs[s]))
484             {
485               AlignmentAnnotation[] revealed = (AlignmentAnnotation[]) command.deletedAnnotationRows.get(command.seqs[s]);
486               command.seqs[s].setAlignmentAnnotation(revealed);
487               if (revealed!=null) {
488                 for (int aa =0; aa<revealed.length; aa++)
489                 {
490                   // iterate through al adding original annotation
491                   command.al.addAnnotation(revealed[aa]);
492                 }
493                 for (int aa =0; aa<revealed.length; aa++)
494                 {
495                   command.al.setAnnotationIndex(revealed[aa], aa);
496                 }
497                 // and then duplicate added annotation on every other alignment view
498                 for (int vnum=0; views!=null && vnum<views.length; vnum++)
499                 {
500                   if (views[vnum]!=command.al)
501                   {
502                     int avwidth = views[vnum].getWidth()+1;
503                     // duplicate in this view
504                     for (int a=0; a<revealed.length; a++)
505                     {
506                       AlignmentAnnotation newann = new AlignmentAnnotation(revealed[a]);
507                       command.seqs[s].addAlignmentAnnotation(newann);
508                       newann.padAnnotation(avwidth);
509                       views[vnum].addAnnotation(newann);
510                       views[vnum].setAnnotationIndex(newann, a);
511                     }
512                   }
513                 }
514               }
515             }
516           }
517           continue;
518         }
519
520         if (command.seqs[s].getAnnotation() == null)
521         {
522           continue;
523         }
524
525         if (aSize == 0)
526         {
527           annotations = command.seqs[s].getAnnotation();
528         }
529         else
530         {
531           tmp = new AlignmentAnnotation
532               [aSize + command.seqs[s].getAnnotation().length];
533
534           System.arraycopy(annotations, 0, tmp, 0, aSize);
535
536           System.arraycopy(command.seqs[s].getAnnotation(),
537                            0, tmp, aSize,
538                            command.seqs[s].getAnnotation().length);
539
540           annotations = tmp;
541         }
542         aSize = annotations.length;
543       }
544     }
545
546     if (annotations == null)
547     {
548       return;
549     }
550
551     if (!insert)
552     {
553       command.deletedAnnotations = new Hashtable();
554     }
555
556     int aSize;
557     Annotation[] temp;
558     for (int a = 0; a < annotations.length; a++)
559     {
560       if (annotations[a].autoCalculated)
561       {
562         continue;
563       }
564
565       int tSize = 0;
566       if (annotations[a].annotations == null)
567       {
568         // nothing to edit here ?
569         continue;
570       }
571       aSize = annotations[a].annotations.length;
572       if (insert)
573       {
574         temp = new Annotation[aSize + command.number];
575         if(annotations[a].padGaps)
576           for (int aa = 0; aa < temp.length; aa++)
577           {
578             temp[aa] = new Annotation(
579                 command.gapChar+"",
580                 null, ' ', 0);
581           }
582       }
583       else
584       {
585         if (command.position < aSize)
586         {
587           if (command.position + command.number > aSize)
588           {
589             tSize = aSize;
590           }
591           else
592           {
593             tSize = aSize - command.number + command.position;
594           }
595         }
596         else
597         {
598           tSize = aSize;
599         }
600
601         if (tSize < 0)
602         {
603           tSize = aSize;
604         }
605         temp = new Annotation[tSize];
606
607       }
608
609       if (insert)
610       {
611         if (command.position < annotations[a].annotations.length)
612         {
613           System.arraycopy(annotations[a].annotations,
614                            0, temp, 0, command.position);
615
616           if (command.deletedAnnotations != null
617               &&
618               command.deletedAnnotations.containsKey(annotations[a].
619               annotationId))
620           {
621             Annotation[] restore = (Annotation[])
622                 command.deletedAnnotations.get(annotations[a].annotationId);
623
624             System.arraycopy(restore,
625                              0,
626                              temp,
627                              command.position,
628                              command.number);
629
630           }
631
632           System.arraycopy(annotations[a].annotations,
633                            command.position, temp,
634                            command.position + command.number,
635                            aSize - command.position);
636         }
637         else
638         {
639           if (command.deletedAnnotations != null
640               &&
641               command.deletedAnnotations.containsKey(annotations[a].
642               annotationId))
643           {
644             Annotation[] restore = (Annotation[])
645                 command.deletedAnnotations.get(annotations[a].annotationId);
646
647             temp = new Annotation[annotations[a].annotations.length +
648                 restore.length];
649             System.arraycopy(annotations[a].annotations,
650                              0, temp, 0,
651                              annotations[a].annotations.length);
652             System.arraycopy(restore, 0, temp,
653                              annotations[a].annotations.length, restore.length);
654           }
655           else
656           {
657             temp = annotations[a].annotations;
658           }
659         }
660       }
661       else
662       {
663         if (tSize != aSize || command.position < 2)
664         {
665           int copylen = Math.min(command.position, annotations[a].annotations.length);
666           if (copylen>0)
667             System.arraycopy(annotations[a].annotations,
668                            0, temp, 0, copylen); //command.position);
669
670           Annotation[] deleted = new Annotation[command.number];
671           if (copylen>=command.position) {
672             copylen = Math.min(command.number, annotations[a].annotations.length-command.position);
673             if (copylen>0)
674             {
675               System.arraycopy(annotations[a].annotations,
676                       command.position, deleted, 0, copylen); // command.number);
677             }
678           }
679
680           command.deletedAnnotations.put(annotations[a].annotationId,
681                                          deleted);
682           if (annotations[a].annotations.length>command.position+command.number) {
683             System.arraycopy(annotations[a].annotations,
684                            command.position + command.number,
685                            temp, command.position,
686                            annotations[a].annotations.length - command.position - command.number); // aSize
687           }
688         }
689         else
690         {
691           int dSize = aSize - command.position;
692
693           if (dSize > 0)
694           {
695             Annotation[] deleted = new Annotation[command.number];
696             System.arraycopy(annotations[a].annotations,
697                              command.position, deleted, 0, dSize);
698
699             command.deletedAnnotations.put(annotations[a].annotationId,
700                                            deleted);
701
702             tSize = Math.min(annotations[a].annotations.length,
703                              command.position);
704             temp = new Annotation[tSize];
705             System.arraycopy(annotations[a].annotations,
706                              0, temp, 0, tSize);
707           }
708           else
709           {
710             temp = annotations[a].annotations;
711           }
712         }
713       }
714
715       annotations[a].annotations = temp;
716     }
717   }
718
719   final void adjustFeatures(Edit command, int index, int i, int j,
720                             boolean insert)
721   {
722     SequenceI seq = command.seqs[index];
723     SequenceI sequence = seq.getDatasetSequence();
724     if (sequence == null)
725     {
726       sequence = seq;
727     }
728
729     if (insert)
730     {
731       if (command.editedFeatures != null
732           && command.editedFeatures.containsKey(seq))
733       {
734         sequence.setSequenceFeatures(
735             (SequenceFeature[]) command.editedFeatures.get(seq)
736             );
737       }
738
739       return;
740     }
741
742     SequenceFeature[] sf = sequence.getSequenceFeatures();
743
744     if (sf == null)
745     {
746       return;
747     }
748
749     SequenceFeature[] oldsf = new SequenceFeature[sf.length];
750
751     int cSize = j - i;
752
753     for (int s = 0; s < sf.length; s++)
754     {
755       SequenceFeature copy = new SequenceFeature(sf[s]);
756
757       oldsf[s] = copy;
758
759       if (sf[s].getEnd() < i)
760       {
761         continue;
762       }
763
764       if (sf[s].getBegin() > j)
765       {
766         sf[s].setBegin(copy.getBegin() - cSize);
767         sf[s].setEnd(copy.getEnd() - cSize);
768         continue;
769       }
770
771       if (sf[s].getBegin() >= i)
772       {
773         sf[s].setBegin(i);
774       }
775
776       if (sf[s].getEnd() < j)
777       {
778         sf[s].setEnd(j - 1);
779       }
780
781       sf[s].setEnd(sf[s].getEnd() - (cSize));
782
783       if (sf[s].getBegin() > sf[s].getEnd())
784       {
785         sequence.deleteFeature(sf[s]);
786       }
787     }
788
789     if (command.editedFeatures == null)
790     {
791       command.editedFeatures = new Hashtable();
792     }
793
794     command.editedFeatures.put(seq, oldsf);
795
796   }
797
798   class Edit
799   {
800     boolean fullAlignmentHeight = false;
801     Hashtable deletedAnnotationRows;
802     Hashtable deletedAnnotations;
803     Hashtable editedFeatures;
804     AlignmentI al;
805     int command;
806     char[][] string;
807     SequenceI[] seqs;
808     int[] alIndex;
809     int position, number;
810     char gapChar;
811
812     Edit(int command,
813          SequenceI[] seqs,
814          int position,
815          int number,
816          char gapChar)
817     {
818       this.command = command;
819       this.seqs = seqs;
820       this.position = position;
821       this.number = number;
822       this.gapChar = gapChar;
823     }
824
825     Edit(int command,
826          SequenceI[] seqs,
827          int position,
828          int number,
829          AlignmentI al)
830     {
831       this.gapChar = al.getGapCharacter();
832       this.command = command;
833       this.seqs = seqs;
834       this.position = position;
835       this.number = number;
836       this.al = al;
837
838       alIndex = new int[seqs.length];
839       for (int i = 0; i < seqs.length; i++)
840       {
841         alIndex[i] = al.findIndex(seqs[i]);
842       }
843
844       fullAlignmentHeight = (al.getHeight() == seqs.length);
845     }
846
847     Edit(int command,
848          SequenceI[] seqs,
849          int position,
850          int number,
851          AlignmentI al,
852          String replace)
853     {
854       this.command = command;
855       this.seqs = seqs;
856       this.position = position;
857       this.number = number;
858       this.al = al;
859       this.gapChar = al.getGapCharacter();
860       string = new char[seqs.length][];
861       for (int i = 0; i < seqs.length; i++)
862       {
863         string[i] = replace.toCharArray();
864       }
865
866       fullAlignmentHeight = (al.getHeight() == seqs.length);
867     }
868   }
869 }