JAL-2541 it works!! it works!!!
[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         sequence.deleteChars(command.position, command.position
540                 + command.number);
541
542         if (command.oldds != null && command.oldds[i] != null)
543         {
544           // oldds entry contains the cut dataset sequence.
545           sequence.setDatasetSequence(command.oldds[i]);
546           command.oldds[i] = oldds;
547         }
548         else
549         {
550           // modify the oldds if necessary
551           if (oldds != sequence.getDatasetSequence()
552                   || sequence.getFeatures().hasFeatures())
553           {
554             if (command.oldds == null)
555             {
556               command.oldds = new SequenceI[command.seqs.length];
557             }
558             command.oldds[i] = oldds;
559             if (oldds != sequence.getDatasetSequence())
560             {
561               oldds.getFeatures().deleteAll();
562             }
563
564             if (cutPositions != null)
565             {
566               cutFeatures(command, sequence, cutPositions.getBegin(),
567                               cutPositions.getEnd(), cutIsInternal);
568             }
569           }
570         }
571       }
572
573       if (sequence.getLength() < 1)
574       {
575         command.al.deleteSequence(sequence);
576         seqDeleted = true;
577       }
578     }
579
580     adjustAnnotations(command, false, seqDeleted, views);
581   }
582
583   /**
584    * Perform the given Paste command. This may be to add cut or copied sequences
585    * to an alignment, or to undo a 'Cut' action on a region of the alignment.
586    * 
587    * @param command
588    * @param views
589    */
590   static void paste(Edit command, AlignmentI[] views)
591   {
592     boolean seqWasDeleted = false;
593
594     for (int i = 0; i < command.seqs.length; i++)
595     {
596       boolean newDSNeeded = false;
597       boolean newDSWasNeeded = command.oldds != null
598               && command.oldds[i] != null;
599       SequenceI sequence = command.seqs[i];
600       if (sequence.getLength() < 1)
601       {
602         /*
603          * sequence was deleted; re-add it to the alignment
604          */
605         if (command.alIndex[i] < command.al.getHeight())
606         {
607           List<SequenceI> sequences;
608           synchronized (sequences = command.al.getSequences())
609           {
610             if (!(command.alIndex[i] < 0))
611             {
612               sequences.add(command.alIndex[i], sequence);
613             }
614           }
615         }
616         else
617         {
618           command.al.addSequence(sequence);
619         }
620         seqWasDeleted = true;
621       }
622       int newStart = sequence.getStart();
623       int newEnd = sequence.getEnd();
624
625       StringBuilder tmp = new StringBuilder();
626       tmp.append(sequence.getSequence());
627       // Undo of a delete does not replace original dataset sequence on to
628       // alignment sequence.
629
630       int start = 0;
631       int length = 0;
632
633       if (command.string != null && command.string[i] != null)
634       {
635         if (command.position >= tmp.length())
636         {
637           // This occurs if padding is on, and residues
638           // are removed from end of alignment
639           int len = command.position - tmp.length();
640           while (len > 0)
641           {
642             tmp.append(command.gapChar);
643             len--;
644           }
645         }
646         tmp.insert(command.position, command.string[i]);
647         for (int s = 0; s < command.string[i].length; s++)
648         {
649           if (!Comparison.isGap(command.string[i][s]))
650           {
651             length++;
652             if (!newDSNeeded)
653             {
654               newDSNeeded = true;
655               start = sequence.findPosition(command.position);
656               // end = sequence
657               // .findPosition(command.position + command.number);
658             }
659             if (sequence.getStart() == start)
660             {
661               newStart--;
662             }
663             else
664             {
665               newEnd++;
666             }
667           }
668         }
669         command.string[i] = null;
670       }
671
672       sequence.setSequence(tmp.toString());
673       sequence.setStart(newStart);
674       sequence.setEnd(newEnd);
675
676       /*
677        * command and Undo share the same dataset sequence if cut was
678        * at start or end of sequence
679        */
680       boolean sameDatasetSequence = false;
681       if (newDSNeeded)
682       {
683         if (sequence.getDatasetSequence() != null)
684         {
685           SequenceI ds;
686           if (newDSWasNeeded)
687           {
688             ds = command.oldds[i];
689           }
690           else
691           {
692             // make a new DS sequence
693             // use new ds mechanism here
694             String ungapped = AlignSeq.extractGaps(Comparison.GapChars,
695                     sequence.getSequenceAsString());
696             ds = new Sequence(sequence.getName(), ungapped,
697                     sequence.getStart(), sequence.getEnd());
698             ds.setDescription(sequence.getDescription());
699           }
700           if (command.oldds == null)
701           {
702             command.oldds = new SequenceI[command.seqs.length];
703           }
704           command.oldds[i] = sequence.getDatasetSequence();
705           sameDatasetSequence = ds == sequence.getDatasetSequence();
706           ds.setSequenceFeatures(sequence.getSequenceFeatures());
707           sequence.setDatasetSequence(ds);
708         }
709         undoCutFeatures(command, command.seqs[i], start, length,
710                 sameDatasetSequence);
711       }
712     }
713     adjustAnnotations(command, true, seqWasDeleted, views);
714
715     command.string = null;
716   }
717
718   static void replace(Edit command)
719   {
720     StringBuffer tmp;
721     String oldstring;
722     int start = command.position;
723     int end = command.number;
724     // TODO TUTORIAL - Fix for replacement with different length of sequence (or
725     // whole sequence)
726     // TODO Jalview 2.4 bugfix change to an aggregate command - original
727     // sequence string is cut, new string is pasted in.
728     command.number = start + command.string[0].length;
729     for (int i = 0; i < command.seqs.length; i++)
730     {
731       boolean newDSWasNeeded = command.oldds != null
732               && command.oldds[i] != null;
733
734       /**
735        * cut addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT,
736        * cut, sg.getStartRes(), sg.getEndRes()-sg.getStartRes()+1,
737        * viewport.alignment));
738        * 
739        */
740       /**
741        * then addHistoryItem(new EditCommand( "Add sequences",
742        * EditCommand.PASTE, sequences, 0, alignment.getWidth(), alignment) );
743        * 
744        */
745       oldstring = command.seqs[i].getSequenceAsString();
746       tmp = new StringBuffer(oldstring.substring(0, start));
747       tmp.append(command.string[i]);
748       String nogaprep = jalview.analysis.AlignSeq.extractGaps(
749               jalview.util.Comparison.GapChars,
750               new String(command.string[i]));
751       int ipos = command.seqs[i].findPosition(start)
752               - command.seqs[i].getStart();
753       tmp.append(oldstring.substring(end));
754       command.seqs[i].setSequence(tmp.toString());
755       command.string[i] = oldstring.substring(start, end).toCharArray();
756       String nogapold = AlignSeq.extractGaps(Comparison.GapChars,
757               new String(command.string[i]));
758       if (!nogaprep.toLowerCase().equals(nogapold.toLowerCase()))
759       {
760         if (newDSWasNeeded)
761         {
762           SequenceI oldds = command.seqs[i].getDatasetSequence();
763           command.seqs[i].setDatasetSequence(command.oldds[i]);
764           command.oldds[i] = oldds;
765         }
766         else
767         {
768           if (command.oldds == null)
769           {
770             command.oldds = new SequenceI[command.seqs.length];
771           }
772           command.oldds[i] = command.seqs[i].getDatasetSequence();
773           SequenceI newds = new Sequence(
774                   command.seqs[i].getDatasetSequence());
775           String fullseq, osp = newds.getSequenceAsString();
776           fullseq = osp.substring(0, ipos) + nogaprep
777                   + osp.substring(ipos + nogaprep.length());
778           newds.setSequence(fullseq.toUpperCase());
779           // TODO: JAL-1131 ensure newly created dataset sequence is added to
780           // the set of
781           // dataset sequences associated with the alignment.
782           // TODO: JAL-1131 fix up any annotation associated with new dataset
783           // sequence to ensure that original sequence/annotation relationships
784           // are preserved.
785           command.seqs[i].setDatasetSequence(newds);
786
787         }
788       }
789       tmp = null;
790       oldstring = null;
791     }
792   }
793
794   final static void adjustAnnotations(Edit command, boolean insert,
795           boolean modifyVisibility, AlignmentI[] views)
796   {
797     AlignmentAnnotation[] annotations = null;
798
799     if (modifyVisibility && !insert)
800     {
801       // only occurs if a sequence was added or deleted.
802       command.deletedAnnotationRows = new Hashtable<SequenceI, AlignmentAnnotation[]>();
803     }
804     if (command.fullAlignmentHeight)
805     {
806       annotations = command.al.getAlignmentAnnotation();
807     }
808     else
809     {
810       int aSize = 0;
811       AlignmentAnnotation[] tmp;
812       for (int s = 0; s < command.seqs.length; s++)
813       {
814         command.seqs[s].sequenceChanged();
815
816         if (modifyVisibility)
817         {
818           // Rows are only removed or added to sequence object.
819           if (!insert)
820           {
821             // remove rows
822             tmp = command.seqs[s].getAnnotation();
823             if (tmp != null)
824             {
825               int alen = tmp.length;
826               for (int aa = 0; aa < tmp.length; aa++)
827               {
828                 if (!command.al.deleteAnnotation(tmp[aa]))
829                 {
830                   // strip out annotation not in the current al (will be put
831                   // back on insert in all views)
832                   tmp[aa] = null;
833                   alen--;
834                 }
835               }
836               command.seqs[s].setAlignmentAnnotation(null);
837               if (alen != tmp.length)
838               {
839                 // save the non-null annotation references only
840                 AlignmentAnnotation[] saved = new AlignmentAnnotation[alen];
841                 for (int aa = 0, aapos = 0; aa < tmp.length; aa++)
842                 {
843                   if (tmp[aa] != null)
844                   {
845                     saved[aapos++] = tmp[aa];
846                     tmp[aa] = null;
847                   }
848                 }
849                 tmp = saved;
850                 command.deletedAnnotationRows.put(command.seqs[s], saved);
851                 // and then remove any annotation in the other views
852                 for (int alview = 0; views != null
853                         && alview < views.length; alview++)
854                 {
855                   if (views[alview] != command.al)
856                   {
857                     AlignmentAnnotation[] toremove = views[alview]
858                             .getAlignmentAnnotation();
859                     if (toremove == null || toremove.length == 0)
860                     {
861                       continue;
862                     }
863                     // remove any alignment annotation on this sequence that's
864                     // on that alignment view.
865                     for (int aa = 0; aa < toremove.length; aa++)
866                     {
867                       if (toremove[aa].sequenceRef == command.seqs[s])
868                       {
869                         views[alview].deleteAnnotation(toremove[aa]);
870                       }
871                     }
872                   }
873                 }
874               }
875               else
876               {
877                 // save all the annotation
878                 command.deletedAnnotationRows.put(command.seqs[s], tmp);
879               }
880             }
881           }
882           else
883           {
884             // recover rows
885             if (command.deletedAnnotationRows != null
886                     && command.deletedAnnotationRows
887                             .containsKey(command.seqs[s]))
888             {
889               AlignmentAnnotation[] revealed = command.deletedAnnotationRows
890                       .get(command.seqs[s]);
891               command.seqs[s].setAlignmentAnnotation(revealed);
892               if (revealed != null)
893               {
894                 for (int aa = 0; aa < revealed.length; aa++)
895                 {
896                   // iterate through al adding original annotation
897                   command.al.addAnnotation(revealed[aa]);
898                 }
899                 for (int aa = 0; aa < revealed.length; aa++)
900                 {
901                   command.al.setAnnotationIndex(revealed[aa], aa);
902                 }
903                 // and then duplicate added annotation on every other alignment
904                 // view
905                 for (int vnum = 0; views != null && vnum < views.length; vnum++)
906                 {
907                   if (views[vnum] != command.al)
908                   {
909                     int avwidth = views[vnum].getWidth() + 1;
910                     // duplicate in this view
911                     for (int a = 0; a < revealed.length; a++)
912                     {
913                       AlignmentAnnotation newann = new AlignmentAnnotation(
914                               revealed[a]);
915                       command.seqs[s].addAlignmentAnnotation(newann);
916                       newann.padAnnotation(avwidth);
917                       views[vnum].addAnnotation(newann);
918                       views[vnum].setAnnotationIndex(newann, a);
919                     }
920                   }
921                 }
922               }
923             }
924           }
925           continue;
926         }
927
928         if (command.seqs[s].getAnnotation() == null)
929         {
930           continue;
931         }
932
933         if (aSize == 0)
934         {
935           annotations = command.seqs[s].getAnnotation();
936         }
937         else
938         {
939           tmp = new AlignmentAnnotation[aSize
940                   + command.seqs[s].getAnnotation().length];
941
942           System.arraycopy(annotations, 0, tmp, 0, aSize);
943
944           System.arraycopy(command.seqs[s].getAnnotation(), 0, tmp, aSize,
945                   command.seqs[s].getAnnotation().length);
946
947           annotations = tmp;
948         }
949         aSize = annotations.length;
950       }
951     }
952
953     if (annotations == null)
954     {
955       return;
956     }
957
958     if (!insert)
959     {
960       command.deletedAnnotations = new Hashtable<String, Annotation[]>();
961     }
962
963     int aSize;
964     Annotation[] temp;
965     for (int a = 0; a < annotations.length; a++)
966     {
967       if (annotations[a].autoCalculated
968               || annotations[a].annotations == null)
969       {
970         continue;
971       }
972
973       int tSize = 0;
974
975       aSize = annotations[a].annotations.length;
976       if (insert)
977       {
978         temp = new Annotation[aSize + command.number];
979         if (annotations[a].padGaps)
980         {
981           for (int aa = 0; aa < temp.length; aa++)
982           {
983             temp[aa] = new Annotation(command.gapChar + "", null, ' ', 0);
984           }
985         }
986       }
987       else
988       {
989         if (command.position < aSize)
990         {
991           if (command.position + command.number >= aSize)
992           {
993             tSize = aSize;
994           }
995           else
996           {
997             tSize = aSize - command.number;
998           }
999         }
1000         else
1001         {
1002           tSize = aSize;
1003         }
1004
1005         if (tSize < 0)
1006         {
1007           tSize = aSize;
1008         }
1009         temp = new Annotation[tSize];
1010       }
1011
1012       if (insert)
1013       {
1014         if (command.position < annotations[a].annotations.length)
1015         {
1016           System.arraycopy(annotations[a].annotations, 0, temp, 0,
1017                   command.position);
1018
1019           if (command.deletedAnnotations != null
1020                   && command.deletedAnnotations
1021                           .containsKey(annotations[a].annotationId))
1022           {
1023             Annotation[] restore = command.deletedAnnotations
1024                     .get(annotations[a].annotationId);
1025
1026             System.arraycopy(restore, 0, temp, command.position,
1027                     command.number);
1028
1029           }
1030
1031           System.arraycopy(annotations[a].annotations, command.position,
1032                   temp, command.position + command.number,
1033                   aSize - command.position);
1034         }
1035         else
1036         {
1037           if (command.deletedAnnotations != null
1038                   && command.deletedAnnotations
1039                           .containsKey(annotations[a].annotationId))
1040           {
1041             Annotation[] restore = command.deletedAnnotations
1042                     .get(annotations[a].annotationId);
1043
1044             temp = new Annotation[annotations[a].annotations.length
1045                     + restore.length];
1046             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1047                     annotations[a].annotations.length);
1048             System.arraycopy(restore, 0, temp,
1049                     annotations[a].annotations.length, restore.length);
1050           }
1051           else
1052           {
1053             temp = annotations[a].annotations;
1054           }
1055         }
1056       }
1057       else
1058       {
1059         if (tSize != aSize || command.position < 2)
1060         {
1061           int copylen = Math.min(command.position,
1062                   annotations[a].annotations.length);
1063           if (copylen > 0)
1064           {
1065             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1066                     copylen); // command.position);
1067           }
1068
1069           Annotation[] deleted = new Annotation[command.number];
1070           if (copylen >= command.position)
1071           {
1072             copylen = Math.min(command.number,
1073                     annotations[a].annotations.length - command.position);
1074             if (copylen > 0)
1075             {
1076               System.arraycopy(annotations[a].annotations, command.position,
1077                       deleted, 0, copylen); // command.number);
1078             }
1079           }
1080
1081           command.deletedAnnotations.put(annotations[a].annotationId,
1082                   deleted);
1083           if (annotations[a].annotations.length > command.position
1084                   + command.number)
1085           {
1086             System.arraycopy(annotations[a].annotations,
1087                     command.position + command.number, temp,
1088                     command.position, annotations[a].annotations.length
1089                             - command.position - command.number); // aSize
1090           }
1091         }
1092         else
1093         {
1094           int dSize = aSize - command.position;
1095
1096           if (dSize > 0)
1097           {
1098             Annotation[] deleted = new Annotation[command.number];
1099             System.arraycopy(annotations[a].annotations, command.position,
1100                     deleted, 0, dSize);
1101
1102             command.deletedAnnotations.put(annotations[a].annotationId,
1103                     deleted);
1104
1105             tSize = Math.min(annotations[a].annotations.length,
1106                     command.position);
1107             temp = new Annotation[tSize];
1108             System.arraycopy(annotations[a].annotations, 0, temp, 0, tSize);
1109           }
1110           else
1111           {
1112             temp = annotations[a].annotations;
1113           }
1114         }
1115       }
1116
1117       annotations[a].annotations = temp;
1118     }
1119   }
1120
1121   /**
1122    * Restores features to the state before a Cut.
1123    * <ul>
1124    * <li>re-add any features deleted by the cut</li>
1125    * <li>remove any truncated features created by the cut</li>
1126    * <li>shift right any features to the right of the cut</li>
1127    * </ul>
1128    * 
1129    * @param command
1130    *          the Cut command
1131    * @param seq
1132    *          the sequence the Cut applied to
1133    * @param start
1134    *          the start residue position of the cut
1135    * @param length
1136    *          the number of residues cut
1137    * @param sameDatasetSequence
1138    *          true if dataset sequence and frame of reference were left
1139    *          unchanged by the Cut
1140    */
1141   final static void undoCutFeatures(Edit command, SequenceI seq,
1142           final int start, final int length, boolean sameDatasetSequence)
1143   {
1144     SequenceI sequence = seq.getDatasetSequence();
1145     if (sequence == null)
1146     {
1147       sequence = seq;
1148     }
1149
1150     /*
1151      * shift right features that lie to the right of the restored cut (but not 
1152      * if dataset sequence unchanged - so coordinates were changed by Cut)
1153      */
1154     if (!sameDatasetSequence)
1155     {
1156       /*
1157        * shift right all features right of and not 
1158        * contiguous with the cut position
1159        */
1160       seq.getFeatures().shiftFeatures(start + 1, length);
1161
1162       /*
1163        * shift right any features that start at the cut position,
1164        * unless they were truncated
1165        */
1166       List<SequenceFeature> sfs = seq.findFeatures(start, start);
1167       for (SequenceFeature sf : sfs)
1168       {
1169         if (sf.getBegin() == start)
1170         {
1171           if (!command.truncatedFeatures.containsKey(seq)
1172                   || !command.truncatedFeatures.get(seq).contains(sf))
1173           {
1174             /*
1175              * feature was shifted left to cut position (not truncated),
1176              * so shift it back right
1177              */
1178             SequenceFeature shifted = new SequenceFeature(sf, sf.getBegin()
1179                     + length, sf.getEnd() + length, sf.getFeatureGroup(),
1180                     sf.getScore());
1181             seq.addSequenceFeature(shifted);
1182             seq.deleteFeature(sf);
1183           }
1184         }
1185       }
1186     }
1187
1188     /*
1189      * restore any features that were deleted or truncated
1190      */
1191     if (command.deletedFeatures != null
1192             && command.deletedFeatures.containsKey(seq))
1193     {
1194       for (SequenceFeature deleted : command.deletedFeatures.get(seq))
1195       {
1196         sequence.addSequenceFeature(deleted);
1197       }
1198     }
1199
1200     /*
1201      * delete any truncated features
1202      */
1203     if (command.truncatedFeatures != null
1204             && command.truncatedFeatures.containsKey(seq))
1205     {
1206       for (SequenceFeature amended : command.truncatedFeatures.get(seq))
1207       {
1208         sequence.deleteFeature(amended);
1209       }
1210     }
1211   }
1212
1213   /**
1214    * Returns the list of edit commands wrapped by this object.
1215    * 
1216    * @return
1217    */
1218   public List<Edit> getEdits()
1219   {
1220     return this.edits;
1221   }
1222
1223   /**
1224    * Returns a map whose keys are the dataset sequences, and values their
1225    * aligned sequences before the command edit list was applied. The aligned
1226    * sequences are copies, which may be updated without affecting the originals.
1227    * 
1228    * The command holds references to the aligned sequences (after editing). If
1229    * the command is an 'undo',then the prior state is simply the aligned state.
1230    * Otherwise, we have to derive the prior state by working backwards through
1231    * the edit list to infer the aligned sequences before editing.
1232    * 
1233    * Note: an alternative solution would be to cache the 'before' state of each
1234    * edit, but this would be expensive in space in the common case that the
1235    * original is never needed (edits are not mirrored).
1236    * 
1237    * @return
1238    * @throws IllegalStateException
1239    *           on detecting an edit command of a type that can't be unwound
1240    */
1241   public Map<SequenceI, SequenceI> priorState(boolean forUndo)
1242   {
1243     Map<SequenceI, SequenceI> result = new HashMap<SequenceI, SequenceI>();
1244     if (getEdits() == null)
1245     {
1246       return result;
1247     }
1248     if (forUndo)
1249     {
1250       for (Edit e : getEdits())
1251       {
1252         for (SequenceI seq : e.getSequences())
1253         {
1254           SequenceI ds = seq.getDatasetSequence();
1255           // SequenceI preEdit = result.get(ds);
1256           if (!result.containsKey(ds))
1257           {
1258             /*
1259              * copy sequence including start/end (but don't use copy constructor
1260              * as we don't need annotations)
1261              */
1262             SequenceI preEdit = new Sequence("", seq.getSequenceAsString(),
1263                     seq.getStart(), seq.getEnd());
1264             preEdit.setDatasetSequence(ds);
1265             result.put(ds, preEdit);
1266           }
1267         }
1268       }
1269       return result;
1270     }
1271
1272     /*
1273      * Work backwards through the edit list, deriving the sequences before each
1274      * was applied. The final result is the sequence set before any edits.
1275      */
1276     Iterator<Edit> editList = new ReverseListIterator<Edit>(getEdits());
1277     while (editList.hasNext())
1278     {
1279       Edit oldEdit = editList.next();
1280       Action action = oldEdit.getAction();
1281       int position = oldEdit.getPosition();
1282       int number = oldEdit.getNumber();
1283       final char gap = oldEdit.getGapCharacter();
1284       for (SequenceI seq : oldEdit.getSequences())
1285       {
1286         SequenceI ds = seq.getDatasetSequence();
1287         SequenceI preEdit = result.get(ds);
1288         if (preEdit == null)
1289         {
1290           preEdit = new Sequence("", seq.getSequenceAsString(),
1291                   seq.getStart(), seq.getEnd());
1292           preEdit.setDatasetSequence(ds);
1293           result.put(ds, preEdit);
1294         }
1295         /*
1296          * 'Undo' this edit action on the sequence (updating the value in the
1297          * map).
1298          */
1299         if (ds != null)
1300         {
1301           if (action == Action.DELETE_GAP)
1302           {
1303             preEdit.setSequence(new String(StringUtils.insertCharAt(
1304                     preEdit.getSequence(), position, number, gap)));
1305           }
1306           else if (action == Action.INSERT_GAP)
1307           {
1308             preEdit.setSequence(new String(StringUtils.deleteChars(
1309                     preEdit.getSequence(), position, position + number)));
1310           }
1311           else
1312           {
1313             System.err.println("Can't undo edit action " + action);
1314             // throw new IllegalStateException("Can't undo edit action " +
1315             // action);
1316           }
1317         }
1318       }
1319     }
1320     return result;
1321   }
1322
1323   public class Edit
1324   {
1325     public SequenceI[] oldds;
1326
1327     boolean fullAlignmentHeight = false;
1328
1329     Map<SequenceI, AlignmentAnnotation[]> deletedAnnotationRows;
1330
1331     Map<String, Annotation[]> deletedAnnotations;
1332
1333     /*
1334      * features deleted by the cut (re-add on Undo)
1335      * (including the original of any shortened features)
1336      */
1337     Map<SequenceI, List<SequenceFeature>> deletedFeatures;
1338
1339     /*
1340      * shortened features added by the cut (delete on Undo)
1341      */
1342     Map<SequenceI, List<SequenceFeature>> truncatedFeatures;
1343
1344     AlignmentI al;
1345
1346     Action command;
1347
1348     char[][] string;
1349
1350     SequenceI[] seqs;
1351
1352     int[] alIndex;
1353
1354     int position, number;
1355
1356     char gapChar;
1357
1358     public Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1359             char gap)
1360     {
1361       this.command = cmd;
1362       this.seqs = sqs;
1363       this.position = pos;
1364       this.number = count;
1365       this.gapChar = gap;
1366     }
1367
1368     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1369             AlignmentI align)
1370     {
1371       this(cmd, sqs, pos, count, align.getGapCharacter());
1372
1373       this.al = align;
1374
1375       alIndex = new int[sqs.length];
1376       for (int i = 0; i < sqs.length; i++)
1377       {
1378         alIndex[i] = align.findIndex(sqs[i]);
1379       }
1380
1381       fullAlignmentHeight = (align.getHeight() == sqs.length);
1382     }
1383
1384     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1385             AlignmentI align, String replace)
1386     {
1387       this(cmd, sqs, pos, count, align);
1388
1389       string = new char[sqs.length][];
1390       for (int i = 0; i < sqs.length; i++)
1391       {
1392         string[i] = replace.toCharArray();
1393       }
1394     }
1395
1396     public SequenceI[] getSequences()
1397     {
1398       return seqs;
1399     }
1400
1401     public int getPosition()
1402     {
1403       return position;
1404     }
1405
1406     public Action getAction()
1407     {
1408       return command;
1409     }
1410
1411     public int getNumber()
1412     {
1413       return number;
1414     }
1415
1416     public char getGapCharacter()
1417     {
1418       return gapChar;
1419     }
1420   }
1421
1422   /**
1423    * Returns an iterator over the list of edit commands which traverses the list
1424    * either forwards or backwards.
1425    * 
1426    * @param forwards
1427    * @return
1428    */
1429   public Iterator<Edit> getEditIterator(boolean forwards)
1430   {
1431     if (forwards)
1432     {
1433       return getEdits().iterator();
1434     }
1435     else
1436     {
1437       return new ReverseListIterator<Edit>(getEdits());
1438     }
1439   }
1440
1441   /**
1442    * Adjusts features for Cut, and saves details of changes made to allow Undo
1443    * <ul>
1444    * <li>features left of the cut are unchanged</li>
1445    * <li>features right of the cut are shifted left</li>
1446    * <li>features internal to the cut region are deleted</li>
1447    * <li>features that overlap or span the cut are shortened</li>
1448    * <li>the originals of any deleted or shorted features are saved, to re-add
1449    * on Undo</li>
1450    * <li>any added (shortened) features are saved, to delete on Undo</li>
1451    * </ul>
1452    * 
1453    * @param command
1454    * @param seq
1455    * @param fromPosition
1456    * @param toPosition
1457    * @param cutIsInternal
1458    */
1459   protected static void cutFeatures(Edit command, SequenceI seq,
1460           int fromPosition, int toPosition, boolean cutIsInternal)
1461   {
1462     if (!cutIsInternal)
1463     {
1464       return;
1465     }
1466     List<SequenceFeature> added = new ArrayList<>();
1467     List<SequenceFeature> removed = new ArrayList<>();
1468   
1469     SequenceFeaturesI featureStore = seq.getFeatures();
1470     if (toPosition < fromPosition || featureStore == null)
1471     {
1472       return;
1473     }
1474   
1475     int cutStartPos = fromPosition;
1476     int cutEndPos = toPosition;
1477     int cutWidth = cutEndPos - cutStartPos + 1;
1478   
1479     synchronized (featureStore)
1480     {
1481       /*
1482        * get features that overlap the cut region
1483        */
1484       List<SequenceFeature> toAmend = featureStore.findFeatures(
1485               cutStartPos, cutEndPos);
1486   
1487       /*
1488        * add any contact features that span the cut region
1489        * (not returned by findFeatures)
1490        */
1491       for (SequenceFeature contact : featureStore.getContactFeatures())
1492       {
1493         if (contact.getBegin() < cutStartPos
1494                 && contact.getEnd() > cutEndPos)
1495         {
1496           toAmend.add(contact);
1497         }
1498       }
1499
1500       /*
1501        * adjust start-end of overlapping features;
1502        * delete features enclosed by the cut;
1503        * delete partially overlapping contact features
1504        */
1505       for (SequenceFeature sf : toAmend)
1506       {
1507         int sfBegin = sf.getBegin();
1508         int sfEnd = sf.getEnd();
1509         int newBegin = sfBegin;
1510         int newEnd = sfEnd;
1511         boolean toDelete = false;
1512         boolean follows = false;
1513         
1514         if (sfBegin >= cutStartPos && sfEnd <= cutEndPos)
1515         {
1516           /*
1517            * feature lies within cut region - delete it
1518            */
1519           toDelete = true;
1520         }
1521         else if (sfBegin < cutStartPos && sfEnd > cutEndPos)
1522         {
1523           /*
1524            * feature spans cut region - left-shift the end
1525            */
1526           newEnd -= cutWidth;
1527         }
1528         else if (sfEnd <= cutEndPos)
1529         {
1530           /*
1531            * feature overlaps left of cut region - truncate right
1532            */
1533           newEnd = cutStartPos - 1;
1534           if (sf.isContactFeature())
1535           {
1536             toDelete = true;
1537           }
1538         }
1539         else if (sfBegin >= cutStartPos)
1540         {
1541           /*
1542            * remaining case - feature overlaps right
1543            * truncate left, adjust end of feature
1544            */
1545           newBegin = cutIsInternal ? cutStartPos : cutEndPos + 1;
1546           newEnd = newBegin + sfEnd - cutEndPos - 1;
1547           if (sf.isContactFeature())
1548           {
1549             toDelete = true;
1550           }
1551         }
1552   
1553         seq.deleteFeature(sf);
1554         if (!follows)
1555         {
1556           removed.add(sf);
1557         }
1558         if (!toDelete)
1559         {
1560           SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1561                   sf.getFeatureGroup(), sf.getScore());
1562           seq.addSequenceFeature(copy);
1563           if (!follows)
1564           {
1565             added.add(copy);
1566           }
1567         }
1568       }
1569   
1570       /*
1571        * and left shift any features lying to the right of the cut region
1572        * (but not if the cut is at start or end of sequence)
1573        */
1574       if (cutIsInternal)
1575       {
1576         featureStore.shiftFeatures(cutEndPos + 1, -cutWidth);
1577       }
1578     }
1579
1580     /*
1581      * save deleted and amended features, so that Undo can 
1582      * re-add or delete them respectively
1583      */
1584     if (command.deletedFeatures == null)
1585     {
1586       command.deletedFeatures = new HashMap<>();
1587     }
1588     if (command.truncatedFeatures == null)
1589     {
1590       command.truncatedFeatures = new HashMap<>();
1591     }
1592     command.deletedFeatures.put(seq, removed);
1593     command.truncatedFeatures.put(seq, added);
1594   }
1595 }