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