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