Annotations do not extend when full alignment is adjusted
[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
236     for (int s = 0; s < command.seqs.length; s++)
237     {
238       command.seqs[s].insertCharAt(command.position,
239                                    command.number,
240                                    command.gapChar);
241     }
242
243     adjustAnnotations(command, true, false, null);
244   }
245
246   final void deleteGap(Edit command)
247   {
248     for (int s = 0; s < command.seqs.length; s++)
249     {
250       command.seqs[s].deleteChars(command.position,
251                                   command.position + command.number);
252     }
253
254     adjustAnnotations(command, false, false, null);
255   }
256
257   void cut(Edit command, AlignmentI[] views)
258   {
259     boolean seqDeleted=false;
260     command.string = new char[command.seqs.length][];
261
262     for (int i = 0; i < command.seqs.length; i++)
263     {
264       if (command.seqs[i].getLength() > command.position)
265       {
266         command.string[i] = command.seqs[i].getSequence(command.position,
267             command.position + command.number);
268
269         if (command.seqs[i].getDatasetSequence() != null
270             || command.seqs[i].getSequenceFeatures() != null)
271         {
272           for (int s = command.position; s < command.position + command.number;
273                s++)
274           {
275             if (jalview.schemes.ResidueProperties
276                 .aaIndex[command.seqs[i].getCharAt(s)] != 23)
277             {
278               adjustFeatures(command, i,
279                              command.seqs[i].findPosition(command.position),
280                              command.seqs[i].findPosition(command.position +
281                   command.number),
282                              false);
283               break;
284             }
285           }
286         }
287         command.seqs[i].deleteChars(command.position,
288                                     command.position + command.number);
289       }
290
291       if (command.seqs[i].getLength() < 1)
292       {
293         command.al.deleteSequence(command.seqs[i]);
294         seqDeleted=true;
295       }
296     }
297
298     adjustAnnotations(command, false, seqDeleted, views);
299   }
300
301   void paste(Edit command, AlignmentI[] views)
302   {
303     StringBuffer tmp;
304     boolean newDSNeeded;
305     boolean seqWasDeleted=false;
306     int start = 0, end = 0;
307
308     for (int i = 0; i < command.seqs.length; i++)
309     {
310       newDSNeeded = false;
311       if (command.seqs[i].getLength() < 1)
312       {
313         // ie this sequence was deleted, we need to
314         // read it to the alignment
315         if (command.alIndex[i] < command.al.getHeight())
316         {
317           command.al.getSequences().insertElementAt(command.seqs[i],
318               command.alIndex[i]);
319         }
320         else
321         {
322           command.al.addSequence(command.seqs[i]);
323         }
324         seqWasDeleted=true;
325       }
326       tmp = new StringBuffer();
327       tmp.append(command.seqs[i].getSequence());
328
329       if (command.string != null && command.string[i] != null)
330       {
331         if (command.position >= tmp.length())
332         {
333           //This occurs if padding is on, and residues
334           //are removed from end of alignment
335           int length = command.position - tmp.length();
336           while (length > 0)
337           {
338             tmp.append(command.gapChar);
339             length--;
340           }
341         }
342         tmp.insert(command.position, command.string[i]);
343
344         for (int s = 0; s < command.string[i].length; s++)
345         {
346           if (jalview.schemes.ResidueProperties.aaIndex[command.string[i][s]] !=
347               23)
348           {
349             newDSNeeded = true;
350             start = command.seqs[i].findPosition(command.position);
351             end = command.seqs[i].findPosition(command.position +
352                                                command.number);
353             break;
354           }
355         }
356         command.string[i] = null;
357       }
358
359       command.seqs[i].setSequence(tmp.toString());
360
361       if (newDSNeeded)
362       {
363         if (command.seqs[i].getDatasetSequence() != null)
364         { // use new ds mechanism here
365           Sequence ds = new Sequence(command.seqs[i].getName(),
366                                      jalview.analysis.AlignSeq.extractGaps(
367                                          jalview.util.Comparison.GapChars,
368                                          command.seqs[i].getSequenceAsString()
369                                      ),
370                                      command.seqs[i].getStart(),
371                                      command.seqs[i].getEnd());
372           ds.setDescription(command.seqs[i].getDescription());
373           command.seqs[i].setDatasetSequence(ds);
374         }
375
376         adjustFeatures(command, i, start, end, true);
377       }
378     }
379     adjustAnnotations(command, true, seqWasDeleted, views);
380
381     command.string = null;
382   }
383
384   void replace(Edit command)
385   {
386     StringBuffer tmp;
387     String oldstring;
388     int start = command.position;
389     int end = command.number;
390
391     command.number = start + command.string[0].length;
392     for (int i = 0; i < command.seqs.length; i++)
393     {
394       oldstring = command.seqs[i].getSequenceAsString();
395       tmp = new StringBuffer(oldstring.substring(0, start));
396       tmp.append(command.string[i]);
397       tmp.append(oldstring.substring(end));
398       command.seqs[i].setSequence(tmp.toString());
399       command.string[i] = oldstring.substring(start, end).toCharArray();
400       tmp = null;
401       oldstring = null;
402     }
403   }
404
405   final void adjustAnnotations(Edit command, boolean insert, boolean modifyVisibility, AlignmentI[] views)
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 || annotations[a].annotations == null)
561       {
562         continue;
563       }
564
565       int tSize = 0;
566
567       aSize = annotations[a].annotations.length;
568       if (insert)
569       {
570         temp = new Annotation[aSize + command.number];
571         if(annotations[a].padGaps)
572           for (int aa = 0; aa < temp.length; aa++)
573           {
574             temp[aa] = new Annotation(
575                 command.gapChar+"",
576                 null, ' ', 0);
577           }
578       }
579       else
580       {
581         if (command.position < aSize)
582         {
583           if (command.position + command.number >= aSize)
584           {
585             tSize = aSize;
586           }
587           else
588           {
589             tSize = aSize - command.number;
590           }
591         }
592         else
593         {
594           tSize = aSize;
595         }
596
597         if (tSize < 0)
598         {
599           tSize = aSize;
600         }
601         temp = new Annotation[tSize];
602       }
603
604
605       if (insert)
606       {
607         if (command.position < annotations[a].annotations.length)
608         {
609           System.arraycopy(annotations[a].annotations,
610                            0, temp, 0, command.position);
611
612           if (command.deletedAnnotations != null
613               &&
614               command.deletedAnnotations.containsKey(annotations[a].
615               annotationId))
616           {
617             Annotation[] restore = (Annotation[])
618                 command.deletedAnnotations.get(annotations[a].annotationId);
619
620             System.arraycopy(restore,
621                              0,
622                              temp,
623                              command.position,
624                              command.number);
625
626           }
627
628           System.arraycopy(annotations[a].annotations,
629                            command.position, temp,
630                            command.position + command.number,
631                            aSize - command.position);
632         }
633         else
634         {
635           if (command.deletedAnnotations != null
636               &&
637               command.deletedAnnotations.containsKey(annotations[a].
638               annotationId))
639           {
640             Annotation[] restore = (Annotation[])
641                 command.deletedAnnotations.get(annotations[a].annotationId);
642
643             temp = new Annotation[annotations[a].annotations.length +
644                 restore.length];
645             System.arraycopy(annotations[a].annotations,
646                              0, temp, 0,
647                              annotations[a].annotations.length);
648             System.arraycopy(restore, 0, temp,
649                              annotations[a].annotations.length, restore.length);
650           }
651           else
652           {
653             temp = annotations[a].annotations;
654           }
655         }
656       }
657       else
658       {
659         if (tSize != aSize || command.position < 2)
660         {
661           int copylen = Math.min(command.position, annotations[a].annotations.length);
662           if (copylen>0)
663             System.arraycopy(annotations[a].annotations,
664                            0, temp, 0, copylen); //command.position);
665
666           Annotation[] deleted = new Annotation[command.number];
667           if (copylen>=command.position) {
668             copylen = Math.min(command.number, annotations[a].annotations.length-command.position);
669             if (copylen>0)
670             {
671               System.arraycopy(annotations[a].annotations,
672                       command.position, deleted, 0, copylen); // command.number);
673             }
674           }
675
676           command.deletedAnnotations.put(annotations[a].annotationId,
677                                          deleted);
678           if (annotations[a].annotations.length>command.position+command.number) {
679             System.arraycopy(annotations[a].annotations,
680                            command.position + command.number,
681                            temp, command.position,
682                            annotations[a].annotations.length - command.position - command.number); // aSize
683           }
684         }
685         else
686         {
687           int dSize = aSize - command.position;
688
689           if (dSize > 0)
690           {
691             Annotation[] deleted = new Annotation[command.number];
692             System.arraycopy(annotations[a].annotations,
693                              command.position, deleted, 0, dSize);
694
695             command.deletedAnnotations.put(annotations[a].annotationId,
696                                            deleted);
697
698             tSize = Math.min(annotations[a].annotations.length,
699                              command.position);
700             temp = new Annotation[tSize];
701             System.arraycopy(annotations[a].annotations,
702                              0, temp, 0, tSize);
703           }
704           else
705           {
706             temp = annotations[a].annotations;
707           }
708         }
709       }
710
711       annotations[a].annotations = temp;
712     }
713   }
714
715   final void adjustFeatures(Edit command, int index, int i, int j,
716                             boolean insert)
717   {
718     SequenceI seq = command.seqs[index];
719     SequenceI sequence = seq.getDatasetSequence();
720     if (sequence == null)
721     {
722       sequence = seq;
723     }
724
725     if (insert)
726     {
727       if (command.editedFeatures != null
728           && command.editedFeatures.containsKey(seq))
729       {
730         sequence.setSequenceFeatures(
731             (SequenceFeature[]) command.editedFeatures.get(seq)
732             );
733       }
734
735       return;
736     }
737
738     SequenceFeature[] sf = sequence.getSequenceFeatures();
739
740     if (sf == null)
741     {
742       return;
743     }
744
745     SequenceFeature[] oldsf = new SequenceFeature[sf.length];
746
747     int cSize = j - i;
748
749     for (int s = 0; s < sf.length; s++)
750     {
751       SequenceFeature copy = new SequenceFeature(sf[s]);
752
753       oldsf[s] = copy;
754
755       if (sf[s].getEnd() < i)
756       {
757         continue;
758       }
759
760       if (sf[s].getBegin() > j)
761       {
762         sf[s].setBegin(copy.getBegin() - cSize);
763         sf[s].setEnd(copy.getEnd() - cSize);
764         continue;
765       }
766
767       if (sf[s].getBegin() >= i)
768       {
769         sf[s].setBegin(i);
770       }
771
772       if (sf[s].getEnd() < j)
773       {
774         sf[s].setEnd(j - 1);
775       }
776
777       sf[s].setEnd(sf[s].getEnd() - (cSize));
778
779       if (sf[s].getBegin() > sf[s].getEnd())
780       {
781         sequence.deleteFeature(sf[s]);
782       }
783     }
784
785     if (command.editedFeatures == null)
786     {
787       command.editedFeatures = new Hashtable();
788     }
789
790     command.editedFeatures.put(seq, oldsf);
791
792   }
793
794   class Edit
795   {
796     boolean fullAlignmentHeight = false;
797     Hashtable deletedAnnotationRows;
798     Hashtable deletedAnnotations;
799     Hashtable editedFeatures;
800     AlignmentI al;
801     int command;
802     char[][] string;
803     SequenceI[] seqs;
804     int[] alIndex;
805     int position, number;
806     char gapChar;
807
808     Edit(int command,
809          SequenceI[] seqs,
810          int position,
811          int number,
812          char gapChar)
813     {
814       this.command = command;
815       this.seqs = seqs;
816       this.position = position;
817       this.number = number;
818       this.gapChar = gapChar;
819     }
820
821     Edit(int command,
822          SequenceI[] seqs,
823          int position,
824          int number,
825          AlignmentI al)
826     {
827       this.gapChar = al.getGapCharacter();
828       this.command = command;
829       this.seqs = seqs;
830       this.position = position;
831       this.number = number;
832       this.al = al;
833
834       alIndex = new int[seqs.length];
835       for (int i = 0; i < seqs.length; i++)
836       {
837         alIndex[i] = al.findIndex(seqs[i]);
838       }
839
840       fullAlignmentHeight = (al.getHeight() == seqs.length);
841     }
842
843     Edit(int command,
844          SequenceI[] seqs,
845          int position,
846          int number,
847          AlignmentI al,
848          String replace)
849     {
850       this.command = command;
851       this.seqs = seqs;
852       this.position = position;
853       this.number = number;
854       this.al = al;
855       this.gapChar = al.getGapCharacter();
856       string = new char[seqs.length][];
857       for (int i = 0; i < seqs.length; i++)
858       {
859         string[i] = replace.toCharArray();
860       }
861
862       fullAlignmentHeight = (al.getHeight() == seqs.length);
863     }
864   }
865 }