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