JAL-2446 merged to spike branch
[jalview.git] / src / jalview / io / JSONFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21
22 package jalview.io;
23
24 import jalview.api.AlignExportSettingI;
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.api.ComplexAlignFile;
28 import jalview.api.FeatureRenderer;
29 import jalview.api.FeatureSettingsModelI;
30 import jalview.api.FeaturesDisplayedI;
31 import jalview.bin.BuildDetails;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.Annotation;
35 import jalview.datamodel.HiddenColumns;
36 import jalview.datamodel.HiddenSequences;
37 import jalview.datamodel.Sequence;
38 import jalview.datamodel.SequenceFeature;
39 import jalview.datamodel.SequenceGroup;
40 import jalview.datamodel.SequenceI;
41 import jalview.json.binding.biojson.v1.AlignmentAnnotationPojo;
42 import jalview.json.binding.biojson.v1.AlignmentPojo;
43 import jalview.json.binding.biojson.v1.AnnotationDisplaySettingPojo;
44 import jalview.json.binding.biojson.v1.AnnotationPojo;
45 import jalview.json.binding.biojson.v1.ColourSchemeMapper;
46 import jalview.json.binding.biojson.v1.SequenceFeaturesPojo;
47 import jalview.json.binding.biojson.v1.SequenceGrpPojo;
48 import jalview.json.binding.biojson.v1.SequencePojo;
49 import jalview.renderer.seqfeatures.FeatureColourFinder;
50 import jalview.schemes.ColourSchemeProperty;
51 import jalview.schemes.JalviewColourScheme;
52 import jalview.schemes.ResidueColourScheme;
53 import jalview.util.ColorUtils;
54 import jalview.util.Format;
55 import jalview.viewmodel.seqfeatures.FeaturesDisplayed;
56
57 import java.awt.Color;
58 import java.io.IOException;
59 import java.io.Reader;
60 import java.util.ArrayList;
61 import java.util.Hashtable;
62 import java.util.Iterator;
63 import java.util.List;
64 import java.util.Vector;
65
66 import org.json.simple.JSONArray;
67 import org.json.simple.JSONObject;
68 import org.json.simple.parser.JSONParser;
69
70 public class JSONFile extends AlignFile implements ComplexAlignFile
71 {
72   private static String version = new BuildDetails().getVersion();
73
74   private String webstartUrl = "http://www.jalview.org/services/launchApp";
75
76   private String application = "Jalview";
77
78   private String globalColourScheme;
79
80   private boolean showSeqFeatures;
81
82   private Hashtable<String, Sequence> seqMap;
83
84   private FeaturesDisplayedI displayedFeatures;
85
86   private FeatureRenderer fr;
87
88   private HiddenColumns hiddenColumns;
89
90   private List<String> hiddenSeqRefs;
91
92   private ArrayList<SequenceI> hiddenSequences;
93
94   private final static String TCOFFEE_SCORE = "TCoffeeScore";
95
96   public JSONFile()
97   {
98     super();
99   }
100
101   public JSONFile(FileParse source) throws IOException
102   {
103     super(source);
104   }
105
106   public JSONFile(String inFile, DataSourceType sourceType)
107           throws IOException
108   {
109     super(inFile, sourceType);
110   }
111
112   @Override
113   public void parse() throws IOException
114   {
115     parse(getReader());
116
117   }
118
119   @Override
120   public String print(SequenceI[] sqs, boolean jvsuffix)
121   {
122     String jsonOutput = null;
123     try
124     {
125       AlignmentPojo jsonAlignmentPojo = new AlignmentPojo();
126       AlignExportSettingI exportSettings = getExportSettings();
127
128       // if no export settings were supplied use the following with all values
129       // defaulting to true
130       if (exportSettings == null)
131       {
132         exportSettings = new AlignExportSettingI()
133         {
134           @Override
135           public boolean isExportHiddenSequences()
136           {
137             return true;
138           }
139
140           @Override
141           public boolean isExportHiddenColumns()
142           {
143             return true;
144           }
145
146           @Override
147           public boolean isExportGroups()
148           {
149             return true;
150           }
151
152           @Override
153           public boolean isExportFeatures()
154           {
155             return true;
156           }
157
158           @Override
159           public boolean isExportAnnotations()
160           {
161             return true;
162           }
163
164           @Override
165           public boolean isCancelled()
166           {
167             return false;
168           }
169         };
170       }
171
172       int count = 0;
173       for (SequenceI seq : sqs)
174       {
175         StringBuilder name = new StringBuilder();
176         name.append(seq.getName()).append("/").append(seq.getStart())
177                 .append("-").append(seq.getEnd());
178         SequencePojo jsonSeqPojo = new SequencePojo();
179         jsonSeqPojo.setId(String.valueOf(seq.hashCode()));
180         jsonSeqPojo.setOrder(++count);
181         jsonSeqPojo.setEnd(seq.getEnd());
182         jsonSeqPojo.setStart(seq.getStart());
183         jsonSeqPojo.setName(name.toString());
184         jsonSeqPojo.setSeq(seq.getSequenceAsString());
185         jsonAlignmentPojo.getSeqs().add(jsonSeqPojo);
186       }
187       jsonAlignmentPojo.setGlobalColorScheme(globalColourScheme);
188       jsonAlignmentPojo.getAppSettings().put("application", application);
189       jsonAlignmentPojo.getAppSettings().put("version", version);
190       jsonAlignmentPojo.getAppSettings().put("webStartUrl", webstartUrl);
191       jsonAlignmentPojo.getAppSettings().put("showSeqFeatures",
192               String.valueOf(showSeqFeatures));
193
194       String[] hiddenSections = getHiddenSections();
195       if (hiddenSections != null)
196       {
197         if (hiddenSections[0] != null
198                 && exportSettings.isExportHiddenColumns())
199         {
200           jsonAlignmentPojo.getAppSettings().put("hiddenCols",
201                   String.valueOf(hiddenSections[0]));
202         }
203         if (hiddenSections[1] != null
204                 && exportSettings.isExportHiddenSequences())
205         {
206           jsonAlignmentPojo.getAppSettings().put("hiddenSeqs",
207                   String.valueOf(hiddenSections[1]));
208         }
209       }
210
211       if (exportSettings.isExportAnnotations())
212       {
213         jsonAlignmentPojo
214                 .setAlignAnnotation(annotationToJsonPojo(annotations));
215       }
216       else
217       {
218         // These color schemes require annotation, disable them if annotations
219         // are not exported
220         if (globalColourScheme
221                 .equalsIgnoreCase(JalviewColourScheme.RNAHelices.toString())
222                 || globalColourScheme
223                         .equalsIgnoreCase(JalviewColourScheme.TCoffee
224                                 .toString()))
225         {
226           jsonAlignmentPojo.setGlobalColorScheme(ResidueColourScheme.NONE);
227         }
228       }
229
230       if (exportSettings.isExportFeatures())
231       {
232         jsonAlignmentPojo.setSeqFeatures(sequenceFeatureToJsonPojo(sqs));
233       }
234
235       if (exportSettings.isExportGroups() && seqGroups != null
236               && seqGroups.size() > 0)
237       {
238         for (SequenceGroup seqGrp : seqGroups)
239         {
240           SequenceGrpPojo seqGrpPojo = new SequenceGrpPojo();
241           seqGrpPojo.setGroupName(seqGrp.getName());
242           seqGrpPojo.setColourScheme(ColourSchemeProperty
243                   .getColourName(seqGrp.getColourScheme()));
244           seqGrpPojo.setColourText(seqGrp.getColourText());
245           seqGrpPojo.setDescription(seqGrp.getDescription());
246           seqGrpPojo.setDisplayBoxes(seqGrp.getDisplayBoxes());
247           seqGrpPojo.setDisplayText(seqGrp.getDisplayText());
248           seqGrpPojo.setEndRes(seqGrp.getEndRes());
249           seqGrpPojo.setStartRes(seqGrp.getStartRes());
250           seqGrpPojo.setShowNonconserved(seqGrp.getShowNonconserved());
251           for (SequenceI seq : seqGrp.getSequences())
252           {
253             seqGrpPojo.getSequenceRefs()
254                     .add(String.valueOf(seq.hashCode()));
255           }
256           jsonAlignmentPojo.getSeqGroups().add(seqGrpPojo);
257         }
258       }
259       org.json.JSONObject generatedJSon = new org.json.JSONObject(
260               jsonAlignmentPojo);
261       jsonOutput = generatedJSon.toString();
262       return jsonOutput.replaceAll("xstart", "xStart").replaceAll("xend",
263               "xEnd");
264     } catch (Exception e)
265     {
266       e.printStackTrace();
267     }
268     return jsonOutput;
269   }
270
271   public String[] getHiddenSections()
272   {
273     String[] hiddenSections = new String[2];
274     if (getViewport() == null)
275     {
276       return null;
277     }
278
279     // hidden column business
280     if (getViewport().hasHiddenColumns())
281     {
282       List<int[]> hiddenCols = getViewport().getAlignment()
283               .getHiddenColumns()
284               .getHiddenRegions();
285       StringBuilder hiddenColsBuilder = new StringBuilder();
286       for (int[] range : hiddenCols)
287       {
288         hiddenColsBuilder.append(";").append(range[0]).append("-")
289                 .append(range[1]);
290       }
291
292       hiddenColsBuilder.deleteCharAt(0);
293       hiddenSections[0] = hiddenColsBuilder.toString();
294     }
295
296     // hidden rows/seqs business
297     HiddenSequences hiddenSeqsObj = getViewport().getAlignment()
298             .getHiddenSequences();
299     if (hiddenSeqsObj == null || hiddenSeqsObj.hiddenSequences == null)
300     {
301       return hiddenSections;
302     }
303
304     SequenceI[] hiddenSeqs = hiddenSeqsObj.hiddenSequences;
305     StringBuilder hiddenSeqsBuilder = new StringBuilder();
306     for (SequenceI hiddenSeq : hiddenSeqs)
307     {
308       if (hiddenSeq != null)
309       {
310         hiddenSeqsBuilder.append(";").append(hiddenSeq.hashCode());
311       }
312     }
313     if (hiddenSeqsBuilder.length() > 0)
314     {
315       hiddenSeqsBuilder.deleteCharAt(0);
316     }
317     hiddenSections[1] = hiddenSeqsBuilder.toString();
318
319     return hiddenSections;
320   }
321
322   protected List<SequenceFeaturesPojo> sequenceFeatureToJsonPojo(
323           SequenceI[] sqs)
324   {
325     displayedFeatures = (fr == null) ? null : fr.getFeaturesDisplayed();
326     List<SequenceFeaturesPojo> sequenceFeaturesPojo = new ArrayList<SequenceFeaturesPojo>();
327     if (sqs == null)
328     {
329       return sequenceFeaturesPojo;
330     }
331
332     FeatureColourFinder finder = new FeatureColourFinder(fr);
333
334     String[] visibleFeatureTypes = displayedFeatures == null ? null
335             : displayedFeatures.getVisibleFeatures().toArray(
336                     new String[displayedFeatures.getVisibleFeatureCount()]);
337
338     for (SequenceI seq : sqs)
339     {
340       /*
341        * get all features currently visible (and any non-positional features)
342        */
343       List<SequenceFeature> seqFeatures = seq.getFeatures().getAllFeatures(
344               visibleFeatureTypes);
345       for (SequenceFeature sf : seqFeatures)
346       {
347         SequenceFeaturesPojo jsonFeature = new SequenceFeaturesPojo(
348                 String.valueOf(seq.hashCode()));
349
350         String featureColour = (fr == null) ? null : Format
351                 .getHexString(finder.findFeatureColour(Color.white, seq,
352                         seq.findIndex(sf.getBegin())));
353         int xStart = sf.getBegin() == 0 ? 0
354                 : seq.findIndex(sf.getBegin()) - 1;
355         int xEnd = sf.getEnd() == 0 ? 0 : seq.findIndex(sf.getEnd());
356         jsonFeature.setXstart(xStart);
357         jsonFeature.setXend(xEnd);
358         jsonFeature.setType(sf.getType());
359         jsonFeature.setDescription(sf.getDescription());
360         jsonFeature.setLinks(sf.links);
361         jsonFeature.setOtherDetails(sf.otherDetails);
362         jsonFeature.setScore(sf.getScore());
363         jsonFeature.setFillColor(featureColour);
364         jsonFeature.setFeatureGroup(sf.getFeatureGroup());
365         sequenceFeaturesPojo.add(jsonFeature);
366       }
367     }
368     return sequenceFeaturesPojo;
369   }
370
371   public static List<AlignmentAnnotationPojo> annotationToJsonPojo(
372           Vector<AlignmentAnnotation> annotations)
373   {
374     List<AlignmentAnnotationPojo> jsonAnnotations = new ArrayList<AlignmentAnnotationPojo>();
375     if (annotations == null)
376     {
377       return jsonAnnotations;
378     }
379     for (AlignmentAnnotation annot : annotations)
380     {
381       AlignmentAnnotationPojo alignAnnotPojo = new AlignmentAnnotationPojo();
382       alignAnnotPojo.setDescription(annot.description);
383       alignAnnotPojo.setLabel(annot.label);
384       if (!Double.isNaN(annot.score))
385       {
386         alignAnnotPojo.setScore(annot.score);
387       }
388       alignAnnotPojo.setCalcId(annot.getCalcId());
389       alignAnnotPojo.setGraphType(annot.graph);
390
391       AnnotationDisplaySettingPojo annotSetting = new AnnotationDisplaySettingPojo();
392       annotSetting.setBelowAlignment(annot.belowAlignment);
393       annotSetting.setCentreColLabels(annot.centreColLabels);
394       annotSetting.setScaleColLabel(annot.scaleColLabel);
395       annotSetting.setShowAllColLabels(annot.showAllColLabels);
396       annotSetting.setVisible(annot.visible);
397       annotSetting.setHasIcon(annot.hasIcons);
398       alignAnnotPojo.setAnnotationSettings(annotSetting);
399       SequenceI refSeq = annot.sequenceRef;
400       if (refSeq != null)
401       {
402         alignAnnotPojo.setSequenceRef(String.valueOf(refSeq.hashCode()));
403       }
404       for (Annotation annotation : annot.annotations)
405       {
406         AnnotationPojo annotationPojo = new AnnotationPojo();
407         if (annotation != null)
408         {
409           annotationPojo.setDescription(annotation.description);
410           annotationPojo.setValue(annotation.value);
411           annotationPojo
412                   .setSecondaryStructure(annotation.secondaryStructure);
413           String displayChar = annotation.displayCharacter == null ? null
414                   : annotation.displayCharacter;
415           // System.out.println("--------------------->[" + displayChar + "]");
416           annotationPojo.setDisplayCharacter(displayChar);
417           if (annotation.colour != null)
418           {
419             annotationPojo.setColour(jalview.util.Format
420                     .getHexString(annotation.colour));
421           }
422           alignAnnotPojo.getAnnotations().add(annotationPojo);
423         }
424         else
425         {
426           if (annot.getCalcId() != null
427                   && annot.getCalcId().equalsIgnoreCase(TCOFFEE_SCORE))
428           {
429             // do nothing
430           }
431           else
432           {
433             alignAnnotPojo.getAnnotations().add(annotationPojo);
434           }
435         }
436       }
437       jsonAnnotations.add(alignAnnotPojo);
438     }
439     return jsonAnnotations;
440   }
441
442   @SuppressWarnings("unchecked")
443   public JSONFile parse(Reader jsonAlignmentString)
444   {
445     try
446     {
447       JSONParser jsonParser = new JSONParser();
448       JSONObject alignmentJsonObj = (JSONObject) jsonParser
449               .parse(jsonAlignmentString);
450       JSONArray seqJsonArray = (JSONArray) alignmentJsonObj.get("seqs");
451       JSONArray alAnnotJsonArray = (JSONArray) alignmentJsonObj
452               .get("alignAnnotation");
453       JSONArray jsonSeqArray = (JSONArray) alignmentJsonObj
454               .get("seqFeatures");
455       JSONArray seqGrpJsonArray = (JSONArray) alignmentJsonObj
456               .get("seqGroups");
457       JSONObject jvSettingsJsonObj = (JSONObject) alignmentJsonObj
458               .get("appSettings");
459
460       if (jvSettingsJsonObj != null)
461       {
462         globalColourScheme = (String) jvSettingsJsonObj
463                 .get("globalColorScheme");
464         Boolean showFeatures = Boolean.valueOf(jvSettingsJsonObj.get(
465                 "showSeqFeatures").toString());
466         setShowSeqFeatures(showFeatures);
467         parseHiddenSeqRefsAsList(jvSettingsJsonObj);
468         parseHiddenCols(jvSettingsJsonObj);
469       }
470
471       hiddenSequences = new ArrayList<SequenceI>();
472       seqMap = new Hashtable<String, Sequence>();
473       for (Iterator<JSONObject> sequenceIter = seqJsonArray.iterator(); sequenceIter
474               .hasNext();)
475       {
476         JSONObject sequence = sequenceIter.next();
477         String sequcenceString = sequence.get("seq").toString();
478         String sequenceName = sequence.get("name").toString();
479         String seqUniqueId = sequence.get("id").toString();
480         int start = Integer.valueOf(sequence.get("start").toString());
481         int end = Integer.valueOf(sequence.get("end").toString());
482         Sequence seq = new Sequence(sequenceName, sequcenceString, start,
483                 end);
484         if (hiddenSeqRefs != null && hiddenSeqRefs.contains(seqUniqueId))
485         {
486           hiddenSequences.add(seq);
487         }
488         seqs.add(seq);
489         seqMap.put(seqUniqueId, seq);
490       }
491
492       parseFeatures(jsonSeqArray);
493
494       for (Iterator<JSONObject> seqGrpIter = seqGrpJsonArray.iterator(); seqGrpIter
495               .hasNext();)
496       {
497         JSONObject seqGrpObj = seqGrpIter.next();
498         String grpName = seqGrpObj.get("groupName").toString();
499         String colourScheme = seqGrpObj.get("colourScheme").toString();
500         String description = (seqGrpObj.get("description") == null) ? null
501                 : seqGrpObj.get("description").toString();
502         boolean displayBoxes = Boolean.valueOf(seqGrpObj
503                 .get("displayBoxes").toString());
504         boolean displayText = Boolean.valueOf(seqGrpObj.get("displayText")
505                 .toString());
506         boolean colourText = Boolean.valueOf(seqGrpObj.get("colourText")
507                 .toString());
508         boolean showNonconserved = Boolean.valueOf(seqGrpObj.get(
509                 "showNonconserved").toString());
510         int startRes = Integer
511                 .valueOf(seqGrpObj.get("startRes").toString());
512         int endRes = Integer.valueOf(seqGrpObj.get("endRes").toString());
513         JSONArray sequenceRefs = (JSONArray) seqGrpObj.get("sequenceRefs");
514
515         ArrayList<SequenceI> grpSeqs = new ArrayList<SequenceI>();
516         if (sequenceRefs.size() > 0)
517         {
518           Iterator<String> seqHashIter = sequenceRefs.iterator();
519           while (seqHashIter.hasNext())
520           {
521             String seqHash = seqHashIter.next();
522             Sequence sequence = seqMap.get(seqHash);
523             if (sequence != null)
524             {
525               grpSeqs.add(sequence);
526             }
527           }
528         }
529         SequenceGroup seqGrp = new SequenceGroup(grpSeqs, grpName, null,
530                 displayBoxes, displayText, colourText, startRes, endRes);
531         seqGrp.setColourScheme(ColourSchemeMapper.getJalviewColourScheme(
532                 colourScheme, seqGrp));
533         seqGrp.setShowNonconserved(showNonconserved);
534         seqGrp.setDescription(description);
535         this.seqGroups.add(seqGrp);
536
537       }
538
539       for (Iterator<JSONObject> alAnnotIter = alAnnotJsonArray.iterator(); alAnnotIter
540               .hasNext();)
541       {
542         JSONObject alAnnot = alAnnotIter.next();
543         JSONArray annotJsonArray = (JSONArray) alAnnot.get("annotations");
544         Annotation[] annotations = new Annotation[annotJsonArray.size()];
545         int count = 0;
546         for (Iterator<JSONObject> annotIter = annotJsonArray.iterator(); annotIter
547                 .hasNext();)
548         {
549           JSONObject annot = annotIter.next();
550           if (annot == null)
551           {
552             annotations[count] = null;
553           }
554           else
555           {
556             float val = annot.get("value") == null ? null : Float
557                     .valueOf(annot.get("value").toString());
558             String desc = annot.get("description") == null ? null : annot
559                     .get("description").toString();
560             char ss = annot.get("secondaryStructure") == null
561                     || annot.get("secondaryStructure").toString()
562                             .equalsIgnoreCase("u0000") ? ' ' : annot
563                     .get("secondaryStructure").toString().charAt(0);
564             String displayChar = annot.get("displayCharacter") == null ? ""
565                     : annot.get("displayCharacter").toString();
566
567             annotations[count] = new Annotation(displayChar, desc, ss, val);
568             if (annot.get("colour") != null)
569             {
570               Color color = ColorUtils.parseColourString(annot.get(
571                       "colour").toString());
572               annotations[count].colour = color;
573             }
574           }
575           ++count;
576         }
577
578         AlignmentAnnotation alignAnnot = new AlignmentAnnotation(alAnnot
579                 .get("label").toString(), alAnnot.get("description")
580                 .toString(), annotations);
581         alignAnnot.graph = (alAnnot.get("graphType") == null) ? 0 : Integer
582                 .valueOf(alAnnot.get("graphType").toString());
583
584         JSONObject diplaySettings = (JSONObject) alAnnot
585                 .get("annotationSettings");
586         if (diplaySettings != null)
587         {
588
589           alignAnnot.scaleColLabel = (diplaySettings.get("scaleColLabel") == null) ? false
590                   : Boolean.valueOf(diplaySettings.get("scaleColLabel")
591                           .toString());
592           alignAnnot.showAllColLabels = (diplaySettings
593                   .get("showAllColLabels") == null) ? true : Boolean
594                   .valueOf(diplaySettings.get("showAllColLabels")
595                           .toString());
596           alignAnnot.centreColLabels = (diplaySettings
597                   .get("centreColLabels") == null) ? true
598                   : Boolean.valueOf(diplaySettings.get("centreColLabels")
599                           .toString());
600           alignAnnot.belowAlignment = (diplaySettings.get("belowAlignment") == null) ? false
601                   : Boolean.valueOf(diplaySettings.get("belowAlignment")
602                           .toString());
603           alignAnnot.visible = (diplaySettings.get("visible") == null) ? true
604                   : Boolean.valueOf(diplaySettings.get("visible")
605                           .toString());
606           alignAnnot.hasIcons = (diplaySettings.get("hasIcon") == null) ? true
607                   : Boolean.valueOf(diplaySettings.get("hasIcon")
608                           .toString());
609
610         }
611         if (alAnnot.get("score") != null)
612         {
613           alignAnnot.score = Double
614                   .valueOf(alAnnot.get("score").toString());
615         }
616
617         String calcId = (alAnnot.get("calcId") == null) ? "" : alAnnot.get(
618                 "calcId").toString();
619         alignAnnot.setCalcId(calcId);
620         String seqHash = (alAnnot.get("sequenceRef") != null) ? alAnnot
621                 .get("sequenceRef").toString() : null;
622
623         Sequence sequence = (seqHash != null) ? seqMap.get(seqHash) : null;
624         if (sequence != null)
625         {
626           alignAnnot.sequenceRef = sequence;
627           sequence.addAlignmentAnnotation(alignAnnot);
628           if (alignAnnot.label.equalsIgnoreCase("T-COFFEE"))
629           {
630             alignAnnot.createSequenceMapping(sequence, sequence.getStart(),
631                     false);
632             sequence.addAlignmentAnnotation(alignAnnot);
633             alignAnnot.adjustForAlignment();
634           }
635         }
636         alignAnnot.validateRangeAndDisplay();
637         this.annotations.add(alignAnnot);
638
639       }
640     } catch (Exception e)
641     {
642       e.printStackTrace();
643     }
644     return this;
645   }
646
647   public void parseHiddenSeqRefsAsList(JSONObject jvSettingsJson)
648   {
649     hiddenSeqRefs = new ArrayList<String>();
650     String hiddenSeqs = (String) jvSettingsJson.get("hiddenSeqs");
651     if (hiddenSeqs != null && !hiddenSeqs.isEmpty())
652     {
653       String[] seqRefs = hiddenSeqs.split(";");
654       for (String seqRef : seqRefs)
655       {
656         hiddenSeqRefs.add(seqRef);
657       }
658     }
659   }
660
661   public void parseHiddenCols(JSONObject jvSettingsJson)
662   {
663     String hiddenCols = (String) jvSettingsJson.get("hiddenCols");
664     if (hiddenCols != null && !hiddenCols.isEmpty())
665     {
666       hiddenColumns = new HiddenColumns();
667       String[] rangeStrings = hiddenCols.split(";");
668       for (String rangeString : rangeStrings)
669       {
670         String[] range = rangeString.split("-");
671         hiddenColumns.hideColumns(Integer.valueOf(range[0]),
672                 Integer.valueOf(range[1]));
673       }
674     }
675   }
676
677   @SuppressWarnings("unchecked")
678   private void parseFeatures(JSONArray jsonSeqFeatures)
679   {
680     if (jsonSeqFeatures != null)
681     {
682       displayedFeatures = new FeaturesDisplayed();
683       for (Iterator<JSONObject> seqFeatureItr = jsonSeqFeatures.iterator(); seqFeatureItr
684               .hasNext();)
685       {
686         JSONObject jsonFeature = seqFeatureItr.next();
687         Long begin = (Long) jsonFeature.get("xStart");
688         Long end = (Long) jsonFeature.get("xEnd");
689         String type = (String) jsonFeature.get("type");
690         String featureGrp = (String) jsonFeature.get("featureGroup");
691         String description = (String) jsonFeature.get("description");
692         String seqRef = (String) jsonFeature.get("sequenceRef");
693         Float score = Float.valueOf(jsonFeature.get("score").toString());
694
695         Sequence seq = seqMap.get(seqRef);
696
697         /*
698          * begin/end of 0 is for a non-positional feature
699          */
700         int featureBegin = begin.intValue() == 0 ? 0 : seq
701                 .findPosition(begin.intValue());
702         int featureEnd = end.intValue() == 0 ? 0 : seq.findPosition(end
703                 .intValue()) - 1;
704
705         SequenceFeature sequenceFeature = new SequenceFeature(type,
706                 description, featureBegin, featureEnd, score, featureGrp);
707
708         JSONArray linksJsonArray = (JSONArray) jsonFeature.get("links");
709         if (linksJsonArray != null && linksJsonArray.size() > 0)
710         {
711           Iterator<String> linkList = linksJsonArray.iterator();
712           while (linkList.hasNext())
713           {
714             String link = linkList.next();
715             sequenceFeature.addLink(link);
716           }
717         }
718
719         seq.addSequenceFeature(sequenceFeature);
720         displayedFeatures.setVisible(type);
721       }
722     }
723   }
724
725   @Override
726   public String getGlobalColourScheme()
727   {
728     return globalColourScheme;
729   }
730
731   public void setGlobalColorScheme(String globalColourScheme)
732   {
733     this.globalColourScheme = globalColourScheme;
734   }
735
736   @Override
737   public FeaturesDisplayedI getDisplayedFeatures()
738   {
739     return displayedFeatures;
740   }
741
742   public void setDisplayedFeatures(FeaturesDisplayedI displayedFeatures)
743   {
744     this.displayedFeatures = displayedFeatures;
745   }
746
747   @Override
748   public void configureForView(AlignmentViewPanel avpanel)
749   {
750     if (avpanel == null)
751     {
752       return;
753     }
754     super.configureForView(avpanel);
755     AlignViewportI viewport = avpanel.getAlignViewport();
756     AlignmentI alignment = viewport.getAlignment();
757     AlignmentAnnotation[] annots = alignment.getAlignmentAnnotation();
758
759     seqGroups = alignment.getGroups();
760     fr = avpanel.cloneFeatureRenderer();
761
762     // Add non auto calculated annotation to AlignFile
763     if (annots != null)
764     {
765       for (AlignmentAnnotation annot : annots)
766       {
767         if (annot != null && !annot.autoCalculated)
768         {
769           annotations.add(annot);
770         }
771       }
772     }
773     globalColourScheme = ColourSchemeProperty.getColourName(viewport
774             .getGlobalColourScheme());
775     setDisplayedFeatures(viewport.getFeaturesDisplayed());
776     showSeqFeatures = viewport.isShowSequenceFeatures();
777
778   }
779
780   @Override
781   public boolean isShowSeqFeatures()
782   {
783     return showSeqFeatures;
784   }
785
786   public void setShowSeqFeatures(boolean showSeqFeatures)
787   {
788     this.showSeqFeatures = showSeqFeatures;
789   }
790
791   public Vector<AlignmentAnnotation> getAnnotations()
792   {
793     return annotations;
794   }
795
796   @Override
797   public HiddenColumns getHiddenColumns()
798   {
799     return hiddenColumns;
800   }
801
802   public void setHiddenColumns(HiddenColumns hidden)
803   {
804     this.hiddenColumns = hidden;
805   }
806
807   @Override
808   public SequenceI[] getHiddenSequences()
809   {
810     if (hiddenSequences == null || hiddenSequences.isEmpty())
811     {
812       return new SequenceI[] {};
813     }
814     synchronized (hiddenSequences)
815     {
816       return hiddenSequences.toArray(new SequenceI[hiddenSequences.size()]);
817     }
818   }
819
820   public void setHiddenSequences(ArrayList<SequenceI> hiddenSequences)
821   {
822     this.hiddenSequences = hiddenSequences;
823   }
824
825   public class JSONExportSettings
826   {
827     private boolean exportSequence;
828
829     private boolean exportSequenceFeatures;
830
831     private boolean exportAnnotations;
832
833     private boolean exportGroups;
834
835     private boolean exportJalviewSettings;
836
837     public boolean isExportSequence()
838     {
839       return exportSequence;
840     }
841
842     public void setExportSequence(boolean exportSequence)
843     {
844       this.exportSequence = exportSequence;
845     }
846
847     public boolean isExportSequenceFeatures()
848     {
849       return exportSequenceFeatures;
850     }
851
852     public void setExportSequenceFeatures(boolean exportSequenceFeatures)
853     {
854       this.exportSequenceFeatures = exportSequenceFeatures;
855     }
856
857     public boolean isExportAnnotations()
858     {
859       return exportAnnotations;
860     }
861
862     public void setExportAnnotations(boolean exportAnnotations)
863     {
864       this.exportAnnotations = exportAnnotations;
865     }
866
867     public boolean isExportGroups()
868     {
869       return exportGroups;
870     }
871
872     public void setExportGroups(boolean exportGroups)
873     {
874       this.exportGroups = exportGroups;
875     }
876
877     public boolean isExportJalviewSettings()
878     {
879       return exportJalviewSettings;
880     }
881
882     public void setExportJalviewSettings(boolean exportJalviewSettings)
883     {
884       this.exportJalviewSettings = exportJalviewSettings;
885     }
886   }
887
888   /**
889    * Returns a descriptor for suitable feature display settings with
890    * <ul>
891    * <li>ResNums or insertions features visible</li>
892    * <li>insertions features coloured red</li>
893    * <li>ResNum features coloured by label</li>
894    * <li>Insertions displayed above (on top of) ResNums</li>
895    * </ul>
896    */
897   @Override
898   public FeatureSettingsModelI getFeatureColourScheme()
899   {
900     return new PDBFeatureSettings();
901   }
902 }