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