JAL-1683 replace year/version strings with tokens in source
[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.ResidueProperties;
36 import jalview.schemes.UserColourScheme;
37
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.8.3 annotation files which have no view,
92    * hidden 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     public String viewname;
113
114     public HiddenSequences hidseqs;
115
116     public ColumnSelection hiddencols;
117
118     public Vector visibleGroups;
119
120     public Hashtable hiddenRepSeqs;
121
122     public ViewDef(String viewname, HiddenSequences hidseqs,
123             ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
124     {
125       this.viewname = viewname;
126       this.hidseqs = hidseqs;
127       this.hiddencols = hiddencols;
128       this.hiddenRepSeqs = hiddenRepSeqs;
129     }
130   }
131
132   /**
133    * Prepare an annotation file given a set of annotations, groups, alignment
134    * properties and views.
135    * 
136    * @param annotations
137    * @param list
138    * @param properties
139    * @param views
140    * @return annotation file
141    */
142   public String printAnnotations(AlignmentAnnotation[] annotations,
143           List<SequenceGroup> list, Hashtable properties,
144           ColumnSelection cs, AlignmentI al, ViewDef view)
145   {
146     if (view != null)
147     {
148       if (view.viewname != null)
149       {
150         text.append("VIEW_DEF\t" + view.viewname + "\n");
151       }
152       if (list == null)
153       {
154         list = view.visibleGroups;
155       }
156       if (cs == null)
157       {
158         cs = view.hiddencols;
159       }
160       if (al == null)
161       {
162         // add hidden rep sequences.
163       }
164     }
165     // first target - store and restore all settings for a view.
166     if (al != null && al.hasSeqrep())
167     {
168       text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
169     }
170     if (cs != null && cs.hasHiddenColumns())
171     {
172       text.append("VIEW_HIDECOLS\t");
173       List<int[]> hc = cs.getHiddenColumns();
174       boolean comma = false;
175       for (int[] r : hc)
176       {
177         if (!comma)
178         {
179           comma = true;
180         }
181         else
182         {
183           text.append(",");
184         }
185         text.append(r[0]);
186         text.append("-");
187         text.append(r[1]);
188       }
189       text.append("\n");
190     }
191     // TODO: allow efficient recovery of annotation data shown in several
192     // different views
193     if (annotations != null)
194     {
195       boolean oneColour = true;
196       AlignmentAnnotation row;
197       String comma;
198       SequenceI refSeq = null;
199       SequenceGroup refGroup = null;
200
201       StringBuffer colours = new StringBuffer();
202       StringBuffer graphLine = new StringBuffer();
203       StringBuffer rowprops = new StringBuffer();
204       Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
205       Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
206       BitSet graphGroupSeen = new BitSet();
207
208       java.awt.Color color;
209
210       for (int i = 0; i < annotations.length; i++)
211       {
212         row = annotations[i];
213
214         if (!row.visible
215                 && !row.hasScore()
216                 && !(row.graphGroup > -1 && graphGroupSeen
217                         .get(row.graphGroup)))
218         {
219           continue;
220         }
221
222         color = null;
223         oneColour = true;
224
225         // mark any sequence references for the row
226         writeSequence_Ref(refSeq, row.sequenceRef);
227         refSeq = row.sequenceRef;
228         // mark any group references for the row
229         writeGroup_Ref(refGroup, row.groupRef);
230         refGroup = row.groupRef;
231
232         boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
233         // lookahead to check what the annotation row object actually contains.
234         for (int j = 0; row.annotations != null
235                 && j < row.annotations.length
236                 && (!hasGlyphs || !hasLabels || !hasValues); j++)
237         {
238           if (row.annotations[j] != null)
239           {
240             hasLabels |= (row.annotations[j].displayCharacter != null
241                     && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
242                     .equals(" "));
243             hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
244             hasValues |= (row.annotations[j].value != Float.NaN); // NaNs can't
245             // be
246             // rendered..
247             hasText |= (row.annotations[j].description != null && row.annotations[j].description
248                     .length() > 0);
249           }
250         }
251
252         if (row.graph == AlignmentAnnotation.NO_GRAPH)
253         {
254           text.append("NO_GRAPH\t");
255           hasValues = false; // only secondary structure
256           // hasLabels = false; // and annotation description string.
257         }
258         else
259         {
260           if (row.graph == AlignmentAnnotation.BAR_GRAPH)
261           {
262             text.append("BAR_GRAPH\t");
263             hasGlyphs = false; // no secondary structure
264
265           }
266           else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
267           {
268             hasGlyphs = false; // no secondary structure
269             text.append("LINE_GRAPH\t");
270           }
271
272           if (row.getThreshold() != null)
273           {
274             graphLine.append("GRAPHLINE\t");
275             graphLine.append(row.label);
276             graphLine.append("\t");
277             graphLine.append(row.getThreshold().value);
278             graphLine.append("\t");
279             graphLine.append(row.getThreshold().label);
280             graphLine.append("\t");
281             graphLine.append(jalview.util.Format.getHexString(row
282                     .getThreshold().colour));
283             graphLine.append(newline);
284           }
285
286           if (row.graphGroup > -1)
287           {
288             graphGroupSeen.set(row.graphGroup);
289             Integer key = new Integer(row.graphGroup);
290             if (graphGroup.containsKey(key))
291             {
292               graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
293
294             }
295             else
296             {
297               graphGroup_refs.put(key, new Object[]
298               { 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 (row.annotations[j].value != Float.NaN)
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 as visible/hidden, and emmitting view properties.
476       // View specific annotation is 
477     }
478
479     return text.toString();
480   }
481
482   private Object writeGroup_Ref(SequenceGroup refGroup,
483           SequenceGroup next_refGroup)
484   {
485     if (next_refGroup == null)
486     {
487
488       if (refGroup != null)
489       {
490         text.append(newline);
491         text.append("GROUP_REF\t");
492         text.append("ALIGNMENT");
493         text.append(newline);
494       }
495       return true;
496     }
497     else
498     {
499       if (refGroup == null || refGroup != next_refGroup)
500       {
501         text.append(newline);
502         text.append("GROUP_REF\t");
503         text.append(next_refGroup.getName());
504         text.append(newline);
505         return true;
506       }
507     }
508     return false;
509   }
510
511   private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
512   {
513
514     if (next_refSeq == null)
515     {
516       if (refSeq != null)
517       {
518         text.append(newline);
519         text.append("SEQUENCE_REF\t");
520         text.append("ALIGNMENT");
521         text.append(newline);
522         return true;
523       }
524     }
525     else
526     {
527       if (refSeq == null || refSeq != next_refSeq)
528       {
529         text.append(newline);
530         text.append("SEQUENCE_REF\t");
531         text.append(next_refSeq.getName());
532         text.append(newline);
533         return true;
534       }
535     }
536     return false;
537   }
538
539   public void printGroups(List<SequenceGroup> list)
540   {
541     SequenceI seqrep = null;
542     for (SequenceGroup sg : list)
543     {
544       if (!sg.hasSeqrep())
545       {
546         text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
547                 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
548                 + "\t" + "-1\t");
549         seqrep = null;
550       }
551       else
552       {
553         seqrep = sg.getSeqrep();
554         text.append("SEQUENCE_REF\t");
555         text.append(seqrep.getName());
556         text.append(newline);
557         text.append("SEQUENCE_GROUP\t");
558         text.append(sg.getName());
559         text.append("\t");
560         text.append((seqrep.findPosition(sg.getStartRes())));
561         text.append("\t");
562         text.append((seqrep.findPosition(sg.getEndRes())));
563         text.append("\t");
564         text.append("-1\t");
565       }
566       for (int s = 0; s < sg.getSize(); s++)
567       {
568         text.append(sg.getSequenceAt(s).getName());
569         text.append("\t");
570       }
571       text.append(newline);
572       text.append("PROPERTIES\t");
573       text.append(sg.getName());
574       text.append("\t");
575
576       if (sg.getDescription() != null)
577       {
578         text.append("description=");
579         text.append(sg.getDescription());
580         text.append("\t");
581       }
582       if (sg.cs != null)
583       {
584         text.append("colour=");
585         text.append(ColourSchemeProperty.getColourName(sg.cs));
586         text.append("\t");
587         if (sg.cs.getThreshold() != 0)
588         {
589           text.append("pidThreshold=");
590           text.append(sg.cs.getThreshold());
591         }
592         if (sg.cs.conservationApplied())
593         {
594           text.append("consThreshold=");
595           text.append(sg.cs.getConservationInc());
596           text.append("\t");
597         }
598       }
599       text.append("outlineColour=");
600       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
601       text.append("\t");
602
603       text.append("displayBoxes=");
604       text.append(sg.getDisplayBoxes());
605       text.append("\t");
606       text.append("displayText=");
607       text.append(sg.getDisplayText());
608       text.append("\t");
609       text.append("colourText=");
610       text.append(sg.getColourText());
611       text.append("\t");
612       text.append("showUnconserved=");
613       text.append(sg.getShowNonconserved());
614       text.append("\t");
615       if (sg.textColour != java.awt.Color.black)
616       {
617         text.append("textCol1=");
618         text.append(jalview.util.Format.getHexString(sg.textColour));
619         text.append("\t");
620       }
621       if (sg.textColour2 != java.awt.Color.white)
622       {
623         text.append("textCol2=");
624         text.append(jalview.util.Format.getHexString(sg.textColour2));
625         text.append("\t");
626       }
627       if (sg.thresholdTextColour != 0)
628       {
629         text.append("textColThreshold=");
630         text.append(sg.thresholdTextColour);
631         text.append("\t");
632       }
633       if (sg.idColour != null)
634       {
635         text.append("idColour=");
636         text.append(jalview.util.Format.getHexString(sg.idColour));
637         text.append("\t");
638       }
639       if (sg.isHidereps())
640       {
641         text.append("hide=true\t");
642       }
643       if (sg.isHideCols())
644       {
645         text.append("hidecols=true\t");
646       }
647       if (seqrep != null)
648       {
649         // terminate the last line and clear the sequence ref for the group
650         text.append(newline);
651         text.append("SEQUENCE_REF");
652       }
653       text.append(newline);
654       text.append(newline);
655
656     }
657   }
658
659   SequenceI refSeq = null;
660
661   String refSeqId = null;
662
663   public boolean annotateAlignmentView(AlignViewportI viewport,
664           String file, String protocol)
665   {
666     ColumnSelection colSel = viewport.getColumnSelection();
667     if (colSel == null)
668     {
669       colSel = new ColumnSelection();
670     }
671     boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
672             file, protocol);
673     if (rslt
674             && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
675     {
676       viewport.setColumnSelection(colSel);
677     }
678
679     return rslt;
680   }
681   public boolean readAnnotationFile(AlignmentI al, String file,
682           String protocol)
683   {
684     return readAnnotationFile(al, null, file, protocol);
685   }
686
687   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
688           String file, String protocol)
689   {
690     BufferedReader in = null;
691     try
692     {
693       if (protocol.equals(AppletFormatAdapter.FILE))
694       {
695         in = new BufferedReader(new FileReader(file));
696       }
697       else if (protocol.equals(AppletFormatAdapter.URL))
698       {
699         URL url = new URL(file);
700         in = new BufferedReader(new InputStreamReader(url.openStream()));
701       }
702       else if (protocol.equals(AppletFormatAdapter.PASTE))
703       {
704         in = new BufferedReader(new StringReader(file));
705       }
706       else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
707       {
708         java.io.InputStream is = getClass().getResourceAsStream("/" + file);
709         if (is != null)
710         {
711           in = new BufferedReader(new java.io.InputStreamReader(is));
712         }
713       }
714       if (in != null)
715       {
716         return parseAnnotationFrom(al, colSel, in);
717       }
718
719     } catch (Exception ex)
720     {
721       ex.printStackTrace();
722       System.out.println("Problem reading annotation file: " + ex);
723       if (nlinesread > 0)
724       {
725         System.out.println("Last read line " + nlinesread + ": '"
726                 + lastread + "' (first 80 chars) ...");
727       }
728       return false;
729     }
730     return false;
731   }
732
733   long nlinesread = 0;
734
735   String lastread = "";
736
737   private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
738
739   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
740           BufferedReader in)
741           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.add(new Object[]
835           { 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[]
849           { GRAPHLINE, st, 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     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1229     // do the
1230     // glyph
1231     // test
1232     // if we
1233     // don't
1234     // want
1235     // secondary
1236     // structure
1237     String desc = null, displayChar = null;
1238     char ss = ' '; // secondaryStructure
1239     float value = 0;
1240     boolean parsedValue = false, dcset = false;
1241
1242     // find colour here
1243     java.awt.Color colour = null;
1244     int i = string.indexOf("[");
1245     int j = string.indexOf("]");
1246     if (i > -1 && j > -1)
1247     {
1248       UserColourScheme ucs = new UserColourScheme();
1249
1250       colour = ucs.getColourFromString(string.substring(i + 1, j));
1251       if (i > 0 && string.charAt(i - 1) == ',')
1252       {
1253         // clip the preceding comma as well
1254         i--;
1255       }
1256       string = string.substring(0, i) + string.substring(j + 1);
1257     }
1258
1259     StringTokenizer st = new StringTokenizer(string, ",", true);
1260     String token;
1261     boolean seenContent = false;
1262     int pass = 0;
1263     while (st.hasMoreTokens())
1264     {
1265       pass++;
1266       token = st.nextToken().trim();
1267       if (token.equals(","))
1268       {
1269         if (!seenContent && parsedValue && !dcset)
1270         {
1271           // allow the value below the bar/line to be empty
1272           dcset = true;
1273           displayChar = " ";
1274         }
1275         seenContent = false;
1276         continue;
1277       }
1278       else
1279       {
1280         seenContent = true;
1281       }
1282
1283       if (!parsedValue)
1284       {
1285         try
1286         {
1287           displayChar = token;
1288           // foo
1289           value = new Float(token).floatValue();
1290           parsedValue = true;
1291           continue;
1292         } catch (NumberFormatException ex)
1293         {
1294         }
1295       }
1296       else
1297       {
1298         if (token.length() == 1)
1299         {
1300           displayChar = token;
1301         }
1302       }
1303       if (hasSymbols
1304               && (token.equals("H") || token.equals("E")
1305                       || token.equals("S") || token.equals(" ")))
1306       {
1307         // Either this character represents a helix or sheet
1308         // or an integer which can be displayed
1309         ss = token.charAt(0);
1310         if (displayChar.equals(token.substring(0, 1)))
1311         {
1312           displayChar = "";
1313         }
1314       }
1315       else if (desc == null || (parsedValue && pass > 2))
1316       {
1317         desc = token;
1318       }
1319
1320     }
1321     // if (!dcset && string.charAt(string.length() - 1) == ',')
1322     // {
1323     // displayChar = " "; // empty display char symbol.
1324     // }
1325     if (displayChar != null && desc != null && desc.length() == 1)
1326     {
1327       if (displayChar.length() > 1)
1328       {
1329         // switch desc and displayChar - legacy support
1330         String tmp = displayChar;
1331         displayChar = desc;
1332         desc = tmp;
1333       }
1334       else
1335       {
1336         if (displayChar.equals(desc))
1337         {
1338           // duplicate label - hangover from the 'robust parser' above
1339           desc = null;
1340         }
1341       }
1342     }
1343     Annotation anot = new Annotation(displayChar, desc, ss, value);
1344
1345     anot.colour = colour;
1346
1347     return anot;
1348   }
1349
1350   void colourAnnotations(AlignmentI al, String label, String colour)
1351   {
1352     UserColourScheme ucs = new UserColourScheme(colour);
1353     Annotation[] annotations;
1354     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1355     {
1356       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1357       {
1358         annotations = al.getAlignmentAnnotation()[i].annotations;
1359         for (int j = 0; j < annotations.length; j++)
1360         {
1361           if (annotations[j] != null)
1362           {
1363             annotations[j].colour = ucs.findColour('A');
1364           }
1365         }
1366       }
1367     }
1368   }
1369
1370   void combineAnnotations(AlignmentI al, int combineCount,
1371           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1372   {
1373     String group = st.nextToken();
1374     // First make sure we are not overwriting the graphIndex
1375     int graphGroup = 0;
1376     if (al.getAlignmentAnnotation() != null)
1377     {
1378       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1379       {
1380         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1381
1382         if (aa.graphGroup > graphGroup)
1383         {
1384           // try to number graphGroups in order of occurence.
1385           graphGroup = aa.graphGroup + 1;
1386         }
1387         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1388                 && aa.label.equalsIgnoreCase(group))
1389         {
1390           if (aa.graphGroup > -1)
1391           {
1392             graphGroup = aa.graphGroup;
1393           }
1394           else
1395           {
1396             if (graphGroup <= combineCount)
1397             {
1398               graphGroup = combineCount + 1;
1399             }
1400             aa.graphGroup = graphGroup;
1401           }
1402           break;
1403         }
1404       }
1405
1406       // Now update groups
1407       while (st.hasMoreTokens())
1408       {
1409         group = st.nextToken();
1410         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1411         {
1412           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1413           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1414                   && aa.label.equalsIgnoreCase(group))
1415           {
1416             aa.graphGroup = graphGroup;
1417             break;
1418           }
1419         }
1420       }
1421     }
1422     else
1423     {
1424       System.err
1425               .println("Couldn't combine annotations. None are added to alignment yet!");
1426     }
1427   }
1428
1429   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1430           SequenceGroup groupRef)
1431   {
1432     String group = st.nextToken();
1433     AlignmentAnnotation annotation = null, alannot[] = al
1434             .getAlignmentAnnotation();
1435     float value = new Float(st.nextToken()).floatValue();
1436     String label = st.hasMoreTokens() ? st.nextToken() : null;
1437     java.awt.Color colour = null;
1438     if (st.hasMoreTokens())
1439     {
1440       UserColourScheme ucs = new UserColourScheme(st.nextToken());
1441       colour = ucs.findColour('A');
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     if (annotation == null)
1456     {
1457       return;
1458     }
1459   }
1460
1461   void addGroup(AlignmentI al, StringTokenizer st)
1462   {
1463     SequenceGroup sg = new SequenceGroup();
1464     sg.setName(st.nextToken());
1465     String rng = "";
1466     try
1467     {
1468       rng = st.nextToken();
1469       if (rng.length() > 0 && !rng.startsWith("*"))
1470       {
1471         sg.setStartRes(Integer.parseInt(rng) - 1);
1472       }
1473       else
1474       {
1475         sg.setStartRes(0);
1476       }
1477       rng = st.nextToken();
1478       if (rng.length() > 0 && !rng.startsWith("*"))
1479       {
1480         sg.setEndRes(Integer.parseInt(rng) - 1);
1481       }
1482       else
1483       {
1484         sg.setEndRes(al.getWidth() - 1);
1485       }
1486     } catch (Exception e)
1487     {
1488       System.err
1489               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1490                       + rng + "' - assuming alignment width for group.");
1491       // assume group is full width
1492       sg.setStartRes(0);
1493       sg.setEndRes(al.getWidth() - 1);
1494     }
1495
1496     String index = st.nextToken();
1497     if (index.equals("-1"))
1498     {
1499       while (st.hasMoreElements())
1500       {
1501         sg.addSequence(al.findName(st.nextToken()), false);
1502       }
1503     }
1504     else
1505     {
1506       StringTokenizer st2 = new StringTokenizer(index, ",");
1507
1508       while (st2.hasMoreTokens())
1509       {
1510         String tmp = st2.nextToken();
1511         if (tmp.equals("*"))
1512         {
1513           for (int i = 0; i < al.getHeight(); i++)
1514           {
1515             sg.addSequence(al.getSequenceAt(i), false);
1516           }
1517         }
1518         else if (tmp.indexOf("-") >= 0)
1519         {
1520           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1521
1522           int start = (Integer.parseInt(st3.nextToken()));
1523           int end = (Integer.parseInt(st3.nextToken()));
1524
1525           if (end > start)
1526           {
1527             for (int i = start; i <= end; i++)
1528             {
1529               sg.addSequence(al.getSequenceAt(i - 1), false);
1530             }
1531           }
1532         }
1533         else
1534         {
1535           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1536         }
1537       }
1538     }
1539
1540     if (refSeq != null)
1541     {
1542       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1543       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1544       sg.setSeqrep(refSeq);
1545     }
1546
1547     if (sg.getSize() > 0)
1548     {
1549       al.addGroup(sg);
1550     }
1551   }
1552
1553   void addRowProperties(AlignmentI al, StringTokenizer st)
1554   {
1555     String label = st.nextToken(), keyValue, key, value;
1556     boolean scaletofit = false, centerlab = false, showalllabs = false;
1557     while (st.hasMoreTokens())
1558     {
1559       keyValue = st.nextToken();
1560       key = keyValue.substring(0, keyValue.indexOf("="));
1561       value = keyValue.substring(keyValue.indexOf("=") + 1);
1562       if (key.equalsIgnoreCase("scaletofit"))
1563       {
1564         scaletofit = Boolean.valueOf(value).booleanValue();
1565       }
1566       if (key.equalsIgnoreCase("showalllabs"))
1567       {
1568         showalllabs = Boolean.valueOf(value).booleanValue();
1569       }
1570       if (key.equalsIgnoreCase("centrelabs"))
1571       {
1572         centerlab = Boolean.valueOf(value).booleanValue();
1573       }
1574       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1575       if (alr != null)
1576       {
1577         for (int i = 0; i < alr.length; i++)
1578         {
1579           if (alr[i].label.equalsIgnoreCase(label))
1580           {
1581             alr[i].centreColLabels = centerlab;
1582             alr[i].scaleColLabel = scaletofit;
1583             alr[i].showAllColLabels = showalllabs;
1584           }
1585         }
1586       }
1587     }
1588   }
1589
1590   void addProperties(AlignmentI al, StringTokenizer st)
1591   {
1592
1593     // So far we have only added groups to the annotationHash,
1594     // the idea is in the future properties can be added to
1595     // alignments, other annotations etc
1596     if (al.getGroups() == null)
1597     {
1598       return;
1599     }
1600
1601     String name = st.nextToken();
1602     SequenceGroup sg = null;
1603     for (SequenceGroup _sg : al.getGroups())
1604     {
1605       if ((sg = _sg).getName().equals(name))
1606       {
1607         break;
1608       }
1609       else
1610       {
1611         sg = null;
1612       }
1613     }
1614
1615     if (sg != null)
1616     {
1617       String keyValue, key, value;
1618       ColourSchemeI def = sg.cs;
1619       sg.cs = null;
1620       while (st.hasMoreTokens())
1621       {
1622         keyValue = st.nextToken();
1623         key = keyValue.substring(0, keyValue.indexOf("="));
1624         value = keyValue.substring(keyValue.indexOf("=") + 1);
1625
1626         if (key.equalsIgnoreCase("description"))
1627         {
1628           sg.setDescription(value);
1629         }
1630         else if (key.equalsIgnoreCase("colour"))
1631         {
1632           sg.cs = ColourSchemeProperty.getColour(al, value);
1633         }
1634         else if (key.equalsIgnoreCase("pidThreshold"))
1635         {
1636           sg.cs.setThreshold(Integer.parseInt(value), true);
1637
1638         }
1639         else if (key.equalsIgnoreCase("consThreshold"))
1640         {
1641           sg.cs.setConservationInc(Integer.parseInt(value));
1642           Conservation c = new Conservation("Group",
1643                   ResidueProperties.propHash, 3, sg.getSequences(null),
1644                   sg.getStartRes(), sg.getEndRes() + 1);
1645
1646           c.calculate();
1647           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1648
1649           sg.cs.setConservation(c);
1650
1651         }
1652         else if (key.equalsIgnoreCase("outlineColour"))
1653         {
1654           sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1655         }
1656         else if (key.equalsIgnoreCase("displayBoxes"))
1657         {
1658           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1659         }
1660         else if (key.equalsIgnoreCase("showUnconserved"))
1661         {
1662           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1663         }
1664         else if (key.equalsIgnoreCase("displayText"))
1665         {
1666           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1667         }
1668         else if (key.equalsIgnoreCase("colourText"))
1669         {
1670           sg.setColourText(Boolean.valueOf(value).booleanValue());
1671         }
1672         else if (key.equalsIgnoreCase("textCol1"))
1673         {
1674           sg.textColour = new UserColourScheme(value).findColour('A');
1675         }
1676         else if (key.equalsIgnoreCase("textCol2"))
1677         {
1678           sg.textColour2 = new UserColourScheme(value).findColour('A');
1679         }
1680         else if (key.equalsIgnoreCase("textColThreshold"))
1681         {
1682           sg.thresholdTextColour = Integer.parseInt(value);
1683         }
1684         else if (key.equalsIgnoreCase("idColour"))
1685         {
1686           // consider warning if colour doesn't resolve to a real colour
1687           sg.setIdColour((def = new UserColourScheme(value))
1688                   .findColour('A'));
1689         }
1690         else if (key.equalsIgnoreCase("hide"))
1691         {
1692           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1693           sg.setHidereps(true);
1694         }
1695         else if (key.equalsIgnoreCase("hidecols"))
1696         {
1697           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1698           sg.setHideCols(true);
1699         }
1700         sg.recalcConservation();
1701       }
1702       if (sg.cs == null)
1703       {
1704         sg.cs = def;
1705       }
1706     }
1707   }
1708
1709   void setBelowAlignment(AlignmentI al, StringTokenizer st)
1710   {
1711     String token;
1712     AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1713     if (ala == null)
1714     {
1715       System.err
1716               .print("Warning - no annotation to set below for sequence associated annotation:");
1717     }
1718     while (st.hasMoreTokens())
1719     {
1720       token = st.nextToken();
1721       if (ala == null)
1722       {
1723         System.err.print(" " + token);
1724       }
1725       else
1726       {
1727         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1728         {
1729           aa = al.getAlignmentAnnotation()[i];
1730           if (aa.sequenceRef == refSeq && aa.label.equals(token))
1731           {
1732             aa.belowAlignment = true;
1733           }
1734         }
1735       }
1736     }
1737     if (ala == null)
1738     {
1739       System.err.print("\n");
1740     }
1741   }
1742
1743   void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1744   {
1745     String keyValue, key, value;
1746     while (st.hasMoreTokens())
1747     {
1748       keyValue = st.nextToken();
1749       key = keyValue.substring(0, keyValue.indexOf("="));
1750       value = keyValue.substring(keyValue.indexOf("=") + 1);
1751       al.setProperty(key, value);
1752     }
1753   }
1754
1755   /**
1756    * Write annotations as a CSV file of the form 'label, value, value, ...' for
1757    * each row.
1758    * 
1759    * @param annotations
1760    * @return CSV file as a string.
1761    */
1762   public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1763   {
1764     StringBuffer sp = new StringBuffer();
1765     for (int i = 0; i < annotations.length; i++)
1766     {
1767       String atos = annotations[i].toString();
1768       int p = 0;
1769       do
1770       {
1771         int cp = atos.indexOf("\n", p);
1772         sp.append(annotations[i].label);
1773         sp.append(",");
1774         if (cp > p)
1775         {
1776           sp.append(atos.substring(p, cp + 1));
1777         }
1778         else
1779         {
1780           sp.append(atos.substring(p));
1781           sp.append(newline);
1782         }
1783         p = cp + 1;
1784       } while (p > 0);
1785     }
1786     return sp.toString();
1787   }
1788
1789   public String printAnnotationsForView(AlignViewportI viewport)
1790   {
1791     return printAnnotations(viewport.isShowAnnotation() ? viewport
1792             .getAlignment().getAlignmentAnnotation() : null, viewport
1793             .getAlignment().getGroups(), viewport.getAlignment()
1794             .getProperties(), viewport.getColumnSelection(),
1795             viewport.getAlignment(), null);
1796   }
1797
1798   public String printAnnotationsForAlignment(AlignmentI al)
1799   {
1800     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1801             al.getProperties(), null, al, null);
1802   }
1803 }