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