a92dca786928a4a0fbd56aa1bb64e7b8154d9835
[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>, or</li>
230      * <li>a new Delete <n> gaps which is <n> positions to the left of the last
231      * delete.</li>
232      * </ul>
233      */
234     boolean contiguous = (action == Action.INSERT_GAP && e.position == lastEdit.position
235             + lastEdit.number)
236             || (action == Action.DELETE_GAP && e.position + e.number == lastEdit.position);
237     if (contiguous)
238     {
239       /*
240        * We are just expanding the range of the last edit. For delete gap, also
241        * moving the start position left.
242        */
243       lastEdit.number += e.number;
244       lastEdit.seqs = e.seqs;
245       if (action == Action.DELETE_GAP)
246       {
247         lastEdit.position--;
248       }
249       return true;
250     }
251     return false;
252   }
253
254   /**
255    * Clear the list of stored edit commands.
256    * 
257    */
258   protected void clearEdits()
259   {
260     edits.clear();
261   }
262
263   /**
264    * Returns the i'th stored Edit command.
265    * 
266    * @param i
267    * @return
268    */
269   protected Edit getEdit(int i)
270   {
271     if (i >= 0 && i < edits.size())
272     {
273       return edits.get(i);
274     }
275     return null;
276   }
277
278   @Override
279   final public String getDescription()
280   {
281     return description;
282   }
283
284   @Override
285   public int getSize()
286   {
287     return edits.size();
288   }
289
290   /**
291    * Return the alignment for the first edit (or null if no edit).
292    * 
293    * @return
294    */
295   final public AlignmentI getAlignment()
296   {
297     return (edits.isEmpty() ? null : edits.get(0).al);
298   }
299
300   /**
301    * append a new editCommand Note. this shouldn't be called if the edit is an
302    * operation affects more alignment objects than the one referenced in al (for
303    * example, cut or pasting whole sequences). Use the form with an additional
304    * AlignmentI[] views parameter.
305    * 
306    * @param command
307    * @param seqs
308    * @param position
309    * @param number
310    * @param al
311    * @param performEdit
312    */
313   final public void appendEdit(Action command, SequenceI[] seqs,
314           int position, int number, AlignmentI al, boolean performEdit)
315   {
316     appendEdit(command, seqs, position, number, al, performEdit, null);
317   }
318
319   /**
320    * append a new edit command with a set of alignment views that may be
321    * operated on
322    * 
323    * @param command
324    * @param seqs
325    * @param position
326    * @param number
327    * @param al
328    * @param performEdit
329    * @param views
330    */
331   final public void appendEdit(Action command, SequenceI[] seqs,
332           int position, int number, AlignmentI al, boolean performEdit,
333           AlignmentI[] views)
334   {
335     Edit edit = new Edit(command, seqs, position, number, al);
336     appendEdit(edit, al, performEdit, views);
337   }
338
339   /**
340    * Overloaded method that accepts an Edit object with additional parameters.
341    * 
342    * @param edit
343    * @param al
344    * @param performEdit
345    * @param views
346    */
347   final public void appendEdit(Edit edit, AlignmentI al,
348           boolean performEdit, AlignmentI[] views)
349   {
350     if (al.getHeight() == edit.seqs.length)
351     {
352       edit.al = al;
353       edit.fullAlignmentHeight = true;
354     }
355
356     addEdit(edit);
357
358     if (performEdit)
359     {
360       performEdit(edit, views);
361     }
362   }
363
364   /**
365    * Execute all the edit commands, starting at the given commandIndex
366    * 
367    * @param commandIndex
368    * @param views
369    */
370   public final void performEdit(int commandIndex, AlignmentI[] views)
371   {
372     ListIterator<Edit> iterator = edits.listIterator(commandIndex);
373     while (iterator.hasNext())
374     {
375       Edit edit = iterator.next();
376       performEdit(edit, views);
377     }
378   }
379
380   /**
381    * Execute one edit command in all the specified alignment views
382    * 
383    * @param edit
384    * @param views
385    */
386   protected static void performEdit(Edit edit, AlignmentI[] views)
387   {
388     switch (edit.command)
389     {
390     case INSERT_GAP:
391       insertGap(edit);
392       break;
393     case DELETE_GAP:
394       deleteGap(edit);
395       break;
396     case CUT:
397       cut(edit, views);
398       break;
399     case PASTE:
400       paste(edit, views);
401       break;
402     case REPLACE:
403       replace(edit);
404       break;
405     case INSERT_NUC:
406       // TODO:add deleteNuc for UNDO
407       // case INSERT_NUC:
408       // insertNuc(edits[e]);
409       break;
410     default:
411       break;
412     }
413   }
414
415   @Override
416   final public void doCommand(AlignmentI[] views)
417   {
418     performEdit(0, views);
419   }
420
421   /**
422    * Undo the stored list of commands, in reverse order.
423    */
424   @Override
425   final public void undoCommand(AlignmentI[] views)
426   {
427     ListIterator<Edit> iterator = edits.listIterator(edits.size());
428     while (iterator.hasPrevious())
429     {
430       Edit e = iterator.previous();
431       switch (e.command)
432       {
433       case INSERT_GAP:
434         deleteGap(e);
435         break;
436       case DELETE_GAP:
437         insertGap(e);
438         break;
439       case CUT:
440         paste(e, views);
441         break;
442       case PASTE:
443         cut(e, views);
444         break;
445       case REPLACE:
446         replace(e);
447         break;
448       case INSERT_NUC:
449         // not implemented
450         break;
451       default:
452         break;
453       }
454     }
455   }
456
457   /**
458    * Insert gap(s) in sequences as specified by the command, and adjust
459    * annotations.
460    * 
461    * @param command
462    */
463   final private static void insertGap(Edit command)
464   {
465
466     for (int s = 0; s < command.seqs.length; s++)
467     {
468       command.seqs[s].insertCharAt(command.position, command.number,
469               command.gapChar);
470       // System.out.println("pos: "+command.position+" number: "+command.number);
471     }
472
473     adjustAnnotations(command, true, false, null);
474   }
475
476   //
477   // final void insertNuc(Edit command)
478   // {
479   //
480   // for (int s = 0; s < command.seqs.length; s++)
481   // {
482   // System.out.println("pos: "+command.position+" number: "+command.number);
483   // command.seqs[s].insertCharAt(command.position, command.number,'A');
484   // }
485   //
486   // adjustAnnotations(command, true, false, null);
487   // }
488
489   /**
490    * Delete gap(s) in sequences as specified by the command, and adjust
491    * annotations.
492    * 
493    * @param command
494    */
495   final static private void deleteGap(Edit command)
496   {
497     for (int s = 0; s < command.seqs.length; s++)
498     {
499       command.seqs[s].deleteChars(command.position, command.position
500               + command.number);
501     }
502
503     adjustAnnotations(command, false, false, null);
504   }
505
506   /**
507    * Carry out a Cut action. The cut characters are saved in case Undo is
508    * requested.
509    * 
510    * @param command
511    * @param views
512    */
513   static void cut(Edit command, AlignmentI[] views)
514   {
515     boolean seqDeleted = false;
516     command.string = new char[command.seqs.length][];
517
518     for (int i = 0; i < command.seqs.length; i++)
519     {
520       final SequenceI sequence = command.seqs[i];
521       if (sequence.getLength() > command.position)
522       {
523         command.string[i] = sequence.getSequence(command.position,
524                 command.position + command.number);
525         SequenceI oldds = sequence.getDatasetSequence();
526         if (command.oldds != null && command.oldds[i] != null)
527         {
528           // we are redoing an undone cut.
529           sequence.setDatasetSequence(null);
530         }
531         Range cutPositions = sequence.findPositions(command.position + 1,
532                 command.position + command.number);
533         boolean cutIsInternal = cutPositions != null
534                 && sequence.getStart() != cutPositions
535                 .getBegin() && sequence.getEnd() != cutPositions.getEnd();
536         sequence.deleteChars(command.position, command.position
537                 + command.number);
538         if (command.oldds != null && command.oldds[i] != null)
539         {
540           // oldds entry contains the cut dataset sequence.
541           sequence.setDatasetSequence(command.oldds[i]);
542           command.oldds[i] = oldds;
543         }
544         else
545         {
546           // modify the oldds if necessary
547           if (oldds != sequence.getDatasetSequence()
548                   || sequence.getFeatures().hasFeatures())
549           {
550             if (command.oldds == null)
551             {
552               command.oldds = new SequenceI[command.seqs.length];
553             }
554             command.oldds[i] = oldds;
555
556             if (cutPositions != null)
557             {
558               cutFeatures(command, sequence, cutPositions.getBegin(),
559                               cutPositions.getEnd(), cutIsInternal);
560             }
561           }
562         }
563       }
564
565       if (sequence.getLength() < 1)
566       {
567         command.al.deleteSequence(sequence);
568         seqDeleted = true;
569       }
570     }
571
572     adjustAnnotations(command, false, seqDeleted, views);
573   }
574
575   /**
576    * Perform the given Paste command. This may be to add cut or copied sequences
577    * to an alignment, or to undo a 'Cut' action on a region of the alignment.
578    * 
579    * @param command
580    * @param views
581    */
582   static void paste(Edit command, AlignmentI[] views)
583   {
584     StringBuffer tmp;
585     boolean newDSNeeded;
586     boolean newDSWasNeeded;
587     int newstart, newend;
588     boolean seqWasDeleted = false;
589     int start = 0, end = 0;
590
591     for (int i = 0; i < command.seqs.length; i++)
592     {
593       newDSNeeded = false;
594       newDSWasNeeded = command.oldds != null && command.oldds[i] != null;
595       SequenceI sequence = command.seqs[i];
596       if (sequence.getLength() < 1)
597       {
598         // ie this sequence was deleted, we need to
599         // readd it to the alignment
600         if (command.alIndex[i] < command.al.getHeight())
601         {
602           List<SequenceI> sequences;
603           synchronized (sequences = command.al.getSequences())
604           {
605             if (!(command.alIndex[i] < 0))
606             {
607               sequences.add(command.alIndex[i], sequence);
608             }
609           }
610         }
611         else
612         {
613           command.al.addSequence(sequence);
614         }
615         seqWasDeleted = true;
616       }
617       newstart = sequence.getStart();
618       newend = sequence.getEnd();
619
620       tmp = new StringBuffer();
621       tmp.append(sequence.getSequence());
622       // Undo of a delete does not replace original dataset sequence on to
623       // alignment sequence.
624
625       if (command.string != null && command.string[i] != null)
626       {
627         if (command.position >= tmp.length())
628         {
629           // This occurs if padding is on, and residues
630           // are removed from end of alignment
631           int length = command.position - tmp.length();
632           while (length > 0)
633           {
634             tmp.append(command.gapChar);
635             length--;
636           }
637         }
638         tmp.insert(command.position, command.string[i]);
639         for (int s = 0; s < command.string[i].length; s++)
640         {
641           if (!Comparison.isGap(command.string[i][s]))
642           {
643             if (!newDSNeeded)
644             {
645               newDSNeeded = true;
646               start = sequence.findPosition(command.position);
647               end = sequence.findPosition(command.position
648                       + command.number);
649             }
650             if (sequence.getStart() == start)
651             {
652               newstart--;
653             }
654             else
655             {
656               newend++;
657             }
658           }
659         }
660         command.string[i] = null;
661       }
662
663       sequence.setSequence(tmp.toString());
664       sequence.setStart(newstart);
665       sequence.setEnd(newend);
666       if (newDSNeeded)
667       {
668         if (sequence.getDatasetSequence() != null)
669         {
670           SequenceI ds;
671           if (newDSWasNeeded)
672           {
673             ds = command.oldds[i];
674           }
675           else
676           {
677             // make a new DS sequence
678             // use new ds mechanism here
679             String ungapped = AlignSeq.extractGaps(Comparison.GapChars,
680                     sequence.getSequenceAsString());
681             ds = new Sequence(sequence.getName(), ungapped,
682                     sequence.getStart(), sequence.getEnd());
683             ds.setDescription(sequence.getDescription());
684           }
685           if (command.oldds == null)
686           {
687             command.oldds = new SequenceI[command.seqs.length];
688           }
689           command.oldds[i] = sequence.getDatasetSequence();
690           sequence.setDatasetSequence(ds);
691         }
692         undoCutFeatures(command, i, start, end);
693       }
694     }
695     adjustAnnotations(command, true, seqWasDeleted, views);
696
697     command.string = null;
698   }
699
700   static void replace(Edit command)
701   {
702     StringBuffer tmp;
703     String oldstring;
704     int start = command.position;
705     int end = command.number;
706     // TODO TUTORIAL - Fix for replacement with different length of sequence (or
707     // whole sequence)
708     // TODO Jalview 2.4 bugfix change to an aggregate command - original
709     // sequence string is cut, new string is pasted in.
710     command.number = start + command.string[0].length;
711     for (int i = 0; i < command.seqs.length; i++)
712     {
713       boolean newDSWasNeeded = command.oldds != null
714               && command.oldds[i] != null;
715
716       /**
717        * cut addHistoryItem(new EditCommand("Cut Sequences", EditCommand.CUT,
718        * cut, sg.getStartRes(), sg.getEndRes()-sg.getStartRes()+1,
719        * viewport.alignment));
720        * 
721        */
722       /**
723        * then addHistoryItem(new EditCommand( "Add sequences",
724        * EditCommand.PASTE, sequences, 0, alignment.getWidth(), alignment) );
725        * 
726        */
727       oldstring = command.seqs[i].getSequenceAsString();
728       tmp = new StringBuffer(oldstring.substring(0, start));
729       tmp.append(command.string[i]);
730       String nogaprep = jalview.analysis.AlignSeq.extractGaps(
731               jalview.util.Comparison.GapChars, new String(
732                       command.string[i]));
733       int ipos = command.seqs[i].findPosition(start)
734               - command.seqs[i].getStart();
735       tmp.append(oldstring.substring(end));
736       command.seqs[i].setSequence(tmp.toString());
737       command.string[i] = oldstring.substring(start, end).toCharArray();
738       String nogapold = jalview.analysis.AlignSeq.extractGaps(
739               jalview.util.Comparison.GapChars, new String(
740                       command.string[i]));
741       if (!nogaprep.toLowerCase().equals(nogapold.toLowerCase()))
742       {
743         if (newDSWasNeeded)
744         {
745           SequenceI oldds = command.seqs[i].getDatasetSequence();
746           command.seqs[i].setDatasetSequence(command.oldds[i]);
747           command.oldds[i] = oldds;
748         }
749         else
750         {
751           if (command.oldds == null)
752           {
753             command.oldds = new SequenceI[command.seqs.length];
754           }
755           command.oldds[i] = command.seqs[i].getDatasetSequence();
756           SequenceI newds = new Sequence(
757                   command.seqs[i].getDatasetSequence());
758           String fullseq, osp = newds.getSequenceAsString();
759           fullseq = osp.substring(0, ipos) + nogaprep
760                   + osp.substring(ipos + nogaprep.length());
761           newds.setSequence(fullseq.toUpperCase());
762           // TODO: JAL-1131 ensure newly created dataset sequence is added to
763           // the set of
764           // dataset sequences associated with the alignment.
765           // TODO: JAL-1131 fix up any annotation associated with new dataset
766           // sequence to ensure that original sequence/annotation relationships
767           // are preserved.
768           command.seqs[i].setDatasetSequence(newds);
769
770         }
771       }
772       tmp = null;
773       oldstring = null;
774     }
775   }
776
777   final static void adjustAnnotations(Edit command, boolean insert,
778           boolean modifyVisibility, AlignmentI[] views)
779   {
780     AlignmentAnnotation[] annotations = null;
781
782     if (modifyVisibility && !insert)
783     {
784       // only occurs if a sequence was added or deleted.
785       command.deletedAnnotationRows = new Hashtable<SequenceI, AlignmentAnnotation[]>();
786     }
787     if (command.fullAlignmentHeight)
788     {
789       annotations = command.al.getAlignmentAnnotation();
790     }
791     else
792     {
793       int aSize = 0;
794       AlignmentAnnotation[] tmp;
795       for (int s = 0; s < command.seqs.length; s++)
796       {
797         command.seqs[s].sequenceChanged();
798
799         if (modifyVisibility)
800         {
801           // Rows are only removed or added to sequence object.
802           if (!insert)
803           {
804             // remove rows
805             tmp = command.seqs[s].getAnnotation();
806             if (tmp != null)
807             {
808               int alen = tmp.length;
809               for (int aa = 0; aa < tmp.length; aa++)
810               {
811                 if (!command.al.deleteAnnotation(tmp[aa]))
812                 {
813                   // strip out annotation not in the current al (will be put
814                   // back on insert in all views)
815                   tmp[aa] = null;
816                   alen--;
817                 }
818               }
819               command.seqs[s].setAlignmentAnnotation(null);
820               if (alen != tmp.length)
821               {
822                 // save the non-null annotation references only
823                 AlignmentAnnotation[] saved = new AlignmentAnnotation[alen];
824                 for (int aa = 0, aapos = 0; aa < tmp.length; aa++)
825                 {
826                   if (tmp[aa] != null)
827                   {
828                     saved[aapos++] = tmp[aa];
829                     tmp[aa] = null;
830                   }
831                 }
832                 tmp = saved;
833                 command.deletedAnnotationRows.put(command.seqs[s], saved);
834                 // and then remove any annotation in the other views
835                 for (int alview = 0; views != null && alview < views.length; alview++)
836                 {
837                   if (views[alview] != command.al)
838                   {
839                     AlignmentAnnotation[] toremove = views[alview]
840                             .getAlignmentAnnotation();
841                     if (toremove == null || toremove.length == 0)
842                     {
843                       continue;
844                     }
845                     // remove any alignment annotation on this sequence that's
846                     // on that alignment view.
847                     for (int aa = 0; aa < toremove.length; aa++)
848                     {
849                       if (toremove[aa].sequenceRef == command.seqs[s])
850                       {
851                         views[alview].deleteAnnotation(toremove[aa]);
852                       }
853                     }
854                   }
855                 }
856               }
857               else
858               {
859                 // save all the annotation
860                 command.deletedAnnotationRows.put(command.seqs[s], tmp);
861               }
862             }
863           }
864           else
865           {
866             // recover rows
867             if (command.deletedAnnotationRows != null
868                     && command.deletedAnnotationRows
869                             .containsKey(command.seqs[s]))
870             {
871               AlignmentAnnotation[] revealed = command.deletedAnnotationRows
872                       .get(command.seqs[s]);
873               command.seqs[s].setAlignmentAnnotation(revealed);
874               if (revealed != null)
875               {
876                 for (int aa = 0; aa < revealed.length; aa++)
877                 {
878                   // iterate through al adding original annotation
879                   command.al.addAnnotation(revealed[aa]);
880                 }
881                 for (int aa = 0; aa < revealed.length; aa++)
882                 {
883                   command.al.setAnnotationIndex(revealed[aa], aa);
884                 }
885                 // and then duplicate added annotation on every other alignment
886                 // view
887                 for (int vnum = 0; views != null && vnum < views.length; vnum++)
888                 {
889                   if (views[vnum] != command.al)
890                   {
891                     int avwidth = views[vnum].getWidth() + 1;
892                     // duplicate in this view
893                     for (int a = 0; a < revealed.length; a++)
894                     {
895                       AlignmentAnnotation newann = new AlignmentAnnotation(
896                               revealed[a]);
897                       command.seqs[s].addAlignmentAnnotation(newann);
898                       newann.padAnnotation(avwidth);
899                       views[vnum].addAnnotation(newann);
900                       views[vnum].setAnnotationIndex(newann, a);
901                     }
902                   }
903                 }
904               }
905             }
906           }
907           continue;
908         }
909
910         if (command.seqs[s].getAnnotation() == null)
911         {
912           continue;
913         }
914
915         if (aSize == 0)
916         {
917           annotations = command.seqs[s].getAnnotation();
918         }
919         else
920         {
921           tmp = new AlignmentAnnotation[aSize
922                   + command.seqs[s].getAnnotation().length];
923
924           System.arraycopy(annotations, 0, tmp, 0, aSize);
925
926           System.arraycopy(command.seqs[s].getAnnotation(), 0, tmp, aSize,
927                   command.seqs[s].getAnnotation().length);
928
929           annotations = tmp;
930         }
931         aSize = annotations.length;
932       }
933     }
934
935     if (annotations == null)
936     {
937       return;
938     }
939
940     if (!insert)
941     {
942       command.deletedAnnotations = new Hashtable<String, Annotation[]>();
943     }
944
945     int aSize;
946     Annotation[] temp;
947     for (int a = 0; a < annotations.length; a++)
948     {
949       if (annotations[a].autoCalculated
950               || annotations[a].annotations == null)
951       {
952         continue;
953       }
954
955       int tSize = 0;
956
957       aSize = annotations[a].annotations.length;
958       if (insert)
959       {
960         temp = new Annotation[aSize + command.number];
961         if (annotations[a].padGaps)
962         {
963           for (int aa = 0; aa < temp.length; aa++)
964           {
965             temp[aa] = new Annotation(command.gapChar + "", null, ' ', 0);
966           }
967         }
968       }
969       else
970       {
971         if (command.position < aSize)
972         {
973           if (command.position + command.number >= aSize)
974           {
975             tSize = aSize;
976           }
977           else
978           {
979             tSize = aSize - command.number;
980           }
981         }
982         else
983         {
984           tSize = aSize;
985         }
986
987         if (tSize < 0)
988         {
989           tSize = aSize;
990         }
991         temp = new Annotation[tSize];
992       }
993
994       if (insert)
995       {
996         if (command.position < annotations[a].annotations.length)
997         {
998           System.arraycopy(annotations[a].annotations, 0, temp, 0,
999                   command.position);
1000
1001           if (command.deletedAnnotations != null
1002                   && command.deletedAnnotations
1003                           .containsKey(annotations[a].annotationId))
1004           {
1005             Annotation[] restore = command.deletedAnnotations
1006                     .get(annotations[a].annotationId);
1007
1008             System.arraycopy(restore, 0, temp, command.position,
1009                     command.number);
1010
1011           }
1012
1013           System.arraycopy(annotations[a].annotations, command.position,
1014                   temp, command.position + command.number, aSize
1015                           - command.position);
1016         }
1017         else
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             temp = new Annotation[annotations[a].annotations.length
1027                     + restore.length];
1028             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1029                     annotations[a].annotations.length);
1030             System.arraycopy(restore, 0, temp,
1031                     annotations[a].annotations.length, restore.length);
1032           }
1033           else
1034           {
1035             temp = annotations[a].annotations;
1036           }
1037         }
1038       }
1039       else
1040       {
1041         if (tSize != aSize || command.position < 2)
1042         {
1043           int copylen = Math.min(command.position,
1044                   annotations[a].annotations.length);
1045           if (copylen > 0)
1046           {
1047             System.arraycopy(annotations[a].annotations, 0, temp, 0,
1048                     copylen); // command.position);
1049           }
1050
1051           Annotation[] deleted = new Annotation[command.number];
1052           if (copylen >= command.position)
1053           {
1054             copylen = Math.min(command.number,
1055                     annotations[a].annotations.length - command.position);
1056             if (copylen > 0)
1057             {
1058               System.arraycopy(annotations[a].annotations,
1059                       command.position, deleted, 0, copylen); // command.number);
1060             }
1061           }
1062
1063           command.deletedAnnotations.put(annotations[a].annotationId,
1064                   deleted);
1065           if (annotations[a].annotations.length > command.position
1066                   + command.number)
1067           {
1068             System.arraycopy(annotations[a].annotations, command.position
1069                     + command.number, temp, command.position,
1070                     annotations[a].annotations.length - command.position
1071                             - command.number); // aSize
1072           }
1073         }
1074         else
1075         {
1076           int dSize = aSize - command.position;
1077
1078           if (dSize > 0)
1079           {
1080             Annotation[] deleted = new Annotation[command.number];
1081             System.arraycopy(annotations[a].annotations, command.position,
1082                     deleted, 0, dSize);
1083
1084             command.deletedAnnotations.put(annotations[a].annotationId,
1085                     deleted);
1086
1087             tSize = Math.min(annotations[a].annotations.length,
1088                     command.position);
1089             temp = new Annotation[tSize];
1090             System.arraycopy(annotations[a].annotations, 0, temp, 0, tSize);
1091           }
1092           else
1093           {
1094             temp = annotations[a].annotations;
1095           }
1096         }
1097       }
1098
1099       annotations[a].annotations = temp;
1100     }
1101   }
1102
1103   final static void undoCutFeatures(Edit command, int index, final int i,
1104           final int j)
1105   {
1106     SequenceI seq = command.seqs[index];
1107     SequenceI sequence = seq.getDatasetSequence();
1108     if (sequence == null)
1109     {
1110       sequence = seq;
1111     }
1112
1113     /*
1114      * TODO: shift right features that lie to the right of the restored cut
1115      * Currently not needed as all features restored with saved dataset sequence
1116      * nor if no saved dataset sequence (as coordinates left unchanged by Cut)
1117      */
1118
1119     /*
1120      * restore any features that were deleted or truncated
1121      */
1122     if (command.deletedFeatures != null
1123             && command.deletedFeatures.containsKey(seq))
1124     {
1125       for (SequenceFeature deleted : command.deletedFeatures.get(seq))
1126       {
1127         sequence.addSequenceFeature(deleted);
1128       }
1129     }
1130
1131     /*
1132      * delete any truncated features
1133      */
1134     if (command.truncatedFeatures != null
1135             && command.truncatedFeatures.containsKey(seq))
1136     {
1137       for (SequenceFeature amended : command.truncatedFeatures.get(seq))
1138       {
1139         sequence.deleteFeature(amended);
1140       }
1141     }
1142   }
1143
1144   /**
1145    * Returns the list of edit commands wrapped by this object.
1146    * 
1147    * @return
1148    */
1149   public List<Edit> getEdits()
1150   {
1151     return this.edits;
1152   }
1153
1154   /**
1155    * Returns a map whose keys are the dataset sequences, and values their
1156    * aligned sequences before the command edit list was applied. The aligned
1157    * sequences are copies, which may be updated without affecting the originals.
1158    * 
1159    * The command holds references to the aligned sequences (after editing). If
1160    * the command is an 'undo',then the prior state is simply the aligned state.
1161    * Otherwise, we have to derive the prior state by working backwards through
1162    * the edit list to infer the aligned sequences before editing.
1163    * 
1164    * Note: an alternative solution would be to cache the 'before' state of each
1165    * edit, but this would be expensive in space in the common case that the
1166    * original is never needed (edits are not mirrored).
1167    * 
1168    * @return
1169    * @throws IllegalStateException
1170    *           on detecting an edit command of a type that can't be unwound
1171    */
1172   public Map<SequenceI, SequenceI> priorState(boolean forUndo)
1173   {
1174     Map<SequenceI, SequenceI> result = new HashMap<SequenceI, SequenceI>();
1175     if (getEdits() == null)
1176     {
1177       return result;
1178     }
1179     if (forUndo)
1180     {
1181       for (Edit e : getEdits())
1182       {
1183         for (SequenceI seq : e.getSequences())
1184         {
1185           SequenceI ds = seq.getDatasetSequence();
1186           // SequenceI preEdit = result.get(ds);
1187           if (!result.containsKey(ds))
1188           {
1189             /*
1190              * copy sequence including start/end (but don't use copy constructor
1191              * as we don't need annotations)
1192              */
1193             SequenceI preEdit = new Sequence("", seq.getSequenceAsString(),
1194                     seq.getStart(), seq.getEnd());
1195             preEdit.setDatasetSequence(ds);
1196             result.put(ds, preEdit);
1197           }
1198         }
1199       }
1200       return result;
1201     }
1202
1203     /*
1204      * Work backwards through the edit list, deriving the sequences before each
1205      * was applied. The final result is the sequence set before any edits.
1206      */
1207     Iterator<Edit> editList = new ReverseListIterator<Edit>(getEdits());
1208     while (editList.hasNext())
1209     {
1210       Edit oldEdit = editList.next();
1211       Action action = oldEdit.getAction();
1212       int position = oldEdit.getPosition();
1213       int number = oldEdit.getNumber();
1214       final char gap = oldEdit.getGapCharacter();
1215       for (SequenceI seq : oldEdit.getSequences())
1216       {
1217         SequenceI ds = seq.getDatasetSequence();
1218         SequenceI preEdit = result.get(ds);
1219         if (preEdit == null)
1220         {
1221           preEdit = new Sequence("", seq.getSequenceAsString(),
1222                   seq.getStart(), seq.getEnd());
1223           preEdit.setDatasetSequence(ds);
1224           result.put(ds, preEdit);
1225         }
1226         /*
1227          * 'Undo' this edit action on the sequence (updating the value in the
1228          * map).
1229          */
1230         if (ds != null)
1231         {
1232           if (action == Action.DELETE_GAP)
1233           {
1234             preEdit.setSequence(new String(StringUtils.insertCharAt(
1235                     preEdit.getSequence(), position, number, gap)));
1236           }
1237           else if (action == Action.INSERT_GAP)
1238           {
1239             preEdit.setSequence(new String(StringUtils.deleteChars(
1240                     preEdit.getSequence(), position, position + number)));
1241           }
1242           else
1243           {
1244             System.err.println("Can't undo edit action " + action);
1245             // throw new IllegalStateException("Can't undo edit action " +
1246             // action);
1247           }
1248         }
1249       }
1250     }
1251     return result;
1252   }
1253
1254   public class Edit
1255   {
1256     public SequenceI[] oldds;
1257
1258     boolean fullAlignmentHeight = false;
1259
1260     Map<SequenceI, AlignmentAnnotation[]> deletedAnnotationRows;
1261
1262     Map<String, Annotation[]> deletedAnnotations;
1263
1264     /*
1265      * features deleted by the cut (re-add on Undo)
1266      * (including the original of any shortened features)
1267      */
1268     Map<SequenceI, List<SequenceFeature>> deletedFeatures;
1269
1270     /*
1271      * shortened features added by the cut (delete on Undo)
1272      */
1273     Map<SequenceI, List<SequenceFeature>> truncatedFeatures;
1274
1275     AlignmentI al;
1276
1277     Action command;
1278
1279     char[][] string;
1280
1281     SequenceI[] seqs;
1282
1283     int[] alIndex;
1284
1285     int position, number;
1286
1287     char gapChar;
1288
1289     public Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1290             char gap)
1291     {
1292       this.command = cmd;
1293       this.seqs = sqs;
1294       this.position = pos;
1295       this.number = count;
1296       this.gapChar = gap;
1297     }
1298
1299     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1300             AlignmentI align)
1301     {
1302       this(cmd, sqs, pos, count, align.getGapCharacter());
1303
1304       this.al = align;
1305
1306       alIndex = new int[sqs.length];
1307       for (int i = 0; i < sqs.length; i++)
1308       {
1309         alIndex[i] = align.findIndex(sqs[i]);
1310       }
1311
1312       fullAlignmentHeight = (align.getHeight() == sqs.length);
1313     }
1314
1315     Edit(Action cmd, SequenceI[] sqs, int pos, int count,
1316             AlignmentI align, String replace)
1317     {
1318       this(cmd, sqs, pos, count, align);
1319
1320       string = new char[sqs.length][];
1321       for (int i = 0; i < sqs.length; i++)
1322       {
1323         string[i] = replace.toCharArray();
1324       }
1325     }
1326
1327     public SequenceI[] getSequences()
1328     {
1329       return seqs;
1330     }
1331
1332     public int getPosition()
1333     {
1334       return position;
1335     }
1336
1337     public Action getAction()
1338     {
1339       return command;
1340     }
1341
1342     public int getNumber()
1343     {
1344       return number;
1345     }
1346
1347     public char getGapCharacter()
1348     {
1349       return gapChar;
1350     }
1351   }
1352
1353   /**
1354    * Returns an iterator over the list of edit commands which traverses the list
1355    * either forwards or backwards.
1356    * 
1357    * @param forwards
1358    * @return
1359    */
1360   public Iterator<Edit> getEditIterator(boolean forwards)
1361   {
1362     if (forwards)
1363     {
1364       return getEdits().iterator();
1365     }
1366     else
1367     {
1368       return new ReverseListIterator<Edit>(getEdits());
1369     }
1370   }
1371
1372   /**
1373    * Adjusts features for Cut, and saves details of changes made to allow Undo
1374    * <ul>
1375    * <li>features left of the cut are unchanged</li>
1376    * <li>features right of the cut are shifted left</li>
1377    * <li>features internal to the cut region are deleted</li>
1378    * <li>features that overlap or span the cut are shortened</li>
1379    * <li>the originals of any deleted or shorted features are saved, to re-add
1380    * on Undo</li>
1381    * <li>any added (shortened) features are saved, to delete on Undo</li>
1382    * </ul>
1383    * 
1384    * @param command
1385    * @param seq
1386    * @param fromPosition
1387    * @param toPosition
1388    * @param cutIsInternal
1389    */
1390   protected static void cutFeatures(Edit command, SequenceI seq,
1391           int fromPosition, int toPosition, boolean cutIsInternal)
1392   {
1393     List<SequenceFeature> added = new ArrayList<>();
1394     List<SequenceFeature> removed = new ArrayList<>();
1395   
1396     SequenceFeaturesI featureStore = seq.getFeatures();
1397     if (toPosition < fromPosition || featureStore == null)
1398     {
1399       return;
1400     }
1401   
1402     int cutStartPos = fromPosition;
1403     int cutEndPos = toPosition;
1404     int cutWidth = cutEndPos - cutStartPos + 1;
1405   
1406     synchronized (featureStore)
1407     {
1408       /*
1409        * get features that overlap the cut region
1410        */
1411       List<SequenceFeature> toAmend = featureStore.findFeatures(
1412               cutStartPos, cutEndPos);
1413   
1414       /*
1415        * add any contact features that span the cut region
1416        * (not returned by findFeatures)
1417        */
1418       for (SequenceFeature contact : featureStore.getContactFeatures())
1419       {
1420         if (contact.getBegin() < cutStartPos
1421                 && contact.getEnd() > cutEndPos)
1422         {
1423           toAmend.add(contact);
1424         }
1425       }
1426
1427       /*
1428        * adjust start-end of overlapping features;
1429        * delete features enclosed by the cut;
1430        * delete partially overlapping contact features
1431        */
1432       for (SequenceFeature sf : toAmend)
1433       {
1434         int sfBegin = sf.getBegin();
1435         int sfEnd = sf.getEnd();
1436         int newBegin = sfBegin;
1437         int newEnd = sfEnd;
1438         boolean toDelete = false;
1439         
1440         if (sfBegin >= cutStartPos && sfEnd <= cutEndPos)
1441         {
1442           /*
1443            * feature lies within cut region - delete it
1444            */
1445           toDelete = true;
1446         }
1447         else if (sfBegin < cutStartPos && sfEnd > cutEndPos)
1448         {
1449           /*
1450            * feature spans cut region - left-shift the end
1451            */
1452           newEnd -= cutWidth;
1453         }
1454         else if (sfEnd <= cutEndPos)
1455         {
1456           /*
1457            * feature overlaps left of cut region - truncate right
1458            */
1459           newEnd = cutStartPos - 1;
1460           if (sf.isContactFeature())
1461           {
1462             toDelete = true;
1463           }
1464         }
1465         else if (sfBegin >= cutStartPos)
1466         {
1467           /*
1468            * remaining case - feature overlaps right
1469            * truncate left, adjust end of feature
1470            */
1471           newBegin = cutIsInternal ? cutStartPos : cutEndPos + 1;
1472           // newEnd = newBegin + (sfEnd - sfBegin) - overlapsBy;
1473           newEnd = newBegin + sfEnd - cutEndPos - 1;
1474           if (sf.isContactFeature())
1475           {
1476             toDelete = true;
1477           }
1478         }
1479   
1480         seq.deleteFeature(sf);
1481         removed.add(sf);
1482         if (!toDelete)
1483         {
1484           SequenceFeature copy = new SequenceFeature(sf, newBegin, newEnd,
1485                   sf.getFeatureGroup(), sf.getScore());
1486           seq.addSequenceFeature(copy);
1487           added.add(copy);
1488         }
1489       }
1490   
1491       /*
1492        * and left shift any features lying to the right of the cut region
1493        * (but not if the cut is at start or end of sequence)
1494        */
1495       if (cutIsInternal)
1496       {
1497         featureStore.shiftFeatures(cutEndPos + 1, -cutWidth);
1498       }
1499     }
1500
1501     /*
1502      * save deleted and amended features, so that Undo can 
1503      * re-add or delete them respectively
1504      */
1505     if (command.deletedFeatures == null)
1506     {
1507       command.deletedFeatures = new HashMap<>();
1508     }
1509     if (command.truncatedFeatures == null)
1510     {
1511       command.truncatedFeatures = new HashMap<>();
1512     }
1513     command.deletedFeatures.put(seq, removed);
1514     command.truncatedFeatures.put(seq, added);
1515   }
1516 }