AlignmentAnnotation: added annotation score attribute and allowed for annotation...
[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       if (annotations[a].annotations == null)
476       {
477         // nothing to edit here ?
478         continue;
479       }
480       aSize = annotations[a].annotations.length;
481       if (insert)
482       {
483         temp = new Annotation[aSize + command.number];
484         if(annotations[a].padGaps)
485           for (int aa = 0; aa < temp.length; aa++)
486           {
487             temp[aa] = new Annotation(
488                 command.gapChar+"",
489                 null, ' ', 0);
490           }
491       }
492       else
493       {
494         if (command.position < aSize)
495         {
496           if (command.position + command.number > aSize)
497           {
498             tSize = aSize;
499           }
500           else
501           {
502             tSize = aSize - command.number + command.position;
503           }
504         }
505         else
506         {
507           tSize = aSize;
508         }
509
510         if (tSize < 0)
511         {
512           tSize = aSize;
513         }
514         temp = new Annotation[tSize];
515
516       }
517
518       if (insert)
519       {
520         if (command.position < annotations[a].annotations.length)
521         {
522           System.arraycopy(annotations[a].annotations,
523                            0, temp, 0, command.position);
524
525           if (command.deletedAnnotations != null
526               &&
527               command.deletedAnnotations.containsKey(annotations[a].
528               annotationId))
529           {
530             Annotation[] restore = (Annotation[])
531                 command.deletedAnnotations.get(annotations[a].annotationId);
532
533             System.arraycopy(restore,
534                              0,
535                              temp,
536                              command.position,
537                              command.number);
538
539           }
540
541           System.arraycopy(annotations[a].annotations,
542                            command.position, temp,
543                            command.position + command.number,
544                            aSize - command.position);
545         }
546         else
547         {
548           if (command.deletedAnnotations != null
549               &&
550               command.deletedAnnotations.containsKey(annotations[a].
551               annotationId))
552           {
553             Annotation[] restore = (Annotation[])
554                 command.deletedAnnotations.get(annotations[a].annotationId);
555
556             temp = new Annotation[annotations[a].annotations.length +
557                 restore.length];
558             System.arraycopy(annotations[a].annotations,
559                              0, temp, 0,
560                              annotations[a].annotations.length);
561             System.arraycopy(restore, 0, temp,
562                              annotations[a].annotations.length, restore.length);
563           }
564           else
565           {
566             temp = annotations[a].annotations;
567           }
568         }
569       }
570       else
571       {
572         if (tSize != aSize || command.position < 2)
573         {
574           int copylen = Math.min(command.position, annotations[a].annotations.length);
575           if (copylen>0)
576             System.arraycopy(annotations[a].annotations,
577                            0, temp, 0, copylen); //command.position);
578
579           Annotation[] deleted = new Annotation[command.number];
580           if (copylen>command.position) {
581             copylen = Math.min(command.number, annotations[a].annotations.length-command.position);
582             if (copylen>0)
583             {
584               System.arraycopy(annotations[a].annotations,
585                       command.position, deleted, 0, copylen); // command.number);
586             }
587           }
588
589           command.deletedAnnotations.put(annotations[a].annotationId,
590                                          deleted);
591           if (annotations[a].annotations.length>command.position+command.number) {
592             System.arraycopy(annotations[a].annotations,
593                            command.position + command.number,
594                            temp, command.position,
595                            annotations[a].annotations.length - command.position - command.number); // aSize
596           }
597         }
598         else
599         {
600           int dSize = aSize - command.position;
601
602           if (dSize > 0)
603           {
604             Annotation[] deleted = new Annotation[command.number];
605             System.arraycopy(annotations[a].annotations,
606                              command.position, deleted, 0, dSize);
607
608             command.deletedAnnotations.put(annotations[a].annotationId,
609                                            deleted);
610
611             tSize = Math.min(annotations[a].annotations.length,
612                              command.position);
613             temp = new Annotation[tSize];
614             System.arraycopy(annotations[a].annotations,
615                              0, temp, 0, tSize);
616           }
617           else
618           {
619             temp = annotations[a].annotations;
620           }
621         }
622       }
623
624       annotations[a].annotations = temp;
625     }
626   }
627
628   final void adjustFeatures(Edit command, int index, int i, int j,
629                             boolean insert)
630   {
631     SequenceI seq = command.seqs[index];
632     SequenceI sequence = seq.getDatasetSequence();
633     if (sequence == null)
634     {
635       sequence = seq;
636     }
637
638     if (insert)
639     {
640       if (command.editedFeatures != null
641           && command.editedFeatures.containsKey(seq))
642       {
643         sequence.setSequenceFeatures(
644             (SequenceFeature[]) command.editedFeatures.get(seq)
645             );
646       }
647
648       return;
649     }
650
651     SequenceFeature[] sf = sequence.getSequenceFeatures();
652
653     if (sf == null)
654     {
655       return;
656     }
657
658     SequenceFeature[] oldsf = new SequenceFeature[sf.length];
659
660     int cSize = j - i;
661
662     for (int s = 0; s < sf.length; s++)
663     {
664       SequenceFeature copy = new SequenceFeature(sf[s]);
665
666       oldsf[s] = copy;
667
668       if (sf[s].getEnd() < i)
669       {
670         continue;
671       }
672
673       if (sf[s].getBegin() > j)
674       {
675         sf[s].setBegin(copy.getBegin() - cSize);
676         sf[s].setEnd(copy.getEnd() - cSize);
677         continue;
678       }
679
680       if (sf[s].getBegin() >= i)
681       {
682         sf[s].setBegin(i);
683       }
684
685       if (sf[s].getEnd() < j)
686       {
687         sf[s].setEnd(j - 1);
688       }
689
690       sf[s].setEnd(sf[s].getEnd() - (cSize));
691
692       if (sf[s].getBegin() > sf[s].getEnd())
693       {
694         sequence.deleteFeature(sf[s]);
695       }
696     }
697
698     if (command.editedFeatures == null)
699     {
700       command.editedFeatures = new Hashtable();
701     }
702
703     command.editedFeatures.put(seq, oldsf);
704
705   }
706
707   class Edit
708   {
709     boolean fullAlignmentHeight = false;
710     Hashtable deletedAnnotationRows;
711     Hashtable deletedAnnotations;
712     Hashtable editedFeatures;
713     AlignmentI al;
714     int command;
715     char[][] string;
716     SequenceI[] seqs;
717     int[] alIndex;
718     int position, number;
719     char gapChar;
720
721     Edit(int command,
722          SequenceI[] seqs,
723          int position,
724          int number,
725          char gapChar)
726     {
727       this.command = command;
728       this.seqs = seqs;
729       this.position = position;
730       this.number = number;
731       this.gapChar = gapChar;
732     }
733
734     Edit(int command,
735          SequenceI[] seqs,
736          int position,
737          int number,
738          AlignmentI al)
739     {
740       this.gapChar = al.getGapCharacter();
741       this.command = command;
742       this.seqs = seqs;
743       this.position = position;
744       this.number = number;
745       this.al = al;
746
747       alIndex = new int[seqs.length];
748       for (int i = 0; i < seqs.length; i++)
749       {
750         alIndex[i] = al.findIndex(seqs[i]);
751       }
752
753       fullAlignmentHeight = (al.getHeight() == seqs.length);
754     }
755
756     Edit(int command,
757          SequenceI[] seqs,
758          int position,
759          int number,
760          AlignmentI al,
761          String replace)
762     {
763       this.command = command;
764       this.seqs = seqs;
765       this.position = position;
766       this.number = number;
767       this.al = al;
768       this.gapChar = al.getGapCharacter();
769       string = new char[seqs.length][];
770       for (int i = 0; i < seqs.length; i++)
771       {
772         string[i] = replace.toCharArray();
773       }
774
775       fullAlignmentHeight = (al.getHeight() == seqs.length);
776     }
777   }
778 }