REPLACE added to edit command
[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);
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);
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   final public void appendEdit(int command,
113                                SequenceI[] seqs,
114                                int position,
115                                int number,
116                                AlignmentI al,
117                                boolean performEdit)
118   {
119     Edit edit = new Edit(command, seqs, position, number, al.getGapCharacter());
120     if (al.getHeight() == seqs.length)
121     {
122       edit.al = al;
123       edit.fullAlignmentHeight = true;
124     }
125
126     if (edits != null)
127     {
128       Edit[] temp = new Edit[edits.length + 1];
129       System.arraycopy(edits, 0, temp, 0, edits.length);
130       edits = temp;
131       edits[edits.length - 1] = edit;
132     }
133     else
134     {
135       edits = new Edit[]
136           {
137           edit};
138     }
139
140     if (performEdit)
141     {
142       performEdit(edits.length - 1);
143     }
144   }
145
146   final void performEdit(int commandIndex)
147   {
148     int eSize = edits.length;
149     for (int e = commandIndex; e < eSize; e++)
150     {
151       switch(edits[e].command)
152       {
153         case INSERT_GAP:
154           insertGap(edits[e]);
155           break;
156         case DELETE_GAP:
157           deleteGap(edits[e]);
158           break;
159         case CUT:
160           cut(edits[e]);
161           break;
162         case PASTE:
163           paste(edits[e]);
164           break;
165         case REPLACE:
166           replace(edits[e]);
167           break;
168       }
169     }
170   }
171
172   final public void doCommand()
173   {
174     performEdit(0);
175   }
176
177   final public void undoCommand()
178   {
179     int e = 0, eSize = edits.length;
180     for (e = eSize - 1; e > -1; e--)
181     {
182       switch (edits[e].command)
183       {
184         case INSERT_GAP:
185           deleteGap(edits[e]);
186           break;
187         case DELETE_GAP:
188           insertGap(edits[e]);
189           break;
190         case CUT:
191           paste(edits[e]);
192           break;
193         case PASTE:
194           cut(edits[e]);
195           break;
196         case REPLACE:
197           replace(edits[e]);
198           break;
199       }
200     }
201   }
202
203   final void insertGap(Edit command)
204   {
205     for (int s = 0; s < command.seqs.length; s++)
206     {
207       command.seqs[s].insertCharAt(command.position,
208                                    command.number,
209                                    command.gapChar);
210     }
211
212     adjustAnnotations(command, true, false);
213   }
214
215   final void deleteGap(Edit command)
216   {
217     for (int s = 0; s < command.seqs.length; s++)
218     {
219       command.seqs[s].deleteChars(command.position,
220                                   command.position + command.number);
221     }
222
223     adjustAnnotations(command, false, false);
224   }
225
226   void cut(Edit command)
227   {
228     boolean seqDeleted=false;
229     command.string = new char[command.seqs.length][];
230
231     for (int i = 0; i < command.seqs.length; i++)
232     {
233       if (command.seqs[i].getLength() > command.position)
234       {
235         command.string[i] = command.seqs[i].getSequence(command.position,
236             command.position + command.number);
237
238         if (command.seqs[i].getDatasetSequence() != null
239             || command.seqs[i].getSequenceFeatures() != null)
240         {
241           for (int s = command.position; s < command.position + command.number;
242                s++)
243           {
244             if (jalview.schemes.ResidueProperties
245                 .aaIndex[command.seqs[i].getCharAt(s)] != 23)
246             {
247               adjustFeatures(command, i,
248                              command.seqs[i].findPosition(command.position),
249                              command.seqs[i].findPosition(command.position +
250                   command.number),
251                              false);
252               break;
253             }
254           }
255         }
256         command.seqs[i].deleteChars(command.position,
257                                     command.position + command.number);
258       }
259
260       if (command.seqs[i].getLength() < 1)
261       {
262         command.al.deleteSequence(command.seqs[i]);
263         seqDeleted=true;
264       }
265     }
266
267     adjustAnnotations(command, false, seqDeleted);
268   }
269
270   void paste(Edit command)
271   {
272     StringBuffer tmp;
273     boolean newDSNeeded;
274     boolean seqWasDeleted=false;
275     int start = 0, end = 0;
276
277     for (int i = 0; i < command.seqs.length; i++)
278     {
279       newDSNeeded = false;
280       if (command.seqs[i].getLength() < 1)
281       {
282         // ie this sequence was deleted, we need to
283         // read it to the alignment
284         if (command.alIndex[i] < command.al.getHeight())
285         {
286           command.al.getSequences().insertElementAt(command.seqs[i],
287               command.alIndex[i]);
288         }
289         else
290         {
291           command.al.addSequence(command.seqs[i]);
292         }
293         seqWasDeleted=true;
294       }
295       tmp = new StringBuffer();
296       tmp.append(command.seqs[i].getSequence());
297
298       if (command.string != null && command.string[i] != null)
299       {
300         if (command.position >= tmp.length())
301         {
302           //This occurs if padding is on, and residues
303           //are removed from end of alignment
304           int length = command.position - tmp.length();
305           while (length > 0)
306           {
307             tmp.append(command.gapChar);
308             length--;
309           }
310         }
311         tmp.insert(command.position, command.string[i]);
312
313         for (int s = 0; s < command.string[i].length; s++)
314         {
315           if (jalview.schemes.ResidueProperties.aaIndex[command.string[i][s]] !=
316               23)
317           {
318             newDSNeeded = true;
319             start = command.seqs[i].findPosition(command.position);
320             end = command.seqs[i].findPosition(command.position +
321                                                command.number);
322             break;
323           }
324         }
325         command.string[i] = null;
326       }
327
328       command.seqs[i].setSequence(tmp.toString());
329
330       if (newDSNeeded)
331       {
332         if (command.seqs[i].getDatasetSequence() != null)
333         { // use new ds mechanism here
334           Sequence ds = new Sequence(command.seqs[i].getName(),
335                                      jalview.analysis.AlignSeq.extractGaps(
336                                          jalview.util.Comparison.GapChars,
337                                          command.seqs[i].getSequenceAsString()
338                                      ),
339                                      command.seqs[i].getStart(),
340                                      command.seqs[i].getEnd());
341           ds.setDescription(command.seqs[i].getDescription());
342           command.seqs[i].setDatasetSequence(ds);
343         }
344
345         adjustFeatures(command, i, start, end, true);
346       }
347     }
348     adjustAnnotations(command, true, seqWasDeleted);
349
350     command.string = null;
351   }
352
353   void replace(Edit command)
354   {
355     StringBuffer tmp;
356     String oldstring;
357     int start = command.position;
358     int end = command.number;
359
360     command.number = start + command.string[0].length;
361     for (int i = 0; i < command.seqs.length; i++)
362     {
363       oldstring = command.seqs[i].getSequenceAsString();
364       tmp = new StringBuffer(oldstring.substring(0, start));
365       tmp.append(command.string[i]);
366       tmp.append(oldstring.substring(end));
367       command.seqs[i].setSequence(tmp.toString());
368       command.string[i] = oldstring.substring(start, end).toCharArray();
369       tmp = null;
370       oldstring = null;
371     }
372   }
373
374   final void adjustAnnotations(Edit command, boolean insert, boolean modifyVisibility)
375   {
376     AlignmentAnnotation[] annotations = null;
377
378     if (modifyVisibility && !insert)
379     {
380       // only occurs if a sequence was added or deleted.
381       command.deletedAnnotationRows = new Hashtable();
382     }
383     if (command.fullAlignmentHeight)
384     {
385       annotations = command.al.getAlignmentAnnotation();
386     }
387     else
388     {
389       int aSize = 0;
390       AlignmentAnnotation[] tmp;
391       for (int s = 0; s < command.seqs.length; s++)
392       {
393         if (modifyVisibility)
394         {
395           // Rows are only removed or added to sequence object.
396           if (!insert) {
397             // remove rows
398             tmp = command.seqs[s].getAnnotation();
399             if (tmp!=null) {
400               command.deletedAnnotationRows.put(command.seqs[s], tmp);
401               for (int aa =0; aa<tmp.length; aa++)
402               {
403                 command.al.deleteAnnotation(tmp[aa]);
404               }
405               command.seqs[s].setAlignmentAnnotation(null);
406             }
407           } else {
408             // recover rows
409             if (command.deletedAnnotationRows!=null && command.deletedAnnotationRows.containsKey(command.seqs[s]))
410             {
411               AlignmentAnnotation[] revealed = (AlignmentAnnotation[]) command.deletedAnnotationRows.get(command.seqs[s]);
412               command.seqs[s].setAlignmentAnnotation(revealed);
413               if (revealed!=null) {
414                 for (int aa =0; aa<revealed.length; aa++)
415                 {
416                   command.al.addAnnotation(revealed[aa]);
417                 }
418                 for (int aa =0; aa<revealed.length; aa++)
419                 {
420                   command.al.setAnnotationIndex(revealed[aa], aa);
421                 }
422               }
423             }
424           }
425           continue;
426         }
427
428         if (command.seqs[s].getAnnotation() == null)
429         {
430           continue;
431         }
432
433         if (aSize == 0)
434         {
435           annotations = command.seqs[s].getAnnotation();
436         }
437         else
438         {
439           tmp = new AlignmentAnnotation
440               [aSize + command.seqs[s].getAnnotation().length];
441
442           System.arraycopy(annotations, 0, tmp, 0, aSize);
443
444           System.arraycopy(command.seqs[s].getAnnotation(),
445                            0, tmp, aSize,
446                            command.seqs[s].getAnnotation().length);
447
448           annotations = tmp;
449         }
450         aSize = annotations.length;
451       }
452     }
453
454     if (annotations == null)
455     {
456       return;
457     }
458
459     if (!insert)
460     {
461       command.deletedAnnotations = new Hashtable();
462     }
463
464     int aSize;
465     Annotation[] temp;
466     for (int a = 0; a < annotations.length; a++)
467     {
468       if (annotations[a].autoCalculated)
469       {
470         continue;
471       }
472
473       int tSize = 0;
474
475       aSize = annotations[a].annotations.length;
476       if (insert)
477       {
478         temp = new Annotation[aSize + command.number];
479         if(annotations[a].padGaps)
480           for (int aa = 0; aa < temp.length; aa++)
481           {
482             temp[aa] = new Annotation(
483                 command.al.getGapCharacter()+"",
484                 null, ' ', 0);
485           }
486       }
487       else
488       {
489         if (command.position < aSize)
490         {
491           if (command.position + command.number > aSize)
492           {
493             tSize = aSize;
494           }
495           else
496           {
497             tSize = aSize - command.number + command.position;
498           }
499         }
500         else
501         {
502           tSize = aSize;
503         }
504
505         if (tSize < 0)
506         {
507           tSize = aSize;
508         }
509         temp = new Annotation[tSize];
510
511       }
512
513       if (insert)
514       {
515         if (command.position < annotations[a].annotations.length)
516         {
517           System.arraycopy(annotations[a].annotations,
518                            0, temp, 0, command.position);
519
520           if (command.deletedAnnotations != null
521               &&
522               command.deletedAnnotations.containsKey(annotations[a].
523               annotationId))
524           {
525             Annotation[] restore = (Annotation[])
526                 command.deletedAnnotations.get(annotations[a].annotationId);
527
528             System.arraycopy(restore,
529                              0,
530                              temp,
531                              command.position,
532                              command.number);
533
534           }
535
536           System.arraycopy(annotations[a].annotations,
537                            command.position, temp,
538                            command.position + command.number,
539                            aSize - command.position);
540         }
541         else
542         {
543           if (command.deletedAnnotations != null
544               &&
545               command.deletedAnnotations.containsKey(annotations[a].
546               annotationId))
547           {
548             Annotation[] restore = (Annotation[])
549                 command.deletedAnnotations.get(annotations[a].annotationId);
550
551             temp = new Annotation[annotations[a].annotations.length +
552                 restore.length];
553             System.arraycopy(annotations[a].annotations,
554                              0, temp, 0,
555                              annotations[a].annotations.length);
556             System.arraycopy(restore, 0, temp,
557                              annotations[a].annotations.length, restore.length);
558           }
559           else
560           {
561             temp = annotations[a].annotations;
562           }
563         }
564       }
565       else
566       {
567         if (tSize != aSize || command.position < 2)
568         {
569           int copylen = Math.min(command.position, annotations[a].annotations.length);
570           if (copylen>0)
571             System.arraycopy(annotations[a].annotations,
572                            0, temp, 0, copylen); //command.position);
573
574           Annotation[] deleted = new Annotation[command.number];
575           if (copylen>command.position) {
576             copylen = Math.min(command.number, annotations[a].annotations.length-command.position);
577             if (copylen>0)
578             {
579               System.arraycopy(annotations[a].annotations,
580                       command.position, deleted, 0, copylen); // command.number);
581             }
582           }
583
584           command.deletedAnnotations.put(annotations[a].annotationId,
585                                          deleted);
586           if (annotations[a].annotations.length>command.position+command.number) {
587             System.arraycopy(annotations[a].annotations,
588                            command.position + command.number,
589                            temp, command.position,
590                            annotations[a].annotations.length - command.position - command.number); // aSize
591           }
592         }
593         else
594         {
595           int dSize = aSize - command.position;
596
597           if (dSize > 0)
598           {
599             Annotation[] deleted = new Annotation[command.number];
600             System.arraycopy(annotations[a].annotations,
601                              command.position, deleted, 0, dSize);
602
603             command.deletedAnnotations.put(annotations[a].annotationId,
604                                            deleted);
605
606             tSize = Math.min(annotations[a].annotations.length,
607                              command.position);
608             temp = new Annotation[tSize];
609             System.arraycopy(annotations[a].annotations,
610                              0, temp, 0, tSize);
611           }
612           else
613           {
614             temp = annotations[a].annotations;
615           }
616         }
617       }
618
619       annotations[a].annotations = temp;
620     }
621   }
622
623   final void adjustFeatures(Edit command, int index, int i, int j,
624                             boolean insert)
625   {
626     SequenceI seq = command.seqs[index];
627     SequenceI sequence = seq.getDatasetSequence();
628     if (sequence == null)
629     {
630       sequence = seq;
631     }
632
633     if (insert)
634     {
635       if (command.editedFeatures != null
636           && command.editedFeatures.containsKey(seq))
637       {
638         sequence.setSequenceFeatures(
639             (SequenceFeature[]) command.editedFeatures.get(seq)
640             );
641       }
642
643       return;
644     }
645
646     SequenceFeature[] sf = sequence.getSequenceFeatures();
647
648     if (sf == null)
649     {
650       return;
651     }
652
653     SequenceFeature[] oldsf = new SequenceFeature[sf.length];
654
655     int cSize = j - i;
656
657     for (int s = 0; s < sf.length; s++)
658     {
659       SequenceFeature copy = new SequenceFeature(sf[s]);
660
661       oldsf[s] = copy;
662
663       if (sf[s].getEnd() < i)
664       {
665         continue;
666       }
667
668       if (sf[s].getBegin() > j)
669       {
670         sf[s].setBegin(copy.getBegin() - cSize);
671         sf[s].setEnd(copy.getEnd() - cSize);
672         continue;
673       }
674
675       if (sf[s].getBegin() >= i)
676       {
677         sf[s].setBegin(i);
678       }
679
680       if (sf[s].getEnd() < j)
681       {
682         sf[s].setEnd(j - 1);
683       }
684
685       sf[s].setEnd(sf[s].getEnd() - (cSize));
686
687       if (sf[s].getBegin() > sf[s].getEnd())
688       {
689         sequence.deleteFeature(sf[s]);
690       }
691     }
692
693     if (command.editedFeatures == null)
694     {
695       command.editedFeatures = new Hashtable();
696     }
697
698     command.editedFeatures.put(seq, oldsf);
699
700   }
701
702   class Edit
703   {
704     boolean fullAlignmentHeight = false;
705     Hashtable deletedAnnotationRows;
706     Hashtable deletedAnnotations;
707     Hashtable editedFeatures;
708     AlignmentI al;
709     int command;
710     char[][] string;
711     SequenceI[] seqs;
712     int[] alIndex;
713     int position, number;
714     char gapChar;
715
716     Edit(int command,
717          SequenceI[] seqs,
718          int position,
719          int number,
720          char gapChar)
721     {
722       this.command = command;
723       this.seqs = seqs;
724       this.position = position;
725       this.number = number;
726       this.gapChar = gapChar;
727     }
728
729     Edit(int command,
730          SequenceI[] seqs,
731          int position,
732          int number,
733          AlignmentI al)
734     {
735       this.gapChar = al.getGapCharacter();
736       this.command = command;
737       this.seqs = seqs;
738       this.position = position;
739       this.number = number;
740       this.al = al;
741
742       alIndex = new int[seqs.length];
743       for (int i = 0; i < seqs.length; i++)
744       {
745         alIndex[i] = al.findIndex(seqs[i]);
746       }
747
748       fullAlignmentHeight = (al.getHeight() == seqs.length);
749     }
750
751     Edit(int command,
752          SequenceI[] seqs,
753          int position,
754          int number,
755          AlignmentI al,
756          String replace)
757     {
758       this.command = command;
759       this.seqs = seqs;
760       this.position = position;
761       this.number = number;
762       this.al = al;
763       string = new char[seqs.length][];
764       for (int i = 0; i < seqs.length; i++)
765       {
766         string[i] = replace.toCharArray();
767       }
768
769       fullAlignmentHeight = (al.getHeight() == seqs.length);
770     }
771   }
772
773 }