JAL-2822 stash start/end before setSequence (which will modify ‘end’) and catch cases...
[jalview.git] / src / jalview / commands / EditCommand.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.commands;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.Annotation;
27 import jalview.datamodel.Range;
28 import jalview.datamodel.Sequence;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.datamodel.features.SequenceFeaturesI;
32 import jalview.util.Comparison;
33 import jalview.util.ReverseListIterator;
34 import jalview.util.StringUtils;
35
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.Hashtable;
39 import java.util.Iterator;
40 import java.util.List;
41 import java.util.ListIterator;
42 import java.util.Map;
43
44 /**
45  * 
46  * <p>
47  * Title: EditCommmand
48  * </p>
49  * 
50  * <p>
51  * Description: Essential information for performing undo and redo for cut/paste
52  * insert/delete gap which can be stored in the HistoryList
53  * </p>
54  * 
55  * <p>
56  * Copyright: Copyright (c) 2006
57  * </p>
58  * 
59  * <p>
60  * Company: Dundee University
61  * </p>
62  * 
63  * @author not attributable
64  * @version 1.0
65  */
66 public class EditCommand implements CommandI
67 {
68   public enum Action
69   {
70     INSERT_GAP
71     {
72       @Override
73       public Action getUndoAction()
74       {
75         return DELETE_GAP;
76       }
77     },
78     DELETE_GAP
79     {
80       @Override
81       public Action getUndoAction()
82       {
83         return INSERT_GAP;
84       }
85     },
86     CUT
87     {
88       @Override
89       public Action getUndoAction()
90       {
91         return PASTE;
92       }
93     },
94     PASTE
95     {
96       @Override
97       public Action getUndoAction()
98       {
99         return CUT;
100       }
101     },
102     REPLACE
103     {
104       @Override
105       public Action getUndoAction()
106       {
107         return REPLACE;
108       }
109     },
110     INSERT_NUC
111     {
112       @Override
113       public Action getUndoAction()
114       {
115         return null;
116       }
117     };
118     public abstract Action getUndoAction();
119   };
120
121   private List<Edit> edits = new ArrayList<Edit>();
122
123   String description;
124
125   public EditCommand()
126   {
127   }
128
129   public EditCommand(String desc)
130   {
131     this.description = desc;
132   }
133
134   public EditCommand(String desc, Action command, SequenceI[] seqs,
135           int position, int number, AlignmentI al)
136   {
137     this.description = desc;
138     if (command == Action.CUT || command == Action.PASTE)
139     {
140       setEdit(new Edit(command, seqs, position, number, al));
141     }
142
143     performEdit(0, null);
144   }
145
146   public EditCommand(String desc, Action command, String replace,
147           SequenceI[] seqs, int position, int number, AlignmentI al)
148   {
149     this.description = desc;
150     if (command == Action.REPLACE)
151     {
152       setEdit(new Edit(command, seqs, position, number, al, replace));
153     }
154
155     performEdit(0, null);
156   }
157
158   /**
159    * Set the list of edits to the specified item (only).
160    * 
161    * @param e
162    */
163   protected void setEdit(Edit e)
164   {
165     edits.clear();
166     edits.add(e);
167   }
168
169   /**
170    * Add the given edit command to the stored list of commands. If simply
171    * expanding the range of the last command added, then modify it instead of
172    * adding a new command.
173    * 
174    * @param e
175    */
176   public void addEdit(Edit e)
177   {
178     if (!expandEdit(edits, e))
179     {
180       edits.add(e);
181     }
182   }
183
184   /**
185    * Returns true if the new edit is incorporated by updating (expanding the
186    * range of) the last edit on the list, else false. We can 'expand' the last
187    * edit if the new one is the same action, on the same sequences, and acts on
188    * a contiguous range. This is the case where a mouse drag generates a series
189    * of contiguous gap insertions or deletions.
190    * 
191    * @param edits
192    * @param e
193    * @return
194    */
195   protected static boolean expandEdit(List<Edit> edits, Edit e)
196   {
197     if (edits == null || edits.isEmpty())
198     {
199       return false;
200     }
201     Edit lastEdit = edits.get(edits.size() - 1);
202     Action action = e.command;
203     if (lastEdit.command != action)
204     {
205       return false;
206     }
207
208     /*
209      * Both commands must act on the same sequences - compare the underlying
210      * dataset sequences, rather than the aligned sequences, which change as
211      * they are edited.
212      */
213     if (lastEdit.seqs.length != e.seqs.length)
214     {
215       return false;
216     }
217     for (int i = 0; i < e.seqs.length; i++)
218     {
219       if (lastEdit.seqs[i].getDatasetSequence() != e.seqs[i]
220               .getDatasetSequence())
221       {
222         return false;
223       }
224     }
225
226     /**
227      * Check a contiguous edit; either
228      * <ul>
229      * <li>a new Insert <n> positions to the right of the last <insert n>,
230      * or</li>
231      * <li>a new Delete <n> gaps which is <n> positions to the left of the last
232      * delete.</li>
233      * </ul>
234      */
235     boolean contiguous = (action == Action.INSERT_GAP
236             && e.position == lastEdit.position + lastEdit.number)
237             || (action == Action.DELETE_GAP
238                     && e.position + e.number == lastEdit.position);
239     if (contiguous)
240     {
241       /*
242        * We are just expanding the range of the last edit. For delete gap, also
243        * moving the start position left.
244        */
245       lastEdit.number += e.number;
246       lastEdit.seqs = e.seqs;
247       if (action == Action.DELETE_GAP)
248       {
249         lastEdit.position--;
250       }
251       return true;
252     }
253     return false;
254   }
255
256   /**
257    * Clear the list of stored edit commands.
258    * 
259    */
260   protected void clearEdits()
261   {
262     edits.clear();
263   }
264
265   /**
266    * Returns the i'th stored Edit command.
267    * 
268    * @param i
269    * @return
270    */
271   protected Edit getEdit(int i)
272   {
273     if (i >= 0 && i < edits.size())
274     {
275       return edits.get(i);
276     }
277     return null;
278   }
279
280   @Override
281   final public String getDescription()
282   {
283     return description;
284   }
285
286   @Override
287   public int getSize()
288   {
289     return edits.size();
290   }
291
292   /**
293    * Return the alignment for the first edit (or null if no edit).
294    * 
295    * @return
296    */
297   final public AlignmentI getAlignment()
298   {
299     return (edits.isEmpty() ? null : edits.get(0).al);
300   }
301
302   /**
303    * append a new editCommand Note. this shouldn't be called if the edit is an
304    * operation affects more alignment objects than the one referenced in al (for
305    * example, cut or pasting whole sequences). Use the form with an additional
306    * AlignmentI[] views parameter.
307    * 
308    * @param command
309    * @param seqs
310    * @param position
311    * @param number
312    * @param al
313    * @param performEdit
314    */
315   final public void appendEdit(Action command, SequenceI[] seqs,
316           int position, int number, AlignmentI al, boolean performEdit)
317   {
318     appendEdit(command, seqs, position, number, al, performEdit, null);
319   }
320
321   /**
322    * append a new edit command with a set of alignment views that may be
323    * operated on
324    * 
325    * @param command
326    * @param seqs
327    * @param position
328    * @param number
329    * @param al
330    * @param performEdit
331    * @param views
332    */
333   final public void appendEdit(Action command, SequenceI[] seqs,
334           int position, int number, AlignmentI al, boolean performEdit,
335           AlignmentI[] views)
336   {
337     Edit edit = new Edit(command, seqs, position, number, al);
338     appendEdit(edit, al, performEdit, views);
339   }
340
341   /**
342    * Overloaded method that accepts an Edit object with additional parameters.
343    * 
344    * @param edit
345    * @param al
346    * @param performEdit
347    * @param views
348    */
349   final public void appendEdit(Edit edit, AlignmentI al,
350           boolean performEdit, AlignmentI[] views)
351   {
352     if (al.getHeight() == edit.seqs.length)
353     {
354       edit.al = al;
355       edit.fullAlignmentHeight = true;
356     }
357
358     addEdit(edit);
359
360     if (performEdit)
361     {
362       performEdit(edit, views);
363     }
364   }
365
366   /**
367    * Execute all the edit commands, starting at the given commandIndex
368    * 
369    * @param commandIndex
370    * @param views
371    */
372   public final void performEdit(int commandIndex, AlignmentI[] views)
373   {
374     ListIterator<Edit> iterator = edits.listIterator(commandIndex);
375     while (iterator.hasNext())
376     {
377       Edit edit = iterator.next();
378       performEdit(edit, views);
379     }
380   }
381
382   /**
383    * Execute one edit command in all the specified alignment views
384    * 
385    * @param edit
386    * @param views
387    */
388   protected static void performEdit(Edit edit, AlignmentI[] views)
389   {
390     switch (edit.command)
391     {
392     case INSERT_GAP:
393       insertGap(edit);
394       break;
395     case DELETE_GAP:
396       deleteGap(edit);
397       break;
398     case CUT:
399       cut(edit, views);
400       break;
401     case PASTE:
402       paste(edit, views);
403       break;
404     case REPLACE:
405       replace(edit);
406       break;
407     case INSERT_NUC:
408       // TODO:add deleteNuc for UNDO
409       // case INSERT_NUC:
410       // insertNuc(edits[e]);
411       break;
412     default:
413       break;
414     }
415   }
416
417   @Override
418   final public void doCommand(AlignmentI[] views)
419   {
420     performEdit(0, views);
421   }
422
423   /**
424    * Undo the stored list of commands, in reverse order.
425    */
426   @Override
427   final public void undoCommand(AlignmentI[] views)
428   {
429     ListIterator<Edit> iterator = edits.listIterator(edits.size());
430     while (iterator.hasPrevious())
431     {
432       Edit e = iterator.previous();
433       switch (e.command)
434       {
435       case INSERT_GAP:
436         deleteGap(e);
437         break;
438       case DELETE_GAP:
439         insertGap(e);
440         break;
441       case CUT:
442         paste(e, views);
443         break;
444       case PASTE:
445         cut(e, views);
446         break;
447       case REPLACE:
448         replace(e);
449         break;
450       case INSERT_NUC:
451         // not implemented
452         break;
453       default:
454         break;
455       }
456     }
457   }
458
459   /**
460    * Insert gap(s) in sequences as specified by the command, and adjust
461    * annotations.
462    * 
463    * @param command
464    */
465   final private static void insertGap(Edit command)
466   {
467
468     for (int s = 0; s < command.seqs.length; s++)
469     {
470       command.seqs[s].insertCharAt(command.position, command.number,
471               command.gapChar);
472       // System.out.println("pos: "+command.position+" number:
473       // "+command.number);
474     }
475
476     adjustAnnotations(command, true, false, null);
477   }
478
479   //
480   // final void insertNuc(Edit command)
481   // {
482   //
483   // for (int s = 0; s < command.seqs.length; s++)
484   // {
485   // System.out.println("pos: "+command.position+" number: "+command.number);
486   // command.seqs[s].insertCharAt(command.position, command.number,'A');
487   // }
488   //
489   // adjustAnnotations(command, true, false, null);
490   // }
491
492   /**
493    * Delete gap(s) in sequences as specified by the command, and adjust
494    * annotations.
495    * 
496    * @param command
497    */
498   final static private void deleteGap(Edit command)
499   {
500     for (int s = 0; s < command.seqs.length; s++)
501     {
502       command.seqs[s].deleteChars(command.position,
503               command.position + command.number);
504     }
505
506     adjustAnnotations(command, false, false, null);
507   }
508
509   /**
510    * Carry out a Cut action. The cut characters are saved in case Undo is
511    * requested.
512    * 
513    * @param command
514    * @param views
515    */
516   static void cut(Edit command, AlignmentI[] views)
517   {
518     boolean seqDeleted = false;
519     command.string = new char[command.seqs.length][];
520
521     for (int i = 0; i < command.seqs.length; i++)
522     {
523       final SequenceI sequence = command.seqs[i];
524       if (sequence.getLength() > command.position)
525       {
526         command.string[i] = sequence.getSequence(command.position,
527                 command.position + command.number);
528         SequenceI oldds = sequence.getDatasetSequence();
529         if (command.oldds != null && command.oldds[i] != null)
530         {
531           // we are redoing an undone cut.
532           sequence.setDatasetSequence(null);
533         }
534         Range cutPositions = sequence.findPositions(command.position + 1,
535                 command.position + command.number);
536         boolean cutIsInternal = cutPositions != null
537                 && sequence.getStart() != cutPositions
538                 .getBegin() && sequence.getEnd() != cutPositions.getEnd();
539
540         /*
541          * perform the cut; if this results in a new dataset sequence, add
542          * that to the alignment dataset
543          */
544         SequenceI ds = sequence.getDatasetSequence();
545         sequence.deleteChars(command.position, command.position
546                 + command.number);
547         SequenceI newDs = sequence.getDatasetSequence();
548         if (newDs != ds && command.al != null
549                 && command.al.getDataset() != null
550                 && !command.al.getDataset().getSequences().contains(newDs))
551         {
552           command.al.getDataset().addSequence(newDs);
553         }
554
555         if (command.oldds != null && command.oldds[i] != null)
556         {
557           // Undoing previous Paste - so
558           // oldds entry contains the cut dataset sequence,
559           // with sequence features in expected place.
560           sequence.setDatasetSequence(command.oldds[i]);
561           command.oldds[i] = oldds;
562         }
563         else
564         {
565           // New cut operation
566           // We always keep track of the dataset sequence so we can safely
567           // restore it during the Undo
568           if (command.oldds == null)
569           {
570             command.oldds = new SequenceI[command.seqs.length];
571           }
572           command.oldds[i] = oldds;// todo not if !cutIsInternal?
573
574           // do we need to edit sequence features for new sequence ?
575           if (oldds != sequence.getDatasetSequence()
576                   || (cutIsInternal
577                           && sequence.getFeatures().hasFeatures()))
578           // todo or just test cutIsInternal && cutPositions != null ?
579           {
580             if (cutPositions != null)
581             {
582               cutFeatures(command, sequence, cutPositions.getBegin(),
583                               cutPositions.getEnd(), cutIsInternal);
584             }
585           }
586         }
587       }
588
589       if (sequence.getLength() < 1)
590       {
591         command.al.deleteSequence(sequence);
592         seqDeleted = true;
593       }
594     }
595
596     adjustAnnotations(command, false, seqDeleted, views);
597   }
598
599   /**
600    * Perform the given Paste command. This may be to add cut or copied sequences
601    * to an alignment, or to undo a 'Cut' action on a region of the alignment.
602    * 
603    * @param command
604    * @param views
605    */
606   static void paste(Edit command, AlignmentI[] views)
607   {
608     boolean seqWasDeleted = false;
609
610     for (int i = 0; i < command.seqs.length; i++)
611     {
612       boolean newDSNeeded = false;
613       boolean newDSWasNeeded = command.oldds != null
614               && command.oldds[i] != null;
615       SequenceI sequence = command.seqs[i];
616       if (sequence.getLength() < 1)
617       {
618         /*
619          * sequence was deleted; re-add it to the alignment
620          */
621         if (command.alIndex[i] < command.al.getHeight())
622         {
623           List<SequenceI> sequences;
624           synchronized (sequences = command.al.getSequences())
625           {
626             if (!(command.alIndex[i] < 0))
627             {
628               sequences.add(command.alIndex[i], sequence);
629             }
630           }
631         }
632         else
633         {
634           command.al.addSequence(sequence);
635         }
636         seqWasDeleted = true;
637       }
638       int newStart = sequence.getStart();
639       int newEnd = sequence.getEnd();
640
641       StringBuilder tmp = new StringBuilder();
642       tmp.append(sequence.getSequence());
643       // Undo of a delete does not replace original dataset sequence on to
644       // alignment sequence.
645
646       int start = 0;
647       int length = 0;
648
649       if (command.string != null && command.string[i] != null)
650       {
651         if (command.position >= tmp.length())
652         {
653           // This occurs if padding is on, and residues
654           // are removed from end of alignment
655           int len = command.position - tmp.length();
656           while (len > 0)
657           {
658             tmp.append(command.gapChar);
659             len--;
660           }
661         }
662         tmp.insert(command.position, command.string[i]);
663         for (int s = 0; s < command.string[i].length; s++)
664         {
665           if (!Comparison.isGap(command.string[i][s]))
666           {
667             length++;
668             if (!newDSNeeded)
669             {
670               newDSNeeded = true;
671               start = sequence.findPosition(command.position);
672               // end = sequence
673               // .findPosition(command.position + command.number);
674             }
675             if (sequence.getStart() == start)
676             {
677               newStart--;
678             }
679             else
680             {
681               newEnd++;
682             }
683           }
684         }
685         command.string[i] = null;
686       }
687
688       sequence.setSequence(tmp.toString());
689       sequence.setStart(newStart);
690       sequence.setEnd(newEnd);
691
692       /*
693        * command and Undo share the same dataset sequence if cut was
694        * at start or end of sequence
695        */
696       boolean sameDatasetSequence = false;
697       if (newDSNeeded)
698       {
699         if (sequence.getDatasetSequence() != null)
700         {
701           SequenceI ds;
702           if (newDSWasNeeded)
703           {
704             ds = command.oldds[i];
705           }
706           else
707           {
708             // make a new DS sequence
709             // use new ds mechanism here
710             String ungapped = AlignSeq.extractGaps(Comparison.GapChars,
711                     sequence.getSequenceAsString());
712             ds = new Sequence(sequence.getName(), ungapped,
713                     sequence.getStart(), sequence.getEnd());
714             ds.setDescription(sequence.getDescription());
715           }
716           if (command.oldds == null)
717           {
718             command.oldds = new SequenceI[command.seqs.length];
719           }
720           command.oldds[i] = sequence.getDatasetSequence();
721           sameDatasetSequence = ds == sequence.getDatasetSequence();
722           ds.setSequenceFeatures(sequence.getSequenceFeatures());
723           sequence.setDatasetSequence(ds);
724         }
725         undoCutFeatures(command, command.seqs[i], start, length,
726                 sameDatasetSequence);
727       }
728     }
729     adjustAnnotations(command, true, seqWasDeleted, views);
730
731     command.string = null;
732   }
733
734   static void replace(Edit command)
735   {
736     StringBuffer tmp;
737     String oldstring;
738     int start = command.position;
739     int end = command.number;
740     // TODO TUTORIAL - Fix for replacement with different length of sequence (or
741     // whole sequence)
742     // TODO Jalview 2.4 bugfix change to an aggregate command - original
743     // sequence string is cut, new string is pasted in.
744     command.number = start + command.string[0].length;
745     for (int i = 0; i < command.seqs.length; i++)
746     {
747       boolean newDSWasNeeded = command.oldds != null
748               && command.oldds[i] != null;
749       boolean newStartEndWasNeeded = command.oldStartEnd!=null && command.oldStartEnd[i]!=null;
750
751       /**
752        * cut addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT,
753        * cut, sg.getStartRes(), sg.getEndRes()-sg.getStartRes()+1,
754        * viewport.alignment));
755        * 
756        */
757       /**
758        * then addHistoryItem(new EditCommand( "Add sequences",
759        * EditCommand.PASTE, sequences, 0, alignment.getWidth(), alignment) );
760        * 
761        */
762
763       Range beforeEditedPositions = command.seqs[i].findPositions(1, start);
764       Range afterEditedPositions = command.seqs[i]
765               .findPositions(start + end + 1, command.seqs[i].getLength());
766       
767       oldstring = command.seqs[i].getSequenceAsString();
768       tmp = new StringBuffer(oldstring.substring(0, start));
769       tmp.append(command.string[i]);
770       String nogaprep = jalview.analysis.AlignSeq.extractGaps(
771               jalview.util.Comparison.GapChars,
772               new String(command.string[i]));
773       int ipos = command.seqs[i].findPosition(start)
774               - command.seqs[i].getStart();
775       if (end < oldstring.length())
776       {
777         tmp.append(oldstring.substring(end));
778       }
779       // stash end prior to updating the sequence object so we can save it if
780       // need be.
781       Range oldstartend = new Range(command.seqs[i].getStart(),
782               command.seqs[i].getEnd());
783       command.seqs[i].setSequence(tmp.toString());
784       command.string[i] = oldstring
785               .substring(start, Math.min(end, oldstring.length()))
786               .toCharArray();
787       String nogapold = AlignSeq.extractGaps(Comparison.GapChars,
788               new String(command.string[i]));
789
790       if (!nogaprep.toLowerCase().equals(nogapold.toLowerCase()))
791       {
792         // we may already have dataset and limits stashed...
793         if (newDSWasNeeded || newStartEndWasNeeded)
794         {
795           if (newDSWasNeeded)
796           {
797           // then just switch the dataset sequence
798           SequenceI oldds = command.seqs[i].getDatasetSequence();
799           command.seqs[i].setDatasetSequence(command.oldds[i]);
800           command.oldds[i] = oldds;
801           }
802           if (newStartEndWasNeeded)
803           {
804             Range newStart = command.oldStartEnd[i];
805             command.oldStartEnd[i] = oldstartend;
806             command.seqs[i].setStart(newStart.getBegin());
807             command.seqs[i].setEnd(newStart.getEnd());
808           }
809         }
810         else         
811         {
812           // decide if we need a new dataset sequence or modify start/end
813           // first edit the original dataset sequence string
814           SequenceI oldds = command.seqs[i].getDatasetSequence();
815           String osp = oldds.getSequenceAsString();
816
817           String fullseq = osp.substring(0, ipos) + nogaprep
818                   + osp.substring(ipos + nogaprep.length());
819
820           // and check if new sequence data is different..
821           if (!fullseq.equalsIgnoreCase(osp))
822           {
823             // old ds and edited ds are different, so
824             // create the new dataset sequence
825             SequenceI newds = new Sequence(oldds);
826             newds.setSequence(fullseq.toUpperCase());
827
828             if (command.oldds == null)
829             {
830               command.oldds = new SequenceI[command.seqs.length];
831             }
832             command.oldds[i] = command.seqs[i].getDatasetSequence();
833             // TODO: JAL-1131 ensure newly created dataset sequence is added to
834             // the set of
835             // dataset sequences associated with the alignment.
836             // TODO: JAL-1131 fix up any annotation associated with new dataset
837             // sequence to ensure that original sequence/annotation
838             // relationships
839             // are preserved.
840             command.seqs[i].setDatasetSequence(newds);
841           }
842           else
843           {
844             if (command.oldStartEnd == null)
845             {
846               command.oldStartEnd = new Range[command.seqs.length];
847             }
848             command.oldStartEnd[i] = new Range(command.seqs[i].getStart(),
849                     command.seqs[i].getEnd());
850             if (beforeEditedPositions != null
851                     && afterEditedPositions == null)
852             {
853               // modification at end
854               command.seqs[i].setEnd(
855                       beforeEditedPositions.getEnd() + nogaprep.length()
856                               - nogapold.length());
857             }
858             else if (afterEditedPositions != null
859                     && beforeEditedPositions == null)
860             {
861               // modification at start
862               command.seqs[i].setStart(
863                       afterEditedPositions.getBegin() - nogaprep.length());
864             }
865             else
866             {
867               // edit covered both start and end. Here we can only guess the
868               // new
869               // start/end
870               String nogapalseq = jalview.analysis.AlignSeq.extractGaps(
871                       jalview.util.Comparison.GapChars,
872                       command.seqs[i].getSequenceAsString().toUpperCase());
873               int newStart = command.seqs[i].getDatasetSequence()
874                       .getSequenceAsString().indexOf(nogapalseq);
875               if (newStart == -1)
876               {
877                 throw new Error(
878                         "Implementation Error: could not locate start/end "
879                                 + "in dataset sequence after an edit of the sequence string");
880               }
881               int newEnd = newStart + nogapalseq.length() - 1;
882               command.seqs[i].setStart(newStart);
883               command.seqs[i].setEnd(newEnd);
884             }
885           }
886         }
887       }
888       tmp = null;
889       oldstring = null;
890     }
891   }
892
893   final static void adjustAnnotations(Edit command, boolean insert,
894           boolean modifyVisibility, AlignmentI[] views)
895   {
896     AlignmentAnnotation[] annotations = null;
897
898     if (modifyVisibility && !insert)
899     {
900       // only occurs if a sequence was added or deleted.
901       command.deletedAnnotationRows = new Hashtable<SequenceI, AlignmentAnnotation[]>();
902     }
903     if (command.fullAlignmentHeight)
904     {
905       annotations = command.al.getAlignmentAnnotation();
906     }
907     else
908     {
909       int aSize = 0;
910       AlignmentAnnotation[] tmp;
911       for (int s = 0; s < command.seqs.length; s++)
912       {
913         command.seqs[s].sequenceChanged();
914
915         if (modifyVisibility)
916         {
917           // Rows are only removed or added to sequence object.
918           if (!insert)
919           {
920             // remove rows
921             tmp = command.seqs[s].getAnnotation();
922             if (tmp != null)
923             {
924               int alen = tmp.length;
925               for (int aa = 0; aa < tmp.length; aa++)
926               {
927                 if (!command.al.deleteAnnotation(tmp[aa]))
928                 {
929                   // strip out annotation not in the current al (will be put
930                   // back on insert in all views)
931                   tmp[aa] = null;
932                   alen--;
933                 }
934               }
935               command.seqs[s].setAlignmentAnnotation(null);
936               if (alen != tmp.length)
937               {
938                 // save the non-null annotation references only
939                 AlignmentAnnotation[] saved = new AlignmentAnnotation[alen];
940                 for (int aa = 0, aapos = 0; aa < tmp.length; aa++)
941                 {
942                   if (tmp[aa] != null)
943                   {
944                     saved[aapos++] = tmp[aa];
945                     tmp[aa] = null;
946                   }
947                 }
948                 tmp = saved;
949                 command.deletedAnnotationRows.put(command.seqs[s], saved);
950                 // and then remove any annotation in the other views
951                 for (int alview = 0; views != null
952                         && alview < views.length; alview++)
953                 {
954                   if (views[alview] != command.al)
955                   {
956                     AlignmentAnnotation[] toremove = views[alview]
957                             .getAlignmentAnnotation();
958                     if (toremove == null || toremove.length == 0)
959                     {
960                       continue;
961                     }
962                     // remove any alignment annotation on this sequence that's
963                     // on that alignment view.
964                     for (int aa = 0; aa < toremove.length; aa++)
965                     {
966                       if (toremove[aa].sequenceRef == command.seqs[s])
967                       {
968                         views[alview].deleteAnnotation(toremove[aa]);
969                       }
970                     }
971                   }
972                 }
973               }
974               else
975               {
976                 // save all the annotation
977                 command.deletedAnnotationRows.put(command.seqs[s], tmp);
978               }
979             }
980           }
981           else
982           {
983             // recover rows
984             if (command.deletedAnnotationRows != null
985                     && command.deletedAnnotationRows
986                             .containsKey(command.seqs[s]))
987             {
988               AlignmentAnnotation[] revealed = command.deletedAnnotationRows
989                       .get(command.seqs[s]);
990               command.seqs[s].setAlignmentAnnotation(revealed);
991               if (revealed != null)
992               {
993                 for (int aa = 0; aa < revealed.length; aa++)
994                 {
995                   // iterate through al adding original annotation
996                   command.al.addAnnotation(revealed[aa]);
997                 }
998                 for (int aa = 0; aa < revealed.length; aa++)
999                 {
1000                   command.al.setAnnotationIndex(revealed[aa], aa);
1001                 }
1002                 // and then duplicate added annotation on every other alignment
1003                 // view
1004                 for (int vnum = 0; views != null && vnum < views.length; vnum++)
1005                 {
1006                   if (views[vnum] != command.al)
1007                   {
1008                     int avwidth = views[vnum].getWidth() + 1;
1009                     // duplicate in this view
1010                     for (int a = 0; a < revealed.length; a++)
1011                     {
1012                       AlignmentAnnotation newann = new AlignmentAnnotation(
1013                               revealed[a]);
1014                       command.seqs[s].addAlignmentAnnotation(newann);
1015                       newann.padAnnotation(avwidth);
1016                       views[vnum].addAnnotation(newann);
1017                       views[vnum].setAnnotationIndex(newann, a);
1018                     }
1019                   }
1020                 }
1021               }
1022             }
1023           }
1024           continue;
1025         }
1026
1027         if (command.seqs[s].getAnnotation() == null)
1028         {
1029           continue;
1030         }
1031
1032         if (aSize == 0)
1033         {
1034           annotations = command.seqs[s].getAnnotation();
1035         }
1036         else
1037         {
1038           tmp = new AlignmentAnnotation[aSize
1039                   + command.seqs[s].getAnnotation().length];
1040
1041           System.arraycopy(annotations, 0, tmp, 0, aSize);
1042
1043           System.arraycopy(command.seqs[s].getAnnotation(), 0, tmp, aSize,
1044                   command.seqs[s].getAnnotation().length);
1045
1046           annotations = tmp;
1047         }
1048         aSize = annotations.length;
1049       }
1050     }
1051
1052     if (annotations == null)
1053     {
1054       return;
1055     }
1056
1057     if (!insert)
1058     {
1059       command.deletedAnnotations = new Hashtable<String, Annotation[]>();
1060     }
1061
1062     int aSize;
1063     Annotation[] temp;
1064     for (int a = 0; a < annotations.length; a++)
1065     {
1066       if (annotations[a].autoCalculated
1067               || annotations[a].annotations == null)
1068       {
1069         continue;
1070       }
1071
1072       int tSize = 0;
1073
1074       aSize = annotations[a].annotations.length;
1075       if (insert)
1076       {
1077         temp = new Annotation[aSize + command.number];
1078         if (annotations[a].padGaps)
1079         {
1080           for (int aa = 0; aa < temp.length; aa++)
1081           {
1082             temp[aa] = new Annotation(command.gapChar + "", null, ' ', 0);
1083           }
1084         }
1085       }
1086       else
1087       {
1088         if (command.position < aSize)
1089         {
1090           if (command.position + command.number >= aSize)
1091           {
1092             tSize = aSize;
1093           }
1094           else
1095           {
1096             tSize = aSize - command.number;
1097           }
1098         }
1099         else
1100         {
1101           tSize = aSize;
1102         }
1103
1104         if (tSize < 0)
1105         {
1106           tSize = aSize;
1107         }
1108         temp = new Annotation[tSize];
1109       }
1110
1111       if (insert)
1112       {
1113         if (command.position < annotations[a].annotations.length)
1114         {
1115           System.arraycopy(annotations[a].annotations, 0, temp, 0,
1116                   command.position);
1117
1118           if (command.deletedAnnotations != null
1119                   && command.deletedAnnotations
1120                           .containsKey(annotations[a].annotationId))
1121           {
1122             Annotation[] restore = command.deletedAnnotations
1123                     .get(annotations[a].annotationId);
1124
1125             System.arraycopy(restore, 0, temp, command.position,
1126                     command.number);
1127
1128           }
1129
1130           System.arraycopy(annotations[a].annotations, command.position,
1131                   temp, command.position + command.number,
1132                   aSize - command.position);
1133         }
1134         else
1135         {
1136           if (command.deletedAnnotations != null
1137                   && command.deletedAnnotations
1138                           .containsKey(annotations[a].annotationId))
1139           {
1140             Annotation[] restore = command.deletedAnnotations
1141                     .get(annotations[a].annotationId);
1142
1143             temp = new Annotation[annotations[a].annotations.length
1144                     + restore.length];
1145             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1146                     annotations[a].annotations.length);
1147             System.arraycopy(restore, 0, temp,
1148                     annotations[a].annotations.length, restore.length);
1149           }
1150           else
1151           {
1152             temp = annotations[a].annotations;
1153           }
1154         }
1155       }
1156       else
1157       {
1158         if (tSize != aSize || command.position < 2)
1159         {
1160           int copylen = Math.min(command.position,
1161                   annotations[a].annotations.length);
1162           if (copylen > 0)
1163           {
1164             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1165                     copylen); // command.position);
1166           }
1167
1168           Annotation[] deleted = new Annotation[command.number];
1169           if (copylen >= command.position)
1170           {
1171             copylen = Math.min(command.number,
1172                     annotations[a].annotations.length - command.position);
1173             if (copylen > 0)
1174             {
1175               System.arraycopy(annotations[a].annotations, command.position,
1176                       deleted, 0, copylen); // command.number);
1177             }
1178           }
1179
1180           command.deletedAnnotations.put(annotations[a].annotationId,
1181                   deleted);
1182           if (annotations[a].annotations.length > command.position
1183                   + command.number)
1184           {
1185             System.arraycopy(annotations[a].annotations,
1186                     command.position + command.number, temp,
1187                     command.position, annotations[a].annotations.length
1188                             - command.position - command.number); // aSize
1189           }
1190         }
1191         else
1192         {
1193           int dSize = aSize - command.position;
1194
1195           if (dSize > 0)
1196           {
1197             Annotation[] deleted = new Annotation[command.number];
1198             System.arraycopy(annotations[a].annotations, command.position,
1199                     deleted, 0, dSize);
1200
1201             command.deletedAnnotations.put(annotations[a].annotationId,
1202                     deleted);
1203
1204             tSize = Math.min(annotations[a].annotations.length,
1205                     command.position);
1206             temp = new Annotation[tSize];
1207             System.arraycopy(annotations[a].annotations, 0, temp, 0, tSize);
1208           }
1209           else
1210           {
1211             temp = annotations[a].annotations;
1212           }
1213         }
1214       }
1215
1216       annotations[a].annotations = temp;
1217     }
1218   }
1219
1220   /**
1221    * Restores features to the state before a Cut.
1222    * <ul>
1223    * <li>re-add any features deleted by the cut</li>
1224    * <li>remove any truncated features created by the cut</li>
1225    * <li>shift right any features to the right of the cut</li>
1226    * </ul>
1227    * 
1228    * @param command
1229    *          the Cut command
1230    * @param seq
1231    *          the sequence the Cut applied to
1232    * @param start
1233    *          the start residue position of the cut
1234    * @param length
1235    *          the number of residues cut
1236    * @param sameDatasetSequence
1237    *          true if dataset sequence and frame of reference were left
1238    *          unchanged by the Cut
1239    */
1240   final static void undoCutFeatures(Edit command, SequenceI seq,
1241           final int start, final int length, boolean sameDatasetSequence)
1242   {
1243     SequenceI sequence = seq.getDatasetSequence();
1244     if (sequence == null)
1245     {
1246       sequence = seq;
1247     }
1248
1249     /*
1250      * shift right features that lie to the right of the restored cut (but not 
1251      * if dataset sequence unchanged - so coordinates were changed by Cut)
1252      */
1253     if (!sameDatasetSequence)
1254     {
1255       /*
1256        * shift right all features right of and not 
1257        * contiguous with the cut position
1258        */
1259       seq.getFeatures().shiftFeatures(start + 1, length);
1260
1261       /*
1262        * shift right any features that start at the cut position,
1263        * unless they were truncated
1264        */
1265       List<SequenceFeature> sfs = seq.getFeatures().findFeatures(start,
1266               start);
1267       for (SequenceFeature sf : sfs)
1268       {
1269         if (sf.getBegin() == start)
1270         {
1271           if (!command.truncatedFeatures.containsKey(seq)
1272                   || !command.truncatedFeatures.get(seq).contains(sf))
1273           {
1274             /*
1275              * feature was shifted left to cut position (not truncated),
1276              * so shift it back right
1277              */
1278             SequenceFeature shifted = new SequenceFeature(sf, sf.getBegin()
1279                     + length, sf.getEnd() + length, sf.getFeatureGroup(),
1280                     sf.getScore());
1281             seq.addSequenceFeature(shifted);
1282             seq.deleteFeature(sf);
1283           }
1284         }
1285       }
1286     }
1287
1288     /*
1289      * restore any features that were deleted or truncated
1290      */
1291     if (command.deletedFeatures != null
1292             && command.deletedFeatures.containsKey(seq))
1293     {
1294       for (SequenceFeature deleted : command.deletedFeatures.get(seq))
1295       {
1296         sequence.addSequenceFeature(deleted);
1297       }
1298     }
1299
1300     /*
1301      * delete any truncated features
1302      */
1303     if (command.truncatedFeatures != null
1304             && command.truncatedFeatures.containsKey(seq))
1305     {
1306       for (SequenceFeature amended : command.truncatedFeatures.get(seq))
1307       {
1308         sequence.deleteFeature(amended);
1309       }
1310     }
1311   }
1312
1313   /**
1314    * Returns the list of edit commands wrapped by this object.
1315    * 
1316    * @return
1317    */
1318   public List<Edit> getEdits()
1319   {
1320     return this.edits;
1321   }
1322
1323   /**
1324    * Returns a map whose keys are the dataset sequences, and values their
1325    * aligned sequences before the command edit list was applied. The aligned
1326    * sequences are copies, which may be updated without affecting the originals.
1327    * 
1328    * The command holds references to the aligned sequences (after editing). If
1329    * the command is an 'undo',then the prior state is simply the aligned state.
1330    * Otherwise, we have to derive the prior state by working backwards through
1331    * the edit list to infer the aligned sequences before editing.
1332    * 
1333    * Note: an alternative solution would be to cache the 'before' state of each
1334    * edit, but this would be expensive in space in the common case that the
1335    * original is never needed (edits are not mirrored).
1336    * 
1337    * @return
1338    * @throws IllegalStateException
1339    *           on detecting an edit command of a type that can't be unwound
1340    */
1341   public Map<SequenceI, SequenceI> priorState(boolean forUndo)
1342   {
1343     Map<SequenceI, SequenceI> result = new HashMap<SequenceI, SequenceI>();
1344     if (getEdits() == null)
1345     {
1346       return result;
1347     }
1348     if (forUndo)
1349     {
1350       for (Edit e : getEdits())
1351       {
1352         for (SequenceI seq : e.getSequences())
1353         {
1354           SequenceI ds = seq.getDatasetSequence();
1355           // SequenceI preEdit = result.get(ds);
1356           if (!result.containsKey(ds))
1357           {
1358             /*
1359              * copy sequence including start/end (but don't use copy constructor
1360              * as we don't need annotations)
1361              */
1362             SequenceI preEdit = new Sequence("", seq.getSequenceAsString(),
1363                     seq.getStart(), seq.getEnd());
1364             preEdit.setDatasetSequence(ds);
1365             result.put(ds, preEdit);
1366           }
1367         }
1368       }
1369       return result;
1370     }
1371
1372     /*
1373      * Work backwards through the edit list, deriving the sequences before each
1374      * was applied. The final result is the sequence set before any edits.
1375      */
1376     Iterator<Edit> editList = new ReverseListIterator<Edit>(getEdits());
1377     while (editList.hasNext())
1378     {
1379       Edit oldEdit = editList.next();
1380       Action action = oldEdit.getAction();
1381       int position = oldEdit.getPosition();
1382       int number = oldEdit.getNumber();
1383       final char gap = oldEdit.getGapCharacter();
1384       for (SequenceI seq : oldEdit.getSequences())
1385       {
1386         SequenceI ds = seq.getDatasetSequence();
1387         SequenceI preEdit = result.get(ds);
1388         if (preEdit == null)
1389         {
1390           preEdit = new Sequence("", seq.getSequenceAsString(),
1391                   seq.getStart(), seq.getEnd());
1392           preEdit.setDatasetSequence(ds);
1393           result.put(ds, preEdit);
1394         }
1395         /*
1396          * 'Undo' this edit action on the sequence (updating the value in the
1397          * map).
1398          */
1399         if (ds != null)
1400         {
1401           if (action == Action.DELETE_GAP)
1402           {
1403             preEdit.setSequence(new String(StringUtils.insertCharAt(
1404                     preEdit.getSequence(), position, number, gap)));
1405           }
1406           else if (action == Action.INSERT_GAP)
1407           {
1408             preEdit.setSequence(new String(StringUtils.deleteChars(
1409                     preEdit.getSequence(), position, position + number)));
1410           }
1411           else
1412           {
1413             System.err.println("Can't undo edit action " + action);
1414             // throw new IllegalStateException("Can't undo edit action " +
1415             // action);
1416           }
1417         }
1418       }
1419     }
1420     return result;
1421   }
1422
1423   public class Edit
1424   {
1425     private SequenceI[] oldds;
1426
1427     /**
1428      * start and end of sequence prior to edit
1429      */
1430     private Range[] oldStartEnd;
1431
1432     private boolean fullAlignmentHeight = false;
1433
1434     private Map<SequenceI, AlignmentAnnotation[]> deletedAnnotationRows;
1435
1436     private Map<String, Annotation[]> deletedAnnotations;
1437
1438     /*
1439      * features deleted by the cut (re-add on Undo)
1440      * (including the original of any shortened features)
1441      */
1442     private Map<SequenceI, List<SequenceFeature>> deletedFeatures;
1443
1444     /*
1445      * shortened features added by the cut (delete on Undo)
1446      */
1447     private Map<SequenceI, List<SequenceFeature>> truncatedFeatures;
1448
1449     private AlignmentI al;
1450
1451     final private Action command;
1452
1453     char[][] string;
1454
1455     SequenceI[] seqs;
1456
1457     private int[] alIndex;
1458
1459     private int position;
1460
1461     private int number;
1462
1463     private char gapChar;
1464
1465     public Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1466             char gap)
1467     {
1468       this.command = cmd;
1469       this.seqs = sqs;
1470       this.position = pos;
1471       this.number = count;
1472       this.gapChar = gap;
1473     }
1474
1475     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1476             AlignmentI align)
1477     {
1478       this(cmd, sqs, pos, count, align.getGapCharacter());
1479
1480       this.al = align;
1481
1482       alIndex = new int[sqs.length];
1483       for (int i = 0; i < sqs.length; i++)
1484       {
1485         alIndex[i] = align.findIndex(sqs[i]);
1486       }
1487
1488       fullAlignmentHeight = (align.getHeight() == sqs.length);
1489     }
1490
1491     /**
1492      * Constructor given a REPLACE command and the replacement string
1493      * 
1494      * @param cmd
1495      * @param sqs
1496      * @param pos
1497      * @param count
1498      * @param align
1499      * @param replace
1500      */
1501     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1502             AlignmentI align, String replace)
1503     {
1504       this(cmd, sqs, pos, count, align);
1505
1506       string = new char[sqs.length][];
1507       for (int i = 0; i < sqs.length; i++)
1508       {
1509         string[i] = replace.toCharArray();
1510       }
1511     }
1512
1513     public SequenceI[] getSequences()
1514     {
1515       return seqs;
1516     }
1517
1518     public int getPosition()
1519     {
1520       return position;
1521     }
1522
1523     public Action getAction()
1524     {
1525       return command;
1526     }
1527
1528     public int getNumber()
1529     {
1530       return number;
1531     }
1532
1533     public char getGapCharacter()
1534     {
1535       return gapChar;
1536     }
1537   }
1538
1539   /**
1540    * Returns an iterator over the list of edit commands which traverses the list
1541    * either forwards or backwards.
1542    * 
1543    * @param forwards
1544    * @return
1545    */
1546   public Iterator<Edit> getEditIterator(boolean forwards)
1547   {
1548     if (forwards)
1549     {
1550       return getEdits().iterator();
1551     }
1552     else
1553     {
1554       return new ReverseListIterator<Edit>(getEdits());
1555     }
1556   }
1557
1558   /**
1559    * Adjusts features for Cut, and saves details of changes made to allow Undo
1560    * <ul>
1561    * <li>features left of the cut are unchanged</li>
1562    * <li>features right of the cut are shifted left</li>
1563    * <li>features internal to the cut region are deleted</li>
1564    * <li>features that overlap or span the cut are shortened</li>
1565    * <li>the originals of any deleted or shortened features are saved, to re-add
1566    * on Undo</li>
1567    * <li>any added (shortened) features are saved, to delete on Undo</li>
1568    * </ul>
1569    * 
1570    * @param command
1571    * @param seq
1572    * @param fromPosition
1573    * @param toPosition
1574    * @param cutIsInternal
1575    */
1576   protected static void cutFeatures(Edit command, SequenceI seq,
1577           int fromPosition, int toPosition, boolean cutIsInternal)
1578   {
1579     /* 
1580      * if the cut is at start or end of sequence
1581      * then we don't modify the sequence feature store
1582      */
1583     if (!cutIsInternal)
1584     {
1585       return;
1586     }
1587     List<SequenceFeature> added = new ArrayList<>();
1588     List<SequenceFeature> removed = new ArrayList<>();
1589   
1590     SequenceFeaturesI featureStore = seq.getFeatures();
1591     if (toPosition < fromPosition || featureStore == null)
1592     {
1593       return;
1594     }
1595   
1596     int cutStartPos = fromPosition;
1597     int cutEndPos = toPosition;
1598     int cutWidth = cutEndPos - cutStartPos + 1;
1599   
1600     synchronized (featureStore)
1601     {
1602       /*
1603        * get features that overlap the cut region
1604        */
1605       List<SequenceFeature> toAmend = featureStore.findFeatures(
1606               cutStartPos, cutEndPos);
1607   
1608       /*
1609        * add any contact features that span the cut region
1610        * (not returned by findFeatures)
1611        */
1612       for (SequenceFeature contact : featureStore.getContactFeatures())
1613       {
1614         if (contact.getBegin() < cutStartPos
1615                 && contact.getEnd() > cutEndPos)
1616         {
1617           toAmend.add(contact);
1618         }
1619       }
1620
1621       /*
1622        * adjust start-end of overlapping features;
1623        * delete features enclosed by the cut;
1624        * delete partially overlapping contact features
1625        */
1626       for (SequenceFeature sf : toAmend)
1627       {
1628         int sfBegin = sf.getBegin();
1629         int sfEnd = sf.getEnd();
1630         int newBegin = sfBegin;
1631         int newEnd = sfEnd;
1632         boolean toDelete = false;
1633         boolean follows = false;
1634         
1635         if (sfBegin >= cutStartPos && sfEnd <= cutEndPos)
1636         {
1637           /*
1638            * feature lies within cut region - delete it
1639            */
1640           toDelete = true;
1641         }
1642         else if (sfBegin < cutStartPos && sfEnd > cutEndPos)
1643         {
1644           /*
1645            * feature spans cut region - left-shift the end
1646            */
1647           newEnd -= cutWidth;
1648         }
1649         else if (sfEnd <= cutEndPos)
1650         {
1651           /*
1652            * feature overlaps left of cut region - truncate right
1653            */
1654           newEnd = cutStartPos - 1;
1655           if (sf.isContactFeature())
1656           {
1657             toDelete = true;
1658           }
1659         }
1660         else if (sfBegin >= cutStartPos)
1661         {
1662           /*
1663            * remaining case - feature overlaps right
1664            * truncate left, adjust end of feature
1665            */
1666           newBegin = cutIsInternal ? cutStartPos : cutEndPos + 1;
1667           newEnd = newBegin + sfEnd - cutEndPos - 1;
1668           if (sf.isContactFeature())
1669           {
1670             toDelete = true;
1671           }
1672         }
1673   
1674         seq.deleteFeature(sf);
1675         if (!follows)
1676         {
1677           removed.add(sf);
1678         }
1679         if (!toDelete)
1680         {
1681           SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1682                   sf.getFeatureGroup(), sf.getScore());
1683           seq.addSequenceFeature(copy);
1684           if (!follows)
1685           {
1686             added.add(copy);
1687           }
1688         }
1689       }
1690   
1691       /*
1692        * and left shift any features lying to the right of the cut region
1693        */
1694
1695       featureStore.shiftFeatures(cutEndPos + 1, -cutWidth);
1696     }
1697
1698     /*
1699      * save deleted and amended features, so that Undo can 
1700      * re-add or delete them respectively
1701      */
1702     if (command.deletedFeatures == null)
1703     {
1704       command.deletedFeatures = new HashMap<>();
1705     }
1706     if (command.truncatedFeatures == null)
1707     {
1708       command.truncatedFeatures = new HashMap<>();
1709     }
1710     command.deletedFeatures.put(seq, removed);
1711     command.truncatedFeatures.put(seq, added);
1712   }
1713 }