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