JAL-2489 JAL-2371 reinstate calls to
[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.util.ColorUtils;
36
37 import java.awt.Color;
38 import java.io.BufferedReader;
39 import java.io.FileReader;
40 import java.io.InputStreamReader;
41 import java.io.StringReader;
42 import java.net.URL;
43 import java.util.ArrayList;
44 import java.util.BitSet;
45 import java.util.Enumeration;
46 import java.util.Hashtable;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
51
52 public class AnnotationFile
53 {
54   public AnnotationFile()
55   {
56     init();
57   }
58
59   /**
60    * character used to write newlines
61    */
62   protected String newline = System.getProperty("line.separator");
63
64   /**
65    * set new line string and reset the output buffer
66    * 
67    * @param nl
68    */
69   public void setNewlineString(String nl)
70   {
71     newline = nl;
72     init();
73   }
74
75   public String getNewlineString()
76   {
77     return newline;
78   }
79
80   StringBuffer text;
81
82   private void init()
83   {
84     text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
85             + new java.util.Date() + newline + newline);
86     refSeq = null;
87     refSeqId = null;
88   }
89
90   /**
91    * convenience method for pre-2.9 annotation files which have no view, hidden
92    * columns or hidden row keywords.
93    * 
94    * @param annotations
95    * @param list
96    * @param properties
97    * @return annotation file as a string.
98    */
99   public String printAnnotations(AlignmentAnnotation[] annotations,
100           List<SequenceGroup> list, Hashtable properties)
101   {
102     return printAnnotations(annotations, list, properties, null, null, null);
103
104   }
105
106   /**
107    * hold all the information about a particular view definition read from or
108    * written out in an annotations file.
109    */
110   public class ViewDef
111   {
112     // TODO this class is not used - remove?
113     public final String viewname;
114
115     public final HiddenSequences hidseqs;
116
117     public final ColumnSelection hiddencols;
118
119     // public final Vector visibleGroups;
120
121     public final Hashtable hiddenRepSeqs;
122
123     public ViewDef(String vname, HiddenSequences hseqs,
124             ColumnSelection hcols, Hashtable hRepSeqs)
125     {
126       this.viewname = vname;
127       this.hidseqs = hseqs;
128       this.hiddencols = hcols;
129       this.hiddenRepSeqs = hRepSeqs;
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   protected 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(ColourSchemeProperty.getColourName(sg.cs
587                 .getColourScheme()));
588         text.append("\t");
589         if (sg.cs.getThreshold() != 0)
590         {
591           text.append("pidThreshold=");
592           text.append(sg.cs.getThreshold());
593         }
594         if (sg.cs.conservationApplied())
595         {
596           text.append("consThreshold=");
597           text.append(sg.cs.getConservationInc());
598           text.append("\t");
599         }
600       }
601       text.append("outlineColour=");
602       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
603       text.append("\t");
604
605       text.append("displayBoxes=");
606       text.append(sg.getDisplayBoxes());
607       text.append("\t");
608       text.append("displayText=");
609       text.append(sg.getDisplayText());
610       text.append("\t");
611       text.append("colourText=");
612       text.append(sg.getColourText());
613       text.append("\t");
614       text.append("showUnconserved=");
615       text.append(sg.getShowNonconserved());
616       text.append("\t");
617       if (sg.textColour != java.awt.Color.black)
618       {
619         text.append("textCol1=");
620         text.append(jalview.util.Format.getHexString(sg.textColour));
621         text.append("\t");
622       }
623       if (sg.textColour2 != java.awt.Color.white)
624       {
625         text.append("textCol2=");
626         text.append(jalview.util.Format.getHexString(sg.textColour2));
627         text.append("\t");
628       }
629       if (sg.thresholdTextColour != 0)
630       {
631         text.append("textColThreshold=");
632         text.append(sg.thresholdTextColour);
633         text.append("\t");
634       }
635       if (sg.idColour != null)
636       {
637         text.append("idColour=");
638         text.append(jalview.util.Format.getHexString(sg.idColour));
639         text.append("\t");
640       }
641       if (sg.isHidereps())
642       {
643         text.append("hide=true\t");
644       }
645       if (sg.isHideCols())
646       {
647         text.append("hidecols=true\t");
648       }
649       if (seqrep != null)
650       {
651         // terminate the last line and clear the sequence ref for the group
652         text.append(newline);
653         text.append("SEQUENCE_REF");
654       }
655       text.append(newline);
656       text.append(newline);
657
658     }
659   }
660
661   SequenceI refSeq = null;
662
663   String refSeqId = null;
664
665   public boolean annotateAlignmentView(AlignViewportI viewport,
666           String file, DataSourceType protocol)
667   {
668     ColumnSelection colSel = viewport.getColumnSelection();
669     if (colSel == null)
670     {
671       colSel = new ColumnSelection();
672     }
673     boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
674             file, protocol);
675     if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
676     {
677       viewport.setColumnSelection(colSel);
678     }
679
680     return rslt;
681   }
682
683   public boolean readAnnotationFile(AlignmentI al, String file,
684           DataSourceType sourceType)
685   {
686     return readAnnotationFile(al, null, file, sourceType);
687   }
688
689   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
690           String file, DataSourceType sourceType)
691   {
692     BufferedReader in = null;
693     try
694     {
695       if (sourceType == DataSourceType.FILE)
696       {
697         in = new BufferedReader(new FileReader(file));
698       }
699       else if (sourceType == DataSourceType.URL)
700       {
701         URL url = new URL(file);
702         in = new BufferedReader(new InputStreamReader(url.openStream()));
703       }
704       else if (sourceType == DataSourceType.PASTE)
705       {
706         in = new BufferedReader(new StringReader(file));
707       }
708       else if (sourceType == DataSourceType.CLASSLOADER)
709       {
710         java.io.InputStream is = getClass().getResourceAsStream("/" + file);
711         if (is != null)
712         {
713           in = new BufferedReader(new java.io.InputStreamReader(is));
714         }
715       }
716       if (in != null)
717       {
718         return parseAnnotationFrom(al, colSel, in);
719       }
720
721     } catch (Exception ex)
722     {
723       ex.printStackTrace();
724       System.out.println("Problem reading annotation file: " + ex);
725       if (nlinesread > 0)
726       {
727         System.out.println("Last read line " + nlinesread + ": '"
728                 + lastread + "' (first 80 chars) ...");
729       }
730       return false;
731     }
732     return false;
733   }
734
735   long nlinesread = 0;
736
737   String lastread = "";
738
739   private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
740
741   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
742           BufferedReader in) throws Exception
743   {
744     nlinesread = 0;
745     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
746     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
747     boolean modified = false;
748     String groupRef = null;
749     Hashtable groupRefRows = new Hashtable();
750
751     Hashtable autoAnnots = new Hashtable();
752     {
753       String line, label, description, token;
754       int graphStyle, index;
755       int refSeqIndex = 1;
756       int existingAnnotations = 0;
757       // when true - will add new rows regardless of whether they are duplicate
758       // auto-annotation like consensus or conservation graphs
759       boolean overrideAutoAnnot = false;
760       if (al.getAlignmentAnnotation() != null)
761       {
762         existingAnnotations = al.getAlignmentAnnotation().length;
763         if (existingAnnotations > 0)
764         {
765           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
766           for (int aai = 0; aai < aa.length; aai++)
767           {
768             if (aa[aai].autoCalculated)
769             {
770               // make a note of the name and description
771               autoAnnots.put(
772                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
773                               (aa[aai].groupRef == null ? null
774                                       : aa[aai].groupRef.getName())),
775                       new Integer(1));
776             }
777           }
778         }
779       }
780
781       int alWidth = al.getWidth();
782
783       StringTokenizer st;
784       Annotation[] annotations;
785       AlignmentAnnotation annotation = null;
786
787       // First confirm this is an Annotation file
788       boolean jvAnnotationFile = false;
789       while ((line = in.readLine()) != null)
790       {
791         nlinesread++;
792         lastread = new String(line);
793         if (line.indexOf("#") == 0)
794         {
795           continue;
796         }
797
798         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
799         {
800           jvAnnotationFile = true;
801           break;
802         }
803       }
804
805       if (!jvAnnotationFile)
806       {
807         in.close();
808         return false;
809       }
810
811       while ((line = in.readLine()) != null)
812       {
813         nlinesread++;
814         lastread = new String(line);
815         if (line.indexOf("#") == 0
816                 || line.indexOf("JALVIEW_ANNOTATION") > -1
817                 || line.length() == 0)
818         {
819           continue;
820         }
821
822         st = new StringTokenizer(line, "\t");
823         token = st.nextToken();
824         if (token.equalsIgnoreCase("COLOUR"))
825         {
826           // TODO: use graduated colour def'n here too
827           colourAnnotations(al, st.nextToken(), st.nextToken());
828           modified = true;
829           continue;
830         }
831
832         else if (token.equalsIgnoreCase(COMBINE))
833         {
834           // keep a record of current state and resolve groupRef at end
835           combineAnnotation_calls
836                   .add(new Object[] { st, refSeq, groupRef });
837           modified = true;
838           continue;
839         }
840         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
841         {
842           addRowProperties(al, st);
843           modified = true;
844           continue;
845         }
846         else if (token.equalsIgnoreCase(GRAPHLINE))
847         {
848           // resolve at end
849           deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
850               refSeq, groupRef });
851           modified = true;
852           continue;
853         }
854
855         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
856         {
857           if (st.hasMoreTokens())
858           {
859             refSeq = al.findName(refSeqId = st.nextToken());
860             if (refSeq == null)
861             {
862               refSeqId = null;
863             }
864             try
865             {
866               refSeqIndex = Integer.parseInt(st.nextToken());
867               if (refSeqIndex < 1)
868               {
869                 refSeqIndex = 1;
870                 System.out
871                         .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
872               }
873             } catch (Exception ex)
874             {
875               refSeqIndex = 1;
876             }
877           }
878           else
879           {
880             refSeq = null;
881             refSeqId = null;
882           }
883           continue;
884         }
885         else if (token.equalsIgnoreCase("GROUP_REF"))
886         {
887           // Group references could be forward or backwards, so they are
888           // resolved after the whole file is read in
889           groupRef = null;
890           if (st.hasMoreTokens())
891           {
892             groupRef = st.nextToken();
893             if (groupRef.length() < 1)
894             {
895               groupRef = null; // empty string
896             }
897             else
898             {
899               if (groupRefRows.get(groupRef) == null)
900               {
901                 groupRefRows.put(groupRef, new Vector());
902               }
903             }
904           }
905           continue;
906         }
907         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
908         {
909           addGroup(al, st);
910           modified = true;
911           continue;
912         }
913
914         else if (token.equalsIgnoreCase("PROPERTIES"))
915         {
916           addProperties(al, st);
917           modified = true;
918           continue;
919         }
920
921         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
922         {
923           setBelowAlignment(al, st);
924           modified = true;
925           continue;
926         }
927         else if (token.equalsIgnoreCase("ALIGNMENT"))
928         {
929           addAlignmentDetails(al, st);
930           modified = true;
931           continue;
932         }
933         // else if (token.equalsIgnoreCase("VIEW_DEF"))
934         // {
935         // addOrSetView(al,st);
936         // modified = true;
937         // continue;
938         // }
939         else if (token.equalsIgnoreCase("VIEW_SETREF"))
940         {
941           if (refSeq != null)
942           {
943             al.setSeqrep(refSeq);
944           }
945           modified = true;
946           continue;
947         }
948         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
949         {
950           if (st.hasMoreTokens())
951           {
952             if (colSel == null)
953             {
954               colSel = new ColumnSelection();
955             }
956             parseHideCols(colSel, st.nextToken());
957           }
958           modified = true;
959           continue;
960         }
961         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
962         {
963           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
964           if (sr == null)
965           {
966             sr = al.getSequenceAt(0);
967           }
968           if (sr != null)
969           {
970             if (colSel == null)
971             {
972               System.err
973                       .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
974                               + line);
975             }
976             else
977             {
978               // consider deferring this till after the file has been parsed ?
979               colSel.hideInsertionsFor(sr);
980             }
981           }
982           modified = true;
983           continue;
984         }
985
986         // Parse out the annotation row
987         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
988         label = st.nextToken();
989
990         index = 0;
991         annotations = new Annotation[alWidth];
992         description = null;
993         float score = Float.NaN;
994
995         if (st.hasMoreTokens())
996         {
997           line = st.nextToken();
998
999           if (line.indexOf("|") == -1)
1000           {
1001             description = line;
1002             if (st.hasMoreTokens())
1003             {
1004               line = st.nextToken();
1005             }
1006           }
1007
1008           if (st.hasMoreTokens())
1009           {
1010             // This must be the score
1011             score = Float.valueOf(st.nextToken()).floatValue();
1012           }
1013
1014           st = new StringTokenizer(line, "|", true);
1015
1016           boolean emptyColumn = true;
1017           boolean onlyOneElement = (st.countTokens() == 1);
1018
1019           while (st.hasMoreElements() && index < alWidth)
1020           {
1021             token = st.nextToken().trim();
1022
1023             if (onlyOneElement)
1024             {
1025               try
1026               {
1027                 score = Float.valueOf(token).floatValue();
1028                 break;
1029               } catch (NumberFormatException ex)
1030               {
1031               }
1032             }
1033
1034             if (token.equals("|"))
1035             {
1036               if (emptyColumn)
1037               {
1038                 index++;
1039               }
1040
1041               emptyColumn = true;
1042             }
1043             else
1044             {
1045               annotations[index++] = parseAnnotation(token, graphStyle);
1046               emptyColumn = false;
1047             }
1048           }
1049
1050         }
1051
1052         annotation = new AlignmentAnnotation(label, description,
1053                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1054
1055         annotation.score = score;
1056         if (!overrideAutoAnnot
1057                 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1058                         groupRef)))
1059         {
1060           // skip - we've already got an automatic annotation of this type.
1061           continue;
1062         }
1063         // otherwise add it!
1064         if (refSeq != null)
1065         {
1066
1067           annotation.belowAlignment = false;
1068           // make a copy of refSeq so we can find other matches in the alignment
1069           SequenceI referedSeq = refSeq;
1070           do
1071           {
1072             // copy before we do any mapping business.
1073             // TODO: verify that undo/redo with 1:many sequence associated
1074             // annotations can be undone correctly
1075             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1076             annotation
1077                     .createSequenceMapping(referedSeq, refSeqIndex, false);
1078             annotation.adjustForAlignment();
1079             referedSeq.addAlignmentAnnotation(annotation);
1080             al.addAnnotation(annotation);
1081             al.setAnnotationIndex(annotation,
1082                     al.getAlignmentAnnotation().length
1083                             - existingAnnotations - 1);
1084             if (groupRef != null)
1085             {
1086               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1087             }
1088             // and recover our virgin copy to use again if necessary.
1089             annotation = ann;
1090
1091           } while (refSeqId != null
1092                   && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1093         }
1094         else
1095         {
1096           al.addAnnotation(annotation);
1097           al.setAnnotationIndex(annotation,
1098                   al.getAlignmentAnnotation().length - existingAnnotations
1099                           - 1);
1100           if (groupRef != null)
1101           {
1102             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1103           }
1104         }
1105         // and set modification flag
1106         modified = true;
1107       }
1108       // Resolve the groupRefs
1109       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1110       Enumeration en = groupRefRows.keys();
1111
1112       while (en.hasMoreElements())
1113       {
1114         groupRef = (String) en.nextElement();
1115         boolean matched = false;
1116         // Resolve group: TODO: add a getGroupByName method to alignments
1117         for (SequenceGroup theGroup : al.getGroups())
1118         {
1119           if (theGroup.getName().equals(groupRef))
1120           {
1121             if (matched)
1122             {
1123               // TODO: specify and implement duplication of alignment annotation
1124               // for multiple group references.
1125               System.err
1126                       .println("Ignoring 1:many group reference mappings for group name '"
1127                               + groupRef + "'");
1128             }
1129             else
1130             {
1131               matched = true;
1132               Vector rowset = (Vector) groupRefRows.get(groupRef);
1133               groupRefLookup.put(groupRef, theGroup);
1134               if (rowset != null && rowset.size() > 0)
1135               {
1136                 AlignmentAnnotation alan = null;
1137                 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1138                 {
1139                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1140                   alan.groupRef = theGroup;
1141                 }
1142               }
1143             }
1144           }
1145         }
1146         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1147       }
1148       // process any deferred attribute settings for each context
1149       for (Object[] _deferred_args : deferredAnnotation_calls)
1150       {
1151         if (_deferred_args[0] == GRAPHLINE)
1152         {
1153           addLine(al,
1154                   (StringTokenizer) _deferred_args[1], // st
1155                   (SequenceI) _deferred_args[2], // refSeq
1156                   (_deferred_args[3] == null) ? null : groupRefLookup
1157                           .get(_deferred_args[3]) // the reference
1158                                                   // group, or null
1159           );
1160         }
1161       }
1162
1163       // finally, combine all the annotation rows within each context.
1164       /**
1165        * number of combine statements in this annotation file. Used to create
1166        * new groups for combined annotation graphs without disturbing existing
1167        * ones
1168        */
1169       int combinecount = 0;
1170       for (Object[] _combine_args : combineAnnotation_calls)
1171       {
1172         combineAnnotations(al,
1173                 ++combinecount,
1174                 (StringTokenizer) _combine_args[0], // st
1175                 (SequenceI) _combine_args[1], // refSeq
1176                 (_combine_args[2] == null) ? null : groupRefLookup
1177                         .get(_combine_args[2]) // the reference group,
1178                                                // or null
1179         );
1180       }
1181     }
1182     return modified;
1183   }
1184
1185   private void parseHideCols(ColumnSelection colSel, String nextToken)
1186   {
1187     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1188     while (inval.hasMoreTokens())
1189     {
1190       String range = inval.nextToken().trim();
1191       int from, to = range.indexOf("-");
1192       if (to == -1)
1193       {
1194         from = to = Integer.parseInt(range);
1195         if (from >= 0)
1196         {
1197           colSel.hideColumns(from, to);
1198         }
1199       }
1200       else
1201       {
1202         from = Integer.parseInt(range.substring(0, to));
1203         if (to < range.length() - 1)
1204         {
1205           to = Integer.parseInt(range.substring(to + 1));
1206         }
1207         else
1208         {
1209           to = from;
1210         }
1211         if (from > 0 && to >= from)
1212         {
1213           colSel.hideColumns(from, to);
1214         }
1215       }
1216     }
1217   }
1218
1219   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1220           SequenceI refSeq, String groupRef)
1221   {
1222     return annotation.graph + "\t" + annotation.label + "\t"
1223             + annotation.description + "\t"
1224             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1225   }
1226
1227   Annotation parseAnnotation(String string, int graphStyle)
1228   {
1229     // don't do the glyph test if we don't want secondary structure
1230     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1231     String desc = null, displayChar = null;
1232     char ss = ' '; // secondaryStructure
1233     float value = 0;
1234     boolean parsedValue = false, dcset = false;
1235
1236     // find colour here
1237     Color colour = null;
1238     int i = string.indexOf("[");
1239     int j = string.indexOf("]");
1240     if (i > -1 && j > -1)
1241     {
1242       colour = ColorUtils.parseColourString(string.substring(i + 1,
1243               j));
1244       if (i > 0 && string.charAt(i - 1) == ',')
1245       {
1246         // clip the preceding comma as well
1247         i--;
1248       }
1249       string = string.substring(0, i) + string.substring(j + 1);
1250     }
1251
1252     StringTokenizer st = new StringTokenizer(string, ",", true);
1253     String token;
1254     boolean seenContent = false;
1255     int pass = 0;
1256     while (st.hasMoreTokens())
1257     {
1258       pass++;
1259       token = st.nextToken().trim();
1260       if (token.equals(","))
1261       {
1262         if (!seenContent && parsedValue && !dcset)
1263         {
1264           // allow the value below the bar/line to be empty
1265           dcset = true;
1266           displayChar = " ";
1267         }
1268         seenContent = false;
1269         continue;
1270       }
1271       else
1272       {
1273         seenContent = true;
1274       }
1275
1276       if (!parsedValue)
1277       {
1278         try
1279         {
1280           displayChar = token;
1281           // foo
1282           value = new Float(token).floatValue();
1283           parsedValue = true;
1284           continue;
1285         } catch (NumberFormatException ex)
1286         {
1287         }
1288       }
1289       else
1290       {
1291         if (token.length() == 1)
1292         {
1293           displayChar = token;
1294         }
1295       }
1296       if (hasSymbols
1297               && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1298                       .contains(token)))
1299       {
1300         // Either this character represents a helix or sheet
1301         // or an integer which can be displayed
1302         ss = token.charAt(0);
1303         if (displayChar.equals(token.substring(0, 1)))
1304         {
1305           displayChar = "";
1306         }
1307       }
1308       else if (desc == null || (parsedValue && pass > 2))
1309       {
1310         desc = token;
1311       }
1312
1313     }
1314     // if (!dcset && string.charAt(string.length() - 1) == ',')
1315     // {
1316     // displayChar = " "; // empty display char symbol.
1317     // }
1318     if (displayChar != null && desc != null && desc.length() == 1)
1319     {
1320       if (displayChar.length() > 1)
1321       {
1322         // switch desc and displayChar - legacy support
1323         String tmp = displayChar;
1324         displayChar = desc;
1325         desc = tmp;
1326       }
1327       else
1328       {
1329         if (displayChar.equals(desc))
1330         {
1331           // duplicate label - hangover from the 'robust parser' above
1332           desc = null;
1333         }
1334       }
1335     }
1336     Annotation anot = new Annotation(displayChar, desc, ss, value);
1337
1338     anot.colour = colour;
1339
1340     return anot;
1341   }
1342
1343   void colourAnnotations(AlignmentI al, String label, String colour)
1344   {
1345     Color awtColour = ColorUtils.parseColourString(colour);
1346     Annotation[] annotations;
1347     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1348     {
1349       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1350       {
1351         annotations = al.getAlignmentAnnotation()[i].annotations;
1352         for (int j = 0; j < annotations.length; j++)
1353         {
1354           if (annotations[j] != null)
1355           {
1356             annotations[j].colour = awtColour;
1357           }
1358         }
1359       }
1360     }
1361   }
1362
1363   void combineAnnotations(AlignmentI al, int combineCount,
1364           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1365   {
1366     String group = st.nextToken();
1367     // First make sure we are not overwriting the graphIndex
1368     int graphGroup = 0;
1369     if (al.getAlignmentAnnotation() != null)
1370     {
1371       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1372       {
1373         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1374
1375         if (aa.graphGroup > graphGroup)
1376         {
1377           // try to number graphGroups in order of occurence.
1378           graphGroup = aa.graphGroup + 1;
1379         }
1380         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1381                 && aa.label.equalsIgnoreCase(group))
1382         {
1383           if (aa.graphGroup > -1)
1384           {
1385             graphGroup = aa.graphGroup;
1386           }
1387           else
1388           {
1389             if (graphGroup <= combineCount)
1390             {
1391               graphGroup = combineCount + 1;
1392             }
1393             aa.graphGroup = graphGroup;
1394           }
1395           break;
1396         }
1397       }
1398
1399       // Now update groups
1400       while (st.hasMoreTokens())
1401       {
1402         group = st.nextToken();
1403         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1404         {
1405           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1406           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1407                   && aa.label.equalsIgnoreCase(group))
1408           {
1409             aa.graphGroup = graphGroup;
1410             break;
1411           }
1412         }
1413       }
1414     }
1415     else
1416     {
1417       System.err
1418               .println("Couldn't combine annotations. None are added to alignment yet!");
1419     }
1420   }
1421
1422   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1423           SequenceGroup groupRef)
1424   {
1425     String group = st.nextToken();
1426     AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1427     String nextToken = st.nextToken();
1428     float value = 0f;
1429     try
1430     {
1431       value = Float.valueOf(nextToken);
1432     } catch (NumberFormatException e)
1433     {
1434       System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1435               + "' invalid, setting to zero");
1436     }
1437     String label = st.hasMoreTokens() ? st.nextToken() : null;
1438     Color colour = null;
1439     if (st.hasMoreTokens())
1440     {
1441       colour = ColorUtils.parseColourString(st.nextToken());
1442     }
1443     if (alannot != null)
1444     {
1445       for (int i = 0; i < alannot.length; i++)
1446       {
1447         if (alannot[i].label.equalsIgnoreCase(group)
1448                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1449                 && (groupRef == null || alannot[i].groupRef == groupRef))
1450         {
1451           alannot[i].setThreshold(new GraphLine(value, label, colour));
1452         }
1453       }
1454     }
1455   }
1456
1457   void addGroup(AlignmentI al, StringTokenizer st)
1458   {
1459     SequenceGroup sg = new SequenceGroup();
1460     sg.setName(st.nextToken());
1461     String rng = "";
1462     try
1463     {
1464       rng = st.nextToken();
1465       if (rng.length() > 0 && !rng.startsWith("*"))
1466       {
1467         sg.setStartRes(Integer.parseInt(rng) - 1);
1468       }
1469       else
1470       {
1471         sg.setStartRes(0);
1472       }
1473       rng = st.nextToken();
1474       if (rng.length() > 0 && !rng.startsWith("*"))
1475       {
1476         sg.setEndRes(Integer.parseInt(rng) - 1);
1477       }
1478       else
1479       {
1480         sg.setEndRes(al.getWidth() - 1);
1481       }
1482     } catch (Exception e)
1483     {
1484       System.err
1485               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1486                       + rng + "' - assuming alignment width for group.");
1487       // assume group is full width
1488       sg.setStartRes(0);
1489       sg.setEndRes(al.getWidth() - 1);
1490     }
1491
1492     String index = st.nextToken();
1493     if (index.equals("-1"))
1494     {
1495       while (st.hasMoreElements())
1496       {
1497         sg.addSequence(al.findName(st.nextToken()), false);
1498       }
1499     }
1500     else
1501     {
1502       StringTokenizer st2 = new StringTokenizer(index, ",");
1503
1504       while (st2.hasMoreTokens())
1505       {
1506         String tmp = st2.nextToken();
1507         if (tmp.equals("*"))
1508         {
1509           for (int i = 0; i < al.getHeight(); i++)
1510           {
1511             sg.addSequence(al.getSequenceAt(i), false);
1512           }
1513         }
1514         else if (tmp.indexOf("-") >= 0)
1515         {
1516           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1517
1518           int start = (Integer.parseInt(st3.nextToken()));
1519           int end = (Integer.parseInt(st3.nextToken()));
1520
1521           if (end > start)
1522           {
1523             for (int i = start; i <= end; i++)
1524             {
1525               sg.addSequence(al.getSequenceAt(i - 1), false);
1526             }
1527           }
1528         }
1529         else
1530         {
1531           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1532         }
1533       }
1534     }
1535
1536     if (refSeq != null)
1537     {
1538       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1539       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1540       sg.setSeqrep(refSeq);
1541     }
1542
1543     if (sg.getSize() > 0)
1544     {
1545       al.addGroup(sg);
1546     }
1547   }
1548
1549   void addRowProperties(AlignmentI al, StringTokenizer st)
1550   {
1551     String label = st.nextToken(), keyValue, key, value;
1552     boolean scaletofit = false, centerlab = false, showalllabs = false;
1553     while (st.hasMoreTokens())
1554     {
1555       keyValue = st.nextToken();
1556       key = keyValue.substring(0, keyValue.indexOf("="));
1557       value = keyValue.substring(keyValue.indexOf("=") + 1);
1558       if (key.equalsIgnoreCase("scaletofit"))
1559       {
1560         scaletofit = Boolean.valueOf(value).booleanValue();
1561       }
1562       if (key.equalsIgnoreCase("showalllabs"))
1563       {
1564         showalllabs = Boolean.valueOf(value).booleanValue();
1565       }
1566       if (key.equalsIgnoreCase("centrelabs"))
1567       {
1568         centerlab = Boolean.valueOf(value).booleanValue();
1569       }
1570       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1571       if (alr != null)
1572       {
1573         for (int i = 0; i < alr.length; i++)
1574         {
1575           if (alr[i].label.equalsIgnoreCase(label))
1576           {
1577             alr[i].centreColLabels = centerlab;
1578             alr[i].scaleColLabel = scaletofit;
1579             alr[i].showAllColLabels = showalllabs;
1580           }
1581         }
1582       }
1583     }
1584   }
1585
1586   void addProperties(AlignmentI al, StringTokenizer st)
1587   {
1588
1589     // So far we have only added groups to the annotationHash,
1590     // the idea is in the future properties can be added to
1591     // alignments, other annotations etc
1592     if (al.getGroups() == null)
1593     {
1594       return;
1595     }
1596
1597     String name = st.nextToken();
1598     SequenceGroup sg = null;
1599     for (SequenceGroup _sg : al.getGroups())
1600     {
1601       if ((sg = _sg).getName().equals(name))
1602       {
1603         break;
1604       }
1605       else
1606       {
1607         sg = null;
1608       }
1609     }
1610
1611     if (sg != null)
1612     {
1613       String keyValue, key, value;
1614       ColourSchemeI def = sg.getColourScheme();
1615       while (st.hasMoreTokens())
1616       {
1617         keyValue = st.nextToken();
1618         key = keyValue.substring(0, keyValue.indexOf("="));
1619         value = keyValue.substring(keyValue.indexOf("=") + 1);
1620
1621         if (key.equalsIgnoreCase("description"))
1622         {
1623           sg.setDescription(value);
1624         }
1625         else if (key.equalsIgnoreCase("colour"))
1626         {
1627           sg.cs.setColourScheme(ColourSchemeProperty
1628                   .getColourScheme(al, value));
1629         }
1630         else if (key.equalsIgnoreCase("pidThreshold"))
1631         {
1632           sg.cs.setThreshold(Integer.parseInt(value), true);
1633
1634         }
1635         else if (key.equalsIgnoreCase("consThreshold"))
1636         {
1637           sg.cs.setConservationInc(Integer.parseInt(value));
1638           Conservation c = new Conservation("Group", sg.getSequences(null),
1639                   sg.getStartRes(), sg.getEndRes() + 1);
1640
1641           c.calculate();
1642           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1643
1644           sg.cs.setConservation(c);
1645
1646         }
1647         else if (key.equalsIgnoreCase("outlineColour"))
1648         {
1649           sg.setOutlineColour(ColorUtils.parseColourString(value));
1650         }
1651         else if (key.equalsIgnoreCase("displayBoxes"))
1652         {
1653           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1654         }
1655         else if (key.equalsIgnoreCase("showUnconserved"))
1656         {
1657           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1658         }
1659         else if (key.equalsIgnoreCase("displayText"))
1660         {
1661           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1662         }
1663         else if (key.equalsIgnoreCase("colourText"))
1664         {
1665           sg.setColourText(Boolean.valueOf(value).booleanValue());
1666         }
1667         else if (key.equalsIgnoreCase("textCol1"))
1668         {
1669           sg.textColour = ColorUtils.parseColourString(value);
1670         }
1671         else if (key.equalsIgnoreCase("textCol2"))
1672         {
1673           sg.textColour2 = ColorUtils.parseColourString(value);
1674         }
1675         else if (key.equalsIgnoreCase("textColThreshold"))
1676         {
1677           sg.thresholdTextColour = Integer.parseInt(value);
1678         }
1679         else if (key.equalsIgnoreCase("idColour"))
1680         {
1681           Color idColour = ColorUtils.parseColourString(value);
1682           sg.setIdColour(idColour == null ? Color.black : idColour);
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 }