4cd599249bbbb321f3a2b64515f068cfb42078f2
[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
377     AlignmentAnnotation[] annotations = null;
378
379     if (modifyVisibility && !insert)
380     {
381       // only occurs if a sequence was added or deleted.
382       command.deletedAnnotationRows = new Hashtable();
383     }
384     if (command.fullAlignmentHeight)
385     {
386       annotations = command.al.getAlignmentAnnotation();
387     }
388     else
389     {
390       int aSize = 0;
391       AlignmentAnnotation[] tmp;
392       for (int s = 0; s < command.seqs.length; s++)
393       {
394         if (modifyVisibility)
395         {
396           // Rows are only removed or added to sequence object.
397           if (!insert) {
398             // remove rows
399             tmp = command.seqs[s].getAnnotation();
400             if (tmp!=null) {
401               command.deletedAnnotationRows.put(command.seqs[s], tmp);
402               for (int aa =0; aa<tmp.length; aa++)
403               {
404                 command.al.deleteAnnotation(tmp[aa]);
405               }
406               command.seqs[s].setAlignmentAnnotation(null);
407             }
408           } else {
409             // recover rows
410             if (command.deletedAnnotationRows!=null && command.deletedAnnotationRows.containsKey(command.seqs[s]))
411             {
412               AlignmentAnnotation[] revealed = (AlignmentAnnotation[]) command.deletedAnnotationRows.get(command.seqs[s]);
413               command.seqs[s].setAlignmentAnnotation(revealed);
414               if (revealed!=null) {
415                 for (int aa =0; aa<revealed.length; aa++)
416                 {
417                   command.al.addAnnotation(revealed[aa]);
418                 }
419                 for (int aa =0; aa<revealed.length; aa++)
420                 {
421                   command.al.setAnnotationIndex(revealed[aa], aa);
422                 }
423               }
424             }
425           }
426           continue;
427         }
428
429         if (command.seqs[s].getAnnotation() == null)
430         {
431           continue;
432         }
433
434         if (aSize == 0)
435         {
436           annotations = command.seqs[s].getAnnotation();
437         }
438         else
439         {
440           tmp = new AlignmentAnnotation
441               [aSize + command.seqs[s].getAnnotation().length];
442
443           System.arraycopy(annotations, 0, tmp, 0, aSize);
444
445           System.arraycopy(command.seqs[s].getAnnotation(),
446                            0, tmp, aSize,
447                            command.seqs[s].getAnnotation().length);
448
449           annotations = tmp;
450         }
451         aSize = annotations.length;
452       }
453     }
454
455     if (annotations == null)
456     {
457       return;
458     }
459
460     if (!insert)
461     {
462       command.deletedAnnotations = new Hashtable();
463     }
464
465     int aSize;
466     Annotation[] temp;
467     for (int a = 0; a < annotations.length; a++)
468     {
469       if (annotations[a].autoCalculated)
470       {
471         continue;
472       }
473
474       int tSize = 0;
475
476       aSize = annotations[a].annotations.length;
477       if (insert)
478       {
479         temp = new Annotation[aSize + command.number];
480         if(annotations[a].padGaps)
481           for (int aa = 0; aa < temp.length; aa++)
482           {
483             temp[aa] = new Annotation(
484                 command.gapChar+"",
485                 null, ' ', 0);
486           }
487       }
488       else
489       {
490         if (command.position < aSize)
491         {
492           if (command.position + command.number > aSize)
493           {
494             tSize = aSize;
495           }
496           else
497           {
498             tSize = aSize - command.number + command.position;
499           }
500         }
501         else
502         {
503           tSize = aSize;
504         }
505
506         if (tSize < 0)
507         {
508           tSize = aSize;
509         }
510         temp = new Annotation[tSize];
511
512       }
513
514       if (insert)
515       {
516         if (command.position < annotations[a].annotations.length)
517         {
518           System.arraycopy(annotations[a].annotations,
519                            0, temp, 0, command.position);
520
521           if (command.deletedAnnotations != null
522               &&
523               command.deletedAnnotations.containsKey(annotations[a].
524               annotationId))
525           {
526             Annotation[] restore = (Annotation[])
527                 command.deletedAnnotations.get(annotations[a].annotationId);
528
529             System.arraycopy(restore,
530                              0,
531                              temp,
532                              command.position,
533                              command.number);
534
535           }
536
537           System.arraycopy(annotations[a].annotations,
538                            command.position, temp,
539                            command.position + command.number,
540                            aSize - command.position);
541         }
542         else
543         {
544           if (command.deletedAnnotations != null
545               &&
546               command.deletedAnnotations.containsKey(annotations[a].
547               annotationId))
548           {
549             Annotation[] restore = (Annotation[])
550                 command.deletedAnnotations.get(annotations[a].annotationId);
551
552             temp = new Annotation[annotations[a].annotations.length +
553                 restore.length];
554             System.arraycopy(annotations[a].annotations,
555                              0, temp, 0,
556                              annotations[a].annotations.length);
557             System.arraycopy(restore, 0, temp,
558                              annotations[a].annotations.length, restore.length);
559           }
560           else
561           {
562             temp = annotations[a].annotations;
563           }
564         }
565       }
566       else
567       {
568         if (tSize != aSize || command.position < 2)
569         {
570           int copylen = Math.min(command.position, annotations[a].annotations.length);
571           if (copylen>0)
572             System.arraycopy(annotations[a].annotations,
573                            0, temp, 0, copylen); //command.position);
574
575           Annotation[] deleted = new Annotation[command.number];
576           if (copylen>command.position) {
577             copylen = Math.min(command.number, annotations[a].annotations.length-command.position);
578             if (copylen>0)
579             {
580               System.arraycopy(annotations[a].annotations,
581                       command.position, deleted, 0, copylen); // command.number);
582             }
583           }
584
585           command.deletedAnnotations.put(annotations[a].annotationId,
586                                          deleted);
587           if (annotations[a].annotations.length>command.position+command.number) {
588             System.arraycopy(annotations[a].annotations,
589                            command.position + command.number,
590                            temp, command.position,
591                            annotations[a].annotations.length - command.position - command.number); // aSize
592           }
593         }
594         else
595         {
596           int dSize = aSize - command.position;
597
598           if (dSize > 0)
599           {
600             Annotation[] deleted = new Annotation[command.number];
601             System.arraycopy(annotations[a].annotations,
602                              command.position, deleted, 0, dSize);
603
604             command.deletedAnnotations.put(annotations[a].annotationId,
605                                            deleted);
606
607             tSize = Math.min(annotations[a].annotations.length,
608                              command.position);
609             temp = new Annotation[tSize];
610             System.arraycopy(annotations[a].annotations,
611                              0, temp, 0, tSize);
612           }
613           else
614           {
615             temp = annotations[a].annotations;
616           }
617         }
618       }
619
620       annotations[a].annotations = temp;
621     }
622   }
623
624   final void adjustFeatures(Edit command, int index, int i, int j,
625                             boolean insert)
626   {
627     SequenceI seq = command.seqs[index];
628     SequenceI sequence = seq.getDatasetSequence();
629     if (sequence == null)
630     {
631       sequence = seq;
632     }
633
634     if (insert)
635     {
636       if (command.editedFeatures != null
637           && command.editedFeatures.containsKey(seq))
638       {
639         sequence.setSequenceFeatures(
640             (SequenceFeature[]) command.editedFeatures.get(seq)
641             );
642       }
643
644       return;
645     }
646
647     SequenceFeature[] sf = sequence.getSequenceFeatures();
648
649     if (sf == null)
650     {
651       return;
652     }
653
654     SequenceFeature[] oldsf = new SequenceFeature[sf.length];
655
656     int cSize = j - i;
657
658     for (int s = 0; s < sf.length; s++)
659     {
660       SequenceFeature copy = new SequenceFeature(sf[s]);
661
662       oldsf[s] = copy;
663
664       if (sf[s].getEnd() < i)
665       {
666         continue;
667       }
668
669       if (sf[s].getBegin() > j)
670       {
671         sf[s].setBegin(copy.getBegin() - cSize);
672         sf[s].setEnd(copy.getEnd() - cSize);
673         continue;
674       }
675
676       if (sf[s].getBegin() >= i)
677       {
678         sf[s].setBegin(i);
679       }
680
681       if (sf[s].getEnd() < j)
682       {
683         sf[s].setEnd(j - 1);
684       }
685
686       sf[s].setEnd(sf[s].getEnd() - (cSize));
687
688       if (sf[s].getBegin() > sf[s].getEnd())
689       {
690         sequence.deleteFeature(sf[s]);
691       }
692     }
693
694     if (command.editedFeatures == null)
695     {
696       command.editedFeatures = new Hashtable();
697     }
698
699     command.editedFeatures.put(seq, oldsf);
700
701   }
702
703   class Edit
704   {
705     boolean fullAlignmentHeight = false;
706     Hashtable deletedAnnotationRows;
707     Hashtable deletedAnnotations;
708     Hashtable editedFeatures;
709     AlignmentI al;
710     int command;
711     char[][] string;
712     SequenceI[] seqs;
713     int[] alIndex;
714     int position, number;
715     char gapChar;
716
717     Edit(int command,
718          SequenceI[] seqs,
719          int position,
720          int number,
721          char gapChar)
722     {
723       this.command = command;
724       this.seqs = seqs;
725       this.position = position;
726       this.number = number;
727       this.gapChar = gapChar;
728     }
729
730     Edit(int command,
731          SequenceI[] seqs,
732          int position,
733          int number,
734          AlignmentI al)
735     {
736       this.gapChar = al.getGapCharacter();
737       this.command = command;
738       this.seqs = seqs;
739       this.position = position;
740       this.number = number;
741       this.al = al;
742
743       alIndex = new int[seqs.length];
744       for (int i = 0; i < seqs.length; i++)
745       {
746         alIndex[i] = al.findIndex(seqs[i]);
747       }
748
749       fullAlignmentHeight = (al.getHeight() == seqs.length);
750     }
751
752     Edit(int command,
753          SequenceI[] seqs,
754          int position,
755          int number,
756          AlignmentI al,
757          String replace)
758     {
759       this.command = command;
760       this.seqs = seqs;
761       this.position = position;
762       this.number = number;
763       this.al = al;
764       this.gapChar = al.getGapCharacter();
765       string = new char[seqs.length][];
766       for (int i = 0; i < seqs.length; i++)
767       {
768         string[i] = replace.toCharArray();
769       }
770
771       fullAlignmentHeight = (al.getHeight() == seqs.length);
772     }
773   }
774 }