refactored document objects and bugfix on jvdataset-vamsasdataset binding
[jalview.git] / src / jalview / io / VamsasAppDatastore.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2005 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
20 package jalview.io;
21
22 import jalview.bin.Cache;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.AlignmentView;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceFeature;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignViewport;
31 import jalview.gui.Desktop;
32 import jalview.gui.TreePanel;
33
34 import java.util.HashMap;
35 import java.util.Hashtable;
36 import java.util.IdentityHashMap;
37 import java.util.Vector;
38
39 import uk.ac.vamsas.client.*;
40 import uk.ac.vamsas.objects.core.*;
41
42 /*
43  *
44  * static {
45  * org.exolab.castor.util.LocalConfiguration.getInstance().getProperties().setProperty(
46  * "org.exolab.castor.serializer", "org.apache.xml.serialize.XMLSerilazizer"); }
47  *
48  */
49
50 public class VamsasAppDatastore
51 {
52   Entry provEntry = null;
53
54   // AlignViewport av;
55
56   org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(
57       new java.util.Date());
58
59   IClientDocument cdoc;
60
61   Hashtable vobj2jv;
62
63   IdentityHashMap jv2vobj;
64
65   public VamsasAppDatastore(IClientDocument cdoc, Hashtable vobj2jv,
66                          IdentityHashMap jv2vobj, Entry provEntry)
67   {
68     this.cdoc = cdoc;
69     this.vobj2jv = vobj2jv;
70     this.jv2vobj = jv2vobj;
71     this.provEntry = provEntry;
72   }
73
74   /*
75    * public void storeJalview(String file, AlignFrame af) { try { // 1. Load the
76    * mapping information from the file Mapping map = new
77    * Mapping(getClass().getClassLoader()); java.net.URL url =
78    * getClass().getResource("/jalview_mapping.xml"); map.loadMapping(url); // 2.
79    * Unmarshal the data // Unmarshaller unmar = new Unmarshaller();
80    * //unmar.setIgnoreExtraElements(true); //unmar.setMapping(map); // uni =
81    * (UniprotFile) unmar.unmarshal(new FileReader(file)); // 3. marshal the data
82    * with the total price back and print the XML in the console Marshaller
83    * marshaller = new Marshaller( new FileWriter(file) );
84    *
85    * marshaller.setMapping(map); marshaller.marshal(af); } catch (Exception e) {
86    * e.printStackTrace(); } }
87    *
88    *
89    */
90   /**
91    * @return the Vobject bound to Jalview datamodel object
92    */
93   protected Vobject getjv2vObj(Object jvobj)
94   {
95     if (jv2vobj.containsKey(jvobj))
96     {
97       return cdoc.getObject( (VorbaId) jv2vobj.get(jvobj));
98     }
99     if (Cache.log.isDebugEnabled())
100     {
101       Cache.log.debug("Returning null VorbaID binding for jalview object "+jvobj);
102     }
103     return null;
104   }
105
106   /**
107    *
108    * @param vobj
109    * @return Jalview datamodel object bound to the vamsas document object
110    */
111   protected Object getvObj2jv(uk.ac.vamsas.client.Vobject vobj)
112   {
113     VorbaId id = vobj.getVorbaId();
114     if (id == null)
115     {
116       id = cdoc.registerObject(vobj);
117       Cache.log
118           .debug("Registering new object and returning null for getvObj2jv");
119       return null;
120     }
121     if (vobj2jv.containsKey(vobj.getVorbaId()))
122     {
123       return vobj2jv.get(vobj.getVorbaId());
124     }
125     return null;
126   }
127
128   protected void bindjvvobj(Object jvobj, uk.ac.vamsas.client.Vobject vobj)
129   {
130     VorbaId id = vobj.getVorbaId();
131     if (id == null)
132     {
133       id = cdoc.registerObject(vobj);
134       if (id == null || vobj.getVorbaId() == null || cdoc.getObject(id)!=vobj)
135       {
136         Cache.log.error("Failed to get id for " +
137                         (vobj.isRegisterable() ? "registerable" :
138                          "unregisterable") + " object " + vobj);
139       }
140     }
141
142     if (vobj2jv.containsKey(vobj.getVorbaId()) &&
143         ! ( (VorbaId) vobj2jv.get(vobj.getVorbaId())).equals(jvobj))
144     {
145       Cache.log.debug("Warning? Overwriting existing vamsas id binding for " +
146                       vobj.getVorbaId(),
147                       new Exception("Overwriting vamsas id binding."));
148     }
149     else if (jv2vobj.containsKey(jvobj) &&
150              ! ( (VorbaId) jv2vobj.get(jvobj)).equals(vobj.getVorbaId()))
151     {
152       Cache.log.debug(
153           "Warning? Overwriting existing jalview object binding for " + jvobj,
154           new Exception("Overwriting jalview object binding."));
155     }
156     /* Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id " +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+" already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to bindjvvobj"));
157          }*/
158     // we just update the hash's regardless!
159     Cache.log.debug("Binding "+vobj.getVorbaId()+" to "+jvobj);
160     vobj2jv.put(vobj.getVorbaId(), jvobj);
161     // JBPNote - better implementing a hybrid invertible hash.
162     jv2vobj.put(jvobj, vobj.getVorbaId());
163   }
164
165   /**
166    * put the alignment viewed by AlignViewport into cdoc.
167    *
168    * @param av alignViewport to be stored
169    * @param aFtitle title for alignment
170    */
171   public void storeVAMSAS(AlignViewport av, String aFtitle)
172   {
173     try
174     {
175       jalview.datamodel.AlignmentI jal = av.getAlignment();
176       boolean nw = false;
177       VAMSAS root = null; // will be resolved based on Dataset Parent.
178       // /////////////////////////////////////////
179       // SAVE THE DATASET
180       DataSet dataset = null;
181       if (jal.getDataset() == null)
182       {
183         Cache.log.warn("Creating new dataset for an alignment.");
184         jal.setDataset(null);
185       }
186       dataset = (DataSet) getjv2vObj(jal.getDataset());
187       if (dataset == null)
188       {
189         // it might be that one of the dataset sequences does actually have a binding, so search for it indirectly.
190         jalview.datamodel.SequenceI[] jdatset = jal.getDataset().getSequencesArray();
191         for (int i=0; i<jdatset.length; i++)
192         {
193           Vobject vbound = getjv2vObj(jdatset[i]);
194           if (vbound!=null)
195           {
196             if (vbound instanceof uk.ac.vamsas.objects.core.Sequence)
197             {
198               if (dataset==null)
199               {
200                 dataset = (DataSet) vbound.getV_parent();
201               } else {
202                 if (dataset!=vbound.getV_parent())
203                 {
204                   throw new Error("IMPLEMENTATION ERROR: Cannot map an alignment of sequences from datasets into the vamsas document.");
205                   // This occurs because the dataset for the alignment we are trying to 
206                 }
207               }
208             }
209           }
210         }
211       }
212       
213       if (dataset == null) {
214         // we create a new dataset on the default vamsas root.
215         root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.
216         dataset = new DataSet();
217         root.addDataSet(dataset);
218         bindjvvobj(jal.getDataset(), dataset);
219         dataset.setProvenance(dummyProvenance());
220         dataset.getProvenance().addEntry(provEntry);
221         nw = true;
222       }
223       else
224       {
225         root = (VAMSAS) dataset.getV_parent();
226       }
227       // update dataset
228       Sequence sequence;
229       DbRef dbref;
230       // set new dataset and alignment sequences based on alignment Nucleotide
231       // flag.
232       // this *will* break when alignment contains both nucleotide and amino
233       // acid sequences.
234       String dict = jal.isNucleotide() ?
235           uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_NA
236           : uk.ac.vamsas.objects.utils.SymbolDictionary.STANDARD_AA;
237       for (int i = 0; i < jal.getHeight(); i++)
238       {
239         SequenceI sq = jal.getSequenceAt(i).getDatasetSequence(); // only insert
240         // referenced
241         // sequences
242         // to dataset.
243         sequence = (Sequence) getjv2vObj(sq);
244         if (sequence == null)
245         {
246           sequence = new Sequence();
247           bindjvvobj(sq, sequence);
248           sq.setVamsasId(sequence.getVorbaId().getId());
249           sequence.setSequence(sq.getSequenceAsString());
250           sequence.setDictionary(dict);
251           sequence.setName(jal.getDataset().getSequenceAt(i).getName());
252           sequence.setStart(jal.getDataset().getSequenceAt(i).getStart());
253           sequence.setEnd(jal.getDataset().getSequenceAt(i).getEnd());
254           dataset.addSequence(sequence);
255         }
256         else
257         {
258           // verify principal attributes. and update any new
259           // features/references.
260           System.out.println("update dataset sequence object.");
261         }
262         if (sq.getSequenceFeatures() != null)
263         {
264           int sfSize = sq.getSequenceFeatures().length;
265
266           for (int sf = 0; sf < sfSize; sf++)
267           {
268             jalview.datamodel.SequenceFeature feature = (jalview.datamodel.
269                 SequenceFeature) sq
270                 .getSequenceFeatures()[sf];
271
272             DataSetAnnotations dsa = (DataSetAnnotations) getjv2vObj(feature);
273             if (dsa == null)
274             {
275               dsa = (DataSetAnnotations) getDSAnnotationFromJalview(
276                   new DataSetAnnotations(), feature);
277               if (dsa.getProvenance() == null)
278               {
279                 dsa.setProvenance(new Provenance());
280               }
281               addProvenance(dsa.getProvenance(), "created"); // JBPNote - need
282               // to update
283               dsa.addSeqRef(sequence); // we have just created this annotation - so safe to use this
284               bindjvvobj(feature, dsa);
285               dataset.addDataSetAnnotations(dsa);
286             }
287             else
288             {
289               // todo: verify and update dataset annotations for sequence
290               System.out.println("update dataset sequence annotations.");
291             }
292           }
293         }
294
295         if (sq.getDBRef() != null)
296         {
297           DBRefEntry[] entries = sq.getDBRef();
298           jalview.datamodel.DBRefEntry dbentry;
299           for (int db = 0; db < entries.length; db++)
300           {
301             dbentry = entries[db];
302             dbref = (DbRef) getjv2vObj(dbentry);
303             if (dbref == null)
304             {
305               dbref = new DbRef();
306               bindjvvobj(dbentry, dbref);
307               dbref.setAccessionId(dbentry.getAccessionId());
308               dbref.setSource(dbentry.getSource());
309               dbref.setVersion(dbentry.getVersion());
310               /*
311                * TODO: Maps are not yet supported by Jalview. Map vMap = new
312                * Map(); vMap.set dbref.addMap(vMap);
313                */
314               sequence.addDbRef(dbref);
315             }
316             else
317             {
318               // TODO: verify and update dbrefs in vamsas document
319               // there will be trouble when a dataset sequence is modified to
320               // contain more residues than were originally referenced - we must
321               // then make a number of dataset sequence entries
322               System.out
323                   .println("update dataset sequence database references.");
324             }
325           }
326
327         }
328       }
329       // dataset.setProvenance(getVamsasProvenance(jal.getDataset().getProvenance()));
330       // ////////////////////////////////////////////
331
332       // ////////////////////////////////////////////
333       // Save the Alignments
334
335       Alignment alignment = (Alignment) getjv2vObj(av); // this is so we can get the alignviewport back
336       if (alignment == null)
337       {
338         alignment = new Alignment();
339         bindjvvobj(av, alignment);
340         if (alignment.getProvenance() == null)
341         {
342           alignment.setProvenance(new Provenance());
343         }
344         addProvenance(alignment.getProvenance(), "added"); // TODO: insert some
345         // sensible source
346         // here
347         dataset.addAlignment(alignment);
348         {
349           Property title = new Property();
350           title.setName("jalview:AlTitle");
351           title.setType("string");
352           title.setContent(aFtitle);
353           alignment.addProperty(title);
354         }
355         alignment.setGapChar(String.valueOf(av.getGapCharacter()));
356         AlignmentSequence alseq = null;
357         for (int i = 0; i < jal.getHeight(); i++)
358         {
359           alseq = new AlignmentSequence();
360           // TODO: VAMSAS: translate lowercase symbols to annotation ?
361           alseq.setSequence(jal.getSequenceAt(i).getSequenceAsString());
362           alseq.setName(jal.getSequenceAt(i).getName());
363           alseq.setStart(jal.getSequenceAt(i).getStart());
364           alseq.setEnd(jal.getSequenceAt(i).getEnd());
365           if (getjv2vObj(jal.getSequenceAt(i).getDatasetSequence())==null)
366           {
367             Cache.log.warn("Serious. Unbound dataset sequence in alignment: "+jal.getSequenceAt(i).getDatasetSequence());
368           }
369           alseq.setRefid(getjv2vObj(jal.getSequenceAt(i).getDatasetSequence()));
370           alignment.addAlignmentSequence(alseq);
371           bindjvvobj(jal.getSequenceAt(i), alseq);
372         }
373       }
374       else
375       {
376         // todo: verify and update mutable alignment props.
377         if (alignment.getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS
378         {
379           System.out.println("update alignment in document.");
380         }
381         else
382         {
383           System.out
384               .println("update edited alignment to new alignment in document.");
385         }
386       }
387       // ////////////////////////////////////////////
388       // SAVE Alignment Sequence Features
389       for (int i = 0, iSize = alignment.getAlignmentSequenceCount(); i < iSize;
390            i++)
391       {
392         AlignmentSequence valseq;
393         SequenceI alseq = (SequenceI) getvObj2jv(valseq = alignment
394                                                  .getAlignmentSequence(i));
395         if (alseq != null && alseq.getSequenceFeatures() != null)
396         {
397           jalview.datamodel.SequenceFeature[] features = alseq
398               .getSequenceFeatures();
399           for (int f = 0; f < features.length; f++)
400           {
401             if (features[f] != null)
402             {
403               AlignmentSequenceAnnotation valseqf = (
404                   AlignmentSequenceAnnotation) getjv2vObj(features[i]);
405               if (valseqf == null)
406               {
407
408                 valseqf = (AlignmentSequenceAnnotation)
409                     getDSAnnotationFromJalview(
410                         new AlignmentSequenceAnnotation(), features[i]);
411                 if (valseqf.getProvenance() == null)
412                 {
413                   valseqf.setProvenance(new Provenance());
414                 }
415                 addProvenance(valseqf.getProvenance(), "created"); // JBPNote -
416                 // need to
417                 // update
418                 bindjvvobj(features[i], valseqf);
419                 valseq.addAlignmentSequenceAnnotation(valseqf);
420               }
421             }
422
423           }
424         }
425       }
426
427       // ////////////////////////////////////////////
428       // SAVE ANNOTATIONS
429       if (jal.getAlignmentAnnotation() != null)
430       {
431         jalview.datamodel.AlignmentAnnotation[] aa = jal
432             .getAlignmentAnnotation();
433         java.util.HashMap AlSeqMaps = new HashMap(); // stores int maps from
434         // alignment columns to
435         // sequence positions.
436         for (int i = 0; i < aa.length; i++)
437         {
438           if (aa[i] == null || isJalviewOnly(aa[i]))
439           {
440             continue;
441           }
442           if (aa[i].sequenceRef != null)
443           {
444             uk.ac.vamsas.objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
445                 objects.core.AlignmentSequence) getjv2vObj(aa[i].sequenceRef);
446             uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation an = (uk.ac.
447                 vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(aa[
448                 i]);
449             int[] gapMap = null;
450             if (AlSeqMaps.containsKey(aa[i].sequenceRef))
451             {
452               gapMap = (int[]) AlSeqMaps.get(aa[i].sequenceRef);
453             }
454             else
455             {
456               gapMap = new int[aa[i].sequenceRef.getLength()];
457               // map from alignment position to sequence position.
458               int[] sgapMap = aa[i].sequenceRef.gapMap();
459               for (int a = 0; a < sgapMap.length; a++)
460               {
461                 gapMap[sgapMap[a]] = a;
462               }
463             }
464             if (an == null)
465             {
466               an = new uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation();
467               Seg vSeg = new Seg();
468               vSeg.setStart(1);
469               vSeg.setInclusive(true);
470               vSeg.setEnd(gapMap.length);
471               an.addSeg(vSeg);
472               an.setType("jalview:SecondaryStructurePrediction"); // TODO: better fix this rough guess ;)
473               alsref.addAlignmentSequenceAnnotation(an);
474               bindjvvobj(aa[i], an);
475               // LATER: much of this is verbatim from the alignmentAnnotation
476               // method below. suggests refactoring to make rangeAnnotation the
477               // base class
478               an.setDescription(aa[i].description);
479               if (aa[i].graph > 0)
480               {
481                 an.setGraph(true); // aa[i].graph);
482               }
483               else
484               {
485                 an.setGraph(false);
486               }
487               an.setLabel(aa[i].label);
488               an.setProvenance(dummyProvenance()); // get provenance as user
489               // created, or jnet, or
490               // something else.
491               an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -
492               // originally we
493               // were going to
494               // store
495               // graphGroup in
496               // the Jalview
497               // specific
498               // bits.
499               AnnotationElement ae;
500               for (int a = 0; a < aa[i].annotations.length; a++)
501               {
502                 if (aa[i].annotations[a] == null)
503                 {
504                   continue;
505                 }
506
507                 ae = new AnnotationElement();
508                 ae.setDescription(aa[i].annotations[a].description);
509                 ae.addGlyph(new Glyph());
510                 ae.getGlyph(0)
511                     .setContent(aa[i].annotations[a].displayCharacter); // assume
512                 // jax-b
513                 // takes
514                 // care
515                 // of
516                 // utf8
517                 // translation
518                 if (aa[i].graph !=
519                     jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
520                 {
521                   ae.addValue(aa[i].annotations[a].value);
522                 }
523                 ae.setPosition(gapMap[a] + 1); // position w.r.t. AlignmentSequence
524                 // symbols
525                 if (aa[i].annotations[a].secondaryStructure != ' ')
526                 {
527                   // we only write an annotation where it really exists.
528                   Glyph ss = new Glyph();
529                   ss
530                       .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.
531                                PROTEIN_SS_3STATE);
532                   ss.setContent(String
533                                 .valueOf(aa[i].annotations[a].
534                                          secondaryStructure));
535                   ae.addGlyph(ss);
536                 }
537                 an.addAnnotationElement(ae);
538               }
539             }
540             else
541             {
542               // update reference sequence Annotation
543               if (an.getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
544               {
545                 // verify existing alignment sequence annotation is up to date
546                 System.out.println("update alignment sequence annotation.");
547               }
548               else
549               {
550                 // verify existing alignment sequence annotation is up to date
551                 System.out
552                     .println(
553                     "make new alignment sequence annotation if modification has happened.");
554               }
555             }
556           }
557           else
558           {
559             // add Alignment Annotation
560             uk.ac.vamsas.objects.core.AlignmentAnnotation an = (uk.ac.vamsas.
561                 objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);
562             if (an == null)
563             {
564               an = new uk.ac.vamsas.objects.core.AlignmentAnnotation();
565               an.setType("jalview:AnnotationRow");
566               an.setDescription(aa[i].description);
567               alignment.addAlignmentAnnotation(an);
568               Seg vSeg = new Seg();
569               vSeg.setStart(1);
570               vSeg.setInclusive(true);
571               vSeg.setEnd(jal.getWidth());
572               an.addSeg(vSeg);
573               if (aa[i].graph > 0)
574               {
575                 an.setGraph(true); // aa[i].graph);
576               }
577               an.setLabel(aa[i].label);
578               an.setProvenance(dummyProvenance());
579               if (aa[i].graph != aa[i].NO_GRAPH)
580               {
581                 an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -
582                 // originally we
583                 // were going to
584                 // store
585                 // graphGroup in
586                 // the Jalview
587                 // specific
588                 // bits.
589                 an.setGraph(true);
590               }
591               else
592               {
593                 an.setGraph(false);
594               }
595               AnnotationElement ae;
596
597               for (int a = 0; a < aa[i].annotations.length; a++)
598               {
599                 if ( (aa[i] == null) || (aa[i].annotations[a] == null))
600                 {
601                   continue;
602                 }
603
604                 ae = new AnnotationElement();
605                 ae.setDescription(aa[i].annotations[a].description);
606                 ae.addGlyph(new Glyph());
607                 ae.getGlyph(0)
608                     .setContent(aa[i].annotations[a].displayCharacter); // assume
609                 // jax-b
610                 // takes
611                 // care
612                 // of
613                 // utf8
614                 // translation
615                 ae.addValue(aa[i].annotations[a].value);
616                 ae.setPosition(a + 1);
617                 if (aa[i].annotations[a].secondaryStructure != ' ')
618                 {
619                   Glyph ss = new Glyph();
620                   ss
621                       .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.
622                                PROTEIN_SS_3STATE);
623                   ss.setContent(String
624                                 .valueOf(aa[i].annotations[a].
625                                          secondaryStructure));
626                   ae.addGlyph(ss);
627                 }
628                 an.addAnnotationElement(ae);
629               }
630               if (aa[i].editable)
631               {
632                 //an.addProperty(newProperty("jalview:editable", null, "true"));
633                 // an.setModifiable(""); // TODO: This is not the way the modifiable flag is supposed to be used.
634               }
635               if (aa[i].graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
636               {
637                 an.setGraph(true);
638                 an.setGroup(Integer.toString(aa[i].graphGroup));
639                 an.addProperty(newProperty("jalview:graphType", null,
640                                            ( (aa[i].graph ==
641                                               jalview.datamodel.AlignmentAnnotation.
642                                               BAR_GRAPH) ? "BAR_GRAPH" :
643                                             "LINE_GRAPH")));
644
645                 /** and on and on..
646                  vProperty=new Property();
647                   vProperty.setName("jalview:graphThreshhold");
648                   vProperty.setContent(aa[i].threshold);
649                  */
650
651               }
652             }
653             else
654             {
655               if (an.getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
656               {
657                 // verify annotation - update (perhaps)
658                 Cache.log.info(
659                     "update alignment sequence annotation. not yet implemented.");
660               }
661               else
662               {
663                 // verify annotation - update (perhaps)
664                 Cache.log.info("updated alignment sequence annotation added.");
665               }
666             }
667           }
668         }
669       }
670       // /////////////////////////////////////////////////////
671
672       // //////////////////////////////////////////////
673       // /SAVE THE TREES
674       // /////////////////////////////////
675       // FIND ANY ASSOCIATED TREES
676       if (Desktop.desktop != null)
677       {
678         javax.swing.JInternalFrame[] frames = Desktop.instance.getAllFrames();
679
680         for (int t = 0; t < frames.length; t++)
681         {
682           if (frames[t] instanceof TreePanel)
683           {
684             TreePanel tp = (TreePanel) frames[t];
685
686             if (tp.getAlignment() == jal)
687             {
688               Tree tree = (Tree) getjv2vObj(tp);
689               if (tree == null)
690               {
691                 tree = new Tree();
692                 bindjvvobj(tp, tree);
693                 tree.setTitle(tp.getTitle());
694                 Newick newick = new Newick();
695                 // TODO: translate sequenceI to leaf mappings to vamsas
696                 // references - see tree specification in schema.
697                 newick.setContent(tp.getTree().toString());
698                 newick.setTitle(tp.getTitle());
699                 tree.addNewick(newick);
700                 tree.setProvenance(makeTreeProvenance(jal, tp));
701                 alignment.addTree(tree);
702               }
703               else
704               {
705                 if (tree.getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
706                 {
707                   // verify any changes.
708                   System.out.println("Update tree in document.");
709                 }
710                 else
711                 {
712                   System.out
713                       .println("Add modified tree as new tree in document.");
714                 }
715               }
716             }
717           }
718         }
719       }
720       // Store Jalview specific stuff in the Jalview appData
721       // not implemented in the SimpleDoc interface.
722     }
723
724     catch (Exception ex)
725     {
726       ex.printStackTrace();
727     }
728
729   }
730
731   private Property newProperty(String name, String type, String content)
732   {
733     Property vProperty = new Property();
734     vProperty.setName(name);
735     if (type != null)
736     {
737       vProperty.setType(type);
738     }
739     else
740     {
741       vProperty.setType("String");
742     }
743     vProperty.setContent(content);
744     return vProperty;
745   }
746
747   /**
748    * correctly create a RangeAnnotation from a jalview sequence feature
749    *
750    * @param dsa
751    *          (typically DataSetAnnotations or AlignmentSequenceAnnotation)
752    * @param feature
753    *          (the feature to be mapped from)
754    * @return
755    */
756   private RangeAnnotation getDSAnnotationFromJalview(RangeAnnotation dsa,
757       SequenceFeature feature)
758   {
759     dsa.setType(feature.getType());
760     Seg vSeg = new Seg();
761     vSeg.setStart(feature.getBegin());
762     vSeg.setEnd(feature.getEnd());
763     vSeg.setInclusive(true);
764     dsa.addSeg(vSeg);
765     dsa.setDescription(feature.getDescription());
766     dsa.setStatus(feature.getStatus());
767     if (feature.links != null && feature.links.size() > 0)
768     {
769       for (int i = 0, iSize = feature.links.size(); i < iSize; i++)
770       {
771         String link = (String) feature.links.elementAt(i);
772         int sep = link.indexOf('|');
773         if (sep > -1)
774         {
775           Link vLink = new Link();
776           if (sep > 0)
777           {
778             vLink.setContent(link.substring(0, sep - 1));
779           }
780           else
781           {
782             vLink.setContent("");
783           }
784           vLink.setHref(link.substring(sep + 1)); // TODO: validate href.
785           dsa.addLink(vLink);
786         }
787       }
788     }
789     dsa.setGroup(feature.getFeatureGroup());
790     return dsa;
791   }
792
793   /**
794    * correctly creates provenance for trees calculated on an alignment by
795    * jalview.
796    *
797    * @param jal
798    * @param tp
799    * @return
800    */
801   private Provenance makeTreeProvenance(AlignmentI jal, TreePanel tp)
802   {
803     Provenance prov = new Provenance();
804     prov.addEntry(new Entry());
805     prov.getEntry(0).setAction("imported " + tp.getTitle());
806     prov.getEntry(0).setUser(provEntry.getUser());
807     prov.getEntry(0).setApp(provEntry.getApp());
808     prov.getEntry(0).setDate(provEntry.getDate());
809     if (tp.getTree().hasOriginalSequenceData())
810     {
811       Input vInput = new Input();
812       // LATER: check to see if tree input data is contained in this alignment -
813       // or just correctly resolve the tree's seqData to the correct alignment in
814       // the document.
815       // vInput.setObjRef(getjv2vObj(jal));
816       vInput.setObjRef(new Object[] { getjv2vObj(tp.getViewPort())});
817       prov.getEntry(0).setAction("created " + tp.getTitle());
818       prov.getEntry(0).addInput(vInput);
819       vInput.setName("jalview:seqdist");
820       prov.getEntry(0).addParam(new Param());
821       prov.getEntry(0).getParam(0).setName("treeType");
822       prov.getEntry(0).getParam(0).setType("utf8");
823       prov.getEntry(0).getParam(0).setContent("NJ");
824
825       int ranges[] = tp.getTree().seqData.getVisibleContigs();
826       // VisibleContigs are with respect to alignment coordinates. Still need offsets
827       int start = tp.getTree().seqData.getAlignmentOrigin();
828       for (int r = 0; r < ranges.length; r += 2)
829       {
830         Seg visSeg = new Seg();
831         visSeg.setStart(1 + start + ranges[r]);
832         visSeg.setEnd(start + ranges[r + 1]);
833         visSeg.setInclusive(true);
834         vInput.addSeg(visSeg);
835       }
836     }
837     return prov;
838   }
839
840   /**
841    *
842    * @param tp
843    * @return Object[] { AlignmentView, AlignmentI - reference alignment for
844    *         input }
845    */
846   private Object[] recoverInputData(Provenance tp)
847   {
848     for (int pe = 0; pe < tp.getEntryCount(); pe++)
849     {
850       if (tp.getEntry(pe).getInputCount() > 0)
851       {
852         if (tp.getEntry(pe).getInputCount() > 1)
853         {
854           Cache.log.warn("Ignoring additional input spec in provenance entry "
855                          + tp.getEntry(pe).toString());
856         }
857         // LATER: deal sensibly with multiple inputs
858         Input vInput = tp.getEntry(pe).getInput(0);
859         // LATER: deal sensibly with multiple object specification for input
860         if (vInput.getObjRef().length==1 && vInput.getObjRef(0) instanceof uk.ac.vamsas.objects.core.Alignment)
861         {
862           // recover an AlignmentView for the input data
863           AlignViewport javport = (AlignViewport) getvObj2jv( (uk.ac.vamsas.
864               client.Vobject) vInput
865               .getObjRef(0));
866           jalview.datamodel.AlignmentI jal = javport.getAlignment();
867           jalview.datamodel.CigarArray view = javport.getAlignment().
868               getCompactAlignment();
869           int from = 1, to = jal.getWidth();
870           int offset = 0; // deleteRange modifies its frame of reference
871           for (int r = 0, s = vInput.getSegCount(); r < s; r++)
872           {
873             Seg visSeg = vInput.getSeg(r);
874             int se[] = getSegRange(visSeg, true); // jalview doesn't do bidirection alignments yet.
875             if (to < se[1])
876             {
877               Cache.log.warn("Ignoring invalid segment in InputData spec.");
878             }
879             else
880             {
881               if (se[0] > from)
882               {
883                 view.deleteRange(offset + from - 1, offset + se[0] - 2);
884                 offset -= se[0] - from;
885               }
886               from = se[1] + 1;
887             }
888           }
889           if (from < to)
890           {
891             view.deleteRange(offset + from - 1, offset + to - 1); // final deletion - TODO: check off by
892             // one for to
893           }
894           return new Object[]
895               {
896               new AlignmentView(view), jal};
897         }
898       }
899     }
900     Cache.log.debug("Returning null for input data recovery from provenance.");
901     return null;
902   }
903
904   /**
905    * get start<end range of segment, adjusting for inclusivity flag and
906    * polarity.
907    *
908    * @param visSeg
909    * @param ensureDirection when true - always ensure start is less than end.
910    * @return int[] { start, end, direction} where direction==1 for range running from end to start.
911    */
912   private int[] getSegRange(Seg visSeg, boolean ensureDirection)
913   {
914     boolean incl = visSeg.getInclusive();
915     // adjust for inclusive flag.
916     int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
917     // region.
918     int start = visSeg.getStart() + (incl ? 0 : pol);
919     int end = visSeg.getEnd() + (incl ? 0 : -pol);
920     if (ensureDirection && pol == -1)
921     {
922       // jalview doesn't deal with inverted ranges, yet.
923       int t = end;
924       end = start;
925       start = t;
926     }
927     return new int[]
928         {
929         start, end, pol < 0 ? 1 : 0};
930   }
931
932   /**
933    *
934    * @param annotation
935    * @return true if annotation is not to be stored in document
936    */
937   private boolean isJalviewOnly(AlignmentAnnotation annotation)
938   {
939     return annotation.label.equals("Quality")
940         || annotation.label.equals("Conservation")
941         || annotation.label.equals("Consensus");
942   }
943
944   /**
945    * This will return the first AlignFrame viewing AlignViewport av.
946    * It will break if there are more than one AlignFrames viewing a particular av.
947    * This also shouldn't be in the io package.
948    * @param av
949    * @return alignFrame for av
950    */
951   public AlignFrame getAlignFrameFor(AlignViewport av)
952   {
953     if (Desktop.desktop != null)
954     {
955       javax.swing.JInternalFrame[] frames = Desktop.instance.getAllFrames();
956
957       for (int t = 0; t < frames.length; t++)
958       {
959         if (frames[t] instanceof AlignFrame)
960         {
961           if ( ( (AlignFrame) frames[t]).getViewport() == av)
962           {
963             return (AlignFrame) frames[t];
964           }
965         }
966       }
967     }
968     return null;
969   }
970
971   public void updateToJalview()
972   {
973     VAMSAS _roots[] = cdoc.getVamsasRoots();
974
975     for (int _root = 0; _root < _roots.length; _root++)
976     {
977       VAMSAS root = _roots[_root];
978       boolean newds = false;
979       for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
980       {
981         // ///////////////////////////////////
982         // ///LOAD DATASET
983         DataSet dataset = root.getDataSet(_ds);
984         int i, iSize = dataset.getSequenceCount();
985         Vector dsseqs;
986         jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment)
987             getvObj2jv(dataset);
988         int jremain = 0;
989         if (jdataset == null)
990         {
991           Cache.log.debug("Initialising new jalview dataset fields");
992           newds = true;
993           dsseqs = new Vector();
994         }
995         else
996         {
997           Cache.log.debug("Update jalview dataset from vamsas.");
998           jremain = jdataset.getHeight();
999           dsseqs = jdataset.getSequences();
1000         }
1001
1002         // TODO: test sequence merging - we preserve existing non vamsas
1003         // sequences but add in any new vamsas ones, and don't yet update any
1004         // sequence attributes
1005         for (i = 0; i < iSize; i++)
1006         {
1007           Sequence vdseq = dataset.getSequence(i);
1008           jalview.datamodel.SequenceI dsseq = (SequenceI) getvObj2jv(vdseq);
1009           if (dsseq != null)
1010           {
1011             if (!dsseq.getSequenceAsString().equals(vdseq.getSequence()))
1012             {
1013               throw new Error(
1014                   "Broken! - mismatch of dataset sequence: and jalview internal dataset sequence.");
1015             }
1016             jremain--;
1017           }
1018           else
1019           {
1020             dsseq = new jalview.datamodel.Sequence(
1021                 dataset.getSequence(i).getName(),
1022                 dataset.getSequence(i).getSequence(),
1023                 (int)dataset.getSequence(i).getStart(),
1024                 (int)dataset.getSequence(i).getEnd());
1025             dsseq.setDescription(dataset.getSequence(i).getDescription());
1026             bindjvvobj(dsseq, dataset.getSequence(i));
1027             dsseq.setVamsasId(dataset.getSequence(i).getVorbaId().getId());
1028             dsseqs.add(dsseq);
1029           }
1030           if (vdseq.getDbRefCount() > 0)
1031           {
1032             DbRef[] dbref = vdseq.getDbRef();
1033             for (int db = 0; db < dbref.length; db++)
1034             {
1035               jalview.datamodel.DBRefEntry dbr = (jalview.datamodel.DBRefEntry)
1036                   getvObj2jv(dbref[db]);
1037               if (dbr == null)
1038               {
1039                 // add new dbref
1040                 dsseq.addDBRef(dbr = new jalview.datamodel.DBRefEntry
1041                                (
1042                                    dbref[db].getSource().toString(),
1043                                    dbref[db].getVersion().toString(),
1044                                    dbref[db].getAccessionId().toString()));
1045                 bindjvvobj(dbr, dbref[db]);
1046               }
1047             }
1048           }
1049         }
1050
1051         if (newds)
1052         {
1053           SequenceI[] seqs = new SequenceI[dsseqs.size()];
1054           for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1055           {
1056             seqs[i] = (SequenceI) dsseqs.elementAt(i);
1057             dsseqs.setElementAt(null, i);
1058           }
1059           jdataset = new jalview.datamodel.Alignment(seqs);
1060           Cache.log.debug("New vamsas dataset imported into jalview.");
1061           bindjvvobj(jdataset, dataset);
1062         }
1063         // ////////
1064         // add any new dataset sequence feature annotations
1065         if (dataset.getDataSetAnnotations() != null)
1066         {
1067           for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++)
1068           {
1069             DataSetAnnotations dseta = dataset.getDataSetAnnotations(dsa);
1070             // TODO: deal with group annotation on datset sequences.
1071             if (dseta.getSeqRefCount()==1)
1072             {
1073               SequenceI dsSeq = (SequenceI) getvObj2jv( (Vobject) dseta.getSeqRef(0)); // TODO: deal with group dataset annotations
1074               if (dsSeq == null)
1075               {
1076                 jalview.bin.Cache.log.warn(
1077                         "Couldn't resolve jalview sequenceI for dataset object reference " +
1078                         ( (Vobject) dataset.getDataSetAnnotations(dsa).getSeqRef(0)).
1079                         getVorbaId().getId());
1080               }
1081               else
1082               {
1083                 if (dseta.getAnnotationElementCount() == 0)
1084               {
1085                 jalview.datamodel.SequenceFeature sf = (jalview.datamodel.
1086                     SequenceFeature) getvObj2jv(dseta);
1087                 if (sf == null)
1088                 {
1089                   dsSeq.addSequenceFeature(sf = getJalviewSeqFeature(dseta));
1090                   bindjvvobj(sf, dseta);
1091                 }
1092               }
1093               else
1094               {
1095                 // TODO: deal with alignmentAnnotation style annotation
1096                 // appearing on dataset sequences.
1097                 // JBPNote: we could just add them to all alignments but
1098                 // that may complicate cross references in the jalview
1099                 // datamodel
1100                 Cache.log.warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
1101               }
1102             }
1103             }
1104           }
1105         }
1106
1107         if (dataset.getAlignmentCount() > 0)
1108         {
1109           // LOAD ALIGNMENTS from DATASET
1110
1111           for (int al = 0, nal = dataset.getAlignmentCount(); al < nal; al++)
1112           {
1113             uk.ac.vamsas.objects.core.Alignment alignment = dataset.getAlignment(
1114                 al);
1115             AlignViewport av = (AlignViewport) getvObj2jv(alignment);
1116             jalview.datamodel.AlignmentI jal = null;
1117             if (av != null)
1118             {
1119               jal = av.getAlignment();
1120             }
1121             iSize = alignment.getAlignmentSequenceCount();
1122             boolean newal = (jal == null) ? true : false;
1123             Vector newasAnnots = new Vector();
1124             char gapChar = ' '; // default for new alignments read in from the document
1125             if (jal != null)
1126             {
1127               dsseqs = jal.getSequences(); // for merge/update
1128               gapChar = jal.getGapCharacter();
1129             }
1130             else
1131             {
1132               dsseqs = new Vector();
1133             }
1134             char valGapchar = alignment.getGapChar().charAt(0);
1135             for (i = 0; i < iSize; i++)
1136             {
1137               AlignmentSequence valseq = alignment.getAlignmentSequence(i);
1138               jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
1139               if (alseq != null)
1140               {
1141                 //TODO: upperCase/LowerCase situation here ? do we allow it ?
1142                 //if (!alseq.getSequence().equals(valseq.getSequence())) {
1143                 // throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");
1144                 if (Cache.log.isDebugEnabled())
1145                 {
1146                   Cache.log.debug("Updating apparently edited sequence " +
1147                                   alseq.getName());
1148                 }
1149                 // this might go *horribly* wrong
1150                 alseq.setSequence(new String(valseq.getSequence()).replace(
1151                     valGapchar, gapChar));
1152                 jremain--;
1153               }
1154               else
1155               {
1156                 alseq = new jalview.datamodel.Sequence(
1157                     valseq.getName(),
1158                     valseq.getSequence().replace(valGapchar, gapChar),
1159                     (int)valseq.getStart(),
1160                     (int)valseq.getEnd());
1161
1162                 Vobject datsetseq = (Vobject) valseq.getRefid();
1163                 if (datsetseq != null)
1164                 {
1165                   alseq.setDatasetSequence( (SequenceI) getvObj2jv(datsetseq)); // exceptions if AlignemntSequence reference isn't a simple SequenceI
1166                 }
1167                 else
1168                 {
1169                   Cache.log.error(
1170                       "Invalid dataset sequence id (null) for alignment sequence " +
1171                       valseq.getVorbaId());
1172                 }
1173                 bindjvvobj(alseq, valseq);
1174                 alseq.setVamsasId(valseq.getVorbaId().getId());
1175                 dsseqs.add(alseq);
1176               }
1177               if (valseq.getAlignmentSequenceAnnotationCount() > 0)
1178               {
1179                 AlignmentSequenceAnnotation[] vasannot = valseq.
1180                     getAlignmentSequenceAnnotation();
1181                 for (int a = 0; a < vasannot.length; a++)
1182                 {
1183                   jalview.datamodel.AlignmentAnnotation asa = (jalview.
1184                       datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO: 1:many jalview alignment sequence annotations
1185                   if (asa == null)
1186                   {
1187                     int se[] = getBounds(vasannot[a]);
1188                     asa = getjAlignmentAnnotation(jal, vasannot[a]);
1189                     asa.sequenceRef = alseq;
1190                     asa.createSequenceMapping(alseq, alseq.getStart() + se[0], false); // TODO: verify that positions in alseqAnnotation correspond to ungapped residue positions.
1191                     bindjvvobj(asa, vasannot[a]);
1192                     newasAnnots.add(asa);
1193                   }
1194                   else
1195                   {
1196                     // update existing annotation - can do this in place
1197                     if (vasannot[a].getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
1198                     {
1199                       Cache.log.info(
1200                           "UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1201                       // TODO: should at least replace with new one - otherwise things will break
1202                       // basically do this:
1203                       // int se[] = getBounds(vasannot[a]);
1204                       // asa.update(getjAlignmentAnnotation(jal, vasannot[a])); //  update from another annotation object in place.
1205                       // asa.createSequenceMapping(alseq, se[0], false);
1206
1207                     }
1208                   }
1209                 }
1210               }
1211             }
1212             if (jal == null)
1213             {
1214               SequenceI[] seqs = new SequenceI[dsseqs.size()];
1215               for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1216               {
1217                 seqs[i] = (SequenceI) dsseqs.elementAt(i);
1218                 dsseqs.setElementAt(null, i);
1219               }
1220               jal = new jalview.datamodel.Alignment(seqs);
1221               Cache.log.debug("New vamsas alignment imported into jalview " +
1222                               alignment.getVorbaId().getId());
1223               jal.setDataset(jdataset);
1224             }
1225             if (newasAnnots != null && newasAnnots.size() > 0)
1226             {
1227               // Add the new sequence annotations in to the alignment.
1228               for (int an = 0, anSize = newasAnnots.size(); an < anSize; an++)
1229               {
1230                 jal.addAnnotation( (AlignmentAnnotation) newasAnnots.elementAt(
1231                     an));
1232                 // TODO: check if anything has to be done - like calling adjustForAlignment or something.
1233                 newasAnnots.setElementAt(null, an);
1234               }
1235               newasAnnots = null;
1236             }
1237             // //////////////////////////////////////////
1238             // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1239             // ////////////////////////////////////
1240             if (alignment.getAlignmentAnnotationCount() > 0)
1241             {
1242               uk.ac.vamsas.objects.core.AlignmentAnnotation[] an = alignment.
1243                   getAlignmentAnnotation();
1244
1245               for (int j = 0; j < an.length; j++)
1246               {
1247                 jalview.datamodel.AlignmentAnnotation jan = (jalview.datamodel.
1248                     AlignmentAnnotation) getvObj2jv(an[j]);
1249                 if (jan != null)
1250                 {
1251                   // update or stay the same.
1252                   // TODO: should at least replace with a new one - otherwise things will break
1253                   // basically do this:
1254                   // jan.update(getjAlignmentAnnotation(jal, an[a])); //  update from another annotation object in place.
1255
1256                   Cache.log.debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1257                   if (an[j].getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
1258                   {
1259                     // TODO: user defined annotation is totally mutable... - so load it up or throw away if locally edited.
1260                     Cache.log.info(
1261                         "NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1262                   }
1263                   // TODO: compare annotation element rows
1264                   // TODO: compare props.
1265                 }
1266                 else
1267                 {
1268                   jan = getjAlignmentAnnotation(jal, an[j]);
1269                   jal.addAnnotation(jan);
1270                   bindjvvobj(jan, an[j]);
1271                 }
1272               }
1273             }
1274             AlignFrame alignFrame;
1275             if (av == null)
1276             {
1277               Cache.log.debug("New alignframe for alignment " +
1278                               alignment.getVorbaId());
1279               // ///////////////////////////////
1280               // construct alignment view
1281               alignFrame = new AlignFrame(jal, AlignFrame.DEFAULT_WIDTH,
1282                                           AlignFrame.DEFAULT_HEIGHT);
1283               av = alignFrame.getViewport();
1284               String title = alignment.getProvenance().getEntry(alignment.
1285                   getProvenance().getEntryCount() - 1).getAction();
1286               if (alignment.getPropertyCount() > 0)
1287               {
1288                 for (int p = 0, pe = alignment.getPropertyCount(); p < pe; p++)
1289                 {
1290                   if (alignment.getProperty(p).getName().equals(
1291                       "jalview:AlTitle"))
1292                   {
1293                     title = alignment.getProperty(p).getContent();
1294                   }
1295                 }
1296               }
1297               // TODO: automatically create meaningful title for a vamsas alignment using its provenance.
1298               jalview.gui.Desktop.addInternalFrame(alignFrame,
1299                   title + "(" + alignment.getVorbaId() + ")",
1300                   AlignFrame.DEFAULT_WIDTH,
1301                   AlignFrame.DEFAULT_HEIGHT);
1302               bindjvvobj(av, alignment);
1303             }
1304             else
1305             {
1306               // find the alignFrame for jal.
1307               // TODO: fix this so we retrieve the alignFrame handing av *directly*
1308               alignFrame = getAlignFrameFor(av);
1309             }
1310             // LOAD TREES
1311             // /////////////////////////////////////
1312             if (alignment.getTreeCount() > 0)
1313             {
1314
1315               for (int t = 0; t < alignment.getTreeCount(); t++)
1316               {
1317                 Tree tree = alignment.getTree(t);
1318                 TreePanel tp = (TreePanel) getvObj2jv(tree);
1319                 if (tp != null)
1320                 {
1321                   Cache.log.info(
1322                       "Update from vamsas document to alignment associated tree not implemented yet.");
1323                 }
1324                 else
1325                 {
1326                   // make a new tree
1327                   Object[] idata = this.recoverInputData(tree.getProvenance());
1328                   try
1329                   {
1330                     AlignmentView inputData = null;
1331                     if (idata != null && idata[0] != null)
1332                     {
1333                       inputData = (AlignmentView) idata[0];
1334                     }
1335                     tp = alignFrame.ShowNewickTree(
1336                         new jalview.io.NewickFile(tree.getNewick(0).getContent()),
1337                         tree.getNewick(0).getTitle() + " (" + tree.getVorbaId() +
1338                         ")", inputData,
1339                         600, 500,
1340                         t * 20 + 50, t * 20 + 50);
1341                     bindjvvobj(tp, tree);
1342                   }
1343                   catch (Exception e)
1344                   {
1345                     Cache.log.warn("Problems parsing treefile '" +
1346                                    tree.getNewick(0).getContent() + "'", e);
1347                   }
1348                 }
1349               }
1350             }
1351
1352           }
1353         }
1354       }
1355     }
1356   }
1357
1358   // bitfields - should be a template in j1.5
1359   private static int HASSECSTR = 0;
1360   private static int HASVALS = 1;
1361   private static int HASHPHOB = 2;
1362   private static int HASDC = 3;
1363   private static int HASDESCSTR = 4;
1364   private static int HASTWOSTATE = 5; // not used yet.
1365   /**
1366    * parses the AnnotationElements - if they exist - into jalview.datamodel.Annotation[] rows
1367    * Two annotation rows are made if there are distinct annotation for both at 'pos' and 'after pos' at any particular site.
1368    * @param annotation
1369    * @return { boolean[static int constants ], int[ae.length] - map to annotated object frame, jalview.datamodel.Annotation[], jalview.datamodel.Annotation[] (after)}
1370    */
1371   private Object[] parseRangeAnnotation(uk.ac.vamsas.objects.core.RangeAnnotation
1372                                         annotation)
1373   {
1374     // set these attributes by looking in the annotation to decide what kind of alignment annotation rows will be made
1375     // TODO: potentially we might make several annotation rows from one vamsas alignment annotation. the jv2Vobj binding mechanism
1376     // may not quite cope with this (without binding an array of annotations to a vamsas alignment annotation)
1377     // summary flags saying what we found over the set of annotation rows.
1378     boolean[] AeContent = new boolean[]
1379         {
1380         false, false, false, false, false};
1381     int[] rangeMap = getMapping(annotation);
1382     jalview.datamodel.Annotation[][] anot = new jalview.datamodel.Annotation[][]
1383         {
1384         new jalview.datamodel.Annotation[rangeMap.length],
1385         new jalview.datamodel.Annotation[rangeMap.length]
1386     };
1387     boolean mergeable = true; //false  if 'after positions cant be placed on same annotation row as positions.
1388
1389     if (annotation.getAnnotationElementCount() > 0)
1390     {
1391       AnnotationElement ae[] = annotation.getAnnotationElement();
1392       for (int aa = 0; aa < ae.length; aa++)
1393       {
1394         int pos = (int) ae[aa].getPosition() - 1; // pos counts from 1 to (|seg.start-seg.end|+1)
1395         if (pos >= 0 && pos < rangeMap.length)
1396         {
1397           int row = ae[aa].getAfter() ? 1 : 0;
1398           if (anot[row][pos] != null)
1399           {
1400             // only time this should happen is if the After flag is set.
1401             Cache.log.debug("Ignoring duplicate annotation site at " + pos);
1402             continue;
1403           }
1404           if (anot[1 - row][pos] != null)
1405           {
1406             mergeable = false;
1407           }
1408           String desc = "";
1409           if (ae[aa].getDescription() != null)
1410           {
1411             desc = ae[aa].getDescription();
1412             if (desc.length() > 0)
1413             {
1414               // have imported valid description string
1415               AeContent[HASDESCSTR] = true;
1416             }
1417           }
1418           String dc = null; //ae[aa].getDisplayCharacter()==null ? "dc" : ae[aa].getDisplayCharacter();
1419           String ss = null; //ae[aa].getSecondaryStructure()==null ? "ss" : ae[aa].getSecondaryStructure();
1420           java.awt.Color colour = null;
1421           if (ae[aa].getGlyphCount() > 0)
1422           {
1423             Glyph[] glyphs = ae[aa].getGlyph();
1424             for (int g = 0; g < glyphs.length; g++)
1425             {
1426               if (glyphs[g].getDict().equals(uk.ac.vamsas.objects.utils.
1427                                              GlyphDictionary.PROTEIN_SS_3STATE))
1428               {
1429                 ss = glyphs[g].getContent();
1430                 AeContent[HASSECSTR] = true;
1431               }
1432               else if (glyphs[g].getDict().equals(uk.ac.vamsas.objects.utils.
1433                                                   GlyphDictionary.
1434                                                   PROTEIN_HD_HYDRO))
1435               {
1436                 Cache.log.debug("ignoring hydrophobicity glyph marker.");
1437                 AeContent[HASHPHOB] = true;
1438                 char c = (dc = glyphs[g].getContent()).charAt(0);
1439                 // dc may get overwritten - but we still set the colour.
1440                 colour = new java.awt.Color(c == '+' ? 255 : 0,
1441                                             c == '.' ? 255 : 0,
1442                                             c == '-' ? 255 : 0);
1443
1444               }
1445               else if (glyphs[g].getDict().equals(uk.ac.vamsas.objects.utils.
1446                                                   GlyphDictionary.DEFAULT))
1447               {
1448                 dc = glyphs[g].getContent();
1449                 AeContent[HASDC] = true;
1450               }
1451               else
1452               {
1453                 Cache.log.debug("Ignoring unknown glyph type " +
1454                                 glyphs[g].getDict());
1455               }
1456             }
1457           }
1458           float val = 0;
1459           if (ae[aa].getValueCount() > 0)
1460           {
1461             AeContent[HASVALS] = true;
1462             if (ae[aa].getValueCount() > 1)
1463             {
1464               Cache.log.warn("ignoring additional " +
1465                              (ae[aa].getValueCount() - 1) +
1466                              "values in annotation element.");
1467             }
1468             val = ae[aa].getValue(0);
1469           }
1470           if (colour == null)
1471           {
1472             anot[row][pos] = new jalview.datamodel.Annotation( (dc != null) ?
1473                 dc : "", desc, (ss != null) ? ss.charAt(0) : ' ', val);
1474           }
1475           else
1476           {
1477             anot[row][pos] = new jalview.datamodel.Annotation( (dc != null) ?
1478                 dc : "", desc, (ss != null) ? ss.charAt(0) : ' ', val, colour);
1479           }
1480         }
1481         else
1482         {
1483           Cache.log.warn("Ignoring out of bound annotation element " + aa +
1484                          " in " + annotation.getVorbaId().getId());
1485         }
1486       }
1487       // decide on how many annotation rows are needed.
1488       if (mergeable)
1489       {
1490         for (int i = 0; i < anot[0].length; i++)
1491         {
1492           if (anot[1][i] != null)
1493           {
1494             anot[0][i] = anot[1][i];
1495             anot[0][i].description = anot[0][i].description + " (after)";
1496             AeContent[HASDESCSTR] = true; // we have valid description string data
1497             anot[1][i] = null;
1498           }
1499         }
1500         anot[1] = null;
1501       }
1502       else
1503       {
1504         for (int i = 0; i < anot[0].length; i++)
1505         {
1506           anot[1][i].description = anot[1][i].description + " (after)";
1507         }
1508       }
1509       return new Object[]
1510           {
1511           AeContent, rangeMap, anot[0], anot[1]};
1512     }
1513     else
1514     {
1515       // no annotations to parse. Just return an empty annotationElement[] array.
1516       return new Object[]
1517           {
1518           AeContent, rangeMap, anot[0], anot[1]};
1519     }
1520     // return null;
1521   }
1522
1523   /**
1524    * @param jal the jalview alignment to which the annotation will be attached (ideally - freshly updated from corresponding vamsas alignment)
1525    * @param annotation
1526    * @return unbound jalview alignment annotation object.
1527    */
1528   private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(jalview.
1529       datamodel.AlignmentI jal,
1530       uk.ac.vamsas.objects.core.RangeAnnotation annotation)
1531   {
1532     jalview.datamodel.AlignmentAnnotation jan = null;
1533     if (annotation == null)
1534     {
1535       return null;
1536     }
1537     // boolean hasSequenceRef=annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation.class);
1538     //boolean hasProvenance=hasSequenceRef || (annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class));
1539     /*int se[] = getBounds(annotation);
1540          if (se==null)
1541       se=new int[] {0,jal.getWidth()-1};
1542      */
1543     Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
1544     String a_label = annotation.getLabel();
1545     String a_descr = annotation.getDescription();
1546     if (a_label == null || a_label.length() == 0)
1547     {
1548       a_label = annotation.getType();
1549       if (a_label.length() == 0)
1550       {
1551         a_label = "Unamed annotation";
1552       }
1553     }
1554     if (a_descr == null || a_descr.length() == 0)
1555     {
1556       a_descr = "Annotation of type '" + annotation.getType() + "'";
1557     }
1558     if (parsedRangeAnnotation == null)
1559     {
1560       Cache.log.debug(
1561           "Inserting empty annotation row elements for a whole-alignment annotation.");
1562
1563     }
1564     else
1565     {
1566       if (parsedRangeAnnotation[3] != null)
1567       {
1568         Cache.log.warn("Ignoring 'After' annotation row in " +
1569                        annotation.getVorbaId());
1570       }
1571       jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[])
1572           parsedRangeAnnotation[2];
1573       boolean[] has = (boolean[]) parsedRangeAnnotation[0];
1574       // VAMSAS: getGraph is only on derived annotation for alignments - in this way its 'odd' - there is already an existing TODO about removing this flag as being redundant
1575       /*if ((annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class) && ((uk.ac.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph())
1576           || (hasSequenceRef=true && ((uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {
1577        */
1578       if (has[HASVALS])
1579       {
1580         // make bounds and automatic description strings for jalview user's benefit (these shouldn't be written back to vamsas document)
1581         boolean first = true;
1582         float min = 0, max = 1;
1583         int lastval = 0;
1584         for (int i = 0; i < arow.length; i++)
1585         {
1586           if (arow[i] != null)
1587           {
1588             if (i - lastval > 1)
1589             {
1590               // do some interpolation *between* points
1591               if (arow[lastval] != null)
1592               {
1593                 float interval = arow[i].value - arow[lastval].value;
1594                 interval /= i - lastval;
1595                 float base = arow[lastval].value;
1596                 for (int ip = lastval + 1, np = 0; ip < i; np++, ip++)
1597                 {
1598                   arow[ip] = new jalview.datamodel.Annotation("", "", ' ',
1599                       interval * np + base);
1600                   // NB - Interpolated points don't get a tooltip and description.
1601                 }
1602               }
1603             }
1604             lastval = i;
1605             // check range - shouldn't we have a min and max property in the annotation object ?
1606             if (first)
1607             {
1608               min = max = arow[i].value;
1609               first = false;
1610             }
1611             else
1612             {
1613               if (arow[i].value < min)
1614               {
1615                 min = arow[i].value;
1616               }
1617               else if (arow[i].value > max)
1618               {
1619                 max = arow[i].value;
1620               }
1621             }
1622             // make tooltip and display char value
1623             if (!has[HASDESCSTR])
1624             {
1625               arow[i].description = arow[i].value + "";
1626             }
1627             if (!has[HASDC])
1628             {
1629               arow[i].displayCharacter = arow[i].value + "";
1630             }
1631           }
1632         }
1633         int type = jalview.datamodel.AlignmentAnnotation.LINE_GRAPH;
1634         if (has[HASHPHOB])
1635         {
1636           type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
1637         }
1638         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow,
1639             min, max, type);
1640       }
1641       else
1642       {
1643         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow);
1644         jan.setThreshold(null);
1645       }
1646       if (annotation.getLinkCount() > 0)
1647       {
1648         Cache.log.warn("Ignoring " + annotation.getLinkCount() +
1649                        "links added to AlignmentAnnotation.");
1650       }
1651       if (annotation.getModifiable()==null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK METHODS)
1652       {
1653         jan.editable = true;
1654       }
1655
1656       if (annotation.getPropertyCount() > 0)
1657       {
1658         // look for special jalview properties
1659         uk.ac.vamsas.objects.core.Property[] props = annotation.getProperty();
1660         for (int p = 0; p < props.length; p++)
1661         {
1662           if (props[p].getName().equalsIgnoreCase("jalview:graphType"))
1663           {
1664             try
1665             {
1666               // probably a jalview annotation graph so recover the visualization hints.
1667               jan.graph = jalview.datamodel.AlignmentAnnotation.
1668                   getGraphValueFromString(props[p].getContent());
1669             }
1670             catch (Exception e)
1671             {
1672               Cache.log.debug(
1673                   "Invalid graph type value in jalview:graphType property.");
1674             }
1675             try
1676             {
1677               if (annotation.getGroup() != null &&
1678                   annotation.getGroup().length() > 0)
1679               {
1680                 jan.graphGroup = Integer.parseInt(annotation.getGroup());
1681               }
1682             }
1683             catch (Exception e)
1684             {
1685               Cache.log.info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
1686             }
1687           }
1688         }
1689       }
1690
1691       return jan;
1692
1693     }
1694
1695     return null;
1696   }
1697
1698   private SequenceFeature getJalviewSeqFeature(RangeAnnotation dseta)
1699   {
1700     int[] se = getBounds(dseta);
1701     SequenceFeature sf = new jalview.datamodel.SequenceFeature(dseta.getType(),
1702         dseta.getDescription(), dseta.getStatus(), se[0], se[1], dseta
1703         .getGroup());
1704     if (dseta.getLinkCount() > 0)
1705     {
1706       Link[] links = dseta.getLink();
1707       for (int i = 0; i < links.length; i++)
1708       {
1709         sf.addLink(links[i].getContent() + "|" + links[i].getHref());
1710       }
1711     }
1712     return sf;
1713   }
1714
1715   /**
1716    * get real bounds of a RangeType's specification. start and end are an
1717    * inclusive range within which all segments and positions lie.
1718    * TODO: refactor to vamsas utils
1719    * @param dseta
1720    * @return int[] { start, end}
1721    */
1722   private int[] getBounds(RangeType dseta)
1723   {
1724     if (dseta != null)
1725     {
1726       int[] se = null;
1727       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
1728       {
1729         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1730       }
1731       if (dseta.getSegCount() > 0)
1732       {
1733         se = getSegRange(dseta.getSeg(0), true);
1734         for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
1735         {
1736           int nse[] = getSegRange(dseta.getSeg(s), true);
1737           if (se[0] > nse[0])
1738           {
1739             se[0] = nse[0];
1740           }
1741           if (se[1] < nse[1])
1742           {
1743             se[1] = nse[1];
1744           }
1745         }
1746       }
1747       if (dseta.getPosCount() > 0)
1748       {
1749         // could do a polarity for pos range too. and pass back indication of discontinuities.
1750         int pos = dseta.getPos(0).getI();
1751         se = new int[]
1752             {
1753             pos, pos};
1754         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1755         {
1756           pos = dseta.getPos(p).getI();
1757           if (se[0] > pos)
1758           {
1759             se[0] = pos;
1760           }
1761           if (se[1] < pos)
1762           {
1763             se[1] = pos;
1764           }
1765         }
1766       }
1767       return se;
1768     }
1769     return null;
1770   }
1771
1772   /**
1773    * map from a rangeType's internal frame to the referenced object's coordinate frame.
1774    * @param dseta
1775    * @return int [] { ref(pos)...} for all pos in rangeType's frame.
1776    */
1777   private int[] getMapping(RangeType dseta)
1778   {
1779     Vector posList = new Vector();
1780     if (dseta != null)
1781     {
1782       int[] se = null;
1783       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
1784       {
1785         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1786       }
1787       if (dseta.getSegCount() > 0)
1788       {
1789         for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
1790         {
1791           se = getSegRange(dseta.getSeg(s), false);
1792           int se_end = se[1 - se[2]] + (se[2] == 0 ? 1 : -1);
1793           for (int p = se[se[2]]; p != se_end; p += se[2] == 0 ? 1 : -1)
1794           {
1795             posList.add(new Integer(p));
1796           }
1797         }
1798       }
1799       else if (dseta.getPosCount() > 0)
1800       {
1801         int pos = dseta.getPos(0).getI();
1802
1803         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1804         {
1805           pos = dseta.getPos(p).getI();
1806           posList.add(new Integer(pos));
1807         }
1808       }
1809     }
1810     if (posList != null && posList.size() > 0)
1811     {
1812       int[] range = new int[posList.size()];
1813       for (int i = 0; i < range.length; i++)
1814       {
1815         range[i] = ( (Integer) posList.elementAt(i)).intValue();
1816       }
1817       posList.clear();
1818       return range;
1819     }
1820     return null;
1821   }
1822
1823   /* not needed now.
1824    * Provenance getVamsasProvenance(jalview.datamodel.Provenance jprov) {
1825     jalview.datamodel.ProvenanceEntry[] entries = null;
1826     // TODO: fix App and Action here.
1827     Provenance prov = new Provenance();
1828     org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(
1829         new java.util.Date());
1830     Entry provEntry;
1831
1832     if (jprov != null)
1833     {
1834       entries = jprov.getEntries();
1835       for (int i = 0; i < entries.length; i++)
1836       {
1837         provEntry = new Entry();
1838         try
1839         {
1840           date = new org.exolab.castor.types.Date(entries[i].getDate());
1841         } catch (Exception ex)
1842         {
1843           ex.printStackTrace();
1844
1845           date = new org.exolab.castor.types.Date(entries[i].getDate());
1846         }
1847         provEntry.setDate(date);
1848         provEntry.setUser(entries[i].getUser());
1849         provEntry.setAction(entries[i].getAction());
1850         prov.addEntry(provEntry);
1851       }
1852     }
1853     else
1854     {
1855       provEntry = new Entry();
1856       provEntry.setDate(date);
1857       provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
1858       provEntry.setApp("JVAPP"); // TODO: ext string
1859       provEntry.setAction(action);
1860       prov.addEntry(provEntry);
1861     }
1862
1863     return prov;
1864      }
1865    */
1866   jalview.datamodel.Provenance getJalviewProvenance(Provenance prov)
1867   {
1868     // TODO: fix App and Action entries and check use of provenance in jalview.
1869     jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
1870     for (int i = 0; i < prov.getEntryCount(); i++)
1871     {
1872       jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i).getAction(),
1873                      prov.getEntry(i).getDate(),
1874                      prov.getEntry(i).getId());
1875     }
1876
1877     return jprov;
1878   }
1879
1880   /**
1881    *
1882    * @return default initial provenance list for a Jalview created vamsas
1883    *         object.
1884    */
1885   Provenance dummyProvenance()
1886   {
1887     return dummyProvenance(null);
1888   }
1889
1890   Entry dummyPEntry(String action)
1891   {
1892     Entry entry = new Entry();
1893     entry.setApp(this.provEntry.getApp());
1894     if (action != null)
1895     {
1896       entry.setAction(action);
1897     }
1898     else
1899     {
1900       entry.setAction("created.");
1901     }
1902     entry.setDate(new java.util.Date());
1903     entry.setUser(this.provEntry.getUser());
1904     return entry;
1905   }
1906
1907   Provenance dummyProvenance(String action)
1908   {
1909     Provenance prov = new Provenance();
1910     prov.addEntry(dummyPEntry(action));
1911     return prov;
1912   }
1913
1914   void addProvenance(Provenance p, String action)
1915   {
1916     p.addEntry(dummyPEntry(action));
1917   }
1918
1919 }