89085c461f1ad44516a69056364cbee52bcc20f6
[jalview.git] / src / jalview / io / AnnotationFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.io;
22
23 import java.awt.Color;
24 import java.io.BufferedReader;
25 import java.util.ArrayList;
26 import java.util.BitSet;
27 import java.util.Enumeration;
28 import java.util.HashMap;
29 import java.util.Hashtable;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.StringTokenizer;
33 import java.util.Vector;
34
35 import jalview.analysis.Conservation;
36 import jalview.api.AlignViewportI;
37 import jalview.datamodel.Alignment;
38 import jalview.datamodel.AlignmentAnnotation;
39 import jalview.datamodel.AlignmentI;
40 import jalview.datamodel.Annotation;
41 import jalview.datamodel.ColumnSelection;
42 import jalview.datamodel.GraphLine;
43 import jalview.datamodel.HiddenColumns;
44 import jalview.datamodel.HiddenSequences;
45 import jalview.datamodel.SequenceGroup;
46 import jalview.datamodel.SequenceI;
47 import jalview.schemes.ColourSchemeI;
48 import jalview.schemes.ColourSchemeProperty;
49 import jalview.util.ColorUtils;
50
51 public class AnnotationFile
52 {
53   private static final String GRAPHLINE = "GRAPHLINE";
54
55   private static final String COMBINE = "COMBINE";
56
57   protected String newline = System.getProperty("line.separator");
58
59   private StringBuffer text;
60
61   private SequenceI refSeq = null;
62
63   private String refSeqId = null;
64
65   private long nlinesread = 0;
66
67   private String lastread = "";
68
69   /**
70    * default calcId string for new annotation
71    */
72   private String defaultCalcId = null;
73
74   /**
75    * Constructor
76    */
77   public AnnotationFile()
78   {
79     init();
80   }
81
82   private void init()
83   {
84     text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
85             + new java.util.Date() + newline + newline);
86     refSeq = null;
87     refSeqId = null;
88   }
89
90   /**
91    * convenience method for pre-2.9 annotation files which have no view, hidden
92    * columns or hidden row keywords.
93    * 
94    * @param annotations
95    * @param list
96    * @param properties
97    * @return annotation file as a string.
98    */
99   public String printAnnotations(AlignmentAnnotation[] annotations,
100           List<SequenceGroup> list, Hashtable properties)
101   {
102     return printAnnotations(annotations, list, properties, null, null,
103             null);
104
105   }
106
107   /**
108    * hold all the information about a particular view definition read from or
109    * written out in an annotations file.
110    */
111   public class ViewDef
112   {
113     // TODO this class is not used - remove?
114     public final String viewname;
115
116     public final HiddenSequences hidseqs;
117
118     public final HiddenColumns hiddencols;
119
120     public final Hashtable hiddenRepSeqs;
121
122     public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
123             Hashtable hRepSeqs)
124     {
125       this.viewname = vname;
126       this.hidseqs = hseqs;
127       this.hiddencols = hcols;
128       this.hiddenRepSeqs = hRepSeqs;
129     }
130   }
131
132   /**
133    * Prepare an annotation file given a set of annotations, groups, alignment
134    * properties and views.
135    * 
136    * @param annotations
137    * @param list
138    * @param properties
139    * @param views
140    * @return annotation file
141    */
142   public String printAnnotations(AlignmentAnnotation[] annotations,
143           List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
144           AlignmentI al, ViewDef view)
145   {
146     if (view != null)
147     {
148       if (view.viewname != null)
149       {
150         text.append("VIEW_DEF\t" + view.viewname + "\n");
151       }
152       if (list == null)
153       {
154         // list = view.visibleGroups;
155       }
156       if (cs == null)
157       {
158         cs = view.hiddencols;
159       }
160       if (al == null)
161       {
162         // add hidden rep sequences.
163       }
164     }
165     // first target - store and restore all settings for a view.
166     if (al != null && al.hasSeqrep())
167     {
168       text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
169     }
170     if (cs != null && cs.hasHiddenColumns())
171     {
172       text.append("VIEW_HIDECOLS\t");
173
174       String regions = cs.regionsToString(",", "-");
175       text.append(regions);
176       text.append("\n");
177     }
178     // TODO: allow efficient recovery of annotation data shown in several
179     // different views
180     if (annotations != null)
181     {
182       boolean oneColour = true;
183       AlignmentAnnotation row;
184       String comma;
185       SequenceI refSeq = null;
186       SequenceGroup refGroup = null;
187
188       StringBuffer colours = new StringBuffer();
189       StringBuffer graphLine = new StringBuffer();
190       StringBuffer rowprops = new StringBuffer();
191       Hashtable<Integer, String> graphGroup = new Hashtable<>();
192       Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
193       BitSet graphGroupSeen = new BitSet();
194
195       java.awt.Color color;
196
197       for (int i = 0; i < annotations.length; i++)
198       {
199         row = annotations[i];
200
201         if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
202                 && graphGroupSeen.get(row.graphGroup)))
203         {
204           continue;
205         }
206
207         color = null;
208         oneColour = true;
209
210         // mark any sequence references for the row
211         writeSequence_Ref(refSeq, row.sequenceRef);
212         refSeq = row.sequenceRef;
213         // mark any group references for the row
214         writeGroup_Ref(refGroup, row.groupRef);
215         refGroup = row.groupRef;
216
217         boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
218                 hasValues = row.hasScore, hasText = false;
219         // lookahead to check what the annotation row object actually contains.
220         for (int j = 0; row.annotations != null
221                 && j < row.annotations.length
222                 && (!hasGlyphs || !hasLabels || !hasValues); j++)
223         {
224           if (row.annotations[j] != null)
225           {
226             hasLabels |= (row.annotations[j].displayCharacter != null
227                     && row.annotations[j].displayCharacter.length() > 0
228                     && !row.annotations[j].displayCharacter.equals(" "));
229             hasGlyphs |= (row.annotations[j].secondaryStructure != 0
230                     && row.annotations[j].secondaryStructure != ' ');
231             hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
232             // be
233             // rendered..
234             hasText |= (row.annotations[j].description != null
235                     && row.annotations[j].description.length() > 0);
236           }
237         }
238
239         if (row.graph == AlignmentAnnotation.NO_GRAPH)
240         {
241           text.append("NO_GRAPH\t");
242           hasValues = false; // only secondary structure
243           // hasLabels = false; // and annotation description string.
244         }
245         else
246         {
247           if (row.graph == AlignmentAnnotation.BAR_GRAPH)
248           {
249             text.append("BAR_GRAPH\t");
250             hasGlyphs = false; // no secondary structure
251
252           }
253           else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
254           {
255             hasGlyphs = false; // no secondary structure
256             text.append("LINE_GRAPH\t");
257           }
258
259           if (row.getThreshold() != null)
260           {
261             graphLine.append("GRAPHLINE\t");
262             graphLine.append(row.label);
263             graphLine.append("\t");
264             graphLine.append(row.getThreshold().value);
265             graphLine.append("\t");
266             graphLine.append(row.getThreshold().label);
267             graphLine.append("\t");
268             graphLine.append(jalview.util.Format
269                     .getHexString(row.getThreshold().colour));
270             graphLine.append(newline);
271           }
272
273           if (row.graphGroup > -1)
274           {
275             graphGroupSeen.set(row.graphGroup);
276             Integer key = Integer.valueOf(row.graphGroup);
277             if (graphGroup.containsKey(key))
278             {
279               graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
280
281             }
282             else
283             {
284               graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
285               graphGroup.put(key, row.label);
286             }
287           }
288         }
289
290         text.append(row.label + "\t");
291         if (row.description != null)
292         {
293           text.append(row.description + "\t");
294         }
295         for (int j = 0; row.annotations != null
296                 && j < row.annotations.length; j++)
297         {
298           if (refSeq != null
299                   && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
300           {
301             continue;
302           }
303
304           if (row.annotations[j] != null)
305           {
306             comma = "";
307             if (hasGlyphs) // could be also hasGlyphs || ...
308             {
309
310               text.append(comma);
311               if (row.annotations[j].secondaryStructure != ' ')
312               {
313                 // only write out the field if its not whitespace.
314                 text.append(row.annotations[j].secondaryStructure);
315               }
316               comma = ",";
317             }
318             if (hasValues)
319             {
320               if (!Float.isNaN(row.annotations[j].value))
321               {
322                 text.append(comma + row.annotations[j].value);
323               }
324               else
325               {
326                 // System.err.println("Skipping NaN - not valid value.");
327                 text.append(comma + 0f);// row.annotations[j].value);
328               }
329               comma = ",";
330             }
331             if (hasLabels)
332             {
333               // TODO: labels are emitted after values for bar graphs.
334               if // empty labels are allowed, so
335               (row.annotations[j].displayCharacter != null
336                       && row.annotations[j].displayCharacter.length() > 0
337                       && !row.annotations[j].displayCharacter.equals(" "))
338               {
339                 text.append(comma + row.annotations[j].displayCharacter);
340                 comma = ",";
341               }
342             }
343             if (hasText)
344             {
345               if (row.annotations[j].description != null
346                       && row.annotations[j].description.length() > 0
347                       && !row.annotations[j].description
348                               .equals(row.annotations[j].displayCharacter))
349               {
350                 text.append(comma + row.annotations[j].description);
351                 comma = ",";
352               }
353             }
354             if (color != null && !color.equals(row.annotations[j].colour))
355             {
356               oneColour = false;
357             }
358
359             color = row.annotations[j].colour;
360
361             if (row.annotations[j].colour != null
362                     && row.annotations[j].colour != java.awt.Color.black)
363             {
364               text.append(comma + "[" + jalview.util.Format
365                       .getHexString(row.annotations[j].colour) + "]");
366               comma = ",";
367             }
368           }
369           text.append("|");
370         }
371
372         if (row.hasScore())
373         {
374           text.append("\t" + row.score);
375         }
376
377         text.append(newline);
378
379         if (color != null && color != java.awt.Color.black && oneColour)
380         {
381           colours.append("COLOUR\t");
382           colours.append(row.label);
383           colours.append("\t");
384           colours.append(jalview.util.Format.getHexString(color));
385           colours.append(newline);
386         }
387         if (row.scaleColLabel || row.showAllColLabels
388                 || row.centreColLabels)
389         {
390           rowprops.append("ROWPROPERTIES\t");
391           rowprops.append(row.label);
392           rowprops.append("\tscaletofit=");
393           rowprops.append(row.scaleColLabel);
394           rowprops.append("\tshowalllabs=");
395           rowprops.append(row.showAllColLabels);
396           rowprops.append("\tcentrelabs=");
397           rowprops.append(row.centreColLabels);
398           rowprops.append(newline);
399         }
400         if (graphLine.length() > 0)
401         {
402           text.append(graphLine.toString());
403           graphLine.setLength(0);
404         }
405       }
406
407       text.append(newline);
408
409       text.append(colours.toString());
410       if (graphGroup.size() > 0)
411       {
412         SequenceI oldRefSeq = refSeq;
413         SequenceGroup oldRefGroup = refGroup;
414         for (Map.Entry<Integer, String> combine_statement : graphGroup
415                 .entrySet())
416         {
417           Object[] seqRefAndGroup = graphGroup_refs
418                   .get(combine_statement.getKey());
419
420           writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
421           refSeq = (SequenceI) seqRefAndGroup[0];
422
423           writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
424           refGroup = (SequenceGroup) seqRefAndGroup[1];
425           text.append("COMBINE\t");
426           text.append(combine_statement.getValue());
427           text.append(newline);
428         }
429         writeSequence_Ref(refSeq, oldRefSeq);
430         refSeq = oldRefSeq;
431
432         writeGroup_Ref(refGroup, oldRefGroup);
433         refGroup = oldRefGroup;
434       }
435       text.append(rowprops.toString());
436     }
437
438     if (list != null)
439     {
440       printGroups(list);
441     }
442
443     if (properties != null)
444     {
445       text.append(newline);
446       text.append(newline);
447       text.append("ALIGNMENT");
448       Enumeration en = properties.keys();
449       while (en.hasMoreElements())
450       {
451         String key = en.nextElement().toString();
452         text.append("\t");
453         text.append(key);
454         text.append("=");
455         text.append(properties.get(key));
456       }
457       // TODO: output alignment visualization settings here if required
458       // iterate through one or more views, defining, marking columns and rows
459       // as visible/hidden, and emmitting view properties.
460       // View specific annotation is
461     }
462
463     return text.toString();
464   }
465
466   private Object writeGroup_Ref(SequenceGroup refGroup,
467           SequenceGroup next_refGroup)
468   {
469     if (next_refGroup == null)
470     {
471
472       if (refGroup != null)
473       {
474         text.append(newline);
475         text.append("GROUP_REF\t");
476         text.append("ALIGNMENT");
477         text.append(newline);
478       }
479       return true;
480     }
481     else
482     {
483       if (refGroup == null || refGroup != next_refGroup)
484       {
485         text.append(newline);
486         text.append("GROUP_REF\t");
487         text.append(next_refGroup.getName());
488         text.append(newline);
489         return true;
490       }
491     }
492     return false;
493   }
494
495   private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
496   {
497
498     if (next_refSeq == null)
499     {
500       if (refSeq != null)
501       {
502         text.append(newline);
503         text.append("SEQUENCE_REF\t");
504         text.append("ALIGNMENT");
505         text.append(newline);
506         return true;
507       }
508     }
509     else
510     {
511       if (refSeq == null || refSeq != next_refSeq)
512       {
513         text.append(newline);
514         text.append("SEQUENCE_REF\t");
515         text.append(next_refSeq.getName());
516         text.append(newline);
517         return true;
518       }
519     }
520     return false;
521   }
522
523   protected void printGroups(List<SequenceGroup> list)
524   {
525     SequenceI seqrep = null;
526     for (SequenceGroup sg : list)
527     {
528       if (!sg.hasSeqrep())
529       {
530         text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
531                 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
532                 + "\t" + "-1\t");
533         seqrep = null;
534       }
535       else
536       {
537         seqrep = sg.getSeqrep();
538         text.append("SEQUENCE_REF\t");
539         text.append(seqrep.getName());
540         text.append(newline);
541         text.append("SEQUENCE_GROUP\t");
542         text.append(sg.getName());
543         text.append("\t");
544         text.append((seqrep.findPosition(sg.getStartRes())));
545         text.append("\t");
546         text.append((seqrep.findPosition(sg.getEndRes())));
547         text.append("\t");
548         text.append("-1\t");
549       }
550       for (int s = 0; s < sg.getSize(); s++)
551       {
552         text.append(sg.getSequenceAt(s).getName());
553         text.append("\t");
554       }
555       text.append(newline);
556       text.append("PROPERTIES\t");
557       text.append(sg.getName());
558       text.append("\t");
559
560       if (sg.getDescription() != null)
561       {
562         text.append("description=");
563         text.append(sg.getDescription());
564         text.append("\t");
565       }
566       if (sg.cs != null)
567       {
568         text.append("colour=");
569         text.append(ColourSchemeProperty
570                 .getColourName(sg.cs.getColourScheme()));
571         text.append("\t");
572         if (sg.cs.getThreshold() != 0)
573         {
574           text.append("pidThreshold=");
575           text.append(sg.cs.getThreshold());
576         }
577         if (sg.cs.conservationApplied())
578         {
579           text.append("consThreshold=");
580           text.append(sg.cs.getConservationInc());
581           text.append("\t");
582         }
583       }
584       text.append("outlineColour=");
585       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
586       text.append("\t");
587
588       text.append("displayBoxes=");
589       text.append(sg.getDisplayBoxes());
590       text.append("\t");
591       text.append("displayText=");
592       text.append(sg.getDisplayText());
593       text.append("\t");
594       text.append("colourText=");
595       text.append(sg.getColourText());
596       text.append("\t");
597       text.append("showUnconserved=");
598       text.append(sg.getShowNonconserved());
599       text.append("\t");
600       if (sg.textColour != java.awt.Color.black)
601       {
602         text.append("textCol1=");
603         text.append(jalview.util.Format.getHexString(sg.textColour));
604         text.append("\t");
605       }
606       if (sg.textColour2 != java.awt.Color.white)
607       {
608         text.append("textCol2=");
609         text.append(jalview.util.Format.getHexString(sg.textColour2));
610         text.append("\t");
611       }
612       if (sg.thresholdTextColour != 0)
613       {
614         text.append("textColThreshold=");
615         text.append(sg.thresholdTextColour);
616         text.append("\t");
617       }
618       if (sg.idColour != null)
619       {
620         text.append("idColour=");
621         text.append(jalview.util.Format.getHexString(sg.idColour));
622         text.append("\t");
623       }
624       if (sg.isHidereps())
625       {
626         text.append("hide=true\t");
627       }
628       if (sg.isHideCols())
629       {
630         text.append("hidecols=true\t");
631       }
632       if (seqrep != null)
633       {
634         // terminate the last line and clear the sequence ref for the group
635         text.append(newline);
636         text.append("SEQUENCE_REF");
637       }
638       text.append(newline);
639       text.append(newline);
640
641     }
642   }
643
644   public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
645           DataSourceType protocol)
646   {
647     ColumnSelection colSel = viewport.getColumnSelection();
648     HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
649     if (colSel == null)
650     {
651       colSel = new ColumnSelection();
652     }
653     if (hidden == null)
654     {
655       hidden = new HiddenColumns();
656     }
657     boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
658             protocol);
659     if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
660     {
661       viewport.setColumnSelection(colSel);
662       viewport.getAlignment().setHiddenColumns(hidden);
663     }
664
665     return rslt;
666   }
667
668   public boolean readAnnotationFile(AlignmentI al, String file,
669           DataSourceType sourceType)
670   {
671     return readAnnotationFile(al, null, file, sourceType);
672   }
673
674   /**
675    * read an annotation file onto the alignment, but apply the given calcId
676    * @param aln
677    * @param calcId
678    * @param file
679    * @param url
680    * @return
681    */
682   public boolean readAnnotationFileWithCalcId(Alignment aln, String calcId, String file,
683           DataSourceType url)
684   {
685     defaultCalcId=calcId;
686     return readAnnotationFile(aln, null, file, url);
687   }
688   
689   public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
690           Object file, DataSourceType sourceType)
691   {
692     BufferedReader in = null;
693     try
694     {
695       in = new FileParse().getBufferedReader(file, sourceType);
696       if (in != null)
697       {
698         return parseAnnotationFrom(al, hidden, in);
699       }
700     } catch (Exception ex)
701     {
702       ex.printStackTrace();
703       System.out.println("Problem reading annotation file: " + ex);
704       if (nlinesread > 0)
705       {
706         System.out.println("Last read line " + nlinesread + ": '" + lastread
707                 + "' (first 80 chars) ...");
708       }
709       return false;
710     }
711     return false;
712   }
713
714   public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
715           BufferedReader in) throws Exception
716   {
717     nlinesread = 0;
718     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
719     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
720     boolean modified = false;
721     String groupRef = null;
722     Hashtable groupRefRows = new Hashtable();
723
724     Hashtable autoAnnots = new Hashtable();
725     {
726       String line, label, description, token;
727       int graphStyle, index;
728       int refSeqIndex = 1;
729       int existingAnnotations = 0;
730       // when true - will add new rows regardless of whether they are duplicate
731       // auto-annotation like consensus or conservation graphs
732       boolean overrideAutoAnnot = false;
733       if (al.getAlignmentAnnotation() != null)
734       {
735         existingAnnotations = al.getAlignmentAnnotation().length;
736         if (existingAnnotations > 0)
737         {
738           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
739           for (int aai = 0; aai < aa.length; aai++)
740           {
741             if (aa[aai].autoCalculated)
742             {
743               // make a note of the name and description
744               autoAnnots.put(
745                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
746                               (aa[aai].groupRef == null ? null
747                                       : aa[aai].groupRef.getName())),
748                       Integer.valueOf(1));
749             }
750           }
751         }
752       }
753
754       int alWidth = al.getWidth();
755
756       StringTokenizer st;
757       Annotation[] annotations;
758       AlignmentAnnotation annotation = null;
759
760       // First confirm this is an Annotation file
761       boolean jvAnnotationFile = false;
762       while ((line = in.readLine()) != null)
763       {
764         nlinesread++;
765         lastread = new String(line);
766         if (line.indexOf("#") == 0)
767         {
768           continue;
769         }
770
771         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
772         {
773           jvAnnotationFile = true;
774           break;
775         }
776       }
777
778       if (!jvAnnotationFile)
779       {
780         in.close();
781         return false;
782       }
783
784       while ((line = in.readLine()) != null)
785       {
786         nlinesread++;
787         lastread = new String(line);
788         if (line.indexOf("#") == 0
789                 || line.indexOf("JALVIEW_ANNOTATION") > -1
790                 || line.length() == 0)
791         {
792           continue;
793         }
794
795         st = new StringTokenizer(line, "\t");
796         token = st.nextToken();
797         if (token.equalsIgnoreCase("COLOUR"))
798         {
799           // TODO: use graduated colour def'n here too
800           colourAnnotations(al, st.nextToken(), st.nextToken());
801           modified = true;
802           continue;
803         }
804
805         else if (token.equalsIgnoreCase(COMBINE))
806         {
807           // keep a record of current state and resolve groupRef at end
808           combineAnnotation_calls
809                   .add(new Object[]
810                   { st, refSeq, groupRef });
811           modified = true;
812           continue;
813         }
814         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
815         {
816           addRowProperties(al, st);
817           modified = true;
818           continue;
819         }
820         else if (token.equalsIgnoreCase(GRAPHLINE))
821         {
822           // resolve at end
823           deferredAnnotation_calls
824                   .add(new Object[]
825                   { GRAPHLINE, st, refSeq, groupRef });
826           modified = true;
827           continue;
828         }
829
830         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
831         {
832           if (st.hasMoreTokens())
833           {
834             refSeq = al.findName(refSeqId = st.nextToken());
835             if (refSeq == null)
836             {
837               refSeqId = null;
838             }
839             try
840             {
841               refSeqIndex = Integer.parseInt(st.nextToken());
842               if (refSeqIndex < 1)
843               {
844                 refSeqIndex = 1;
845                 System.out.println(
846                         "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
847               }
848             } catch (Exception ex)
849             {
850               refSeqIndex = 1;
851             }
852           }
853           else
854           {
855             refSeq = null;
856             refSeqId = null;
857           }
858           continue;
859         }
860         else if (token.equalsIgnoreCase("GROUP_REF"))
861         {
862           // Group references could be forward or backwards, so they are
863           // resolved after the whole file is read in
864           groupRef = null;
865           if (st.hasMoreTokens())
866           {
867             groupRef = st.nextToken();
868             if (groupRef.length() < 1)
869             {
870               groupRef = null; // empty string
871             }
872             else
873             {
874               if (groupRefRows.get(groupRef) == null)
875               {
876                 groupRefRows.put(groupRef, new Vector());
877               }
878             }
879           }
880           continue;
881         }
882         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
883         {
884           addGroup(al, st);
885           modified = true;
886           continue;
887         }
888
889         else if (token.equalsIgnoreCase("PROPERTIES"))
890         {
891           addProperties(al, st);
892           modified = true;
893           continue;
894         }
895
896         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
897         {
898           setBelowAlignment(al, st);
899           modified = true;
900           continue;
901         }
902         else if (token.equalsIgnoreCase("ALIGNMENT"))
903         {
904           addAlignmentDetails(al, st);
905           modified = true;
906           continue;
907         }
908         // else if (token.equalsIgnoreCase("VIEW_DEF"))
909         // {
910         // addOrSetView(al,st);
911         // modified = true;
912         // continue;
913         // }
914         else if (token.equalsIgnoreCase("VIEW_SETREF"))
915         {
916           if (refSeq != null)
917           {
918             al.setSeqrep(refSeq);
919           }
920           modified = true;
921           continue;
922         }
923         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
924         {
925           if (st.hasMoreTokens())
926           {
927             if (hidden == null)
928             {
929               hidden = new HiddenColumns();
930             }
931             parseHideCols(hidden, st.nextToken());
932           }
933           modified = true;
934           continue;
935         }
936         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
937         {
938           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
939           if (sr == null)
940           {
941             sr = al.getSequenceAt(0);
942           }
943           if (sr != null)
944           {
945             if (hidden == null)
946             {
947               System.err.println(
948                       "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
949                               + line);
950             }
951             else
952             {
953               // consider deferring this till after the file has been parsed ?
954               hidden.hideList(sr.getInsertions());
955             }
956           }
957           modified = true;
958           continue;
959         }
960
961         // Parse out the annotation row
962         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
963         label = st.nextToken();
964
965         index = 0;
966         annotations = new Annotation[alWidth];
967         description = null;
968         float score = Float.NaN;
969
970         if (st.hasMoreTokens())
971         {
972           line = st.nextToken();
973
974           if (line.indexOf("|") == -1)
975           {
976             description = line;
977             if (st.hasMoreTokens())
978             {
979               line = st.nextToken();
980             }
981           }
982
983           if (st.hasMoreTokens())
984           {
985             // This must be the score
986             score = Float.valueOf(st.nextToken()).floatValue();
987           }
988
989           st = new StringTokenizer(line, "|", true);
990
991           boolean emptyColumn = true;
992           boolean onlyOneElement = (st.countTokens() == 1);
993
994           while (st.hasMoreElements() && index < alWidth)
995           {
996             token = st.nextToken().trim();
997
998             if (onlyOneElement)
999             {
1000               try
1001               {
1002                 score = Float.valueOf(token).floatValue();
1003                 break;
1004               } catch (NumberFormatException ex)
1005               {
1006               }
1007             }
1008
1009             if (token.equals("|"))
1010             {
1011               if (emptyColumn)
1012               {
1013                 index++;
1014               }
1015
1016               emptyColumn = true;
1017             }
1018             else
1019             {
1020               annotations[index++] = parseAnnotation(token, graphStyle);
1021               emptyColumn = false;
1022             }
1023           }
1024
1025         }
1026
1027         annotation = new AlignmentAnnotation(label, description,
1028                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1029         annotation.setCalcId(defaultCalcId);
1030         annotation.score = score;
1031         if (!overrideAutoAnnot && autoAnnots
1032                 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1033         {
1034           // skip - we've already got an automatic annotation of this type.
1035           continue;
1036         }
1037         // otherwise add it!
1038         if (refSeq != null)
1039         {
1040
1041           annotation.belowAlignment = false;
1042           // make a copy of refSeq so we can find other matches in the alignment
1043           SequenceI referedSeq = refSeq;
1044           do
1045           {
1046             // copy before we do any mapping business.
1047             // TODO: verify that undo/redo with 1:many sequence associated
1048             // annotations can be undone correctly
1049             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1050             annotation.createSequenceMapping(referedSeq, refSeqIndex,
1051                     false);
1052             annotation.adjustForAlignment();
1053             referedSeq.addAlignmentAnnotation(annotation);
1054             al.addAnnotation(annotation);
1055             al.setAnnotationIndex(annotation,
1056                     al.getAlignmentAnnotation().length - existingAnnotations
1057                             - 1);
1058             if (groupRef != null)
1059             {
1060               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1061             }
1062             // and recover our virgin copy to use again if necessary.
1063             annotation = ann;
1064
1065           } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1066                   refSeqId, true)) != null);
1067         }
1068         else
1069         {
1070           al.addAnnotation(annotation);
1071           al.setAnnotationIndex(annotation,
1072                   al.getAlignmentAnnotation().length - existingAnnotations
1073                           - 1);
1074           if (groupRef != null)
1075           {
1076             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1077           }
1078         }
1079         // and set modification flag
1080         modified = true;
1081       }
1082       // Resolve the groupRefs
1083       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1084       Enumeration en = groupRefRows.keys();
1085
1086       while (en.hasMoreElements())
1087       {
1088         groupRef = (String) en.nextElement();
1089         boolean matched = false;
1090         // Resolve group: TODO: add a getGroupByName method to alignments
1091         for (SequenceGroup theGroup : al.getGroups())
1092         {
1093           if (theGroup.getName().equals(groupRef))
1094           {
1095             if (matched)
1096             {
1097               // TODO: specify and implement duplication of alignment annotation
1098               // for multiple group references.
1099               System.err.println(
1100                       "Ignoring 1:many group reference mappings for group name '"
1101                               + groupRef + "'");
1102             }
1103             else
1104             {
1105               matched = true;
1106               Vector rowset = (Vector) groupRefRows.get(groupRef);
1107               groupRefLookup.put(groupRef, theGroup);
1108               if (rowset != null && rowset.size() > 0)
1109               {
1110                 AlignmentAnnotation alan = null;
1111                 for (int elm = 0, elmSize = rowset
1112                         .size(); elm < elmSize; elm++)
1113                 {
1114                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1115                   alan.groupRef = theGroup;
1116                 }
1117               }
1118             }
1119           }
1120         }
1121         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1122       }
1123       // process any deferred attribute settings for each context
1124       for (Object[] _deferred_args : deferredAnnotation_calls)
1125       {
1126         if (_deferred_args[0] == GRAPHLINE)
1127         {
1128           addLine(al, (StringTokenizer) _deferred_args[1], // st
1129                   (SequenceI) _deferred_args[2], // refSeq
1130                   (_deferred_args[3] == null) ? null
1131                           : groupRefLookup.get(_deferred_args[3]) // the
1132                                                                   // reference
1133                                                                   // group, or
1134                                                                   // null
1135           );
1136         }
1137       }
1138
1139       // finally, combine all the annotation rows within each context.
1140       /**
1141        * number of combine statements in this annotation file. Used to create
1142        * new groups for combined annotation graphs without disturbing existing
1143        * ones
1144        */
1145       int combinecount = 0;
1146       for (Object[] _combine_args : combineAnnotation_calls)
1147       {
1148         combineAnnotations(al, ++combinecount,
1149                 (StringTokenizer) _combine_args[0], // st
1150                 (SequenceI) _combine_args[1], // refSeq
1151                 (_combine_args[2] == null) ? null
1152                         : groupRefLookup.get(_combine_args[2]) // the reference
1153                                                                // group,
1154                                                                // or null
1155         );
1156       }
1157     }
1158     return modified;
1159   }
1160
1161   private void parseHideCols(HiddenColumns hidden, String nextToken)
1162   {
1163     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1164     while (inval.hasMoreTokens())
1165     {
1166       String range = inval.nextToken().trim();
1167       int from, to = range.indexOf("-");
1168       if (to == -1)
1169       {
1170         from = to = Integer.parseInt(range);
1171         if (from >= 0)
1172         {
1173           hidden.hideColumns(from, to);
1174         }
1175       }
1176       else
1177       {
1178         from = Integer.parseInt(range.substring(0, to));
1179         if (to < range.length() - 1)
1180         {
1181           to = Integer.parseInt(range.substring(to + 1));
1182         }
1183         else
1184         {
1185           to = from;
1186         }
1187         if (from > 0 && to >= from)
1188         {
1189           hidden.hideColumns(from, to);
1190         }
1191       }
1192     }
1193   }
1194
1195   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1196           SequenceI refSeq, String groupRef)
1197   {
1198     return annotation.graph + "\t" + annotation.label + "\t"
1199             + annotation.description + "\t"
1200             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1201   }
1202
1203   Annotation parseAnnotation(String string, int graphStyle)
1204   {
1205     // don't do the glyph test if we don't want secondary structure
1206     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1207     String desc = null, displayChar = null;
1208     char ss = ' '; // secondaryStructure
1209     float value = 0;
1210     boolean parsedValue = false, dcset = false;
1211
1212     // find colour here
1213     Color colour = null;
1214     int i = string.indexOf("[");
1215     int j = string.indexOf("]");
1216     if (i > -1 && j > -1)
1217     {
1218       colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1219       if (i > 0 && string.charAt(i - 1) == ',')
1220       {
1221         // clip the preceding comma as well
1222         i--;
1223       }
1224       string = string.substring(0, i) + string.substring(j + 1);
1225     }
1226
1227     StringTokenizer st = new StringTokenizer(string, ",", true);
1228     String token;
1229     boolean seenContent = false;
1230     int pass = 0;
1231     while (st.hasMoreTokens())
1232     {
1233       pass++;
1234       token = st.nextToken().trim();
1235       if (token.equals(","))
1236       {
1237         if (!seenContent && parsedValue && !dcset)
1238         {
1239           // allow the value below the bar/line to be empty
1240           dcset = true;
1241           displayChar = " ";
1242         }
1243         seenContent = false;
1244         continue;
1245       }
1246       else
1247       {
1248         seenContent = true;
1249       }
1250
1251       if (!parsedValue)
1252       {
1253         try
1254         {
1255           displayChar = token;
1256           // foo
1257           value = Float.valueOf(token).floatValue();
1258           parsedValue = true;
1259           continue;
1260         } catch (NumberFormatException ex)
1261         {
1262         }
1263       }
1264       else
1265       {
1266         if (token.length() == 1)
1267         {
1268           displayChar = token;
1269         }
1270       }
1271       if (hasSymbols && (token.length() == 1
1272               && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1273                       .contains(token)))
1274       {
1275         // Either this character represents a helix or sheet
1276         // or an integer which can be displayed
1277         ss = token.charAt(0);
1278         if (displayChar.equals(token.substring(0, 1)))
1279         {
1280           displayChar = "";
1281         }
1282       }
1283       else if (desc == null || (parsedValue && pass > 2))
1284       {
1285         desc = token;
1286       }
1287
1288     }
1289     // if (!dcset && string.charAt(string.length() - 1) == ',')
1290     // {
1291     // displayChar = " "; // empty display char symbol.
1292     // }
1293     if (displayChar != null && desc != null && desc.length() == 1)
1294     {
1295       if (displayChar.length() > 1)
1296       {
1297         // switch desc and displayChar - legacy support
1298         String tmp = displayChar;
1299         displayChar = desc;
1300         desc = tmp;
1301       }
1302       else
1303       {
1304         if (displayChar.equals(desc))
1305         {
1306           // duplicate label - hangover from the 'robust parser' above
1307           desc = null;
1308         }
1309       }
1310     }
1311     Annotation anot = new Annotation(displayChar, desc, ss, value);
1312
1313     anot.colour = colour;
1314
1315     return anot;
1316   }
1317
1318   void colourAnnotations(AlignmentI al, String label, String colour)
1319   {
1320     Color awtColour = ColorUtils.parseColourString(colour);
1321     Annotation[] annotations;
1322     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1323     {
1324       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1325       {
1326         annotations = al.getAlignmentAnnotation()[i].annotations;
1327         for (int j = 0; j < annotations.length; j++)
1328         {
1329           if (annotations[j] != null)
1330           {
1331             annotations[j].colour = awtColour;
1332           }
1333         }
1334       }
1335     }
1336   }
1337
1338   void combineAnnotations(AlignmentI al, int combineCount,
1339           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1340   {
1341     String group = st.nextToken();
1342     // First make sure we are not overwriting the graphIndex
1343     int graphGroup = 0;
1344     if (al.getAlignmentAnnotation() != null)
1345     {
1346       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1347       {
1348         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1349
1350         if (aa.graphGroup > graphGroup)
1351         {
1352           // try to number graphGroups in order of occurence.
1353           graphGroup = aa.graphGroup + 1;
1354         }
1355         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1356                 && aa.label.equalsIgnoreCase(group))
1357         {
1358           if (aa.graphGroup > -1)
1359           {
1360             graphGroup = aa.graphGroup;
1361           }
1362           else
1363           {
1364             if (graphGroup <= combineCount)
1365             {
1366               graphGroup = combineCount + 1;
1367             }
1368             aa.graphGroup = graphGroup;
1369           }
1370           break;
1371         }
1372       }
1373
1374       // Now update groups
1375       while (st.hasMoreTokens())
1376       {
1377         group = st.nextToken();
1378         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1379         {
1380           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1381           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1382                   && aa.label.equalsIgnoreCase(group))
1383           {
1384             aa.graphGroup = graphGroup;
1385             break;
1386           }
1387         }
1388       }
1389     }
1390     else
1391     {
1392       System.err.println(
1393               "Couldn't combine annotations. None are added to alignment yet!");
1394     }
1395   }
1396
1397   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1398           SequenceGroup groupRef)
1399   {
1400     String group = st.nextToken();
1401     AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1402     String nextToken = st.nextToken();
1403     float value = 0f;
1404     try
1405     {
1406       value = Float.valueOf(nextToken);
1407     } catch (NumberFormatException e)
1408     {
1409       System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1410               + "' invalid, setting to zero");
1411     }
1412     String label = st.hasMoreTokens() ? st.nextToken() : null;
1413     Color colour = null;
1414     if (st.hasMoreTokens())
1415     {
1416       colour = ColorUtils.parseColourString(st.nextToken());
1417     }
1418     if (alannot != null)
1419     {
1420       for (int i = 0; i < alannot.length; i++)
1421       {
1422         if (alannot[i].label.equalsIgnoreCase(group)
1423                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1424                 && (groupRef == null || alannot[i].groupRef == groupRef))
1425         {
1426           alannot[i].setThreshold(new GraphLine(value, label, colour));
1427         }
1428       }
1429     }
1430   }
1431
1432   void addGroup(AlignmentI al, StringTokenizer st)
1433   {
1434     SequenceGroup sg = new SequenceGroup();
1435     sg.setName(st.nextToken());
1436     String rng = "";
1437     try
1438     {
1439       rng = st.nextToken();
1440       if (rng.length() > 0 && !rng.startsWith("*"))
1441       {
1442         sg.setStartRes(Integer.parseInt(rng) - 1);
1443       }
1444       else
1445       {
1446         sg.setStartRes(0);
1447       }
1448       rng = st.nextToken();
1449       if (rng.length() > 0 && !rng.startsWith("*"))
1450       {
1451         sg.setEndRes(Integer.parseInt(rng) - 1);
1452       }
1453       else
1454       {
1455         sg.setEndRes(al.getWidth() - 1);
1456       }
1457     } catch (Exception e)
1458     {
1459       System.err.println(
1460               "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1461                       + rng + "' - assuming alignment width for group.");
1462       // assume group is full width
1463       sg.setStartRes(0);
1464       sg.setEndRes(al.getWidth() - 1);
1465     }
1466
1467     String index = st.nextToken();
1468     if (index.equals("-1"))
1469     {
1470       while (st.hasMoreElements())
1471       {
1472         sg.addSequence(al.findName(st.nextToken()), false);
1473       }
1474     }
1475     else
1476     {
1477       StringTokenizer st2 = new StringTokenizer(index, ",");
1478
1479       while (st2.hasMoreTokens())
1480       {
1481         String tmp = st2.nextToken();
1482         if (tmp.equals("*"))
1483         {
1484           for (int i = 0; i < al.getHeight(); i++)
1485           {
1486             sg.addSequence(al.getSequenceAt(i), false);
1487           }
1488         }
1489         else if (tmp.indexOf("-") >= 0)
1490         {
1491           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1492
1493           int start = (Integer.parseInt(st3.nextToken()));
1494           int end = (Integer.parseInt(st3.nextToken()));
1495
1496           if (end > start)
1497           {
1498             for (int i = start; i <= end; i++)
1499             {
1500               sg.addSequence(al.getSequenceAt(i - 1), false);
1501             }
1502           }
1503         }
1504         else
1505         {
1506           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1507                   false);
1508         }
1509       }
1510     }
1511
1512     if (refSeq != null)
1513     {
1514       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1515       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1516       sg.setSeqrep(refSeq);
1517     }
1518
1519     if (sg.getSize() > 0)
1520     {
1521       al.addGroup(sg);
1522     }
1523   }
1524
1525   void addRowProperties(AlignmentI al, StringTokenizer st)
1526   {
1527     String label = st.nextToken(), keyValue, key, value;
1528     boolean scaletofit = false, centerlab = false, showalllabs = false;
1529     while (st.hasMoreTokens())
1530     {
1531       keyValue = st.nextToken();
1532       key = keyValue.substring(0, keyValue.indexOf("="));
1533       value = keyValue.substring(keyValue.indexOf("=") + 1);
1534       if (key.equalsIgnoreCase("scaletofit"))
1535       {
1536         scaletofit = Boolean.valueOf(value).booleanValue();
1537       }
1538       if (key.equalsIgnoreCase("showalllabs"))
1539       {
1540         showalllabs = Boolean.valueOf(value).booleanValue();
1541       }
1542       if (key.equalsIgnoreCase("centrelabs"))
1543       {
1544         centerlab = Boolean.valueOf(value).booleanValue();
1545       }
1546       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1547       if (alr != null)
1548       {
1549         for (int i = 0; i < alr.length; i++)
1550         {
1551           if (alr[i].label.equalsIgnoreCase(label))
1552           {
1553             alr[i].centreColLabels = centerlab;
1554             alr[i].scaleColLabel = scaletofit;
1555             alr[i].showAllColLabels = showalllabs;
1556           }
1557         }
1558       }
1559     }
1560   }
1561
1562   void addProperties(AlignmentI al, StringTokenizer st)
1563   {
1564
1565     // So far we have only added groups to the annotationHash,
1566     // the idea is in the future properties can be added to
1567     // alignments, other annotations etc
1568     if (al.getGroups() == null)
1569     {
1570       return;
1571     }
1572
1573     String name = st.nextToken();
1574
1575     Map<String, String> properties = new HashMap<>();
1576     while (st.hasMoreTokens())
1577     {
1578       String keyValue = st.nextToken();
1579       String key = keyValue.substring(0, keyValue.indexOf("="));
1580       String value = keyValue.substring(keyValue.indexOf("=") + 1);
1581       properties.put(key, value);
1582     }
1583
1584     for (SequenceGroup sg : al.getGroups())
1585     {
1586       if (sg.getName().equals(name))
1587       {
1588         addProperties(sg, properties, al);
1589       }
1590     }
1591   }
1592
1593   /**
1594    * Helper method that applies any specified properties to a SequenceGroup
1595    * 
1596    * @param sg
1597    * @param properties
1598    * @param al
1599    */
1600   private void addProperties(SequenceGroup sg,
1601           Map<String, String> properties, AlignmentI al)
1602   {
1603     ColourSchemeI def = sg.getColourScheme();
1604     for (String key : properties.keySet())
1605     {
1606       String value = properties.get(key);
1607       if (key.equalsIgnoreCase("description"))
1608       {
1609         sg.setDescription(value);
1610       }
1611       else if (key.equalsIgnoreCase("colour"))
1612       {
1613         // TODO need to notify colourscheme of view reference once it is
1614         // available
1615         sg.cs.setColourScheme(
1616                 ColourSchemeProperty.getColourScheme(null, al, value));
1617       }
1618       else if (key.equalsIgnoreCase("pidThreshold"))
1619       {
1620         sg.cs.setThreshold(Integer.parseInt(value), true);
1621
1622       }
1623       else if (key.equalsIgnoreCase("consThreshold"))
1624       {
1625         sg.cs.setConservationInc(Integer.parseInt(value));
1626         Conservation c = new Conservation("Group", sg.getSequences(null),
1627                 sg.getStartRes(), sg.getEndRes() + 1);
1628
1629         c.calculate();
1630         c.verdict(false, 25); // TODO: refer to conservation percent threshold
1631
1632         sg.cs.setConservation(c);
1633
1634       }
1635       else if (key.equalsIgnoreCase("outlineColour"))
1636       {
1637         sg.setOutlineColour(ColorUtils.parseColourString(value));
1638       }
1639       else if (key.equalsIgnoreCase("displayBoxes"))
1640       {
1641         sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1642       }
1643       else if (key.equalsIgnoreCase("showUnconserved"))
1644       {
1645         sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1646       }
1647       else if (key.equalsIgnoreCase("displayText"))
1648       {
1649         sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1650       }
1651       else if (key.equalsIgnoreCase("colourText"))
1652       {
1653         sg.setColourText(Boolean.valueOf(value).booleanValue());
1654       }
1655       else if (key.equalsIgnoreCase("textCol1"))
1656       {
1657         sg.textColour = ColorUtils.parseColourString(value);
1658       }
1659       else if (key.equalsIgnoreCase("textCol2"))
1660       {
1661         sg.textColour2 = ColorUtils.parseColourString(value);
1662       }
1663       else if (key.equalsIgnoreCase("textColThreshold"))
1664       {
1665         sg.thresholdTextColour = Integer.parseInt(value);
1666       }
1667       else if (key.equalsIgnoreCase("idColour"))
1668       {
1669         Color idColour = ColorUtils.parseColourString(value);
1670         sg.setIdColour(idColour == null ? Color.black : idColour);
1671       }
1672       else if (key.equalsIgnoreCase("hide"))
1673       {
1674         // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1675         sg.setHidereps(true);
1676       }
1677       else if (key.equalsIgnoreCase("hidecols"))
1678       {
1679         // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1680         sg.setHideCols(true);
1681       }
1682       sg.recalcConservation();
1683     }
1684
1685     if (sg.getColourScheme() == null)
1686     {
1687       sg.setColourScheme(def);
1688     }
1689   }
1690
1691   void setBelowAlignment(AlignmentI al, StringTokenizer st)
1692   {
1693     String token;
1694     AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1695     if (ala == null)
1696     {
1697       System.err.print(
1698               "Warning - no annotation to set below for sequence associated annotation:");
1699     }
1700     while (st.hasMoreTokens())
1701     {
1702       token = st.nextToken();
1703       if (ala == null)
1704       {
1705         System.err.print(" " + token);
1706       }
1707       else
1708       {
1709         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1710         {
1711           aa = al.getAlignmentAnnotation()[i];
1712           if (aa.sequenceRef == refSeq && aa.label.equals(token))
1713           {
1714             aa.belowAlignment = true;
1715           }
1716         }
1717       }
1718     }
1719     if (ala == null)
1720     {
1721       System.err.print("\n");
1722     }
1723   }
1724
1725   void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1726   {
1727     String keyValue, key, value;
1728     while (st.hasMoreTokens())
1729     {
1730       keyValue = st.nextToken();
1731       key = keyValue.substring(0, keyValue.indexOf("="));
1732       value = keyValue.substring(keyValue.indexOf("=") + 1);
1733       al.setProperty(key, value);
1734     }
1735   }
1736
1737   /**
1738    * Write annotations as a CSV file of the form 'label, value, value, ...' for
1739    * each row.
1740    * 
1741    * @param annotations
1742    * @return CSV file as a string.
1743    */
1744   public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1745   {
1746     if (annotations == null)
1747     {
1748       return "";
1749     }
1750     StringBuffer sp = new StringBuffer();
1751     for (int i = 0; i < annotations.length; i++)
1752     {
1753       String atos = annotations[i].toString();
1754       int p = 0;
1755       do
1756       {
1757         int cp = atos.indexOf("\n", p);
1758         sp.append(annotations[i].label);
1759         sp.append(",");
1760         if (cp > p)
1761         {
1762           sp.append(atos.substring(p, cp + 1));
1763         }
1764         else
1765         {
1766           sp.append(atos.substring(p));
1767           sp.append(newline);
1768         }
1769         p = cp + 1;
1770       } while (p > 0);
1771     }
1772     return sp.toString();
1773   }
1774
1775   public String printAnnotationsForView(AlignViewportI viewport)
1776   {
1777     return printAnnotations(
1778             viewport.isShowAnnotation()
1779                     ? viewport.getAlignment().getAlignmentAnnotation()
1780                     : null,
1781             viewport.getAlignment().getGroups(),
1782             viewport.getAlignment().getProperties(),
1783             viewport.getAlignment().getHiddenColumns(),
1784             viewport.getAlignment(), null);
1785   }
1786
1787   public String printAnnotationsForAlignment(AlignmentI al)
1788   {
1789     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1790             al.getProperties(), null, al, null);
1791   }
1792 }