ensure annotationElements in non-graphical annotation objects do not automatically...
[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                 if (an.isGraph())
632                 {
633                   ae.addValue(aa[i].annotations[a].value);
634                 }
635                 ae.setPosition(a + 1);
636                 if (aa[i].annotations[a].secondaryStructure != ' ')
637                 {
638                   Glyph ss = new Glyph();
639                   ss
640                           .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
641                   ss
642                           .setContent(String
643                                   .valueOf(aa[i].annotations[a].secondaryStructure));
644                   ae.addGlyph(ss);
645                 }
646                 an.addAnnotationElement(ae);
647               }
648               if (aa[i].editable)
649               {
650                 // an.addProperty(newProperty("jalview:editable", null,
651                 // "true"));
652                 // an.setModifiable(""); // TODO: This is not the way the
653                 // modifiable flag is supposed to be used.
654               }
655               setAnnotationType(an, aa[i]);
656
657               if (aa[i].graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
658               {
659                 an.setGraph(true);
660                 an.setGroup(Integer.toString(aa[i].graphGroup));
661                 if (aa[i].threshold != null && aa[i].threshold.displayed)
662                 {
663                   an.addProperty(newProperty(THRESHOLD, "float", ""
664                           + aa[i].threshold.value));
665                   if (aa[i].threshold.label != null)
666                   {
667                     an.addProperty(newProperty(THRESHOLD + "Name",
668                             "string", "" + aa[i].threshold.label));
669                   }
670                 }
671               }
672
673             }
674
675             else
676             {
677               if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT
678               // LOCK METHODS)
679               {
680                 // verify annotation - update (perhaps)
681                 Cache.log
682                         .info("update alignment sequence annotation. not yet implemented.");
683               }
684               else
685               {
686                 // verify annotation - update (perhaps)
687                 Cache.log
688                         .info("updated alignment sequence annotation added.");
689               }
690             }
691           }
692         }
693       }
694       // /////////////////////////////////////////////////////
695
696       // //////////////////////////////////////////////
697       // /SAVE THE TREES
698       // /////////////////////////////////
699       // FIND ANY ASSOCIATED TREES
700       if (Desktop.desktop != null)
701       {
702         javax.swing.JInternalFrame[] frames = Desktop.instance
703                 .getAllFrames();
704
705         for (int t = 0; t < frames.length; t++)
706         {
707           if (frames[t] instanceof TreePanel)
708           {
709             TreePanel tp = (TreePanel) frames[t];
710
711             if (tp.getAlignment() == jal)
712             {
713               DatastoreItem vtree = new jalview.io.vamsas.Tree(this, tp,
714                       jal, alignment);
715             }
716           }
717         }
718       }
719       // Store Jalview specific stuff in the Jalview appData
720       // not implemented in the SimpleDoc interface.
721     }
722
723     catch (Exception ex)
724     {
725       ex.printStackTrace();
726     }
727
728   }
729
730   /**
731    * remove docseqs from the given alignment marking provenance appropriately
732    * and removing any references to the sequences.
733    * 
734    * @param alignment
735    * @param docseqs
736    */
737   private void removeValignmentSequences(Alignment alignment, Vector docseqs)
738   {
739     // delete these from document. This really needs to be a generic document
740     // API function derived by CASTOR.
741     Enumeration en = docseqs.elements();
742     while (en.hasMoreElements())
743     {
744       alignment.removeAlignmentSequence((AlignmentSequence) en
745               .nextElement());
746     }
747     Entry pe = addProvenance(alignment.getProvenance(), "Removed "
748             + docseqs.size() + " sequences");
749     en = alignment.enumerateAlignmentAnnotation();
750     Vector toremove = new Vector();
751     while (en.hasMoreElements())
752     {
753       uk.ac.vamsas.objects.core.AlignmentAnnotation alan = (uk.ac.vamsas.objects.core.AlignmentAnnotation) en
754               .nextElement();
755       if (alan.getSeqrefsCount() > 0)
756       {
757         int p = 0;
758         Vector storem = new Vector();
759         Enumeration sr = alan.enumerateSeqrefs();
760         while (sr.hasMoreElements())
761         {
762           Object alsr = sr.nextElement();
763           if (docseqs.contains(alsr))
764           {
765             storem.addElement(alsr);
766           }
767         }
768         // remove references to the deleted sequences
769         sr = storem.elements();
770         while (sr.hasMoreElements())
771         {
772           alan.removeSeqrefs(sr.nextElement());
773         }
774
775         if (alan.getSeqrefsCount() == 0)
776         {
777           // should then delete alan from dataset
778           toremove.addElement(alan);
779         }
780       }
781     }
782     // remove any annotation that used to be associated to a specific bunch of
783     // sequences
784     en = toremove.elements();
785     while (en.hasMoreElements())
786     {
787       alignment
788               .removeAlignmentAnnotation((uk.ac.vamsas.objects.core.AlignmentAnnotation) en
789                       .nextElement());
790     }
791     // TODO: search through alignment annotations to remove any references to
792     // this alignment sequence
793   }
794
795   /**
796    * sync a jalview alignment seuqence into a vamsas alignment assumes all lock
797    * transformation/bindings have been sorted out before hand. creates/syncs the
798    * vamsas alignment sequence for jvalsq and adds it to the alignment if
799    * necessary. unbounddocseq is a duplicate of the vamsas alignment sequences
800    * and these are removed after being processed w.r.t a bound jvalsq
801    * 
802    */
803   private boolean syncToAlignmentSequence(SequenceI jvalsq,
804           Alignment alignment, Vector unbounddocseq)
805   {
806     boolean modal = false;
807     // todo: islocked method here
808     boolean up2doc = false;
809     AlignmentSequence alseq = (AlignmentSequence) getjv2vObj(jvalsq);
810     if (alseq == null)
811     {
812       alseq = new AlignmentSequence();
813       up2doc = true;
814     }
815     else
816     {
817       if (unbounddocseq != null)
818       {
819         unbounddocseq.removeElement(alseq);
820       }
821     }
822     // boolean locked = (alignment.getModifiable()==null ||
823     // alignment.getModifiable().length()>0);
824     // TODO: VAMSAS: translate lowercase symbols to annotation ?
825     if (up2doc || !alseq.getSequence().equals(jvalsq.getSequenceAsString()))
826     {
827       alseq.setSequence(jvalsq.getSequenceAsString());
828       alseq.setStart(jvalsq.getStart());
829       alseq.setEnd(jvalsq.getEnd());
830       modal = true;
831     }
832     if (up2doc || !alseq.getName().equals(jvalsq.getName()))
833     {
834       modal = true;
835       alseq.setName(jvalsq.getName());
836     }
837     if (jvalsq.getDescription() != null
838             && (alseq.getDescription() == null || !jvalsq.getDescription()
839                     .equals(alseq.getDescription())))
840     {
841       modal = true;
842       alseq.setDescription(jvalsq.getDescription());
843     }
844     if (getjv2vObj(jvalsq.getDatasetSequence()) == null)
845     {
846       Cache.log
847               .warn("Serious Implementation error - Unbound dataset sequence in alignment: "
848                       + jvalsq.getDatasetSequence());
849     }
850     alseq.setRefid(getjv2vObj(jvalsq.getDatasetSequence()));
851     if (up2doc)
852     {
853
854       alignment.addAlignmentSequence(alseq);
855       bindjvvobj(jvalsq, alseq);
856     }
857     return up2doc || modal;
858   }
859
860   /**
861    * locally sync a jalview alignment seuqence from a vamsas alignment assumes
862    * all lock transformation/bindings have been sorted out before hand.
863    * creates/syncs the jvalsq from the alignment sequence
864    */
865   private boolean syncFromAlignmentSequence(AlignmentSequence valseq,
866           char valGapchar, char gapChar, Vector dsseqs)
867
868   {
869     boolean modal = false;
870     // todo: islocked method here
871     boolean upFromdoc = false;
872     jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
873     if (alseq == null)
874     {
875       upFromdoc = true;
876     }
877     if (alseq != null)
878     {
879
880       // boolean locked = (alignment.getModifiable()==null ||
881       // alignment.getModifiable().length()>0);
882       // TODO: VAMSAS: translate lowercase symbols to annotation ?
883       if (upFromdoc
884               || !valseq.getSequence().equals(alseq.getSequenceAsString()))
885       {
886         // this might go *horribly* wrong
887         alseq.setSequence(new String(valseq.getSequence()).replace(
888                 valGapchar, gapChar));
889         alseq.setStart((int) valseq.getStart());
890         alseq.setEnd((int) valseq.getEnd());
891         modal = true;
892       }
893       if (!valseq.getName().equals(alseq.getName()))
894       {
895         modal = true;
896         alseq.setName(valseq.getName());
897       }
898       if (alseq.getDescription() == null
899               || (valseq.getDescription() == null || alseq.getDescription()
900                       .equals(valseq.getDescription())))
901       {
902         alseq.setDescription(valseq.getDescription());
903         modal = true;
904       }
905       if (modal && Cache.log.isDebugEnabled())
906       {
907         Cache.log.debug("Updating apparently edited sequence "
908                 + alseq.getName());
909       }
910     }
911     else
912     {
913       alseq = new jalview.datamodel.Sequence(valseq.getName(), valseq
914               .getSequence().replace(valGapchar, gapChar), (int) valseq
915               .getStart(), (int) valseq.getEnd());
916
917       Vobject datsetseq = (Vobject) valseq.getRefid();
918       if (datsetseq != null)
919       {
920         alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
921         // if
922         // AlignemntSequence
923         // reference
924         // isn't
925         // a
926         // simple
927         // SequenceI
928       }
929       else
930       {
931         Cache.log
932                 .error("Invalid dataset sequence id (null) for alignment sequence "
933                         + valseq.getVorbaId());
934       }
935       bindjvvobj(alseq, valseq);
936       alseq.setVamsasId(valseq.getVorbaId().getId());
937       dsseqs.add(alseq);
938     }
939     Vobject datsetseq = (Vobject) valseq.getRefid();
940     if (datsetseq != null)
941     {
942       if (datsetseq != alseq.getDatasetSequence())
943       {
944         modal = true;
945       }
946       alseq.setDatasetSequence((SequenceI) getvObj2jv(datsetseq)); // exceptions
947     }
948     return upFromdoc || modal;
949   }
950
951   private void initRangeAnnotationType(RangeAnnotation an,
952           AlignmentAnnotation alan, int[] gapMap)
953   {
954     Seg vSeg = new Seg();
955     vSeg.setStart(1);
956     vSeg.setInclusive(true);
957     vSeg.setEnd(gapMap.length);
958     an.addSeg(vSeg);
959
960     // LATER: much of this is verbatim from the alignmentAnnotation
961     // method below. suggests refactoring to make rangeAnnotation the
962     // base class
963     an.setDescription(alan.description);
964     an.setLabel(alan.label);
965     an.setGroup(Integer.toString(alan.graphGroup));
966     // // JBPNote -
967     // originally we
968     // were going to
969     // store
970     // graphGroup in
971     // the Jalview
972     // specific
973     // bits.
974     AnnotationElement ae;
975     for (int a = 0; a < alan.annotations.length; a++)
976     {
977       if (alan.annotations[a] == null)
978       {
979         continue;
980       }
981
982       ae = new AnnotationElement();
983       ae.setDescription(alan.annotations[a].description);
984       ae.addGlyph(new Glyph());
985       ae.getGlyph(0).setContent(alan.annotations[a].displayCharacter); // assume
986       // jax-b
987       // takes
988       // care
989       // of
990       // utf8
991       // translation
992       if (alan.graph != jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
993       {
994         ae.addValue(alan.annotations[a].value);
995       }
996       ae.setPosition(gapMap[a] + 1); // position w.r.t. AlignmentSequence
997       // symbols
998       if (alan.annotations[a].secondaryStructure != ' ')
999       {
1000         // we only write an annotation where it really exists.
1001         Glyph ss = new Glyph();
1002         ss
1003                 .setDict(uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
1004         ss.setContent(String
1005                 .valueOf(alan.annotations[a].secondaryStructure));
1006         ae.addGlyph(ss);
1007       }
1008       an.addAnnotationElement(ae);
1009     }
1010
1011   }
1012
1013   private void saveDatasetSequenceAnnotation(HashMap AlSeqMaps,
1014           uk.ac.vamsas.objects.core.Sequence sref, AlignmentAnnotation alan)
1015   {
1016     // {
1017     // uk.ac.vamsas.
1018     // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1019     // objects.core.AlignmentSequence) sref;
1020     uk.ac.vamsas.objects.core.DataSetAnnotations an = (uk.ac.vamsas.objects.core.DataSetAnnotations) getjv2vObj(alan);
1021     int[] gapMap = getGapMap(AlSeqMaps, alan);
1022     if (an == null)
1023     {
1024       an = new uk.ac.vamsas.objects.core.DataSetAnnotations();
1025       initRangeAnnotationType(an, alan, gapMap);
1026
1027       an.setProvenance(dummyProvenance()); // get provenance as user
1028       // created, or jnet, or
1029       // something else.
1030       setAnnotationType(an, alan);
1031       an.setGroup(Integer.toString(alan.graphGroup)); // // JBPNote -
1032       // originally we
1033       // were going to
1034       // store
1035       // graphGroup in
1036       // the Jalview
1037       // specific
1038       // bits.
1039       if (alan.getThreshold() != null && alan.getThreshold().displayed)
1040       {
1041         an.addProperty(newProperty(THRESHOLD, "float", ""
1042                 + alan.getThreshold().value));
1043         if (alan.getThreshold().label != null)
1044           an.addProperty(newProperty(THRESHOLD + "Name", "string", ""
1045                   + alan.getThreshold().label));
1046       }
1047       ((DataSet) sref.getV_parent()).addDataSetAnnotations(an);
1048       bindjvvobj(alan, an);
1049     }
1050     else
1051     {
1052       // update reference sequence Annotation
1053       if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1054       // METHODS)
1055       {
1056         // verify existing alignment sequence annotation is up to date
1057         System.out.println("update dataset sequence annotation.");
1058       }
1059       else
1060       {
1061         // verify existing alignment sequence annotation is up to date
1062         System.out
1063                 .println("make new alignment dataset sequence annotation if modification has happened.");
1064       }
1065     }
1066
1067   }
1068
1069   private int[] getGapMap(HashMap AlSeqMaps, AlignmentAnnotation alan)
1070   {
1071     int[] gapMap;
1072     if (AlSeqMaps.containsKey(alan.sequenceRef))
1073     {
1074       gapMap = (int[]) AlSeqMaps.get(alan.sequenceRef);
1075     }
1076     else
1077     {
1078       gapMap = new int[alan.sequenceRef.getLength()];
1079       // map from alignment position to sequence position.
1080       int[] sgapMap = alan.sequenceRef.gapMap();
1081       for (int a = 0; a < sgapMap.length; a++)
1082       {
1083         gapMap[sgapMap[a]] = a;
1084       }
1085     }
1086     return gapMap;
1087   }
1088
1089   private void saveAlignmentSequenceAnnotation(HashMap AlSeqMaps,
1090           AlignmentSequence alsref, AlignmentAnnotation alan)
1091   {
1092     // {
1093     // uk.ac.vamsas.
1094     // objects.core.AlignmentSequence alsref = (uk.ac.vamsas.
1095     // objects.core.AlignmentSequence) sref;
1096     uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation an = (uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(alan);
1097     int[] gapMap = getGapMap(AlSeqMaps, alan);
1098     if (an == null)
1099     {
1100       an = new uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation();
1101       initRangeAnnotationType(an, alan, gapMap);
1102       /**
1103        * I mean here that we don't actually have a semantic 'type' for the
1104        * annotation (this might be - score, intrinsic property, measurement,
1105        * something extracted from another program, etc)
1106        */
1107       an.setType(JALVIEW_ANNOTATION_ROW); // TODO: better fix
1108       // this rough guess ;)
1109       alsref.addAlignmentSequenceAnnotation(an);
1110       bindjvvobj(alan, an);
1111       // These properties are directly supported by the
1112       // AlignmentSequenceAnnotation type.
1113       setAnnotationType(an, alan);
1114       an.setProvenance(dummyProvenance()); // get provenance as user
1115       // created, or jnet, or
1116       // something else.
1117     }
1118     else
1119     {
1120       // update reference sequence Annotation
1121       if (an.getModifiable() == null) // TODO: USE VAMSAS LIBRARY OBJECT LOCK
1122       // METHODS)
1123       {
1124         // verify existing alignment sequence annotation is up to date
1125         System.out.println("update alignment sequence annotation.");
1126       }
1127       else
1128       {
1129         // verify existing alignment sequence annotation is up to date
1130         System.out
1131                 .println("make new alignment sequence annotation if modification has happened.");
1132       }
1133     }
1134   }
1135
1136   /**
1137    * set vamsas annotation object type from jalview annotation
1138    * 
1139    * @param an
1140    * @param alan
1141    */
1142   private void setAnnotationType(RangeAnnotation an,
1143           AlignmentAnnotation alan)
1144   {
1145     if (an instanceof AlignmentSequenceAnnotation)
1146     {
1147       if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1148       {
1149         ((AlignmentSequenceAnnotation) an).setGraph(true);
1150       }
1151       else
1152       {
1153         ((AlignmentSequenceAnnotation) an).setGraph(false);
1154       }
1155     }
1156     if (an instanceof uk.ac.vamsas.objects.core.AlignmentAnnotation)
1157     {
1158       if (alan.graph != AlignmentAnnotation.NO_GRAPH)
1159       {
1160         ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an).setGraph(true);
1161       }
1162       else
1163       {
1164         ((uk.ac.vamsas.objects.core.AlignmentAnnotation) an)
1165                 .setGraph(false);
1166       }
1167     }
1168     switch (alan.graph)
1169     {
1170     case AlignmentAnnotation.BAR_GRAPH:
1171       an.addProperty(newProperty(DISCRETE_ANNOTATION, "boolean", "true"));
1172       break;
1173     case AlignmentAnnotation.LINE_GRAPH:
1174       an.addProperty(newProperty(CONTINUOUS_ANNOTATION, "boolean", "true"));
1175       break;
1176     default:
1177       // don't add any kind of discrete or continous property info.
1178     }
1179   }
1180
1181   private Property newProperty(String name, String type, String content)
1182   {
1183     Property vProperty = new Property();
1184     vProperty.setName(name);
1185     if (type != null)
1186     {
1187       vProperty.setType(type);
1188     }
1189     else
1190     {
1191       vProperty.setType("String");
1192     }
1193     vProperty.setContent(content);
1194     return vProperty;
1195   }
1196
1197   /**
1198    * correctly create a RangeAnnotation from a jalview sequence feature
1199    * 
1200    * @param dsa
1201    *                (typically DataSetAnnotations or
1202    *                AlignmentSequenceAnnotation)
1203    * @param feature
1204    *                (the feature to be mapped from)
1205    * @return
1206    */
1207   private RangeAnnotation getDSAnnotationFromJalview(RangeAnnotation dsa,
1208           SequenceFeature feature)
1209   {
1210     dsa.setType(feature.getType());
1211     Seg vSeg = new Seg();
1212     vSeg.setStart(feature.getBegin());
1213     vSeg.setEnd(feature.getEnd());
1214     vSeg.setInclusive(true);
1215     dsa.addSeg(vSeg);
1216     dsa.setDescription(feature.getDescription());
1217     dsa.setStatus(feature.getStatus());
1218     if (feature.links != null && feature.links.size() > 0)
1219     {
1220       for (int i = 0, iSize = feature.links.size(); i < iSize; i++)
1221       {
1222         String link = (String) feature.links.elementAt(i);
1223         int sep = link.indexOf('|');
1224         if (sep > -1)
1225         {
1226           Link vLink = new Link();
1227           if (sep > 0)
1228           {
1229             vLink.setContent(link.substring(0, sep - 1));
1230           }
1231           else
1232           {
1233             vLink.setContent("");
1234           }
1235           vLink.setHref(link.substring(sep + 1)); // TODO: validate href.
1236           dsa.addLink(vLink);
1237         }
1238       }
1239     }
1240     dsa.setGroup(feature.getFeatureGroup());
1241     return dsa;
1242   }
1243
1244   /**
1245    * get start<end range of segment, adjusting for inclusivity flag and
1246    * polarity.
1247    * 
1248    * @param visSeg
1249    * @param ensureDirection
1250    *                when true - always ensure start is less than end.
1251    * @return int[] { start, end, direction} where direction==1 for range running
1252    *         from end to start.
1253    */
1254   private int[] getSegRange(Seg visSeg, boolean ensureDirection)
1255   {
1256     boolean incl = visSeg.getInclusive();
1257     // adjust for inclusive flag.
1258     int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
1259     // region.
1260     int start = visSeg.getStart() + (incl ? 0 : pol);
1261     int end = visSeg.getEnd() + (incl ? 0 : -pol);
1262     if (ensureDirection && pol == -1)
1263     {
1264       // jalview doesn't deal with inverted ranges, yet.
1265       int t = end;
1266       end = start;
1267       start = t;
1268     }
1269     return new int[]
1270     { start, end, pol < 0 ? 1 : 0 };
1271   }
1272
1273   /**
1274    * 
1275    * @param annotation
1276    * @return true if annotation is not to be stored in document
1277    */
1278   private boolean isJalviewOnly(AlignmentAnnotation annotation)
1279   {
1280     return annotation.label.equals("Quality")
1281             || annotation.label.equals("Conservation")
1282             || annotation.label.equals("Consensus");
1283   }
1284
1285   /**
1286    * This will return the first AlignFrame viewing AlignViewport av. It will
1287    * break if there are more than one AlignFrames viewing a particular av. This
1288    * also shouldn't be in the io package.
1289    * 
1290    * @param av
1291    * @return alignFrame for av
1292    */
1293   public AlignFrame getAlignFrameFor(AlignViewport av)
1294   {
1295     if (Desktop.desktop != null)
1296     {
1297       javax.swing.JInternalFrame[] frames = Desktop.instance.getAllFrames();
1298
1299       for (int t = 0; t < frames.length; t++)
1300       {
1301         if (frames[t] instanceof AlignFrame)
1302         {
1303           if (((AlignFrame) frames[t]).getViewport() == av)
1304           {
1305             return (AlignFrame) frames[t];
1306           }
1307         }
1308       }
1309     }
1310     return null;
1311   }
1312
1313   public void updateToJalview()
1314   {
1315     VAMSAS _roots[] = cdoc.getVamsasRoots();
1316
1317     for (int _root = 0; _root < _roots.length; _root++)
1318     {
1319       VAMSAS root = _roots[_root];
1320       boolean newds = false;
1321       for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1322       {
1323         // ///////////////////////////////////
1324         // ///LOAD DATASET
1325         DataSet dataset = root.getDataSet(_ds);
1326         int i, iSize = dataset.getSequenceCount();
1327         Vector dsseqs;
1328         jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);
1329         int jremain = 0;
1330         if (jdataset == null)
1331         {
1332           Cache.log.debug("Initialising new jalview dataset fields");
1333           newds = true;
1334           dsseqs = new Vector();
1335         }
1336         else
1337         {
1338           Cache.log.debug("Update jalview dataset from vamsas.");
1339           jremain = jdataset.getHeight();
1340           dsseqs = jdataset.getSequences();
1341         }
1342
1343         // TODO: test sequence merging - we preserve existing non vamsas
1344         // sequences but add in any new vamsas ones, and don't yet update any
1345         // sequence attributes
1346         for (i = 0; i < iSize; i++)
1347         {
1348           Sequence vdseq = dataset.getSequence(i);
1349           jalview.datamodel.SequenceI dsseq = (SequenceI) getvObj2jv(vdseq);
1350           if (dsseq != null)
1351           {
1352             if (!dsseq.getSequenceAsString().equals(vdseq.getSequence()))
1353             {
1354               throw new Error(
1355                       "Broken! - mismatch of dataset sequence: and jalview internal dataset sequence.");
1356             }
1357             jremain--;
1358           }
1359           else
1360           {
1361             dsseq = new jalview.datamodel.Sequence(dataset.getSequence(i)
1362                     .getName(), dataset.getSequence(i).getSequence(),
1363                     (int) dataset.getSequence(i).getStart(), (int) dataset
1364                             .getSequence(i).getEnd());
1365             dsseq.setDescription(dataset.getSequence(i).getDescription());
1366             bindjvvobj(dsseq, dataset.getSequence(i));
1367             dsseq.setVamsasId(dataset.getSequence(i).getVorbaId().getId());
1368             dsseqs.add(dsseq);
1369           }
1370           if (vdseq.getDbRefCount() > 0)
1371           {
1372             DbRef[] dbref = vdseq.getDbRef();
1373             for (int db = 0; db < dbref.length; db++)
1374             {
1375               new jalview.io.vamsas.Dbref(this, dbref[db], vdseq, dsseq);
1376
1377             }
1378             dsseq.updatePDBIds();
1379           }
1380         }
1381
1382         if (newds)
1383         {
1384           SequenceI[] seqs = new SequenceI[dsseqs.size()];
1385           for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1386           {
1387             seqs[i] = (SequenceI) dsseqs.elementAt(i);
1388             dsseqs.setElementAt(null, i);
1389           }
1390           jdataset = new jalview.datamodel.Alignment(seqs);
1391           Cache.log.debug("New vamsas dataset imported into jalview.");
1392           bindjvvobj(jdataset, dataset);
1393         }
1394         // ////////
1395         // add any new dataset sequence feature annotations
1396         if (dataset.getDataSetAnnotations() != null)
1397         {
1398           for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++)
1399           {
1400             DataSetAnnotations dseta = dataset.getDataSetAnnotations(dsa);
1401             // TODO: deal with group annotation on datset sequences.
1402             if (dseta.getSeqRefCount() == 1)
1403             {
1404               SequenceI dsSeq = (SequenceI) getvObj2jv((Vobject) dseta
1405                       .getSeqRef(0)); // TODO: deal with group dataset
1406               // annotations
1407               if (dsSeq == null)
1408               {
1409                 jalview.bin.Cache.log
1410                         .warn("Couldn't resolve jalview sequenceI for dataset object reference "
1411                                 + ((Vobject) dataset.getDataSetAnnotations(
1412                                         dsa).getSeqRef(0)).getVorbaId()
1413                                         .getId());
1414               }
1415               else
1416               {
1417                 if (dseta.getAnnotationElementCount() == 0)
1418                 {
1419                   jalview.datamodel.SequenceFeature sf = (jalview.datamodel.SequenceFeature) getvObj2jv(dseta);
1420                   if (sf == null)
1421                   {
1422                     dsSeq
1423                             .addSequenceFeature(sf = getJalviewSeqFeature(dseta));
1424                     bindjvvobj(sf, dseta);
1425                   }
1426                 }
1427                 else
1428                 {
1429                   // TODO: deal with alignmentAnnotation style annotation
1430                   // appearing on dataset sequences.
1431                   // JBPNote: we could just add them to all alignments but
1432                   // that may complicate cross references in the jalview
1433                   // datamodel
1434                   Cache.log
1435                           .warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
1436                 }
1437               }
1438             }
1439           }
1440         }
1441         if (dataset.getAlignmentCount() > 0)
1442         {
1443           // LOAD ALIGNMENTS from DATASET
1444
1445           for (int al = 0, nal = dataset.getAlignmentCount(); al < nal; al++)
1446           {
1447             uk.ac.vamsas.objects.core.Alignment alignment = dataset
1448                     .getAlignment(al);
1449             AlignViewport av = findViewport(alignment);
1450
1451             jalview.datamodel.AlignmentI jal = null;
1452             if (av != null)
1453             {
1454               jal = av.getAlignment();
1455             }
1456             iSize = alignment.getAlignmentSequenceCount();
1457             boolean newal = (jal == null) ? true : false;
1458             boolean refreshal = false;
1459             Vector newasAnnots = new Vector();
1460             char gapChar = ' '; // default for new alignments read in from the
1461             // document
1462             if (jal != null)
1463             {
1464               dsseqs = jal.getSequences(); // for merge/update
1465               gapChar = jal.getGapCharacter();
1466             }
1467             else
1468             {
1469               dsseqs = new Vector();
1470             }
1471             char valGapchar = alignment.getGapChar().charAt(0);
1472             for (i = 0; i < iSize; i++)
1473             {
1474               AlignmentSequence valseq = alignment.getAlignmentSequence(i);
1475               jalview.datamodel.Sequence alseq = (jalview.datamodel.Sequence) getvObj2jv(valseq);
1476               if (syncFromAlignmentSequence(valseq, valGapchar, gapChar,
1477                       dsseqs)
1478                       && alseq != null)
1479               {
1480
1481                 // updated to sequence from the document
1482                 jremain--;
1483                 refreshal = true;
1484               }
1485               if (valseq.getAlignmentSequenceAnnotationCount() > 0)
1486               {
1487                 AlignmentSequenceAnnotation[] vasannot = valseq
1488                         .getAlignmentSequenceAnnotation();
1489                 for (int a = 0; a < vasannot.length; a++)
1490                 {
1491                   jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO:
1492                   // 1:many
1493                   // jalview
1494                   // alignment
1495                   // sequence
1496                   // annotations
1497                   if (asa == null)
1498                   {
1499                     int se[] = getBounds(vasannot[a]);
1500                     asa = getjAlignmentAnnotation(jal, vasannot[a]);
1501                     asa.setSequenceRef(alseq);
1502                     asa.createSequenceMapping(alseq, se[0], false); // TODO:
1503                     // verify
1504                     // that
1505                     // positions
1506                     // in
1507                     // alseqAnnotation
1508                     // correspond
1509                     // to
1510                     // ungapped
1511                     // residue
1512                     // positions.
1513                     alseq.addAlignmentAnnotation(asa);
1514                     bindjvvobj(asa, vasannot[a]);
1515                     newasAnnots.add(asa);
1516                   }
1517                   else
1518                   {
1519                     // update existing annotation - can do this in place
1520                     if (vasannot[a].getModifiable() == null) // TODO: USE
1521                     // VAMSAS LIBRARY
1522                     // OBJECT LOCK
1523                     // METHODS)
1524                     {
1525                       Cache.log
1526                               .info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1527                       // TODO: should at least replace with new one - otherwise
1528                       // things will break
1529                       // basically do this:
1530                       // int se[] = getBounds(vasannot[a]);
1531                       // asa.update(getjAlignmentAnnotation(jal, vasannot[a]));
1532                       // // update from another annotation object in place.
1533                       // asa.createSequenceMapping(alseq, se[0], false);
1534
1535                     }
1536                   }
1537                 }
1538               }
1539             }
1540             if (jal == null)
1541             {
1542               SequenceI[] seqs = new SequenceI[dsseqs.size()];
1543               for (i = 0, iSize = dsseqs.size(); i < iSize; i++)
1544               {
1545                 seqs[i] = (SequenceI) dsseqs.elementAt(i);
1546                 dsseqs.setElementAt(null, i);
1547               }
1548               jal = new jalview.datamodel.Alignment(seqs);
1549               Cache.log.debug("New vamsas alignment imported into jalview "
1550                       + alignment.getVorbaId().getId());
1551               jal.setDataset(jdataset);
1552             }
1553             if (newasAnnots != null && newasAnnots.size() > 0)
1554             {
1555               // Add the new sequence annotations in to the alignment.
1556               for (int an = 0, anSize = newasAnnots.size(); an < anSize; an++)
1557               {
1558                 jal.addAnnotation((AlignmentAnnotation) newasAnnots
1559                         .elementAt(an));
1560                 // TODO: check if anything has to be done - like calling
1561                 // adjustForAlignment or something.
1562                 newasAnnots.setElementAt(null, an);
1563               }
1564               newasAnnots = null;
1565             }
1566             // //////////////////////////////////////////
1567             // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1568             // ////////////////////////////////////
1569             if (alignment.getAlignmentAnnotationCount() > 0)
1570             {
1571               uk.ac.vamsas.objects.core.AlignmentAnnotation[] an = alignment
1572                       .getAlignmentAnnotation();
1573
1574               for (int j = 0; j < an.length; j++)
1575               {
1576                 jalview.datamodel.AlignmentAnnotation jan = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);
1577                 if (jan != null)
1578                 {
1579                   // update or stay the same.
1580                   // TODO: should at least replace with a new one - otherwise
1581                   // things will break
1582                   // basically do this:
1583                   // jan.update(getjAlignmentAnnotation(jal, an[a])); // update
1584                   // from another annotation object in place.
1585
1586                   Cache.log
1587                           .debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1588                   if (an[j].getModifiable() == null) // TODO: USE VAMSAS
1589                   // LIBRARY OBJECT LOCK
1590                   // METHODS)
1591                   {
1592                     // TODO: user defined annotation is totally mutable... - so
1593                     // load it up or throw away if locally edited.
1594                     Cache.log
1595                             .info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1596                   }
1597                   // TODO: compare annotation element rows
1598                   // TODO: compare props.
1599                 }
1600                 else
1601                 {
1602                   jan = getjAlignmentAnnotation(jal, an[j]);
1603                   jal.addAnnotation(jan);
1604                   bindjvvobj(jan, an[j]);
1605                 }
1606               }
1607             }
1608             AlignFrame alignFrame;
1609             if (av == null)
1610             {
1611               Cache.log.debug("New alignframe for alignment "
1612                       + alignment.getVorbaId());
1613               // ///////////////////////////////
1614               // construct alignment view
1615               alignFrame = new AlignFrame(jal, AlignFrame.DEFAULT_WIDTH,
1616                       AlignFrame.DEFAULT_HEIGHT);
1617               av = alignFrame.getViewport();
1618               String title = alignment.getProvenance().getEntry(
1619                       alignment.getProvenance().getEntryCount() - 1)
1620                       .getAction();
1621               if (alignment.getPropertyCount() > 0)
1622               {
1623                 for (int p = 0, pe = alignment.getPropertyCount(); p < pe; p++)
1624                 {
1625                   if (alignment.getProperty(p).getName().equals("title"))
1626                   {
1627                     title = alignment.getProperty(p).getContent();
1628                   }
1629                 }
1630               }
1631               // TODO: automatically create meaningful title for a vamsas
1632               // alignment using its provenance.
1633               if (Cache.log.isDebugEnabled())
1634               {
1635                 title = title + "(" + alignment.getVorbaId() + ")";
1636
1637               }
1638               jalview.gui.Desktop.addInternalFrame(alignFrame, title,
1639                       AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1640               bindjvvobj(av.getSequenceSetId(), alignment);
1641             }
1642             else
1643             {
1644               // find the alignFrame for jal.
1645               // TODO: fix this so we retrieve the alignFrame handing av
1646               // *directly*
1647               alignFrame = getAlignFrameFor(av);
1648               if (refreshal)
1649               {
1650                 av.alignmentChanged(alignFrame.alignPanel);
1651               }
1652             }
1653             // LOAD TREES
1654             // /////////////////////////////////////
1655             if (alignment.getTreeCount() > 0)
1656             {
1657
1658               for (int t = 0; t < alignment.getTreeCount(); t++)
1659               {
1660                 jalview.io.vamsas.Tree vstree = new jalview.io.vamsas.Tree(
1661                         this, alignFrame, alignment.getTree(t));
1662                 TreePanel tp = null;
1663                 if (vstree.isValidTree())
1664                 {
1665                   tp = alignFrame.ShowNewickTree(vstree.getNewickTree(),
1666                           vstree.getTitle(), vstree.getInputData(), 600,
1667                           500, t * 20 + 50, t * 20 + 50);
1668
1669                 }
1670                 if (tp != null)
1671                 {
1672                   bindjvvobj(tp, alignment.getTree(t));
1673                   try
1674                   {
1675                     vstree.UpdateSequenceTreeMap(tp);
1676                   } catch (RuntimeException e)
1677                   {
1678                     Cache.log.warn("update of labels failed.", e);
1679                   }
1680                 }
1681                 else
1682                 {
1683                   Cache.log.warn("Cannot create tree for tree " + t
1684                           + " in document ("
1685                           + alignment.getTree(t).getVorbaId());
1686                 }
1687
1688               }
1689             }
1690           }
1691         }
1692       }
1693       // we do sequenceMappings last because they span all datasets in a vamsas
1694       // root
1695       for (int _ds = 0, _nds = root.getDataSetCount(); _ds < _nds; _ds++)
1696       {
1697         DataSet dataset = root.getDataSet(_ds);
1698         if (dataset.getSequenceMappingCount() > 0)
1699         {
1700           for (int sm = 0, smCount = dataset.getSequenceMappingCount(); sm < smCount; sm++)
1701           {
1702             Rangetype seqmap = new jalview.io.vamsas.Sequencemapping(this,
1703                     dataset.getSequenceMapping(sm));
1704           }
1705         }
1706       }
1707     }
1708   }
1709
1710   public AlignViewport findViewport(Alignment alignment)
1711   {
1712     AlignViewport av = null;
1713     AlignViewport[] avs = findViewportForSequenceSetId((String) getvObj2jv(alignment));
1714     if (avs != null)
1715     {
1716       av = avs[0];
1717     }
1718     return av;
1719   }
1720
1721   private AlignViewport[] findViewportForSequenceSetId(String sequenceSetId)
1722   {
1723     Vector viewp = new Vector();
1724     if (Desktop.desktop != null)
1725     {
1726       javax.swing.JInternalFrame[] frames = Desktop.instance.getAllFrames();
1727
1728       for (int t = 0; t < frames.length; t++)
1729       {
1730         if (frames[t] instanceof AlignFrame)
1731         {
1732           if (((AlignFrame) frames[t]).getViewport().getSequenceSetId()
1733                   .equals(sequenceSetId))
1734           {
1735             viewp.addElement(((AlignFrame) frames[t]).getViewport());
1736           }
1737         }
1738       }
1739       if (viewp.size() > 0)
1740       {
1741         AlignViewport[] vp = new AlignViewport[viewp.size()];
1742         viewp.copyInto(vp);
1743         return vp;
1744       }
1745     }
1746     return null;
1747   }
1748
1749   // bitfields - should be a template in j1.5
1750   private static int HASSECSTR = 0;
1751
1752   private static int HASVALS = 1;
1753
1754   private static int HASHPHOB = 2;
1755
1756   private static int HASDC = 3;
1757
1758   private static int HASDESCSTR = 4;
1759
1760   private static int HASTWOSTATE = 5; // not used yet.
1761
1762   /**
1763    * parses the AnnotationElements - if they exist - into
1764    * jalview.datamodel.Annotation[] rows Two annotation rows are made if there
1765    * are distinct annotation for both at 'pos' and 'after pos' at any particular
1766    * site.
1767    * 
1768    * @param annotation
1769    * @return { boolean[static int constants ], int[ae.length] - map to annotated
1770    *         object frame, jalview.datamodel.Annotation[],
1771    *         jalview.datamodel.Annotation[] (after)}
1772    */
1773   private Object[] parseRangeAnnotation(
1774           uk.ac.vamsas.objects.core.RangeAnnotation annotation)
1775   {
1776     // set these attributes by looking in the annotation to decide what kind of
1777     // alignment annotation rows will be made
1778     // TODO: potentially we might make several annotation rows from one vamsas
1779     // alignment annotation. the jv2Vobj binding mechanism
1780     // may not quite cope with this (without binding an array of annotations to
1781     // a vamsas alignment annotation)
1782     // summary flags saying what we found over the set of annotation rows.
1783     boolean[] AeContent = new boolean[]
1784     { false, false, false, false, false };
1785     int[] rangeMap = getMapping(annotation);
1786     jalview.datamodel.Annotation[][] anot = new jalview.datamodel.Annotation[][]
1787     { new jalview.datamodel.Annotation[rangeMap.length],
1788         new jalview.datamodel.Annotation[rangeMap.length] };
1789     boolean mergeable = true; // false if 'after positions cant be placed on
1790     // same annotation row as positions.
1791
1792     if (annotation.getAnnotationElementCount() > 0)
1793     {
1794       AnnotationElement ae[] = annotation.getAnnotationElement();
1795       for (int aa = 0; aa < ae.length; aa++)
1796       {
1797         int pos = (int) ae[aa].getPosition() - 1; // pos counts from 1 to
1798         // (|seg.start-seg.end|+1)
1799         if (pos >= 0 && pos < rangeMap.length)
1800         {
1801           int row = ae[aa].getAfter() ? 1 : 0;
1802           if (anot[row][pos] != null)
1803           {
1804             // only time this should happen is if the After flag is set.
1805             Cache.log.debug("Ignoring duplicate annotation site at " + pos);
1806             continue;
1807           }
1808           if (anot[1 - row][pos] != null)
1809           {
1810             mergeable = false;
1811           }
1812           String desc = "";
1813           if (ae[aa].getDescription() != null)
1814           {
1815             desc = ae[aa].getDescription();
1816             if (desc.length() > 0)
1817             {
1818               // have imported valid description string
1819               AeContent[HASDESCSTR] = true;
1820             }
1821           }
1822           String dc = null; // ae[aa].getDisplayCharacter()==null ? "dc" :
1823           // ae[aa].getDisplayCharacter();
1824           String ss = null; // ae[aa].getSecondaryStructure()==null ? "ss" :
1825           // ae[aa].getSecondaryStructure();
1826           java.awt.Color colour = null;
1827           if (ae[aa].getGlyphCount() > 0)
1828           {
1829             Glyph[] glyphs = ae[aa].getGlyph();
1830             for (int g = 0; g < glyphs.length; g++)
1831             {
1832               if (glyphs[g]
1833                       .getDict()
1834                       .equals(
1835                               uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE))
1836               {
1837                 ss = glyphs[g].getContent();
1838                 AeContent[HASSECSTR] = true;
1839               }
1840               else if (glyphs[g]
1841                       .getDict()
1842                       .equals(
1843                               uk.ac.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO))
1844               {
1845                 Cache.log.debug("ignoring hydrophobicity glyph marker.");
1846                 AeContent[HASHPHOB] = true;
1847                 char c = (dc = glyphs[g].getContent()).charAt(0);
1848                 // dc may get overwritten - but we still set the colour.
1849                 colour = new java.awt.Color(c == '+' ? 255 : 0,
1850                         c == '.' ? 255 : 0, c == '-' ? 255 : 0);
1851
1852               }
1853               else if (glyphs[g].getDict().equals(
1854                       uk.ac.vamsas.objects.utils.GlyphDictionary.DEFAULT))
1855               {
1856                 dc = glyphs[g].getContent();
1857                 AeContent[HASDC] = true;
1858               }
1859               else
1860               {
1861                 Cache.log
1862                         .debug("IMPLEMENTATION TODO: Ignoring unknown glyph type "
1863                                 + glyphs[g].getDict());
1864               }
1865             }
1866           }
1867           float val = 0;
1868           if (ae[aa].getValueCount() > 0)
1869           {
1870             AeContent[HASVALS] = true;
1871             if (ae[aa].getValueCount() > 1)
1872             {
1873               Cache.log.warn("ignoring additional "
1874                       + (ae[aa].getValueCount() - 1)
1875                       + "values in annotation element.");
1876             }
1877             val = ae[aa].getValue(0);
1878           }
1879           if (colour == null)
1880           {
1881             anot[row][pos] = new jalview.datamodel.Annotation(
1882                     (dc != null) ? dc : "", desc, (ss != null) ? ss
1883                             .charAt(0) : ' ', val);
1884           }
1885           else
1886           {
1887             anot[row][pos] = new jalview.datamodel.Annotation(
1888                     (dc != null) ? dc : "", desc, (ss != null) ? ss
1889                             .charAt(0) : ' ', val, colour);
1890           }
1891         }
1892         else
1893         {
1894           Cache.log.warn("Ignoring out of bound annotation element " + aa
1895                   + " in " + annotation.getVorbaId().getId());
1896         }
1897       }
1898       // decide on how many annotation rows are needed.
1899       if (mergeable)
1900       {
1901         for (int i = 0; i < anot[0].length; i++)
1902         {
1903           if (anot[1][i] != null)
1904           {
1905             anot[0][i] = anot[1][i];
1906             anot[0][i].description = anot[0][i].description + " (after)";
1907             AeContent[HASDESCSTR] = true; // we have valid description string
1908             // data
1909             anot[1][i] = null;
1910           }
1911         }
1912         anot[1] = null;
1913       }
1914       else
1915       {
1916         for (int i = 0; i < anot[0].length; i++)
1917         {
1918           anot[1][i].description = anot[1][i].description + " (after)";
1919         }
1920       }
1921       return new Object[]
1922       { AeContent, rangeMap, anot[0], anot[1] };
1923     }
1924     else
1925     {
1926       // no annotations to parse. Just return an empty annotationElement[]
1927       // array.
1928       return new Object[]
1929       { AeContent, rangeMap, anot[0], anot[1] };
1930     }
1931     // return null;
1932   }
1933
1934   /**
1935    * @param jal
1936    *                the jalview alignment to which the annotation will be
1937    *                attached (ideally - freshly updated from corresponding
1938    *                vamsas alignment)
1939    * @param annotation
1940    * @return unbound jalview alignment annotation object.
1941    */
1942   private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(
1943           jalview.datamodel.AlignmentI jal,
1944           uk.ac.vamsas.objects.core.RangeAnnotation annotation)
1945   {
1946     if (annotation == null)
1947     {
1948       return null;
1949     }
1950     // boolean
1951     // hasSequenceRef=annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation.class);
1952     // boolean hasProvenance=hasSequenceRef ||
1953     // (annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class));
1954     /*
1955      * int se[] = getBounds(annotation); if (se==null) se=new int[]
1956      * {0,jal.getWidth()-1};
1957      */
1958     Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
1959     String a_label = annotation.getLabel();
1960     String a_descr = annotation.getDescription();
1961     GraphLine gl = null;
1962     int type = 0;
1963     boolean interp = true; // cleared if annotation is DISCRETE
1964     // set type and other attributes from properties
1965     if (annotation.getPropertyCount() > 0)
1966     {
1967       // look for special jalview properties
1968       uk.ac.vamsas.objects.core.Property[] props = annotation.getProperty();
1969       for (int p = 0; p < props.length; p++)
1970       {
1971         if (props[p].getName().equalsIgnoreCase(DISCRETE_ANNOTATION))
1972         {
1973           type = AlignmentAnnotation.BAR_GRAPH;
1974           interp = false;
1975         }
1976         else if (props[p].getName().equalsIgnoreCase(CONTINUOUS_ANNOTATION))
1977         {
1978           type = AlignmentAnnotation.LINE_GRAPH;
1979         }
1980         else if (props[p].getName().equalsIgnoreCase(THRESHOLD))
1981         {
1982           Float val = null;
1983           try
1984           {
1985             val = new Float(props[p].getContent());
1986           } catch (Exception e)
1987           {
1988             Cache.log.warn("Failed to parse threshold property");
1989           }
1990           if (val != null)
1991             if (gl == null)
1992             {
1993               gl = new GraphLine(val.floatValue(), "", java.awt.Color.black);
1994             }
1995             else
1996             {
1997               gl.value = val.floatValue();
1998             }
1999         }
2000         else if (props[p].getName().equalsIgnoreCase(THRESHOLD + "Name"))
2001         {
2002           if (gl == null)
2003             gl = new GraphLine(0, "", java.awt.Color.black);
2004           gl.label = props[p].getContent();
2005         }
2006       }
2007     }
2008     jalview.datamodel.AlignmentAnnotation jan = null;
2009     if (a_label == null || a_label.length() == 0)
2010     {
2011       a_label = annotation.getType();
2012       if (a_label.length() == 0)
2013       {
2014         a_label = "Unamed annotation";
2015       }
2016     }
2017     if (a_descr == null || a_descr.length() == 0)
2018     {
2019       a_descr = "Annotation of type '" + annotation.getType() + "'";
2020     }
2021     if (parsedRangeAnnotation == null)
2022     {
2023       Cache.log
2024               .debug("Inserting empty annotation row elements for a whole-alignment annotation.");
2025     }
2026     else
2027     {
2028       if (parsedRangeAnnotation[3] != null)
2029       {
2030         Cache.log.warn("Ignoring 'After' annotation row in "
2031                 + annotation.getVorbaId());
2032       }
2033       jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
2034       boolean[] has = (boolean[]) parsedRangeAnnotation[0];
2035       // VAMSAS: getGraph is only on derived annotation for alignments - in this
2036       // way its 'odd' - there is already an existing TODO about removing this
2037       // flag as being redundant
2038       /*
2039        * if
2040        * ((annotation.getClass().equals(uk.ac.vamsas.objects.core.AlignmentAnnotation.class) &&
2041        * ((uk.ac.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph()) ||
2042        * (hasSequenceRef=true &&
2043        * ((uk.ac.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {
2044        */
2045       if (has[HASVALS])
2046       {
2047         if (type == 0)
2048         {
2049           type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH; // default
2050                                                                   // type of
2051                                                                   // value
2052                                                                   // annotation
2053           if (has[HASHPHOB])
2054           {
2055             // no hints - so we ensure HPHOB display is like this.
2056             type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
2057           }
2058         }
2059         // make bounds and automatic description strings for jalview user's
2060         // benefit (these shouldn't be written back to vamsas document)
2061         boolean first = true;
2062         float min = 0, max = 1;
2063         int lastval = 0;
2064         for (int i = 0; i < arow.length; i++)
2065         {
2066           if (arow[i] != null)
2067           {
2068             if (i - lastval > 1 && interp)
2069             {
2070               // do some interpolation *between* points
2071               if (arow[lastval] != null)
2072               {
2073                 float interval = arow[i].value - arow[lastval].value;
2074                 interval /= i - lastval;
2075                 float base = arow[lastval].value;
2076                 for (int ip = lastval + 1, np = 0; ip < i; np++, ip++)
2077                 {
2078                   arow[ip] = new jalview.datamodel.Annotation("", "", ' ',
2079                           interval * np + base);
2080                   // NB - Interpolated points don't get a tooltip and
2081                   // description.
2082                 }
2083               }
2084             }
2085             lastval = i;
2086             // check range - shouldn't we have a min and max property in the
2087             // annotation object ?
2088             if (first)
2089             {
2090               min = max = arow[i].value;
2091               first = false;
2092             }
2093             else
2094             {
2095               if (arow[i].value < min)
2096               {
2097                 min = arow[i].value;
2098               }
2099               else if (arow[i].value > max)
2100               {
2101                 max = arow[i].value;
2102               }
2103             }
2104             // make tooltip and display char value
2105             if (!has[HASDESCSTR])
2106             {
2107               arow[i].description = arow[i].value + "";
2108             }
2109             if (!has[HASDC])
2110             {
2111               if (!interp)
2112               {
2113                 if (arow[i].description != null
2114                         && arow[i].description.length() < 3)
2115                 {
2116                   // copy over the description as the display char.
2117                   arow[i].displayCharacter = new String(arow[i].description);
2118                 }
2119               }
2120               else
2121               {
2122                 // mark the position as a point used for the interpolation.
2123                 arow[i].displayCharacter = arow[i].value + "";
2124               }
2125             }
2126           }
2127         }
2128         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2129                 arow, min, max, type);
2130       }
2131       else
2132       {
2133         if (annotation.getAnnotationElementCount() == 0)
2134         {
2135           // empty annotation array
2136           // TODO: alignment 'features' compare rangeType spec to alignment
2137           // width - if it is not complete, then mark regions on the annotation
2138           // row.
2139         }
2140         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr,
2141                 arow);
2142         jan.setThreshold(null);
2143       }
2144       if (annotation.getLinkCount() > 0)
2145       {
2146         Cache.log.warn("Ignoring " + annotation.getLinkCount()
2147                 + "links added to AlignmentAnnotation.");
2148       }
2149       if (annotation.getModifiable() == null
2150               || annotation.getModifiable().length() == 0) // TODO: USE VAMSAS
2151                                                             // LIBRARY OBJECT
2152       // LOCK METHODS)
2153       {
2154         jan.editable = true;
2155       }
2156       try
2157       {
2158         if (annotation.getGroup() != null
2159                 && annotation.getGroup().length() > 0)
2160         {
2161           jan.graphGroup = Integer.parseInt(annotation.getGroup()); // TODO:
2162                                                                     // group
2163                                                                     // similarly
2164                                                                     // named
2165                                                                     // annotation
2166                                                                     // together
2167                                                                     // ?
2168         }
2169       } catch (Exception e)
2170       {
2171         Cache.log
2172                 .info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
2173       }
2174       return jan;
2175
2176     }
2177
2178     return null;
2179   }
2180
2181   private SequenceFeature getJalviewSeqFeature(RangeAnnotation dseta)
2182   {
2183     int[] se = getBounds(dseta);
2184     SequenceFeature sf = new jalview.datamodel.SequenceFeature(dseta
2185             .getType(), dseta.getDescription(), dseta.getStatus(), se[0],
2186             se[1], dseta.getGroup());
2187     if (dseta.getLinkCount() > 0)
2188     {
2189       Link[] links = dseta.getLink();
2190       for (int i = 0; i < links.length; i++)
2191       {
2192         sf.addLink(links[i].getContent() + "|" + links[i].getHref());
2193       }
2194     }
2195     return sf;
2196   }
2197
2198   /**
2199    * get real bounds of a RangeType's specification. start and end are an
2200    * inclusive range within which all segments and positions lie. TODO: refactor
2201    * to vamsas utils
2202    * 
2203    * @param dseta
2204    * @return int[] { start, end}
2205    */
2206   private int[] getBounds(RangeType dseta)
2207   {
2208     if (dseta != null)
2209     {
2210       int[] se = null;
2211       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2212       {
2213         throw new Error(
2214                 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2215       }
2216       if (dseta.getSegCount() > 0)
2217       {
2218         se = getSegRange(dseta.getSeg(0), true);
2219         for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
2220         {
2221           int nse[] = getSegRange(dseta.getSeg(s), true);
2222           if (se[0] > nse[0])
2223           {
2224             se[0] = nse[0];
2225           }
2226           if (se[1] < nse[1])
2227           {
2228             se[1] = nse[1];
2229           }
2230         }
2231       }
2232       if (dseta.getPosCount() > 0)
2233       {
2234         // could do a polarity for pos range too. and pass back indication of
2235         // discontinuities.
2236         int pos = dseta.getPos(0).getI();
2237         se = new int[]
2238         { pos, pos };
2239         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2240         {
2241           pos = dseta.getPos(p).getI();
2242           if (se[0] > pos)
2243           {
2244             se[0] = pos;
2245           }
2246           if (se[1] < pos)
2247           {
2248             se[1] = pos;
2249           }
2250         }
2251       }
2252       return se;
2253     }
2254     return null;
2255   }
2256
2257   /**
2258    * map from a rangeType's internal frame to the referenced object's coordinate
2259    * frame.
2260    * 
2261    * @param dseta
2262    * @return int [] { ref(pos)...} for all pos in rangeType's frame.
2263    */
2264   private int[] getMapping(RangeType dseta)
2265   {
2266     Vector posList = new Vector();
2267     if (dseta != null)
2268     {
2269       int[] se = null;
2270       if (dseta.getSegCount() > 0 && dseta.getPosCount() > 0)
2271       {
2272         throw new Error(
2273                 "Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
2274       }
2275       if (dseta.getSegCount() > 0)
2276       {
2277         for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
2278         {
2279           se = getSegRange(dseta.getSeg(s), false);
2280           int se_end = se[1 - se[2]] + (se[2] == 0 ? 1 : -1);
2281           for (int p = se[se[2]]; p != se_end; p += se[2] == 0 ? 1 : -1)
2282           {
2283             posList.add(new Integer(p));
2284           }
2285         }
2286       }
2287       else if (dseta.getPosCount() > 0)
2288       {
2289         int pos = dseta.getPos(0).getI();
2290
2291         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
2292         {
2293           pos = dseta.getPos(p).getI();
2294           posList.add(new Integer(pos));
2295         }
2296       }
2297     }
2298     if (posList != null && posList.size() > 0)
2299     {
2300       int[] range = new int[posList.size()];
2301       for (int i = 0; i < range.length; i++)
2302       {
2303         range[i] = ((Integer) posList.elementAt(i)).intValue();
2304       }
2305       posList.clear();
2306       return range;
2307     }
2308     return null;
2309   }
2310
2311   /**
2312    * 
2313    * @param maprange
2314    *                where the from range is the local mapped range, and the to
2315    *                range is the 'mapped' range in the MapRangeType
2316    * @param default
2317    *                unit for local
2318    * @param default
2319    *                unit for mapped
2320    * @return MapList
2321    */
2322   private jalview.util.MapList parsemapType(MapType maprange, int localu,
2323           int mappedu)
2324   {
2325     jalview.util.MapList ml = null;
2326     int[] localRange = getMapping(maprange.getLocal());
2327     int[] mappedRange = getMapping(maprange.getMapped());
2328     long lu = maprange.getLocal().hasUnit() ? maprange.getLocal().getUnit()
2329             : localu;
2330     long mu = maprange.getMapped().hasUnit() ? maprange.getMapped()
2331             .getUnit() : mappedu;
2332     ml = new jalview.util.MapList(localRange, mappedRange, (int) lu,
2333             (int) mu);
2334     return ml;
2335   }
2336
2337   /**
2338    * initialise a range type object from a set of start/end inclusive intervals
2339    * 
2340    * @param mrt
2341    * @param range
2342    */
2343   private void initRangeType(RangeType mrt, int[] range)
2344   {
2345     for (int i = 0; i < range.length; i += 2)
2346     {
2347       Seg vSeg = new Seg();
2348       vSeg.setStart(range[i]);
2349       vSeg.setEnd(range[i + 1]);
2350       mrt.addSeg(vSeg);
2351     }
2352   }
2353
2354   /**
2355    * initialise a MapType object from a MapList object.
2356    * 
2357    * @param maprange
2358    * @param ml
2359    * @param setUnits
2360    */
2361   private void initMapType(MapType maprange, jalview.util.MapList ml,
2362           boolean setUnits)
2363   {
2364     maprange.setLocal(new Local());
2365     maprange.setMapped(new Mapped());
2366     initRangeType(maprange.getLocal(), ml.getFromRanges());
2367     initRangeType(maprange.getMapped(), ml.getToRanges());
2368     if (setUnits)
2369     {
2370       maprange.getLocal().setUnit(ml.getFromRatio());
2371       maprange.getLocal().setUnit(ml.getToRatio());
2372     }
2373   }
2374
2375   /*
2376    * not needed now. Provenance getVamsasProvenance(jalview.datamodel.Provenance
2377    * jprov) { jalview.datamodel.ProvenanceEntry[] entries = null; // TODO: fix
2378    * App and Action here. Provenance prov = new Provenance();
2379    * org.exolab.castor.types.Date date = new org.exolab.castor.types.Date( new
2380    * java.util.Date()); Entry provEntry;
2381    * 
2382    * if (jprov != null) { entries = jprov.getEntries(); for (int i = 0; i <
2383    * entries.length; i++) { provEntry = new Entry(); try { date = new
2384    * org.exolab.castor.types.Date(entries[i].getDate()); } catch (Exception ex) {
2385    * ex.printStackTrace();
2386    * 
2387    * date = new org.exolab.castor.types.Date(entries[i].getDate()); }
2388    * provEntry.setDate(date); provEntry.setUser(entries[i].getUser());
2389    * provEntry.setAction(entries[i].getAction()); prov.addEntry(provEntry); } }
2390    * else { provEntry = new Entry(); provEntry.setDate(date);
2391    * provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
2392    * provEntry.setApp("JVAPP"); // TODO: ext string provEntry.setAction(action);
2393    * prov.addEntry(provEntry); }
2394    * 
2395    * return prov; }
2396    */
2397   jalview.datamodel.Provenance getJalviewProvenance(Provenance prov)
2398   {
2399     // TODO: fix App and Action entries and check use of provenance in jalview.
2400     jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
2401     for (int i = 0; i < prov.getEntryCount(); i++)
2402     {
2403       jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i)
2404               .getAction(), prov.getEntry(i).getDate(), prov.getEntry(i)
2405               .getId());
2406     }
2407
2408     return jprov;
2409   }
2410
2411   /**
2412    * 
2413    * @return default initial provenance list for a Jalview created vamsas
2414    *         object.
2415    */
2416   Provenance dummyProvenance()
2417   {
2418     return dummyProvenance(null);
2419   }
2420
2421   Entry dummyPEntry(String action)
2422   {
2423     Entry entry = new Entry();
2424     entry.setApp(this.provEntry.getApp());
2425     if (action != null)
2426     {
2427       entry.setAction(action);
2428     }
2429     else
2430     {
2431       entry.setAction("created.");
2432     }
2433     entry.setDate(new java.util.Date());
2434     entry.setUser(this.provEntry.getUser());
2435     return entry;
2436   }
2437
2438   Provenance dummyProvenance(String action)
2439   {
2440     Provenance prov = new Provenance();
2441     prov.addEntry(dummyPEntry(action));
2442     return prov;
2443   }
2444
2445   Entry addProvenance(Provenance p, String action)
2446   {
2447     Entry dentry = dummyPEntry(action);
2448     p.addEntry(dentry);
2449     return dentry;
2450   }
2451
2452   public Entry getProvEntry()
2453   {
2454     return provEntry;
2455   }
2456
2457   public IClientDocument getClientDocument()
2458   {
2459     return cdoc;
2460   }
2461
2462   public IdentityHashMap getJvObjectBinding()
2463   {
2464     return jv2vobj;
2465   }
2466
2467   public Hashtable getVamsasObjectBinding()
2468   {
2469     return vobj2jv;
2470   }
2471
2472   public void storeSequenceMappings(AlignViewport viewport, String title)
2473           throws Exception
2474   {
2475     AlignViewport av = viewport;
2476     try
2477     {
2478       jalview.datamodel.AlignmentI jal = av.getAlignment();
2479       // /////////////////////////////////////////
2480       // SAVE THE DATASET
2481       DataSet dataset = null;
2482       if (jal.getDataset() == null)
2483       {
2484         Cache.log.warn("Creating new dataset for an alignment.");
2485         jal.setDataset(null);
2486       }
2487       dataset = (DataSet) getjv2vObj(jal.getDataset());
2488       // Store any sequence mappings.
2489       if (av.getAlignment().getCodonFrames() != null
2490               && av.getAlignment().getCodonFrames().length > 0)
2491       {
2492         jalview.datamodel.AlignedCodonFrame[] cframes = av.getAlignment()
2493                 .getCodonFrames();
2494         for (int cf = 0; cf < cframes.length; cf++)
2495         {
2496           if (cframes[cf].getdnaSeqs().length > 0)
2497           {
2498             jalview.datamodel.SequenceI[] dmps = cframes[cf].getdnaSeqs();
2499             jalview.datamodel.Mapping[] mps = cframes[cf].getProtMappings();
2500             for (int smp = 0; smp < mps.length; smp++)
2501             {
2502               uk.ac.vamsas.objects.core.SequenceType mfrom = (SequenceType) getjv2vObj(dmps[smp]);
2503               if (mfrom != null)
2504               {
2505                 new jalview.io.vamsas.Sequencemapping(this, mps[smp],
2506                         mfrom, dataset);
2507               }
2508               else
2509               {
2510                 Cache.log
2511                         .warn("NO Vamsas Binding for local sequence! NOT CREATING MAPPING FOR "
2512                                 + dmps[smp].getDisplayId(true)
2513                                 + " to "
2514                                 + mps[smp].getTo().getName());
2515               }
2516             }
2517           }
2518         }
2519       }
2520     } catch (Exception e)
2521     {
2522       throw new Exception("Couldn't store sequence mappings for " + title,
2523               e);
2524     }
2525   }
2526 }