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