JAL-1116 - location where vamsas sync failure occurs
[jalview.git] / src / jalview / io / VamsasAppDatastore.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *
11  * Jalview is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14  * PURPOSE.  See the GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.io;
19
20 import jalview.bin.Cache;
21 import jalview.datamodel.AlignedCodonFrame;
22 import jalview.datamodel.AlignmentAnnotation;
23 import jalview.datamodel.GraphLine;
24 import jalview.datamodel.SequenceI;
25 import jalview.gui.AlignFrame;
26 import jalview.gui.AlignViewport;
27 import jalview.gui.Desktop;
28 import jalview.gui.TreePanel;
29 import jalview.io.vamsas.Datasetsequence;
30 import jalview.io.vamsas.DatastoreItem;
31 import jalview.io.vamsas.DatastoreRegistry;
32 import jalview.io.vamsas.Rangetype;
33 import java.io.IOException;
34 import java.util.Enumeration;
35 import java.util.HashMap;
36 import java.util.Hashtable;
37 import java.util.IdentityHashMap;
38 import java.util.Iterator;
39 import java.util.List;
40 import java.util.Vector;
41 import java.util.jar.JarInputStream;
42 import java.util.jar.JarOutputStream;
43
44 import uk.ac.vamsas.client.*;
45 import uk.ac.vamsas.objects.core.*;
46 import uk.ac.vamsas.objects.utils.Properties;
47
48 /*
49  *
50  * static {
51  * org.exolab.castor.util.LocalConfiguration.getInstance().getProperties().setProperty(
52  * "org.exolab.castor.serializer", "org.apache.xml.serialize.XMLSerilazizer"); }
53  *
54  */
55 /*
56  * TODO: check/verify consistency for vamsas sync with group associated alignment annotation
57  */
58 public class VamsasAppDatastore
59 {
60   /**
61    * Type used for general jalview generated annotation added to vamsas document
62    */
63   public static final String JALVIEW_ANNOTATION_ROW = "JalviewAnnotation";
64
65   /**
66    * AlignmentAnnotation property to indicate that values should not be
67    * interpolated
68    */
69   public static final String DISCRETE_ANNOTATION = "discrete";
70
71   /**
72    * continuous property - optional to specify that annotation should be
73    * represented as a continous graph line
74    */
75   private static final String CONTINUOUS_ANNOTATION = "continuous";
76
77   private static final String THRESHOLD = "threshold";
78
79   /**
80    * template for provenance entries written to vamsas session document
81    */
82   Entry provEntry = null;
83
84   /**
85    * Instance of the session document being synchronized with
86    */
87   IClientDocument cdoc;
88
89   /**
90    * map Vorba (vamsas object xml ref) IDs to live jalview object references
91    */
92   Hashtable vobj2jv;
93
94   /**
95    * map live jalview object references to Vorba IDs
96    */
97   IdentityHashMap jv2vobj;
98
99   /**
100    * map jalview sequence set ID (which is vorba ID for alignment) to last
101    * recorded hash value for the alignment viewport (the undo/redo hash value)
102    */
103   Hashtable alignRDHash;
104
105   public VamsasAppDatastore(IClientDocument cdoc, Hashtable vobj2jv,
106           IdentityHashMap jv2vobj, Entry provEntry, Hashtable alignRDHash)
107   {
108     this.cdoc = cdoc;
109     this.vobj2jv = vobj2jv;
110     this.jv2vobj = jv2vobj;
111     this.provEntry = provEntry;
112     this.alignRDHash = alignRDHash;
113     buildSkipList();
114   }
115
116   /**
117    * the skipList used to skip over views from Jalview Appdata's that we've
118    * already syncrhonized
119    */
120   Hashtable skipList;
121
122   private void buildSkipList()
123   {
124     skipList = new Hashtable();
125     AlignFrame[] al = Desktop.getAlignframes();
126     for (int f = 0; al != null && f < al.length; f++)
127     {
128       skipList.put(al[f].getViewport().getSequenceSetId(), al[f]);
129     }
130   }
131
132   /**
133    * @return the Vobject bound to Jalview datamodel object
134    */
135   protected Vobject getjv2vObj(Object jvobj)
136   {
137     if (jv2vobj.containsKey(jvobj))
138     {
139       return cdoc.getObject((VorbaId) jv2vobj.get(jvobj));
140     }
141     // check if we're working with a string - then workaround
142     // the use of IdentityHashTable because different strings
143     // have different object IDs.
144     if (jvobj instanceof String)
145     {
146       Object seqsetidobj = null;
147       seqsetidobj = getVamsasObjectBinding().get(jvobj);
148       if (seqsetidobj != null)
149       {
150         if (seqsetidobj instanceof String)
151         {
152           // what is expected. object returned by av.getSequenceSetId() -
153           // reverse lookup to get the 'registered' instance of this string
154           Vobject obj = getjv2vObj(seqsetidobj);
155           if (obj != null && !(obj instanceof Alignment))
156           {
157             Cache.log
158                     .warn("IMPLEMENTATION ERROR?: Unexpected mapping for unmapped jalview string object content:"
159                             + seqsetidobj + " to object " + obj);
160           }
161           return obj;
162         }
163         else
164         {
165           Cache.log.warn("Unexpected mapping for Jalview String Object ID "
166                   + seqsetidobj + " to another jalview dataset object "
167                   + seqsetidobj);
168         }
169       }
170     }
171
172     if (Cache.log.isDebugEnabled())
173     {
174       Cache.log.debug("Returning null VorbaID binding for jalview object "
175               + jvobj);
176     }
177     return null;
178   }
179
180   /**
181    *
182    * @param vobj
183    * @return Jalview datamodel object bound to the vamsas document object
184    */
185   protected Object getvObj2jv(uk.ac.vamsas.client.Vobject vobj)
186   {
187     VorbaId id = vobj.getVorbaId();
188     if (id == null)
189     {
190       id = cdoc.registerObject(vobj);
191       Cache.log
192               .debug("Registering new object and returning null for getvObj2jv");
193       return null;
194     }
195     if (vobj2jv.containsKey(vobj.getVorbaId()))
196     {
197       return vobj2jv.get(vobj.getVorbaId());
198     }
199     return null;
200   }
201
202   protected void bindjvvobj(Object jvobj, uk.ac.vamsas.client.Vobject vobj)
203   {
204     VorbaId id = vobj.getVorbaId();
205     if (id == null)
206     {
207       id = cdoc.registerObject(vobj);
208       if (id == null || vobj.getVorbaId() == null
209               || cdoc.getObject(id) != vobj)
210       {
211         Cache.log.error("Failed to get id for "
212                 + (vobj.isRegisterable() ? "registerable"
213                         : "unregisterable") + " object " + vobj);
214       }
215     }
216
217     if (vobj2jv.containsKey(vobj.getVorbaId())
218             && !((VorbaId) vobj2jv.get(vobj.getVorbaId())).equals(jvobj))
219     {
220       Cache.log.debug(
221               "Warning? Overwriting existing vamsas id binding for "
222                       + vobj.getVorbaId(), new Exception(
223                       "Overwriting vamsas id binding."));
224     }
225     else if (jv2vobj.containsKey(jvobj)
226             && !((VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId()))
227     {
228       Cache.log.debug(
229               "Warning? Overwriting existing jalview object binding for "
230                       + jvobj, new Exception(
231                       "Overwriting jalview object binding."));
232     }
233     /*
234      * Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id "
235      * +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+"
236      * already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to
237      * bindjvvobj")); }
238      */
239     // we just update the hash's regardless!
240     Cache.log.debug("Binding " + vobj.getVorbaId() + " to " + jvobj);
241     vobj2jv.put(vobj.getVorbaId(), jvobj);
242     // JBPNote - better implementing a hybrid invertible hash.
243     jv2vobj.put(jvobj, vobj.getVorbaId());
244   }
245
246   /**
247    * put the alignment viewed by AlignViewport into cdoc.
248    *
249    * @param av
250    *          alignViewport to be stored
251    * @param aFtitle
252    *          title for alignment
253    * @return true if alignment associated with viewport was stored/synchronized
254    *         to document
255    */
256   public boolean storeVAMSAS(AlignViewport av, String aFtitle)
257   {
258     try
259     {
260       jalview.datamodel.AlignmentI jal = av.getAlignment();
261       jalview.datamodel.AlignmentI jds = jal.getDataset();
262       boolean nw = false;
263       VAMSAS root = null; // will be resolved based on Dataset Parent.
264       // /////////////////////////////////////////
265       // SAVE THE DATASET
266       DataSet dataset = null;
267       if (jds == null)
268       {
269         Cache.log.warn("Creating new dataset for an alignment.");
270         jal.setDataset(null);
271         jds = jal.getDataset();
272       }
273
274       // try and get alignment and association for sequence set id
275
276       Alignment alignment = (Alignment) getjv2vObj(av.getSequenceSetId());
277       if (alignment != null)
278       {
279         dataset = (DataSet) alignment.getV_parent();
280       }
281       else
282       {
283         // is the dataset already registered
284         dataset = (DataSet) getjv2vObj(jds);
285       }
286
287       if (dataset == null)
288       {
289         // it might be that one of the dataset sequences does actually have a
290         // binding, so search for it indirectly. If it does, then the local
291         // jalview dataset
292         // must be merged with the existing vamsas dataset.
293         jalview.datamodel.SequenceI[] jdatset = jds.getSequencesArray();
294         for (int i = 0; i < jdatset.length; i++)
295         {
296           Vobject vbound = getjv2vObj(jdatset[i]);
297           if (vbound != null)
298           {
299             if (vbound instanceof uk.ac.vamsas.objects.core.Sequence)
300             {
301               if (dataset == null)
302               {
303                 dataset = (DataSet) vbound.getV_parent();
304               }
305               else
306               {
307                 if (vbound.getV_parent() != null
308                         && dataset != vbound.getV_parent())
309                 {
310                   throw new Error(
311                           "IMPLEMENTATION ERROR: Cannot map an alignment of sequences from different datasets into a single alignment in the vamsas document.");
312                   // This occurs because the dataset for the alignment we are
313                   // trying to
314                 }
315               }
316             }
317           }
318         }
319       }
320
321       if (dataset == null)
322       {
323         Cache.log.warn("Creating new vamsas dataset for alignment view "
324                 + av.getSequenceSetId());
325         // we create a new dataset on the default vamsas root.
326         root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.
327         dataset = new DataSet();
328         root.addDataSet(dataset);
329         bindjvvobj(jds, dataset);
330         dataset.setProvenance(dummyProvenance());
331         // dataset.getProvenance().addEntry(provEntry);
332         nw = true;
333       }
334       else
335       {
336         root = (VAMSAS) dataset.getV_parent();
337       }
338       // update dataset
339       Sequence sequence;
340       // set new dataset and alignment sequences based on alignment Nucleotide
341       // flag.
342       // this *will* break when alignment contains both nucleotide and amino
343       // acid sequences.
344       String dict = jal.isNucleotide() ? uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_NA
345               : uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_AA;
346       Vector dssmods = new Vector();
347       for (int i = 0; i < jal.getHeight(); i++)
348       {
349         SequenceI sq = jal.getSequenceAt(i).getDatasetSequence(); // only insert
350         // referenced
351         // sequences
352         // to dataset.
353         Datasetsequence dssync = new jalview.io.vamsas.Datasetsequence(
354                 this, sq, dict, dataset);
355         sequence = (Sequence) dssync.getVobj();
356         if (dssync.getModified())
357         {
358           dssmods.addElement(sequence);
359         }
360         ;
361       }
362       if (dssmods.size() > 0)
363       {
364         if (!nw)
365         {
366           Entry pentry = this.addProvenance(dataset.getProvenance(),
367                   "updated sequences");
368           // pentry.addInput(vInput); could write in which sequences were
369           // modified.
370           dssmods.removeAllElements();
371         }
372       }
373       // dataset.setProvenance(getVamsasProvenance(jal.getDataset().getProvenance()));
374       // ////////////////////////////////////////////
375       if (alignmentWillBeSkipped(av))
376       {
377         // TODO: trees could be written - but for the moment we just
378         addToSkipList(av);
379         // add to the JalviewXML skipList and ..
380         return false;
381       }
382
383       if (alignment == null)
384       {
385         alignment = new Alignment();
386         bindjvvobj(av.getSequenceSetId(), alignment);
387         if (alignment.getProvenance() == null)
388         {
389           alignment.setProvenance(new Provenance());
390         }
391         addProvenance(alignment.getProvenance(), "added"); // TODO: insert some
392         // sensible source
393         // here
394         dataset.addAlignment(alignment);
395         {
396           Property title = new Property();
397           title.setName("title");
398           title.setType("string");
399           title.setContent(aFtitle);
400           alignment.addProperty(title);
401         }
402         alignment.setGapChar(String.valueOf(av.getGapCharacter()));
403         for (int i = 0; i < jal.getHeight(); i++)
404         {
405           syncToAlignmentSequence(jal.getSequenceAt(i), alignment, null);
406         }
407         alignRDHash.put(av.getSequenceSetId(), av.getUndoRedoHash());
408       }
409       else
410       {
411         // always prepare to clone the alignment
412         boolean alismod = av.isUndoRedoHashModified((long[]) alignRDHash
413                 .get(av.getSequenceSetId()));
414         // todo: verify and update mutable alignment props.
415         // TODO: Use isLocked methods
416         if (alignment.getModifiable() == null
417                 || alignment.getModifiable().length() == 0)
418         // && !alignment.isDependedOn())
419         {
420           boolean modified = false;
421           // check existing sequences in local and in document.
422           Vector docseqs = new Vector(
423                   alignment.getAlignmentSequenceAsReference());
424           for (int i = 0; i < jal.getHeight(); i++)
425           {
426             modified |= syncToAlignmentSequence(jal.getSequenceAt(i),
427                     alignment, docseqs);
428           }
429           if (docseqs.size() > 0)
430           {
431             // removeValignmentSequences(alignment, docseqs);
432             docseqs.removeAllElements();
433             System.out
434                     .println("Sequence deletion from alignment is not implemented.");
435
436           }
437           if (modified)
438           {
439             if (alismod)
440             {
441               // info in the undo
442               addProvenance(alignment.getProvenance(), "Edited"); // TODO:
443               // insert
444               // something
445               // sensible
446               // here again
447             }
448             else
449             {
450               // info in the undo
451               addProvenance(alignment.getProvenance(), "Attributes Edited"); // TODO:
452               // insert
453               // something
454               // sensible
455               // here
456               // again
457             }
458           }
459           if (alismod)
460           {
461             System.out.println("update alignment in document.");
462           }
463           else
464           {
465             System.out.println("alignment in document left unchanged.");
466           }
467         }
468         else
469         {
470           // unbind alignment from view.
471           // create new binding and new alignment.
472           // mark trail on new alignment as being derived from old ?
473           System.out
474                   .println("update edited alignment to new alignment in document.");
475         }
476       }
477       // ////////////////////////////////////////////
478       // SAVE Alignment Sequence Features
479       for (int i = 0, iSize = alignment.getAlignmentSequenceCount(); i < iSize; i++)
480       {
481         AlignmentSequence valseq;
482         SequenceI alseq = (SequenceI) getvObj2jv(valseq = alignment
483                 .getAlignmentSequence(i));
484         if (alseq != null && alseq.getSequenceFeatures() != null)
485         {
486           /*
487            * We do not put local Alignment Sequence Features into the vamsas
488            * document yet.
489            *
490            *
491            * jalview.datamodel.SequenceFeature[] features = alseq
492            * .getSequenceFeatures(); for (int f = 0; f < features.length; f++) {
493            * if (features[f] != null) { AlignmentSequenceAnnotation valseqf = (
494            * AlignmentSequenceAnnotation) getjv2vObj(features[i]); if (valseqf
495            * == null) {
496            *
497            * valseqf = (AlignmentSequenceAnnotation) getDSAnnotationFromJalview(
498            * new AlignmentSequenceAnnotation(), features[i]);
499            * valseqf.setGraph(false);
500            * valseqf.addProperty(newProperty("jalview:feature"
501            * ,"boolean","true")); if (valseqf.getProvenance() == null) {
502            * valseqf.setProvenance(new Provenance()); }
503            * addProvenance(valseqf.getProvenance(), "created"); // JBPNote - //
504            * need to // update bindjvvobj(features[i], valseqf);
505            * valseq.addAlignmentSequenceAnnotation(valseqf); } } }
506            */
507         }
508       }
509
510       // ////////////////////////////////////////////
511       // SAVE ANNOTATIONS
512       if (jal.getAlignmentAnnotation() != null)
513       {
514         jalview.datamodel.AlignmentAnnotation[] aa = jal
515                 .getAlignmentAnnotation();
516         java.util.HashMap AlSeqMaps = new HashMap(); // stores int maps from
517         // alignment columns to
518         // sequence positions.
519         for (int i = 0; i < aa.length; i++)
520         {
521           if (aa[i] == null || isJalviewOnly(aa[i]))
522           {
523             continue;
524           }
525           if (aa[i].groupRef != null)
526           {
527             // TODO: store any group associated annotation references
528             Cache.log
529                     .warn("Group associated sequence annotation is not stored in VAMSAS document.");
530             continue;
531           }
532           if (aa[i].sequenceRef != null)
533           {
534             // Deal with sequence associated annotation
535             Vobject sref = getjv2vObj(aa[i].sequenceRef);
536             if (sref instanceof uk.ac.vamsas.objects.core.AlignmentSequence)
537             {
538               saveAlignmentSequenceAnnotation(AlSeqMaps,
539                       (AlignmentSequence) sref, aa[i]);
540             }
541             else
542             {
543               // first find the alignment sequence to associate this with.
544               for (SequenceI jvalsq:av.getAlignment().getSequences()) {
545                 // saveDatasetSequenceAnnotation(AlSeqMaps,(uk.ac.vamsas.objects.core.Sequence)
546                 // sref, aa[i]);
547                 if (jvalsq.getDatasetSequence() == aa[i].sequenceRef)
548                 {
549                   Vobject alsref = getjv2vObj(jvalsq);
550                   saveAlignmentSequenceAnnotation(AlSeqMaps,
551                           (AlignmentSequence) alsref, aa[i]);
552                   break;
553                 }
554                 ;
555               }
556             }
557           }
558           else
559           {
560             // add Alignment Annotation
561             uk.ac.vamsas.objects.core.AlignmentAnnotation an = (uk.ac.vamsas.objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);
562             if (an == null)
563             {
564               an = new uk.ac.vamsas.objects.core.AlignmentAnnotation();
565               an.setType(JALVIEW_ANNOTATION_ROW);
566               an.setDescription(aa[i].description);
567               alignment.addAlignmentAnnotation(an);
568               Seg vSeg = new Seg(); // TODO: refactor to have a default
569               // rangeAnnotationType initer/updater that
570               // takes a set of int ranges.
571               vSeg.setStart(1);
572               vSeg.setInclusive(true);
573               vSeg.setEnd(jal.getWidth());
574               an.addSeg(vSeg);
575               if (aa[i].graph > 0)
576               {
577                 an.setGraph(true); // aa[i].graph);
578               }
579               an.setLabel(aa[i].label);
580               an.setProvenance(dummyProvenance());
581               if (aa[i].graph != AlignmentAnnotation.NO_GRAPH)
582               {
583                 an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote
584                 // -
585                 // originally we
586                 // were going to
587                 // store
588                 // graphGroup in
589                 // the Jalview
590                 // specific
591                 // bits.
592                 an.setGraph(true);
593               }
594               else
595               {
596                 an.setGraph(false);
597               }
598               AnnotationElement ae;
599
600               for (int a = 0; a < aa[i].annotations.length; a++)
601               {
602                 if ((aa[i] == null) || (aa[i].annotations[a] == null))
603                 {
604                   continue;
605                 }
606
607                 ae = new AnnotationElement();
608                 ae.setDescription(aa[i].annotations[a].description);
609                 ae.addGlyph(new Glyph());
610                 ae.getGlyph(0).setContent(
611                         aa[i].annotations[a].displayCharacter); // assume
612                 // jax-b
613                 // takes
614                 // care
615                 // of
616                 // utf8
617                 // translation
618                 if (an.isGraph())
619                 {
620                   ae.addValue(aa[i].annotations[a].value);
621                 }
622                 ae.setPosition(a + 1);
623                 if (aa[i].annotations[a].secondaryStructure != ' ')
624                 {
625                   Glyph ss = new Glyph();
626                   ss.setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
627                   ss.setContent(String
628                           .valueOf(aa[i].annotations[a].secondaryStructure));
629                   ae.addGlyph(ss);
630                 }
631                 an.addAnnotationElement(ae);
632               }
633               if (aa[i].editable)
634               {
635                 // an.addProperty(newProperty("jalview:editable", null,
636                 // "true"));
637                 // an.setModifiable(""); // TODO: This is not the way the
638                 // modifiable flag is supposed to be used.
639               }
640               setAnnotationType(an, aa[i]);
641
642               if (aa[i].graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
643               {
644                 an.setGraph(true);
645                 an.setGroup(Integer.toString(aa[i].graphGroup));
646                 if (aa[i].threshold != null && aa[i].threshold.displayed)
647                 {
648                   an.addProperty(Properties.newProperty(THRESHOLD,
649                           Properties.FLOATTYPE, "" + aa[i].threshold.value));
650                   if (aa[i].threshold.label != null)
651                   {
652                     an.addProperty(Properties.newProperty(THRESHOLD
653                             + "Name", Properties.STRINGTYPE, ""
654                             + aa[i].threshold.label));
655                   }
656                 }
657               }
658
659             }
660
661             else
662             {
663               if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT
664               // LOCK METHODS)
665               {
666                 // verify annotation - update (perhaps)
667                 Cache.log
668                         .info("update alignment sequence annotation. not yet implemented.");
669               }
670               else
671               {
672                 // verify annotation - update (perhaps)
673                 Cache.log
674                         .info("updated alignment sequence annotation added.");
675               }
676             }
677           }
678         }
679       }
680       // /////////////////////////////////////////////////////
681
682       // //////////////////////////////////////////////
683       // /SAVE THE TREES
684       // /////////////////////////////////
685       // FIND ANY ASSOCIATED TREES
686       if (Desktop.desktop != null)
687       {
688         javax.swing.JInternalFrame[] frames = Desktop.instance
689                 .getAllFrames();
690
691         for (int t = 0; t < frames.length; t++)
692         {
693           if (frames[t] instanceof TreePanel)
694           {
695             TreePanel tp = (TreePanel) frames[t];
696
697             if (tp.getViewPort().getSequenceSetId()
698                     .equals(av.getSequenceSetId()))
699             {
700               DatastoreItem vtree = new jalview.io.vamsas.Tree(this, tp,
701                       jal, alignment);
702             }
703           }
704         }
705       }
706       // Store Jalview specific stuff in the Jalview appData
707       // not implemented in the SimpleDoc interface.
708     }
709
710     catch (Exception ex)
711     {
712       ex.printStackTrace();
713       return false;
714     }
715     return true;
716   }
717
718   /**
719    * very quick test to see if the viewport would be stored in the vamsas
720    * document. Reasons for not storing include the unaligned flag being false
721    * (for all sequences, including the hidden ones!)
722    *
723    * @param av
724    * @return true if alignment associated with this view will be stored in
725    *         document.
726    */
727   public boolean alignmentWillBeSkipped(AlignViewport av)
728   {
729     return (!av.getAlignment().isAligned());
730   }
731
732   private void addToSkipList(AlignViewport av)
733   {
734     if (skipList == null)
735     {
736       skipList = new Hashtable();
737     }
738     skipList.put(av.getSequenceSetId(), av);
739   }
740
741   /**
742    * remove docseqs from the given alignment marking provenance appropriately
743    * and removing any references to the sequences.
744    *
745    * @param alignment
746    * @param docseqs
747    */
748   private void removeValignmentSequences(Alignment alignment, Vector docseqs)
749   {
750     // delete these from document. This really needs to be a generic document
751     // API function derived by CASTOR.
752     Enumeration en = docseqs.elements();
753     while (en.hasMoreElements())
754     {
755       alignment.removeAlignmentSequence((AlignmentSequence) en
756               .nextElement());
757     }
758     Entry pe = addProvenance(alignment.getProvenance(), "Removed "
759             + docseqs.size() + " sequences");
760     en = alignment.enumerateAlignmentAnnotation();
761     Vector toremove = new Vector();
762     while (en.hasMoreElements())
763     {
764       uk.ac.vamsas.objects.core.AlignmentAnnotation alan = (uk.ac.vamsas.objects.core.AlignmentAnnotation) en
765               .nextElement();
766       if (alan.getSeqrefsCount() > 0)
767       {
768         int p = 0;
769         Vector storem = new Vector();
770         Enumeration sr = alan.enumerateSeqrefs();
771         while (sr.hasMoreElements())
772         {
773           Object alsr = sr.nextElement();
774           if (docseqs.contains(alsr))
775           {
776             storem.addElement(alsr);
777           }
778         }
779         // remove references to the deleted sequences
780         sr = storem.elements();
781         while (sr.hasMoreElements())
782         {
783           alan.removeSeqrefs(sr.nextElement());
784         }
785
786         if (alan.getSeqrefsCount() == 0)
787         {
788           // should then delete alan from dataset
789           toremove.addElement(alan);
790         }
791       }
792     }
793     // remove any annotation that used to be associated to a specific bunch of
794     // sequences
795     en = toremove.elements();
796     while (en.hasMoreElements())
797     {
798       alignment
799               .removeAlignmentAnnotation((uk.ac.vamsas.objects.core.AlignmentAnnotation) en
800                       .nextElement());
801     }
802     // TODO: search through alignment annotations to remove any references to
803     // this alignment sequence
804   }
805
806   /**
807    * sync a jalview alignment seuqence into a vamsas alignment assumes all lock
808    * transformation/bindings have been sorted out before hand. creates/syncs the
809    * vamsas alignment sequence for jvalsq and adds it to the alignment if
810    * necessary. unbounddocseq is a duplicate of the vamsas alignment sequences
811    * and these are removed after being processed w.r.t a bound jvalsq
812    *
813    */
814   private boolean syncToAlignmentSequence(SequenceI jvalsq,
815           Alignment alignment, Vector unbounddocseq)
816   {
817     boolean modal = false;
818     // todo: islocked method here
819     boolean up2doc = false;
820     AlignmentSequence alseq = (AlignmentSequence) getjv2vObj(jvalsq);
821     if (alseq == null)
822     {
823       alseq = new AlignmentSequence();
824       up2doc = true;
825     }
826     else
827     {
828       if (unbounddocseq != null)
829       {
830         unbounddocseq.removeElement(alseq);
831       }
832     }
833     // boolean locked = (alignment.getModifiable()==null ||
834     // alignment.getModifiable().length()>0);
835     // TODO: VAMSAS: translate lowercase symbols to annotation ?
836     if (up2doc || !alseq.getSequence().equals(jvalsq.getSequenceAsString()))
837     {
838       alseq.setSequence(jvalsq.getSequenceAsString());
839       alseq.setStart(jvalsq.getStart());
840       alseq.setEnd(jvalsq.getEnd());
841       modal = true;
842     }
843     if (up2doc || !alseq.getName().equals(jvalsq.getName()))
844     {
845       modal = true;
846       alseq.setName(jvalsq.getName());
847     }
848     if (jvalsq.getDescription() != null
849             && (alseq.getDescription() == null || !jvalsq.getDescription()
850                     .equals(alseq.getDescription())))
851     {
852       modal = true;
853       alseq.setDescription(jvalsq.getDescription());
854     }
855     if (getjv2vObj(jvalsq.getDatasetSequence()) == null)
856     {
857       Cache.log
858               .warn("Serious Implementation error - Unbound dataset sequence in alignment: "
859                       + jvalsq.getDatasetSequence());
860     }
861     alseq.setRefid(getjv2vObj(jvalsq.getDatasetSequence()));
862     if (up2doc)
863     {
864
865       alignment.addAlignmentSequence(alseq);
866       bindjvvobj(jvalsq, alseq);
867     }
868     return up2doc || modal;
869   }
870
871   /**
872    * locally sync a jalview alignment seuqence from a vamsas alignment assumes
873    * all lock transformation/bindings have been sorted out before hand.
874    * creates/syncs the jvalsq from the alignment sequence
875    */
876   private boolean syncFromAlignmentSequence(AlignmentSequence valseq,
877           char valGapchar, char gapChar, List<SequenceI> dsseqs)
878
879   {
880     boolean modal = false;
881     // todo: islocked method here
882     boolean upFromdoc = false;
883     jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
884     if (alseq == null)
885     {
886       upFromdoc = true;
887     }
888     if (alseq != null)
889     {
890
891       // boolean locked = (alignment.getModifiable()==null ||
892       // alignment.getModifiable().length()>0);
893       // TODO: VAMSAS: translate lowercase symbols to annotation ?
894       if (upFromdoc
895               || !valseq.getSequence().equals(alseq.getSequenceAsString()))
896       {
897         // this might go *horribly* wrong
898         alseq.setSequence(new String(valseq.getSequence()).replace(
899                 valGapchar, gapChar));
900         alseq.setStart((int) valseq.getStart());
901         alseq.setEnd((int) valseq.getEnd());
902         modal = true;
903       }
904       if (!valseq.getName().equals(alseq.getName()))
905       {
906         modal = true;
907         alseq.setName(valseq.getName());
908       }
909       if (alseq.getDescription() == null
910               || (valseq.getDescription() != null && !alseq
911                       .getDescription().equals(valseq.getDescription())))
912       {
913         alseq.setDescription(valseq.getDescription());
914         modal = true;
915       }
916       if (modal && Cache.log.isDebugEnabled())
917       {
918         Cache.log.debug("Updating apparently edited sequence "
919                 + alseq.getName());
920       }
921     }
922     else
923     {
924       alseq = new jalview.datamodel.Sequence(valseq.getName(), valseq
925               .getSequence().replace(valGapchar, gapChar),
926               (int) valseq.getStart(), (int) valseq.getEnd());
927
928       Vobject datsetseq = (Vobject) valseq.getRefid();
929       if (datsetseq != null)
930       {
931         alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
932         if (valseq.getDescription() != null)
933         {
934           alseq.setDescription(valseq.getDescription());
935         }
936         else
937         {
938           // inherit description line from dataset.
939           if (alseq.getDatasetSequence().getDescription() != null)
940           {
941             alseq.setDescription(alseq.getDatasetSequence()
942                     .getDescription());
943           }
944         }
945         // if
946         // AlignemntSequence
947         // reference
948         // isn't
949         // a
950         // simple
951         // SequenceI
952       }
953       else
954       {
955         Cache.log
956                 .error("Invalid dataset sequence id (null) for alignment sequence "
957                         + valseq.getVorbaId());
958       }
959       bindjvvobj(alseq, valseq);
960       alseq.setVamsasId(valseq.getVorbaId().getId());
961       dsseqs.add(alseq);
962     }
963     Vobject datsetseq = (Vobject) valseq.getRefid();
964     if (datsetseq != null)
965     {
966       if (datsetseq != alseq.getDatasetSequence())
967       {
968         modal = true;
969       }
970       alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
971     }
972     return upFromdoc || modal;
973   }
974
975   private void initRangeAnnotationType(RangeAnnotation an,
976           AlignmentAnnotation alan, int[] gapMap)
977   {
978     Seg vSeg = new Seg();
979     vSeg.setStart(1);
980     vSeg.setInclusive(true);
981     vSeg.setEnd(gapMap.length);
982     an.addSeg(vSeg);
983
984     // LATER: much of this is verbatim from the alignmentAnnotation
985     // method below. suggests refactoring to make rangeAnnotation the
986     // base class
987     an.setDescription(alan.description);
988     an.setLabel(alan.label);
989     an.setGroup(Integer.toString(alan.graphGroup));
990     // // JBPNote -
991     // originally we
992     // were going to
993     // store
994     // graphGroup in
995     // the Jalview
996     // specific
997     // bits.
998     AnnotationElement ae;
999     for (int a = 0; a < alan.annotations.length; a++)
1000     {
1001       if (alan.annotations[a] == null)
1002       {
1003         continue;
1004       }
1005
1006       ae = new AnnotationElement();
1007       ae.setDescription(alan.annotations[a].description);
1008       ae.addGlyph(new Glyph());
1009       ae.getGlyph(0).setContent(alan.annotations[a].displayCharacter); // assume
1010       // jax-b
1011       // takes
1012       // care
1013       // of
1014       // utf8
1015       // translation
1016       if (alan.graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
1017       {
1018         ae.addValue(alan.annotations[a].value);
1019       }
1020       ae.setPosition(gapMap[a] + 1); // position w.r.t. AlignmentSequence
1021       // symbols
1022       if (alan.annotations[a].secondaryStructure != ' ')
1023       {
1024         // we only write an annotation where it really exists.
1025         Glyph ss = new Glyph();
1026         ss.setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
1027         ss.setContent(String
1028                 .valueOf(alan.annotations[a].secondaryStructure));
1029         ae.addGlyph(ss);
1030       }
1031       an.addAnnotationElement(ae);
1032     }
1033
1034   }
1035
1036   private void saveDatasetSequenceAnnotation(HashMap AlSeqMaps,
1037           uk.ac.vamsas.objects.core.Sequence sref, AlignmentAnnotation alan)
1038   {
1039     // {
1040     // uk.ac.vamsas.
1041     // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1042     // objects.core.AlignmentSequence) sref;
1043     uk.ac.vamsas.objects.core.DataSetAnnotations an = (uk.ac.vamsas.objects.core.DataSetAnnotations) getjv2vObj(alan);
1044     int[] gapMap = getGapMap(AlSeqMaps, alan);
1045     if (an == null)
1046     {
1047       an = new uk.ac.vamsas.objects.core.DataSetAnnotations();
1048       initRangeAnnotationType(an, alan, gapMap);
1049
1050       an.setProvenance(dummyProvenance()); // get provenance as user
1051       // created, or jnet, or
1052       // something else.
1053       setAnnotationType(an, alan);
1054       an.setGroup(Integer.toString(alan.graphGroup)); // // JBPNote -
1055       // originally we
1056       // were going to
1057       // store
1058       // graphGroup in
1059       // the Jalview
1060       // specific
1061       // bits.
1062       if (alan.getThreshold() != null && alan.getThreshold().displayed)
1063       {
1064         an.addProperty(Properties.newProperty(THRESHOLD,
1065                 Properties.FLOATTYPE, "" + alan.getThreshold().value));
1066         if (alan.getThreshold().label != null)
1067           an.addProperty(Properties.newProperty(THRESHOLD + "Name",
1068                   Properties.STRINGTYPE, "" + alan.getThreshold().label));
1069       }
1070       ((DataSet) sref.getV_parent()).addDataSetAnnotations(an);
1071       bindjvvobj(alan, an);
1072     }
1073     else
1074     {
1075       // update reference sequence Annotation
1076       if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1077       // METHODS)
1078       {
1079         // verify existing alignment sequence annotation is up to date
1080         System.out.println("update dataset sequence annotation.");
1081       }
1082       else
1083       {
1084         // verify existing alignment sequence annotation is up to date
1085         System.out
1086                 .println("make new alignment dataset sequence annotation if modification has happened.");
1087       }
1088     }
1089
1090   }
1091
1092   private int[] getGapMap(HashMap AlSeqMaps, AlignmentAnnotation alan)
1093   {
1094     int[] gapMap;
1095     if (AlSeqMaps.containsKey(alan.sequenceRef))
1096     {
1097       gapMap = (int[]) AlSeqMaps.get(alan.sequenceRef);
1098     }
1099     else
1100     {
1101       gapMap = new int[alan.sequenceRef.getLength()];
1102       // map from alignment position to sequence position.
1103       int[] sgapMap = alan.sequenceRef.gapMap();
1104       for (int a = 0; a < sgapMap.length; a++)
1105       {
1106         gapMap[sgapMap[a]] = a;
1107       }
1108     }
1109     return gapMap;
1110   }
1111
1112   private void saveAlignmentSequenceAnnotation(HashMap AlSeqMaps,
1113           AlignmentSequence alsref, AlignmentAnnotation alan)
1114   {
1115     // {
1116     // uk.ac.vamsas.
1117     // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1118     // objects.core.AlignmentSequence) sref;
1119     uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation an = (uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(alan);
1120     int[] gapMap = getGapMap(AlSeqMaps, alan);
1121     if (an == null)
1122     {
1123       an = new uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation();
1124       initRangeAnnotationType(an, alan, gapMap);
1125       /**
1126        * I mean here that we don't actually have a semantic 'type' for the
1127        * annotation (this might be - score, intrinsic property, measurement,
1128        * something extracted from another program, etc)
1129        */
1130       an.setType(JALVIEW_ANNOTATION_ROW); // TODO: better fix
1131       // this rough guess ;)
1132       alsref.addAlignmentSequenceAnnotation(an);
1133       bindjvvobj(alan, an);
1134       // These properties are directly supported by the
1135       // AlignmentSequenceAnnotation type.
1136       setAnnotationType(an, alan);
1137       an.setProvenance(dummyProvenance()); // get provenance as user
1138       // created, or jnet, or
1139       // something else.
1140     }
1141     else
1142     {
1143       // update reference sequence Annotation
1144       if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1145       // METHODS)
1146       {
1147         // verify existing alignment sequence annotation is up to date
1148         System.out.println("update alignment sequence annotation.");
1149       }
1150       else
1151       {
1152         // verify existing alignment sequence annotation is up to date
1153         System.out
1154                 .println("make new alignment sequence annotation if modification has happened.");
1155       }
1156     }
1157   }
1158
1159   /**
1160    * set vamsas annotation object type from jalview annotation
1161    *
1162    * @param an
1163    * @param alan
1164    */
1165   private void setAnnotationType(RangeAnnotation an,
1166           AlignmentAnnotation alan)
1167   {
1168     if (an instanceof AlignmentSequenceAnnotation)
1169     {
1170       if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1171       {
1172         ((AlignmentSequenceAnnotation) an).setGraph(true);
1173       }
1174       else
1175       {
1176         ((AlignmentSequenceAnnotation) an).setGraph(false);
1177       }
1178     }
1179     if (an instanceof uk.ac.vamsas.objects.core.AlignmentAnnotation)
1180     {
1181       if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1182       {
1183         ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an).setGraph(true);
1184       }
1185       else
1186       {
1187         ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an)
1188                 .setGraph(false);
1189       }
1190     }
1191     switch (alan.graph)
1192     {
1193     case AlignmentAnnotation.BAR_GRAPH:
1194       an.addProperty(Properties.newProperty(DISCRETE_ANNOTATION,
1195               Properties.BOOLEANTYPE, "true"));
1196       break;
1197     case AlignmentAnnotation.LINE_GRAPH:
1198       an.addProperty(Properties.newProperty(CONTINUOUS_ANNOTATION,
1199               Properties.BOOLEANTYPE, "true"));
1200       break;
1201     default:
1202       // don't add any kind of discrete or continous property info.
1203     }
1204   }
1205
1206   /**
1207    * get start<end range of segment, adjusting for inclusivity flag and
1208    * polarity.
1209    *
1210    * @param visSeg
1211    * @param ensureDirection
1212    *          when true - always ensure start is less than end.
1213    * @return int[] { start, end, direction} where direction==1 for range running
1214    *         from end to start.
1215    */
1216   private int[] getSegRange(Seg visSeg, boolean ensureDirection)
1217   {
1218     boolean incl = visSeg.getInclusive();
1219     // adjust for inclusive flag.
1220     int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
1221     // region.
1222     int start = visSeg.getStart() + (incl ? 0 : pol);
1223     int end = visSeg.getEnd() + (incl ? 0 : -pol);
1224     if (ensureDirection && pol == -1)
1225     {
1226       // jalview doesn't deal with inverted ranges, yet.
1227       int t = end;
1228       end = start;
1229       start = t;
1230     }
1231     return new int[]
1232     { start, end, pol < 0 ? 1 : 0 };
1233   }
1234
1235   /**
1236    *
1237    * @param annotation
1238    * @return true if annotation is not to be stored in document
1239    */
1240   private boolean isJalviewOnly(AlignmentAnnotation annotation)
1241   {
1242     return annotation.autoCalculated || annotation.label.equals("Quality")
1243             || annotation.label.equals("Conservation")
1244             || annotation.label.equals("Consensus");
1245   }
1246
1247   boolean dojvsync = true;
1248
1249   // boolean dojvsync = false; // disables Jalview AppData IO
1250   /**
1251    * list of alignment views created when updating Jalview from document.
1252    */
1253   private final Vector newAlignmentViews = new Vector();
1254
1255   /**
1256    * update local jalview view settings from the stored appdata (if any)
1257    */
1258   public void updateJalviewFromAppdata()
1259   {
1260     // recover any existing Jalview data from appdata
1261     // TODO: recover any PDB files stored as attachments in the vamsas session
1262     // and initialise the Jalview2XML.alreadyLoadedPDB hashtable with mappings
1263     // to temp files.
1264     {
1265       final IClientAppdata cappdata = cdoc.getClientAppdata();
1266       if (cappdata != null)
1267       {
1268         if (cappdata.hasClientAppdata())
1269         {
1270           // TODO: how to check version of Jalview client app data and whether
1271           // it has been modified
1272           // client data is shared over all app clients
1273           try
1274           {
1275             jalview.gui.Jalview2XML fromxml = new jalview.gui.Jalview2XML();
1276             fromxml.attemptversion1parse = false;
1277             fromxml.setUniqueSetSuffix("");
1278             fromxml.setObjectMappingTables(vobj2jv, jv2vobj); // mapKeysToString
1279             // and
1280             // mapValuesToString
1281             fromxml.setSkipList(skipList);
1282             jalview.util.jarInputStreamProvider jprovider = new jalview.util.jarInputStreamProvider()
1283             {
1284
1285               @Override
1286               public String getFilename()
1287               {
1288
1289                 // TODO Get the vamsas session ID here
1290                 return "Jalview Vamsas Document Client Data";
1291               }
1292
1293               @Override
1294               public JarInputStream getJarInputStream() throws IOException
1295               {
1296                 jalview.bin.Cache.log
1297                         .debug("Returning client input stream for Jalview from Vamsas Document.");
1298                 return new JarInputStream(cappdata.getClientInputStream());
1299               }
1300             };
1301             if (dojvsync)
1302             {
1303               fromxml.LoadJalviewAlign(jprovider);
1304             }
1305           } catch (Exception e)
1306           {
1307
1308           } catch (OutOfMemoryError e)
1309           {
1310
1311           } catch (Error e)
1312           {
1313
1314           }
1315         }
1316       }
1317       if (cappdata.hasUserAppdata())
1318       {
1319         // TODO: how to check version of Jalview user app data and whether it
1320         // has been modified
1321         // user data overrides data shared over all app clients ?
1322         try
1323         {
1324           jalview.gui.Jalview2XML fromxml = new jalview.gui.Jalview2XML();
1325           fromxml.attemptversion1parse = false;
1326           fromxml.setUniqueSetSuffix("");
1327           fromxml.setSkipList(skipList);
1328           fromxml.setObjectMappingTables(mapKeysToString(vobj2jv),
1329                   mapValuesToString(jv2vobj));
1330           jalview.util.jarInputStreamProvider jarstream = new jalview.util.jarInputStreamProvider()
1331           {
1332
1333             @Override
1334             public String getFilename()
1335             {
1336
1337               // TODO Get the vamsas session ID here
1338               return "Jalview Vamsas Document User Data";
1339             }
1340
1341             @Override
1342             public JarInputStream getJarInputStream() throws IOException
1343             {
1344               jalview.bin.Cache.log
1345                       .debug("Returning user input stream for Jalview from Vamsas Document.");
1346               return new JarInputStream(cappdata.getUserInputStream());
1347             }
1348           };
1349           if (dojvsync)
1350           {
1351             fromxml.LoadJalviewAlign(jarstream);
1352           }
1353         } catch (Exception e)
1354         {
1355
1356         } catch (OutOfMemoryError e)
1357         {
1358
1359         } catch (Error e)
1360         {
1361
1362         }
1363       }
1364
1365     }
1366     flushAlignViewports();
1367   }
1368
1369   /**
1370    * remove any spurious views generated by document synchronization
1371    */
1372   private void flushAlignViewports()
1373   {
1374     // remove any additional viewports originally recovered from the vamsas
1375     // document.
1376     // search for all alignframes containing viewports generated from document
1377     // sync,
1378     // and if any contain more than one view, then remove the one generated by
1379     // document update.
1380     AlignViewport views[], av = null;
1381     AlignFrame af = null;
1382     Iterator newviews = newAlignmentViews.iterator();
1383     while (newviews.hasNext())
1384     {
1385       av = (AlignViewport) newviews.next();
1386       af = Desktop.getAlignFrameFor(av);
1387       // TODO implement this : af.getNumberOfViews
1388       String seqsetidobj = av.getSequenceSetId();
1389       views = Desktop.getViewports(seqsetidobj);
1390       Cache.log.debug("Found "
1391               + (views == null ? " no " : "" + views.length)
1392               + " views for '" + av.getSequenceSetId() + "'");
1393       if (views.length > 1)
1394       {
1395         // we need to close the original document view.
1396
1397         // work out how to do this by seeing if the views are gathered.
1398         // pretty clunky but the only way to do this without adding more flags
1399         // to the align frames.
1400         boolean gathered = false;
1401         String newviewid = null;
1402         AlignedCodonFrame[] mappings = av.getAlignment().getCodonFrames();
1403         for (int i = 0; i < views.length; i++)
1404         {
1405           if (views[i] != av)
1406           {
1407             AlignFrame viewframe = Desktop.getAlignFrameFor(views[i]);
1408             if (viewframe == af)
1409             {
1410               gathered = true;
1411             }
1412             newviewid = views[i].getSequenceSetId();
1413           }
1414           else
1415           {
1416             // lose the reference to the vamsas document created view
1417             views[i] = null;
1418           }
1419         }
1420         // close the view generated by the vamsas document synchronization
1421         if (gathered)
1422         {
1423           af.closeView(av);
1424         }
1425         else
1426         {
1427           af.closeMenuItem_actionPerformed(false);
1428         }
1429         replaceJvObjMapping(seqsetidobj, newviewid);
1430         seqsetidobj = newviewid;
1431         // not sure if we need to do this:
1432
1433         if (false) // mappings != null)
1434         {
1435           // ensure sequence mappings from vamsas document view still
1436           // active
1437           if (mappings != null && mappings.length > 0)
1438           {
1439             jalview.structure.StructureSelectionManager
1440                     .getStructureSelectionManager(Desktop.instance).addMappings(mappings);
1441           }
1442         }
1443       }
1444       // ensure vamsas object binds to the stored views retrieved from
1445       // Jalview appdata
1446       // jalview.structure.StructureSelectionManager
1447       // .getStructureSelectionManager()
1448       // .addStructureViewerListener(viewframe.alignPanel);
1449
1450     }
1451
1452     newviews = null;
1453     newAlignmentViews.clear();
1454   }
1455
1456   /**
1457    * replaces oldjvobject with newjvobject in the Jalview Object <> VorbaID
1458    * binding tables
1459    *
1460    * @param oldjvobject
1461    * @param newjvobject
1462    *          (may be null)
1463    */
1464   private void replaceJvObjMapping(Object oldjvobject, Object newjvobject)
1465   {
1466     Object vobject = jv2vobj.remove(oldjvobject);
1467     if (vobject == null)
1468     {
1469       // NOTE: this happens if user deletes object in one session then updates from another client
1470       throw new Error(
1471               "IMPLEMENTATION ERROR: old jalview object is not bound ! ("
1472                       + oldjvobject + ")");
1473     }
1474     if (newjvobject != null)
1475     {
1476       jv2vobj.put(newjvobject, vobject);
1477       vobj2jv.put(vobject, newjvobject);
1478     }
1479   }
1480
1481   /**
1482    * Update the jalview client and user appdata from the local jalview settings
1483    */
1484   public void updateJalviewClientAppdata()
1485   {
1486     final IClientAppdata cappdata = cdoc.getClientAppdata();
1487     if (cappdata != null)
1488     {
1489       try
1490       {
1491         jalview.gui.Jalview2XML jxml = new jalview.gui.Jalview2XML();
1492         jxml.setObjectMappingTables(mapKeysToString(vobj2jv),
1493                 mapValuesToString(jv2vobj));
1494         jxml.setSkipList(skipList);
1495         if (dojvsync)
1496         {
1497           jxml.SaveState(new JarOutputStream(cappdata
1498                   .getClientOutputStream()));
1499         }
1500
1501       } catch (Exception e)
1502       {
1503         // TODO raise GUI warning if user requests it.
1504         jalview.bin.Cache.log
1505                 .error("Couldn't update jalview client application data. Giving up - local settings probably lost.",
1506                         e);
1507       }
1508     }
1509     else
1510     {
1511       jalview.bin.Cache.log
1512               .error("Couldn't access client application data for vamsas session. This is probably a vamsas client bug.");
1513     }
1514   }
1515
1516   /**
1517    * translate the Vobject keys to strings for use in Jalview2XML
1518    *
1519    * @param jv2vobj2
1520    * @return
1521    */
1522   private IdentityHashMap mapValuesToString(IdentityHashMap jv2vobj2)
1523   {
1524     IdentityHashMap mapped = new IdentityHashMap();
1525     Iterator keys = jv2vobj2.keySet().iterator();
1526     while (keys.hasNext())
1527     {
1528       Object key = keys.next();
1529       mapped.put(key, jv2vobj2.get(key).toString());
1530     }
1531     return mapped;
1532   }
1533
1534   /**
1535    * translate the Vobject values to strings for use in Jalview2XML
1536    *
1537    * @param vobj2jv2
1538    * @return hashtable with string values
1539    */
1540   private Hashtable mapKeysToString(Hashtable vobj2jv2)
1541   {
1542     Hashtable mapped = new Hashtable();
1543     Iterator keys = vobj2jv2.keySet().iterator();
1544     while (keys.hasNext())
1545     {
1546       Object key = keys.next();
1547       mapped.put(key.toString(), vobj2jv2.get(key));
1548     }
1549     return mapped;
1550   }
1551
1552   /**
1553    * synchronize Jalview from the vamsas document
1554    *
1555    * @return number of new views from document
1556    */
1557   public int updateToJalview()
1558   {
1559     VAMSAS _roots[] = cdoc.getVamsasRoots();
1560
1561     for (int _root = 0; _root < _roots.length; _root++)
1562     {
1563       VAMSAS root = _roots[_root];
1564       boolean newds = false;
1565       for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1566       {
1567         // ///////////////////////////////////
1568         // ///LOAD DATASET
1569         DataSet dataset = root.getDataSet(_ds);
1570         int i, iSize = dataset.getSequenceCount();
1571         List<SequenceI> dsseqs;
1572         jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);
1573         int jremain = 0;
1574         if (jdataset == null)
1575         {
1576           Cache.log.debug("Initialising new jalview dataset fields");
1577           newds = true;
1578           dsseqs = new Vector();
1579         }
1580         else
1581         {
1582           Cache.log.debug("Update jalview dataset from vamsas.");
1583           jremain = jdataset.getHeight();
1584           dsseqs = jdataset.getSequences();
1585         }
1586
1587         // TODO: test sequence merging - we preserve existing non vamsas
1588         // sequences but add in any new vamsas ones, and don't yet update any
1589         // sequence attributes
1590         for (i = 0; i < iSize; i++)
1591         {
1592           Sequence vdseq = dataset.getSequence(i);
1593           jalview.io.vamsas.Datasetsequence dssync = new Datasetsequence(
1594                   this, vdseq);
1595
1596           jalview.datamodel.SequenceI dsseq = (SequenceI) dssync.getJvobj();
1597           if (dssync.isAddfromdoc())
1598           {
1599             dsseqs.add(dsseq);
1600           }
1601           if (vdseq.getDbRefCount() > 0)
1602           {
1603             DbRef[] dbref = vdseq.getDbRef();
1604             for (int db = 0; db < dbref.length; db++)
1605             {
1606               new jalview.io.vamsas.Dbref(this, dbref[db], vdseq, dsseq);
1607
1608             }
1609             dsseq.updatePDBIds();
1610           }
1611         }
1612
1613         if (newds)
1614         {
1615           SequenceI[] seqs = new SequenceI[dsseqs.size()];
1616           for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1617           {
1618             seqs[i] = dsseqs.get(i);
1619             dsseqs.set(i, null);
1620           }
1621           jdataset = new jalview.datamodel.Alignment(seqs);
1622           Cache.log.debug("New vamsas dataset imported into jalview.");
1623           bindjvvobj(jdataset, dataset);
1624         }
1625         // ////////
1626         // add any new dataset sequence feature annotations
1627         if (dataset.getDataSetAnnotations() != null)
1628         {
1629           for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++)
1630           {
1631             DataSetAnnotations dseta = dataset.getDataSetAnnotations(dsa);
1632             // TODO: deal with group annotation on datset sequences.
1633             if (dseta.getSeqRefCount() == 1)
1634             {
1635               SequenceI dsSeq = (SequenceI) getvObj2jv((Vobject) dseta
1636                       .getSeqRef(0)); // TODO: deal with group dataset
1637               // annotations
1638               if (dsSeq == null)
1639               {
1640                 jalview.bin.Cache.log
1641                         .warn("Couldn't resolve jalview sequenceI for dataset object reference "
1642                                 + ((Vobject) dataset.getDataSetAnnotations(
1643                                         dsa).getSeqRef(0)).getVorbaId()
1644                                         .getId());
1645               }
1646               else
1647               {
1648                 if (dseta.getAnnotationElementCount() == 0)
1649                 {
1650                   new jalview.io.vamsas.Sequencefeature(this, dseta, dsSeq);
1651
1652                 }
1653                 else
1654                 {
1655                   // TODO: deal with alignmentAnnotation style annotation
1656                   // appearing on dataset sequences.
1657                   // JBPNote: we could just add them to all alignments but
1658                   // that may complicate cross references in the jalview
1659                   // datamodel
1660                   Cache.log
1661                           .warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
1662                 }
1663               }
1664             }
1665             else
1666             {
1667               Cache.log
1668                       .warn("Ignoring multiply referenced dataset sequence annotation for binding to datsaet sequence features.");
1669             }
1670           }
1671         }
1672         if (dataset.getAlignmentCount() > 0)
1673         {
1674           // LOAD ALIGNMENTS from DATASET
1675
1676           for (int al = 0, nal = dataset.getAlignmentCount(); al < nal; al++)
1677           {
1678             uk.ac.vamsas.objects.core.Alignment alignment = dataset
1679                     .getAlignment(al);
1680             // TODO check this handles multiple views properly
1681             AlignViewport av = findViewport(alignment);
1682
1683             jalview.datamodel.AlignmentI jal = null;
1684             if (av != null)
1685             {
1686               // TODO check that correct alignment object is retrieved when
1687               // hidden seqs exist.
1688               jal = (av.hasHiddenRows()) ? av.getAlignment()
1689                       .getHiddenSequences().getFullAlignment() : av
1690                       .getAlignment();
1691             }
1692             iSize = alignment.getAlignmentSequenceCount();
1693             boolean refreshal = false;
1694             Vector newasAnnots = new Vector();
1695             char gapChar = ' '; // default for new alignments read in from the
1696             // document
1697             if (jal != null)
1698             {
1699               dsseqs = jal.getSequences(); // for merge/update
1700               gapChar = jal.getGapCharacter();
1701             }
1702             else
1703             {
1704               dsseqs = new Vector();
1705             }
1706             char valGapchar = alignment.getGapChar().charAt(0);
1707             for (i = 0; i < iSize; i++)
1708             {
1709               AlignmentSequence valseq = alignment.getAlignmentSequence(i);
1710               jalview.datamodel.Sequence alseq = (jalview.datamodel.Sequence) getvObj2jv(valseq);
1711               if (syncFromAlignmentSequence(valseq, valGapchar, gapChar,
1712                       dsseqs) && alseq != null)
1713               {
1714
1715                 // updated to sequence from the document
1716                 jremain--;
1717                 refreshal = true;
1718               }
1719               if (valseq.getAlignmentSequenceAnnotationCount() > 0)
1720               {
1721                 AlignmentSequenceAnnotation[] vasannot = valseq
1722                         .getAlignmentSequenceAnnotation();
1723                 for (int a = 0; a < vasannot.length; a++)
1724                 {
1725                   jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO:
1726                   // 1:many
1727                   // jalview
1728                   // alignment
1729                   // sequence
1730                   // annotations
1731                   if (asa == null)
1732                   {
1733                     int se[] = getBounds(vasannot[a]);
1734                     asa = getjAlignmentAnnotation(jal, vasannot[a]);
1735                     asa.setSequenceRef(alseq);
1736                     asa.createSequenceMapping(alseq, se[0], false); // TODO:
1737                     // verify
1738                     // that
1739                     // positions
1740                     // in
1741                     // alseqAnnotation
1742                     // correspond
1743                     // to
1744                     // ungapped
1745                     // residue
1746                     // positions.
1747                     alseq.addAlignmentAnnotation(asa);
1748                     bindjvvobj(asa, vasannot[a]);
1749                     refreshal = true;
1750                     newasAnnots.add(asa);
1751                   }
1752                   else
1753                   {
1754                     // update existing annotation - can do this in place
1755                     if (vasannot[a].getModifiable() == null) // TODO: USE
1756                     // VAMSAS LIBRARY
1757                     // OBJECT LOCK
1758                     // METHODS)
1759                     {
1760                       Cache.log
1761                               .info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1762                       // TODO: should at least replace with new one - otherwise
1763                       // things will break
1764                       // basically do this:
1765                       // int se[] = getBounds(vasannot[a]);
1766                       // asa.update(getjAlignmentAnnotation(jal, vasannot[a]));
1767                       // // update from another annotation object in place.
1768                       // asa.createSequenceMapping(alseq, se[0], false);
1769
1770                     }
1771                   }
1772                 }
1773               }
1774             }
1775             if (jal == null)
1776             {
1777               SequenceI[] seqs = new SequenceI[dsseqs.size()];
1778               for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1779               {
1780                 seqs[i] = dsseqs.get(i);
1781                 dsseqs.set(i,null);
1782               }
1783               jal = new jalview.datamodel.Alignment(seqs);
1784               Cache.log.debug("New vamsas alignment imported into jalview "
1785                       + alignment.getVorbaId().getId());
1786               jal.setDataset(jdataset);
1787             }
1788             if (newasAnnots != null && newasAnnots.size() > 0)
1789             {
1790               // Add the new sequence annotations in to the alignment.
1791               for (int an = 0, anSize = newasAnnots.size(); an < anSize; an++)
1792               {
1793                 jal.addAnnotation((AlignmentAnnotation) newasAnnots
1794                         .elementAt(an));
1795                 // TODO: check if anything has to be done - like calling
1796                 // adjustForAlignment or something.
1797                 newasAnnots.setElementAt(null, an);
1798               }
1799               newasAnnots = null;
1800             }
1801             // //////////////////////////////////////////
1802             // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1803             // ////////////////////////////////////
1804             if (alignment.getAlignmentAnnotationCount() > 0)
1805             {
1806               uk.ac.vamsas.objects.core.AlignmentAnnotation[] an = alignment
1807                       .getAlignmentAnnotation();
1808
1809               for (int j = 0; j < an.length; j++)
1810               {
1811                 jalview.datamodel.AlignmentAnnotation jan = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);
1812                 if (jan != null)
1813                 {
1814                   // update or stay the same.
1815                   // TODO: should at least replace with a new one - otherwise
1816                   // things will break
1817                   // basically do this:
1818                   // jan.update(getjAlignmentAnnotation(jal, an[a])); // update
1819                   // from another annotation object in place.
1820
1821                   Cache.log
1822                           .debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1823                   if (an[j].getModifiable() == null) // TODO: USE VAMSAS
1824                   // LIBRARY OBJECT LOCK
1825                   // METHODS)
1826                   {
1827                     // TODO: user defined annotation is totally mutable... - so
1828                     // load it up or throw away if locally edited.
1829                     Cache.log
1830                             .info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1831                   }
1832                   // TODO: compare annotation element rows
1833                   // TODO: compare props.
1834                 }
1835                 else
1836                 {
1837                   jan = getjAlignmentAnnotation(jal, an[j]);
1838                   // TODO: ensure we add the alignment annotation before the
1839                   // automatic annotation rows
1840                   jal.addAnnotation(jan);
1841                   bindjvvobj(jan, an[j]);
1842                   refreshal = true;
1843                 }
1844               }
1845             }
1846             AlignFrame alignFrame;
1847             if (av == null)
1848             {
1849               Cache.log.debug("New alignframe for alignment "
1850                       + alignment.getVorbaId());
1851               // ///////////////////////////////
1852               // construct alignment view
1853               alignFrame = new AlignFrame(jal, AlignFrame.DEFAULT_WIDTH,
1854                       AlignFrame.DEFAULT_HEIGHT, alignment.getVorbaId()
1855                               .toString());
1856               av = alignFrame.getViewport();
1857               newAlignmentViews.addElement(av);
1858               String title = alignment
1859                       .getProvenance()
1860                       .getEntry(
1861                               alignment.getProvenance().getEntryCount() - 1)
1862                       .getAction();
1863               if (alignment.getPropertyCount() > 0)
1864               {
1865                 for (int p = 0, pe = alignment.getPropertyCount(); p < pe; p++)
1866                 {
1867                   if (alignment.getProperty(p).getName().equals("title"))
1868                   {
1869                     title = alignment.getProperty(p).getContent();
1870                   }
1871                 }
1872               }
1873               // TODO: automatically create meaningful title for a vamsas
1874               // alignment using its provenance.
1875               if (Cache.log.isDebugEnabled())
1876               {
1877                 title = title + "(" + alignment.getVorbaId() + ")";
1878
1879               }
1880               jalview.gui.Desktop.addInternalFrame(alignFrame, title,
1881                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1882               bindjvvobj(av.getSequenceSetId(), alignment);
1883             }
1884             else
1885             {
1886               // find the alignFrame for jal.
1887               // TODO: fix this so we retrieve the alignFrame handing av
1888               // *directly* (JBPNote - don't understand this now)
1889               // TODO: make sure all associated views are refreshed
1890               alignFrame = Desktop.getAlignFrameFor(av);
1891               if (refreshal)
1892               {
1893                 av.alignmentChanged(alignFrame.alignPanel);
1894                 alignFrame.alignPanel.adjustAnnotationHeight();
1895               }
1896             }
1897             // LOAD TREES
1898             // /////////////////////////////////////
1899             if (alignment.getTreeCount() > 0)
1900             {
1901
1902               for (int t = 0; t < alignment.getTreeCount(); t++)
1903               {
1904                 jalview.io.vamsas.Tree vstree = new jalview.io.vamsas.Tree(
1905                         this, alignFrame, alignment.getTree(t));
1906                 TreePanel tp = null;
1907                 if (vstree.isValidTree())
1908                 {
1909                   tp = alignFrame.ShowNewickTree(vstree.getNewickTree(),
1910                           vstree.getTitle(), vstree.getInputData(), 600,
1911                           500, t * 20 + 50, t * 20 + 50);
1912
1913                 }
1914                 if (tp != null)
1915                 {
1916                   bindjvvobj(tp, alignment.getTree(t));
1917                   try
1918                   {
1919                     vstree.UpdateSequenceTreeMap(tp);
1920                   } catch (RuntimeException e)
1921                   {
1922                     Cache.log.warn("update of labels failed.", e);
1923                   }
1924                 }
1925                 else
1926                 {
1927                   Cache.log.warn("Cannot create tree for tree " + t
1928                           + " in document ("
1929                           + alignment.getTree(t).getVorbaId());
1930                 }
1931
1932               }
1933             }
1934           }
1935         }
1936       }
1937       // we do sequenceMappings last because they span all datasets in a vamsas
1938       // root
1939       for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1940       {
1941         DataSet dataset = root.getDataSet(_ds);
1942         if (dataset.getSequenceMappingCount() > 0)
1943         {
1944           for (int sm = 0, smCount = dataset.getSequenceMappingCount(); sm < smCount; sm++)
1945           {
1946             Rangetype seqmap = new jalview.io.vamsas.Sequencemapping(this,
1947                     dataset.getSequenceMapping(sm));
1948           }
1949         }
1950       }
1951     }
1952     return newAlignmentViews.size();
1953   }
1954
1955   public AlignViewport findViewport(Alignment alignment)
1956   {
1957     AlignViewport av = null;
1958     AlignViewport[] avs = Desktop
1959             .getViewports((String) getvObj2jv(alignment));
1960     if (avs != null)
1961     {
1962       av = avs[0];
1963     }
1964     return av;
1965   }
1966
1967   // bitfields - should be a template in j1.5
1968   private static int HASSECSTR = 0;
1969
1970   private static int HASVALS = 1;
1971
1972   private static int HASHPHOB = 2;
1973
1974   private static int HASDC = 3;
1975
1976   private static int HASDESCSTR = 4;
1977
1978   private static int HASTWOSTATE = 5; // not used yet.
1979
1980   /**
1981    * parses the AnnotationElements - if they exist - into
1982    * jalview.datamodel.Annotation[] rows Two annotation rows are made if there
1983    * are distinct annotation for both at 'pos' and 'after pos' at any particular
1984    * site.
1985    *
1986    * @param annotation
1987    * @return { boolean[static int constants ], int[ae.length] - map to annotated
1988    *         object frame, jalview.datamodel.Annotation[],
1989    *         jalview.datamodel.Annotation[] (after)}
1990    */
1991   private Object[] parseRangeAnnotation(
1992           uk.ac.vamsas.objects.core.RangeAnnotation annotation)
1993   {
1994     // set these attributes by looking in the annotation to decide what kind of
1995     // alignment annotation rows will be made
1996     // TODO: potentially we might make several annotation rows from one vamsas
1997     // alignment annotation. the jv2Vobj binding mechanism
1998     // may not quite cope with this (without binding an array of annotations to
1999     // a vamsas alignment annotation)
2000     // summary flags saying what we found over the set of annotation rows.
2001     boolean[] AeContent = new boolean[]
2002     { false, false, false, false, false };
2003     int[] rangeMap = getMapping(annotation);
2004     jalview.datamodel.Annotation[][] anot = new jalview.datamodel.Annotation[][]
2005     { new jalview.datamodel.Annotation[rangeMap.length],
2006         new jalview.datamodel.Annotation[rangeMap.length] };
2007     boolean mergeable = true; // false if 'after positions cant be placed on
2008     // same annotation row as positions.
2009
2010     if (annotation.getAnnotationElementCount() > 0)
2011     {
2012       AnnotationElement ae[] = annotation.getAnnotationElement();
2013       for (int aa = 0; aa < ae.length; aa++)
2014       {
2015         int pos = (int) ae[aa].getPosition() - 1; // pos counts from 1 to
2016         // (|seg.start-seg.end|+1)
2017         if (pos >= 0 && pos < rangeMap.length)
2018         {
2019           int row = ae[aa].getAfter() ? 1 : 0;
2020           if (anot[row][pos] != null)
2021           {
2022             // only time this should happen is if the After flag is set.
2023             Cache.log.debug("Ignoring duplicate annotation site at " + pos);
2024             continue;
2025           }
2026           if (anot[1 - row][pos] != null)
2027           {
2028             mergeable = false;
2029           }
2030           String desc = "";
2031           if (ae[aa].getDescription() != null)
2032           {
2033             desc = ae[aa].getDescription();
2034             if (desc.length() > 0)
2035             {
2036               // have imported valid description string
2037               AeContent[HASDESCSTR] = true;
2038             }
2039           }
2040           String dc = null; // ae[aa].getDisplayCharacter()==null ? "dc" :
2041           // ae[aa].getDisplayCharacter();
2042           String ss = null; // ae[aa].getSecondaryStructure()==null ? "ss" :
2043           // ae[aa].getSecondaryStructure();
2044           java.awt.Color colour = null;
2045           if (ae[aa].getGlyphCount() > 0)
2046           {
2047             Glyph[] glyphs = ae[aa].getGlyph();
2048             for (int g = 0; g < glyphs.length; g++)
2049             {
2050               if (glyphs[g]
2051                       .getDict()
2052                       .equals(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE))
2053               {
2054                 ss = glyphs[g].getContent();
2055                 AeContent[HASSECSTR] = true;
2056               }
2057               else if (glyphs[g]
2058                       .getDict()
2059                       .equals(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO))
2060               {
2061                 Cache.log.debug("ignoring hydrophobicity glyph marker.");
2062                 AeContent[HASHPHOB] = true;
2063                 char c = (dc = glyphs[g].getContent()).charAt(0);
2064                 // dc may get overwritten - but we still set the colour.
2065                 colour = new java.awt.Color(c == '+' ? 255 : 0,
2066                         c == '.' ? 255 : 0, c == '-' ? 255 : 0);
2067
2068               }
2069               else if (glyphs[g].getDict().equals(
2070                       uk.ac.vamsas.objects.utils.GlyphDictionary.DEFAULT))
2071               {
2072                 dc = glyphs[g].getContent();
2073                 AeContent[HASDC] = true;
2074               }
2075               else
2076               {
2077                 Cache.log
2078                         .debug("IMPLEMENTATION TODO: Ignoring unknown glyph type "
2079                                 + glyphs[g].getDict());
2080               }
2081             }
2082           }
2083           float val = 0;
2084           if (ae[aa].getValueCount() > 0)
2085           {
2086             AeContent[HASVALS] = true;
2087             if (ae[aa].getValueCount() > 1)
2088             {
2089               Cache.log.warn("ignoring additional "
2090                       + (ae[aa].getValueCount() - 1)
2091                       + " values in annotation element.");
2092             }
2093             val = ae[aa].getValue(0);
2094           }
2095           if (colour == null)
2096           {
2097             anot[row][pos] = new jalview.datamodel.Annotation(
2098                     (dc != null) ? dc : "", desc,
2099                     (ss != null) ? ss.charAt(0) : ' ', val);
2100           }
2101           else
2102           {
2103             anot[row][pos] = new jalview.datamodel.Annotation(
2104                     (dc != null) ? dc : "", desc,
2105                     (ss != null) ? ss.charAt(0) : ' ', val, colour);
2106           }
2107         }
2108         else
2109         {
2110           Cache.log.warn("Ignoring out of bound annotation element " + aa
2111                   + " in " + annotation.getVorbaId().getId());
2112         }
2113       }
2114       // decide on how many annotation rows are needed.
2115       if (mergeable)
2116       {
2117         for (int i = 0; i < anot[0].length; i++)
2118         {
2119           if (anot[1][i] != null)
2120           {
2121             anot[0][i] = anot[1][i];
2122             anot[0][i].description = anot[0][i].description + " (after)";
2123             AeContent[HASDESCSTR] = true; // we have valid description string
2124             // data
2125             anot[1][i] = null;
2126           }
2127         }
2128         anot[1] = null;
2129       }
2130       else
2131       {
2132         for (int i = 0; i < anot[0].length; i++)
2133         {
2134           anot[1][i].description = anot[1][i].description + " (after)";
2135         }
2136       }
2137       return new Object[]
2138       { AeContent, rangeMap, anot[0], anot[1] };
2139     }
2140     else
2141     {
2142       // no annotations to parse. Just return an empty annotationElement[]
2143       // array.
2144       return new Object[]
2145       { AeContent, rangeMap, anot[0], anot[1] };
2146     }
2147     // return null;
2148   }
2149
2150   /**
2151    * @param jal
2152    *          the jalview alignment to which the annotation will be attached
2153    *          (ideally - freshly updated from corresponding vamsas alignment)
2154    * @param annotation
2155    * @return unbound jalview alignment annotation object.
2156    */
2157   private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(
2158           jalview.datamodel.AlignmentI jal,
2159           uk.ac.vamsas.objects.core.RangeAnnotation annotation)
2160   {
2161     if (annotation == null)
2162     {
2163       return null;
2164     }
2165     // boolean
2166     // hasSequenceRef=annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation.class);
2167     // boolean hasProvenance=hasSequenceRef ||
2168     // (annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class));
2169     /*
2170      * int se[] = getBounds(annotation); if (se==null) se=new int[]
2171      * {0,jal.getWidth()-1};
2172      */
2173     Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
2174     String a_label = annotation.getLabel();
2175     String a_descr = annotation.getDescription();
2176     GraphLine gl = null;
2177     int type = 0;
2178     boolean interp = true; // cleared if annotation is DISCRETE
2179     // set type and other attributes from properties
2180     if (annotation.getPropertyCount() > 0)
2181     {
2182       // look for special jalview properties
2183       uk.ac.vamsas.objects.core.Property[] props = annotation.getProperty();
2184       for (int p = 0; p < props.length; p++)
2185       {
2186         if (props[p].getName().equalsIgnoreCase(DISCRETE_ANNOTATION))
2187         {
2188           type = AlignmentAnnotation.BAR_GRAPH;
2189           interp = false;
2190         }
2191         else if (props[p].getName().equalsIgnoreCase(CONTINUOUS_ANNOTATION))
2192         {
2193           type = AlignmentAnnotation.LINE_GRAPH;
2194         }
2195         else if (props[p].getName().equalsIgnoreCase(THRESHOLD))
2196         {
2197           Float val = null;
2198           try
2199           {
2200             val = new Float(props[p].getContent());
2201           } catch (Exception e)
2202           {
2203             Cache.log.warn("Failed to parse threshold property");
2204           }
2205           if (val != null)
2206             if (gl == null)
2207             {
2208               gl = new GraphLine(val.floatValue(), "", java.awt.Color.black);
2209             }
2210             else
2211             {
2212               gl.value = val.floatValue();
2213             }
2214         }
2215         else if (props[p].getName().equalsIgnoreCase(THRESHOLD + "Name"))
2216         {
2217           if (gl == null)
2218             gl = new GraphLine(0, "", java.awt.Color.black);
2219           gl.label = props[p].getContent();
2220         }
2221       }
2222     }
2223     jalview.datamodel.AlignmentAnnotation jan = null;
2224     if (a_label == null || a_label.length() == 0)
2225     {
2226       a_label = annotation.getType();
2227       if (a_label.length() == 0)
2228       {
2229         a_label = "Unamed annotation";
2230       }
2231     }
2232     if (a_descr == null || a_descr.length() == 0)
2233     {
2234       a_descr = "Annotation of type '" + annotation.getType() + "'";
2235     }
2236     if (parsedRangeAnnotation == null)
2237     {
2238       Cache.log
2239               .debug("Inserting empty annotation row elements for a whole-alignment annotation.");
2240     }
2241     else
2242     {
2243       if (parsedRangeAnnotation[3] != null)
2244       {
2245         Cache.log.warn("Ignoring 'After' annotation row in "
2246                 + annotation.getVorbaId());
2247       }
2248       jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
2249       boolean[] has = (boolean[]) parsedRangeAnnotation[0];
2250       // VAMSAS: getGraph is only on derived annotation for alignments - in this
2251       // way its 'odd' - there is already an existing TODO about removing this
2252       // flag as being redundant
2253       /*
2254        * if((annotation.getClass().equals(uk.ac.vamsas.objects.core.
2255        * AlignmentAnnotation.class) &&
2256        * ((uk.ac.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph())
2257        * || (hasSequenceRef=true &&
2258        * ((uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation
2259        * )annotation).getGraph())) {
2260        */
2261       if (has[HASVALS])
2262       {
2263         if (type == 0)
2264         {
2265           type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH; // default
2266           // type of
2267           // value
2268           // annotation
2269           if (has[HASHPHOB])
2270           {
2271             // no hints - so we ensure HPHOB display is like this.
2272             type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
2273           }
2274         }
2275         // make bounds and automatic description strings for jalview user's
2276         // benefit (these shouldn't be written back to vamsas document)
2277         boolean first = true;
2278         float min = 0, max = 1;
2279         int lastval = 0;
2280         for (int i = 0; i < arow.length; i++)
2281         {
2282           if (arow[i] != null)
2283           {
2284             if (i - lastval > 1 && interp)
2285             {
2286               // do some interpolation *between* points
2287               if (arow[lastval] != null)
2288               {
2289                 float interval = arow[i].value - arow[lastval].value;
2290                 interval /= i - lastval;
2291                 float base = arow[lastval].value;
2292                 for (int ip = lastval + 1, np = 0; ip < i; np++, ip++)
2293                 {
2294                   arow[ip] = new jalview.datamodel.Annotation("", "", ' ',
2295                           interval * np + base);
2296                   // NB - Interpolated points don't get a tooltip and
2297                   // description.
2298                 }
2299               }
2300             }
2301             lastval = i;
2302             // check range - shouldn't we have a min and max property in the
2303             // annotation object ?
2304             if (first)
2305             {
2306               min = max = arow[i].value;
2307               first = false;
2308             }
2309             else
2310             {
2311               if (arow[i].value < min)
2312               {
2313                 min = arow[i].value;
2314               }
2315               else if (arow[i].value > max)
2316               {
2317                 max = arow[i].value;
2318               }
2319             }
2320             // make tooltip and display char value
2321             if (!has[HASDESCSTR])
2322             {
2323               arow[i].description = arow[i].value + "";
2324             }
2325             if (!has[HASDC])
2326             {
2327               if (!interp)
2328               {
2329                 if (arow[i].description != null
2330                         && arow[i].description.length() < 3)
2331                 {
2332                   // copy over the description as the display char.
2333                   arow[i].displayCharacter = new String(arow[i].description);
2334                 }
2335               }
2336               else
2337               {
2338                 // mark the position as a point used for the interpolation.
2339                 arow[i].displayCharacter = arow[i].value + "";
2340               }
2341             }
2342           }
2343         }
2344         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2345                 arow, min, max, type);
2346       }
2347       else
2348       {
2349         if (annotation.getAnnotationElementCount() == 0)
2350         {
2351           // empty annotation array
2352           // TODO: alignment 'features' compare rangeType spec to alignment
2353           // width - if it is not complete, then mark regions on the annotation
2354           // row.
2355         }
2356         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2357                 arow);
2358         jan.setThreshold(null);
2359         jan.annotationId = annotation.getVorbaId().toString(); // keep all the
2360         // ids together.
2361       }
2362       if (annotation.getLinkCount() > 0)
2363       {
2364         Cache.log.warn("Ignoring " + annotation.getLinkCount()
2365                 + "links added to AlignmentAnnotation.");
2366       }
2367       if (annotation.getModifiable() == null
2368               || annotation.getModifiable().length() == 0) // TODO: USE VAMSAS
2369       // LIBRARY OBJECT
2370       // LOCK METHODS)
2371       {
2372         jan.editable = true;
2373       }
2374       try
2375       {
2376         if (annotation.getGroup() != null
2377                 && annotation.getGroup().length() > 0)
2378         {
2379           jan.graphGroup = Integer.parseInt(annotation.getGroup()); // TODO:
2380           // group
2381           // similarly
2382           // named
2383           // annotation
2384           // together
2385           // ?
2386         }
2387       } catch (Exception e)
2388       {
2389         Cache.log
2390                 .info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
2391       }
2392       return jan;
2393
2394     }
2395
2396     return null;
2397   }
2398
2399   /**
2400    * get real bounds of a RangeType's specification. start and end are an
2401    * inclusive range within which all segments and positions lie. TODO: refactor
2402    * to vamsas utils
2403    *
2404    * @param dseta
2405    * @return int[] { start, end}
2406    */
2407   private int[] getBounds(RangeType dseta)
2408   {
2409     if (dseta != null)
2410     {
2411       int[] se = null;
2412       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2413       {
2414         throw new Error(
2415                 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2416       }
2417       if (dseta.getSegCount() > 0)
2418       {
2419         se = getSegRange(dseta.getSeg(0), true);
2420         for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
2421         {
2422           int nse[] = getSegRange(dseta.getSeg(s), true);
2423           if (se[0] > nse[0])
2424           {
2425             se[0] = nse[0];
2426           }
2427           if (se[1] < nse[1])
2428           {
2429             se[1] = nse[1];
2430           }
2431         }
2432       }
2433       if (dseta.getPosCount() > 0)
2434       {
2435         // could do a polarity for pos range too. and pass back indication of
2436         // discontinuities.
2437         int pos = dseta.getPos(0).getI();
2438         se = new int[]
2439         { pos, pos };
2440         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2441         {
2442           pos = dseta.getPos(p).getI();
2443           if (se[0] > pos)
2444           {
2445             se[0] = pos;
2446           }
2447           if (se[1] < pos)
2448           {
2449             se[1] = pos;
2450           }
2451         }
2452       }
2453       return se;
2454     }
2455     return null;
2456   }
2457
2458   /**
2459    * map from a rangeType's internal frame to the referenced object's coordinate
2460    * frame.
2461    *
2462    * @param dseta
2463    * @return int [] { ref(pos)...} for all pos in rangeType's frame.
2464    */
2465   private int[] getMapping(RangeType dseta)
2466   {
2467     Vector posList = new Vector();
2468     if (dseta != null)
2469     {
2470       int[] se = null;
2471       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2472       {
2473         throw new Error(
2474                 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2475       }
2476       if (dseta.getSegCount() > 0)
2477       {
2478         for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
2479         {
2480           se = getSegRange(dseta.getSeg(s), false);
2481           int se_end = se[1 - se[2]] + (se[2] == 0 ? 1 : -1);
2482           for (int p = se[se[2]]; p != se_end; p += se[2] == 0 ? 1 : -1)
2483           {
2484             posList.add(new Integer(p));
2485           }
2486         }
2487       }
2488       else if (dseta.getPosCount() > 0)
2489       {
2490         int pos = dseta.getPos(0).getI();
2491
2492         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2493         {
2494           pos = dseta.getPos(p).getI();
2495           posList.add(new Integer(pos));
2496         }
2497       }
2498     }
2499     if (posList != null && posList.size() > 0)
2500     {
2501       int[] range = new int[posList.size()];
2502       for (int i = 0; i < range.length; i++)
2503       {
2504         range[i] = ((Integer) posList.elementAt(i)).intValue();
2505       }
2506       posList.clear();
2507       return range;
2508     }
2509     return null;
2510   }
2511
2512   /**
2513    *
2514    * @param maprange
2515    *          where the from range is the local mapped range, and the to range
2516    *          is the 'mapped' range in the MapRangeType
2517    * @param default unit for local
2518    * @param default unit for mapped
2519    * @return MapList
2520    */
2521   private jalview.util.MapList parsemapType(MapType maprange, int localu,
2522           int mappedu)
2523   {
2524     jalview.util.MapList ml = null;
2525     int[] localRange = getMapping(maprange.getLocal());
2526     int[] mappedRange = getMapping(maprange.getMapped());
2527     long lu = maprange.getLocal().hasUnit() ? maprange.getLocal().getUnit()
2528             : localu;
2529     long mu = maprange.getMapped().hasUnit() ? maprange.getMapped()
2530             .getUnit() : mappedu;
2531     ml = new jalview.util.MapList(localRange, mappedRange, (int) lu,
2532             (int) mu);
2533     return ml;
2534   }
2535
2536   /**
2537    * initialise a range type object from a set of start/end inclusive intervals
2538    *
2539    * @param mrt
2540    * @param range
2541    */
2542   private void initRangeType(RangeType mrt, int[] range)
2543   {
2544     for (int i = 0; i < range.length; i += 2)
2545     {
2546       Seg vSeg = new Seg();
2547       vSeg.setStart(range[i]);
2548       vSeg.setEnd(range[i + 1]);
2549       mrt.addSeg(vSeg);
2550     }
2551   }
2552
2553   /**
2554    * initialise a MapType object from a MapList object.
2555    *
2556    * @param maprange
2557    * @param ml
2558    * @param setUnits
2559    */
2560   private void initMapType(MapType maprange, jalview.util.MapList ml,
2561           boolean setUnits)
2562   {
2563     maprange.setLocal(new Local());
2564     maprange.setMapped(new Mapped());
2565     initRangeType(maprange.getLocal(), ml.getFromRanges());
2566     initRangeType(maprange.getMapped(), ml.getToRanges());
2567     if (setUnits)
2568     {
2569       maprange.getLocal().setUnit(ml.getFromRatio());
2570       maprange.getLocal().setUnit(ml.getToRatio());
2571     }
2572   }
2573
2574   /*
2575    * not needed now. Provenance getVamsasProvenance(jalview.datamodel.Provenance
2576    * jprov) { jalview.datamodel.ProvenanceEntry[] entries = null; // TODO: fix
2577    * App and Action here. Provenance prov = new Provenance();
2578    * org.exolab.castor.types.Date date = new org.exolab.castor.types.Date( new
2579    * java.util.Date()); Entry provEntry;
2580    *
2581    * if (jprov != null) { entries = jprov.getEntries(); for (int i = 0; i <
2582    * entries.length; i++) { provEntry = new Entry(); try { date = new
2583    * org.exolab.castor.types.Date(entries[i].getDate()); } catch (Exception ex)
2584    * { ex.printStackTrace();
2585    *
2586    * date = new org.exolab.castor.types.Date(entries[i].getDate()); }
2587    * provEntry.setDate(date); provEntry.setUser(entries[i].getUser());
2588    * provEntry.setAction(entries[i].getAction()); prov.addEntry(provEntry); } }
2589    * else { provEntry = new Entry(); provEntry.setDate(date);
2590    * provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
2591    * provEntry.setApp("JVAPP"); // TODO: ext string provEntry.setAction(action);
2592    * prov.addEntry(provEntry); }
2593    *
2594    * return prov; }
2595    */
2596   jalview.datamodel.Provenance getJalviewProvenance(Provenance prov)
2597   {
2598     // TODO: fix App and Action entries and check use of provenance in jalview.
2599     jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
2600     for (int i = 0; i < prov.getEntryCount(); i++)
2601     {
2602       jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i)
2603               .getAction(), prov.getEntry(i).getDate(), prov.getEntry(i)
2604               .getId());
2605     }
2606
2607     return jprov;
2608   }
2609
2610   /**
2611    *
2612    * @return default initial provenance list for a Jalview created vamsas
2613    *         object.
2614    */
2615   Provenance dummyProvenance()
2616   {
2617     return dummyProvenance(null);
2618   }
2619
2620   Entry dummyPEntry(String action)
2621   {
2622     Entry entry = new Entry();
2623     entry.setApp(this.provEntry.getApp());
2624     if (action != null)
2625     {
2626       entry.setAction(action);
2627     }
2628     else
2629     {
2630       entry.setAction("created.");
2631     }
2632     entry.setDate(new java.util.Date());
2633     entry.setUser(this.provEntry.getUser());
2634     return entry;
2635   }
2636
2637   Provenance dummyProvenance(String action)
2638   {
2639     Provenance prov = new Provenance();
2640     prov.addEntry(dummyPEntry(action));
2641     return prov;
2642   }
2643
2644   Entry addProvenance(Provenance p, String action)
2645   {
2646     Entry dentry = dummyPEntry(action);
2647     p.addEntry(dentry);
2648     return dentry;
2649   }
2650
2651   public Entry getProvEntry()
2652   {
2653     return provEntry;
2654   }
2655
2656   public IClientDocument getClientDocument()
2657   {
2658     return cdoc;
2659   }
2660
2661   public IdentityHashMap getJvObjectBinding()
2662   {
2663     return jv2vobj;
2664   }
2665
2666   public Hashtable getVamsasObjectBinding()
2667   {
2668     return vobj2jv;
2669   }
2670
2671   public void storeSequenceMappings(AlignViewport viewport, String title)
2672           throws Exception
2673   {
2674     AlignViewport av = viewport;
2675     try
2676     {
2677       jalview.datamodel.AlignmentI jal = av.getAlignment();
2678       // /////////////////////////////////////////
2679       // SAVE THE DATASET
2680       DataSet dataset = null;
2681       if (jal.getDataset() == null)
2682       {
2683         Cache.log.warn("Creating new dataset for an alignment.");
2684         jal.setDataset(null);
2685       }
2686       dataset = (DataSet) ((Alignment) getjv2vObj(viewport
2687               .getSequenceSetId())).getV_parent(); // jal.getDataset());
2688       if (dataset == null)
2689       {
2690         dataset = (DataSet) getjv2vObj(jal.getDataset());
2691         Cache.log
2692                 .error("Can't find the correct dataset for the alignment in this view. Creating new one.");
2693
2694       }
2695       // Store any sequence mappings.
2696       if (av.getAlignment().getCodonFrames() != null
2697               && av.getAlignment().getCodonFrames().length > 0)
2698       {
2699         jalview.datamodel.AlignedCodonFrame[] cframes = av.getAlignment()
2700                 .getCodonFrames();
2701         for (int cf = 0; cf < cframes.length; cf++)
2702         {
2703           if (cframes[cf].getdnaSeqs() != null
2704                   && cframes[cf].getdnaSeqs().length > 0)
2705           {
2706             jalview.datamodel.SequenceI[] dmps = cframes[cf].getdnaSeqs();
2707             jalview.datamodel.Mapping[] mps = cframes[cf].getProtMappings();
2708             for (int smp = 0; smp < mps.length; smp++)
2709             {
2710               uk.ac.vamsas.objects.core.SequenceType mfrom = (SequenceType) getjv2vObj(dmps[smp]);
2711               if (mfrom != null)
2712               {
2713                 new jalview.io.vamsas.Sequencemapping(this, mps[smp],
2714                         mfrom, dataset);
2715               }
2716               else
2717               {
2718                 Cache.log
2719                         .warn("NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR "
2720                                 + dmps[smp].getDisplayId(true)
2721                                 + " to "
2722                                 + mps[smp].getTo().getName());
2723               }
2724             }
2725           }
2726         }
2727       }
2728     } catch (Exception e)
2729     {
2730       throw new Exception("Couldn't store sequence mappings for " + title,
2731               e);
2732     }
2733   }
2734
2735   public void clearSkipList()
2736   {
2737     if (skipList != null)
2738     {
2739       skipList.clear();
2740     }
2741   }
2742
2743   /**
2744    * @return the skipList
2745    */
2746   public Hashtable getSkipList()
2747   {
2748     return skipList;
2749   }
2750
2751   /**
2752    * @param skipList
2753    *          the skipList to set
2754    */
2755   public void setSkipList(Hashtable skipList)
2756   {
2757     this.skipList = skipList;
2758   }
2759
2760   /**
2761    * registry for datastoreItems
2762    */
2763   DatastoreRegistry dsReg = new DatastoreRegistry();
2764
2765   public DatastoreRegistry getDatastoreRegisty()
2766   {
2767     if (dsReg == null)
2768     {
2769       dsReg = new DatastoreRegistry();
2770     }
2771     return dsReg;
2772   }
2773 }