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