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