8b3aa9832999c72ae0c5dc0f5bcdb4054f07594f
[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.9 annotation files which have no view, hidden
92    * columns or hidden row keywords.
93    * 
94    * @param annotations
95    * @param list
96    * @param properties
97    * @return annotation file as a string.
98    */
99   public String printAnnotations(AlignmentAnnotation[] annotations,
100           List<SequenceGroup> list, Hashtable properties)
101   {
102     return printAnnotations(annotations, list, properties, null, null, null);
103
104   }
105
106   /**
107    * hold all the information about a particular view definition read from or
108    * written out in an annotations file.
109    */
110   public class ViewDef
111   {
112     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 |= (!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   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 && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
674     {
675       viewport.setColumnSelection(colSel);
676     }
677
678     return rslt;
679   }
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) throws Exception
741   {
742     nlinesread = 0;
743     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
744     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
745     boolean modified = false;
746     String groupRef = null;
747     Hashtable groupRefRows = new Hashtable();
748
749     Hashtable autoAnnots = new Hashtable();
750     {
751       String line, label, description, token;
752       int graphStyle, index;
753       int refSeqIndex = 1;
754       int existingAnnotations = 0;
755       // when true - will add new rows regardless of whether they are duplicate
756       // auto-annotation like consensus or conservation graphs
757       boolean overrideAutoAnnot = false;
758       if (al.getAlignmentAnnotation() != null)
759       {
760         existingAnnotations = al.getAlignmentAnnotation().length;
761         if (existingAnnotations > 0)
762         {
763           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
764           for (int aai = 0; aai < aa.length; aai++)
765           {
766             if (aa[aai].autoCalculated)
767             {
768               // make a note of the name and description
769               autoAnnots.put(
770                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
771                               (aa[aai].groupRef == null ? null
772                                       : aa[aai].groupRef.getName())),
773                       new Integer(1));
774             }
775           }
776         }
777       }
778
779       int alWidth = al.getWidth();
780
781       StringTokenizer st;
782       Annotation[] annotations;
783       AlignmentAnnotation annotation = null;
784
785       // First confirm this is an Annotation file
786       boolean jvAnnotationFile = false;
787       while ((line = in.readLine()) != null)
788       {
789         nlinesread++;
790         lastread = new String(line);
791         if (line.indexOf("#") == 0)
792         {
793           continue;
794         }
795
796         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
797         {
798           jvAnnotationFile = true;
799           break;
800         }
801       }
802
803       if (!jvAnnotationFile)
804       {
805         in.close();
806         return false;
807       }
808
809       while ((line = in.readLine()) != null)
810       {
811         nlinesread++;
812         lastread = new String(line);
813         if (line.indexOf("#") == 0
814                 || line.indexOf("JALVIEW_ANNOTATION") > -1
815                 || line.length() == 0)
816         {
817           continue;
818         }
819
820         st = new StringTokenizer(line, "\t");
821         token = st.nextToken();
822         if (token.equalsIgnoreCase("COLOUR"))
823         {
824           // TODO: use graduated colour def'n here too
825           colourAnnotations(al, st.nextToken(), st.nextToken());
826           modified = true;
827           continue;
828         }
829
830         else if (token.equalsIgnoreCase(COMBINE))
831         {
832           // keep a record of current state and resolve groupRef at end
833           combineAnnotation_calls
834                   .add(new Object[] { st, refSeq, groupRef });
835           modified = true;
836           continue;
837         }
838         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
839         {
840           addRowProperties(al, st);
841           modified = true;
842           continue;
843         }
844         else if (token.equalsIgnoreCase(GRAPHLINE))
845         {
846           // resolve at end
847           deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
848               refSeq, groupRef });
849           modified = true;
850           continue;
851         }
852
853         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
854         {
855           if (st.hasMoreTokens())
856           {
857             refSeq = al.findName(refSeqId = st.nextToken());
858             if (refSeq == null)
859             {
860               refSeqId = null;
861             }
862             try
863             {
864               refSeqIndex = Integer.parseInt(st.nextToken());
865               if (refSeqIndex < 1)
866               {
867                 refSeqIndex = 1;
868                 System.out
869                         .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
870               }
871             } catch (Exception ex)
872             {
873               refSeqIndex = 1;
874             }
875           }
876           else
877           {
878             refSeq = null;
879             refSeqId = null;
880           }
881           continue;
882         }
883         else if (token.equalsIgnoreCase("GROUP_REF"))
884         {
885           // Group references could be forward or backwards, so they are
886           // resolved after the whole file is read in
887           groupRef = null;
888           if (st.hasMoreTokens())
889           {
890             groupRef = st.nextToken();
891             if (groupRef.length() < 1)
892             {
893               groupRef = null; // empty string
894             }
895             else
896             {
897               if (groupRefRows.get(groupRef) == null)
898               {
899                 groupRefRows.put(groupRef, new Vector());
900               }
901             }
902           }
903           continue;
904         }
905         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
906         {
907           addGroup(al, st);
908           modified = true;
909           continue;
910         }
911
912         else if (token.equalsIgnoreCase("PROPERTIES"))
913         {
914           addProperties(al, st);
915           modified = true;
916           continue;
917         }
918
919         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
920         {
921           setBelowAlignment(al, st);
922           modified = true;
923           continue;
924         }
925         else if (token.equalsIgnoreCase("ALIGNMENT"))
926         {
927           addAlignmentDetails(al, st);
928           modified = true;
929           continue;
930         }
931         // else if (token.equalsIgnoreCase("VIEW_DEF"))
932         // {
933         // addOrSetView(al,st);
934         // modified = true;
935         // continue;
936         // }
937         else if (token.equalsIgnoreCase("VIEW_SETREF"))
938         {
939           if (refSeq != null)
940           {
941             al.setSeqrep(refSeq);
942           }
943           modified = true;
944           continue;
945         }
946         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
947         {
948           if (st.hasMoreTokens())
949           {
950             if (colSel == null)
951             {
952               colSel = new ColumnSelection();
953             }
954             parseHideCols(colSel, st.nextToken());
955           }
956           modified = true;
957           continue;
958         }
959         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
960         {
961           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
962           if (sr == null)
963           {
964             sr = al.getSequenceAt(0);
965           }
966           if (sr != null)
967           {
968             if (colSel == null)
969             {
970               System.err
971                       .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
972                               + line);
973             }
974             else
975             {
976               // consider deferring this till after the file has been parsed ?
977               colSel.hideInsertionsFor(sr);
978             }
979           }
980           modified = true;
981           continue;
982         }
983
984         // Parse out the annotation row
985         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
986         label = st.nextToken();
987
988         index = 0;
989         annotations = new Annotation[alWidth];
990         description = null;
991         float score = Float.NaN;
992
993         if (st.hasMoreTokens())
994         {
995           line = st.nextToken();
996
997           if (line.indexOf("|") == -1)
998           {
999             description = line;
1000             if (st.hasMoreTokens())
1001             {
1002               line = st.nextToken();
1003             }
1004           }
1005
1006           if (st.hasMoreTokens())
1007           {
1008             // This must be the score
1009             score = Float.valueOf(st.nextToken()).floatValue();
1010           }
1011
1012           st = new StringTokenizer(line, "|", true);
1013
1014           boolean emptyColumn = true;
1015           boolean onlyOneElement = (st.countTokens() == 1);
1016
1017           while (st.hasMoreElements() && index < alWidth)
1018           {
1019             token = st.nextToken().trim();
1020
1021             if (onlyOneElement)
1022             {
1023               try
1024               {
1025                 score = Float.valueOf(token).floatValue();
1026                 break;
1027               } catch (NumberFormatException ex)
1028               {
1029               }
1030             }
1031
1032             if (token.equals("|"))
1033             {
1034               if (emptyColumn)
1035               {
1036                 index++;
1037               }
1038
1039               emptyColumn = true;
1040             }
1041             else
1042             {
1043               annotations[index++] = parseAnnotation(token, graphStyle);
1044               emptyColumn = false;
1045             }
1046           }
1047
1048         }
1049
1050         annotation = new AlignmentAnnotation(label, description,
1051                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1052
1053         annotation.score = score;
1054         if (!overrideAutoAnnot
1055                 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1056                         groupRef)))
1057         {
1058           // skip - we've already got an automatic annotation of this type.
1059           continue;
1060         }
1061         // otherwise add it!
1062         if (refSeq != null)
1063         {
1064
1065           annotation.belowAlignment = false;
1066           // make a copy of refSeq so we can find other matches in the alignment
1067           SequenceI referedSeq = refSeq;
1068           do
1069           {
1070             // copy before we do any mapping business.
1071             // TODO: verify that undo/redo with 1:many sequence associated
1072             // annotations can be undone correctly
1073             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1074             annotation
1075                     .createSequenceMapping(referedSeq, refSeqIndex, false);
1076             annotation.adjustForAlignment();
1077             referedSeq.addAlignmentAnnotation(annotation);
1078             al.addAnnotation(annotation);
1079             al.setAnnotationIndex(annotation,
1080                     al.getAlignmentAnnotation().length
1081                             - existingAnnotations - 1);
1082             if (groupRef != null)
1083             {
1084               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1085             }
1086             // and recover our virgin copy to use again if necessary.
1087             annotation = ann;
1088
1089           } while (refSeqId != null
1090                   && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1091         }
1092         else
1093         {
1094           al.addAnnotation(annotation);
1095           al.setAnnotationIndex(annotation,
1096                   al.getAlignmentAnnotation().length - existingAnnotations
1097                           - 1);
1098           if (groupRef != null)
1099           {
1100             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1101           }
1102         }
1103         // and set modification flag
1104         modified = true;
1105       }
1106       // Resolve the groupRefs
1107       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1108       Enumeration en = groupRefRows.keys();
1109
1110       while (en.hasMoreElements())
1111       {
1112         groupRef = (String) en.nextElement();
1113         boolean matched = false;
1114         // Resolve group: TODO: add a getGroupByName method to alignments
1115         for (SequenceGroup theGroup : al.getGroups())
1116         {
1117           if (theGroup.getName().equals(groupRef))
1118           {
1119             if (matched)
1120             {
1121               // TODO: specify and implement duplication of alignment annotation
1122               // for multiple group references.
1123               System.err
1124                       .println("Ignoring 1:many group reference mappings for group name '"
1125                               + groupRef + "'");
1126             }
1127             else
1128             {
1129               matched = true;
1130               Vector rowset = (Vector) groupRefRows.get(groupRef);
1131               groupRefLookup.put(groupRef, theGroup);
1132               if (rowset != null && rowset.size() > 0)
1133               {
1134                 AlignmentAnnotation alan = null;
1135                 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1136                 {
1137                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1138                   alan.groupRef = theGroup;
1139                 }
1140               }
1141             }
1142           }
1143         }
1144         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1145       }
1146       // process any deferred attribute settings for each context
1147       for (Object[] _deferred_args : deferredAnnotation_calls)
1148       {
1149         if (_deferred_args[0] == GRAPHLINE)
1150         {
1151           addLine(al,
1152                   (StringTokenizer) _deferred_args[1], // st
1153                   (SequenceI) _deferred_args[2], // refSeq
1154                   (_deferred_args[3] == null) ? null : groupRefLookup
1155                           .get(_deferred_args[3]) // the reference
1156                                                   // group, or null
1157           );
1158         }
1159       }
1160
1161       // finally, combine all the annotation rows within each context.
1162       /**
1163        * number of combine statements in this annotation file. Used to create
1164        * new groups for combined annotation graphs without disturbing existing
1165        * ones
1166        */
1167       int combinecount = 0;
1168       for (Object[] _combine_args : combineAnnotation_calls)
1169       {
1170         combineAnnotations(al,
1171                 ++combinecount,
1172                 (StringTokenizer) _combine_args[0], // st
1173                 (SequenceI) _combine_args[1], // refSeq
1174                 (_combine_args[2] == null) ? null : groupRefLookup
1175                         .get(_combine_args[2]) // the reference group,
1176                                                // or null
1177         );
1178       }
1179     }
1180     return modified;
1181   }
1182
1183   private void parseHideCols(ColumnSelection colSel, String nextToken)
1184   {
1185     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1186     while (inval.hasMoreTokens())
1187     {
1188       String range = inval.nextToken().trim();
1189       int from, to = range.indexOf("-");
1190       if (to == -1)
1191       {
1192         from = to = Integer.parseInt(range);
1193         if (from >= 0)
1194         {
1195           colSel.hideColumns(from, to);
1196         }
1197       }
1198       else
1199       {
1200         from = Integer.parseInt(range.substring(0, to));
1201         if (to < range.length() - 1)
1202         {
1203           to = Integer.parseInt(range.substring(to + 1));
1204         }
1205         else
1206         {
1207           to = from;
1208         }
1209         if (from > 0 && to >= from)
1210         {
1211           colSel.hideColumns(from, to);
1212         }
1213       }
1214     }
1215   }
1216
1217   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1218           SequenceI refSeq, String groupRef)
1219   {
1220     return annotation.graph + "\t" + annotation.label + "\t"
1221             + annotation.description + "\t"
1222             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1223   }
1224
1225   Annotation parseAnnotation(String string, int graphStyle)
1226   {
1227     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1228     // do the
1229     // glyph
1230     // test
1231     // if we
1232     // don't
1233     // want
1234     // secondary
1235     // structure
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     java.awt.Color colour = null;
1243     int i = string.indexOf("[");
1244     int j = string.indexOf("]");
1245     if (i > -1 && j > -1)
1246     {
1247       UserColourScheme ucs = new UserColourScheme();
1248
1249       colour = ucs.getColourFromString(string.substring(i + 1, j));
1250       if (i > 0 && string.charAt(i - 1) == ',')
1251       {
1252         // clip the preceding comma as well
1253         i--;
1254       }
1255       string = string.substring(0, i) + string.substring(j + 1);
1256     }
1257
1258     StringTokenizer st = new StringTokenizer(string, ",", true);
1259     String token;
1260     boolean seenContent = false;
1261     int pass = 0;
1262     while (st.hasMoreTokens())
1263     {
1264       pass++;
1265       token = st.nextToken().trim();
1266       if (token.equals(","))
1267       {
1268         if (!seenContent && parsedValue && !dcset)
1269         {
1270           // allow the value below the bar/line to be empty
1271           dcset = true;
1272           displayChar = " ";
1273         }
1274         seenContent = false;
1275         continue;
1276       }
1277       else
1278       {
1279         seenContent = true;
1280       }
1281
1282       if (!parsedValue)
1283       {
1284         try
1285         {
1286           displayChar = token;
1287           // foo
1288           value = new Float(token).floatValue();
1289           parsedValue = true;
1290           continue;
1291         } catch (NumberFormatException ex)
1292         {
1293         }
1294       }
1295       else
1296       {
1297         if (token.length() == 1)
1298         {
1299           displayChar = token;
1300         }
1301       }
1302       if (hasSymbols
1303               && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1304                       .contains(token)))
1305       {
1306         // Either this character represents a helix or sheet
1307         // or an integer which can be displayed
1308         ss = token.charAt(0);
1309         if (displayChar.equals(token.substring(0, 1)))
1310         {
1311           displayChar = "";
1312         }
1313       }
1314       else if (desc == null || (parsedValue && pass > 2))
1315       {
1316         desc = token;
1317       }
1318
1319     }
1320     // if (!dcset && string.charAt(string.length() - 1) == ',')
1321     // {
1322     // displayChar = " "; // empty display char symbol.
1323     // }
1324     if (displayChar != null && desc != null && desc.length() == 1)
1325     {
1326       if (displayChar.length() > 1)
1327       {
1328         // switch desc and displayChar - legacy support
1329         String tmp = displayChar;
1330         displayChar = desc;
1331         desc = tmp;
1332       }
1333       else
1334       {
1335         if (displayChar.equals(desc))
1336         {
1337           // duplicate label - hangover from the 'robust parser' above
1338           desc = null;
1339         }
1340       }
1341     }
1342     Annotation anot = new Annotation(displayChar, desc, ss, value);
1343
1344     anot.colour = colour;
1345
1346     return anot;
1347   }
1348
1349   void colourAnnotations(AlignmentI al, String label, String colour)
1350   {
1351     UserColourScheme ucs = new UserColourScheme(colour);
1352     Annotation[] annotations;
1353     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1354     {
1355       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1356       {
1357         annotations = al.getAlignmentAnnotation()[i].annotations;
1358         for (int j = 0; j < annotations.length; j++)
1359         {
1360           if (annotations[j] != null)
1361           {
1362             annotations[j].colour = ucs.findColour('A');
1363           }
1364         }
1365       }
1366     }
1367   }
1368
1369   void combineAnnotations(AlignmentI al, int combineCount,
1370           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1371   {
1372     String group = st.nextToken();
1373     // First make sure we are not overwriting the graphIndex
1374     int graphGroup = 0;
1375     if (al.getAlignmentAnnotation() != null)
1376     {
1377       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1378       {
1379         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1380
1381         if (aa.graphGroup > graphGroup)
1382         {
1383           // try to number graphGroups in order of occurence.
1384           graphGroup = aa.graphGroup + 1;
1385         }
1386         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1387                 && aa.label.equalsIgnoreCase(group))
1388         {
1389           if (aa.graphGroup > -1)
1390           {
1391             graphGroup = aa.graphGroup;
1392           }
1393           else
1394           {
1395             if (graphGroup <= combineCount)
1396             {
1397               graphGroup = combineCount + 1;
1398             }
1399             aa.graphGroup = graphGroup;
1400           }
1401           break;
1402         }
1403       }
1404
1405       // Now update groups
1406       while (st.hasMoreTokens())
1407       {
1408         group = st.nextToken();
1409         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1410         {
1411           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1412           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1413                   && aa.label.equalsIgnoreCase(group))
1414           {
1415             aa.graphGroup = graphGroup;
1416             break;
1417           }
1418         }
1419       }
1420     }
1421     else
1422     {
1423       System.err
1424               .println("Couldn't combine annotations. None are added to alignment yet!");
1425     }
1426   }
1427
1428   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1429           SequenceGroup groupRef)
1430   {
1431     String group = st.nextToken();
1432     AlignmentAnnotation annotation = null, alannot[] = al
1433             .getAlignmentAnnotation();
1434     float value = new Float(st.nextToken()).floatValue();
1435     String label = st.hasMoreTokens() ? st.nextToken() : null;
1436     java.awt.Color colour = null;
1437     if (st.hasMoreTokens())
1438     {
1439       UserColourScheme ucs = new UserColourScheme(st.nextToken());
1440       colour = ucs.findColour('A');
1441     }
1442     if (alannot != null)
1443     {
1444       for (int i = 0; i < alannot.length; i++)
1445       {
1446         if (alannot[i].label.equalsIgnoreCase(group)
1447                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1448                 && (groupRef == null || alannot[i].groupRef == groupRef))
1449         {
1450           alannot[i].setThreshold(new GraphLine(value, label, colour));
1451         }
1452       }
1453     }
1454     if (annotation == null)
1455     {
1456       return;
1457     }
1458   }
1459
1460   void addGroup(AlignmentI al, StringTokenizer st)
1461   {
1462     SequenceGroup sg = new SequenceGroup();
1463     sg.setName(st.nextToken());
1464     String rng = "";
1465     try
1466     {
1467       rng = st.nextToken();
1468       if (rng.length() > 0 && !rng.startsWith("*"))
1469       {
1470         sg.setStartRes(Integer.parseInt(rng) - 1);
1471       }
1472       else
1473       {
1474         sg.setStartRes(0);
1475       }
1476       rng = st.nextToken();
1477       if (rng.length() > 0 && !rng.startsWith("*"))
1478       {
1479         sg.setEndRes(Integer.parseInt(rng) - 1);
1480       }
1481       else
1482       {
1483         sg.setEndRes(al.getWidth() - 1);
1484       }
1485     } catch (Exception e)
1486     {
1487       System.err
1488               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1489                       + rng + "' - assuming alignment width for group.");
1490       // assume group is full width
1491       sg.setStartRes(0);
1492       sg.setEndRes(al.getWidth() - 1);
1493     }
1494
1495     String index = st.nextToken();
1496     if (index.equals("-1"))
1497     {
1498       while (st.hasMoreElements())
1499       {
1500         sg.addSequence(al.findName(st.nextToken()), false);
1501       }
1502     }
1503     else
1504     {
1505       StringTokenizer st2 = new StringTokenizer(index, ",");
1506
1507       while (st2.hasMoreTokens())
1508       {
1509         String tmp = st2.nextToken();
1510         if (tmp.equals("*"))
1511         {
1512           for (int i = 0; i < al.getHeight(); i++)
1513           {
1514             sg.addSequence(al.getSequenceAt(i), false);
1515           }
1516         }
1517         else if (tmp.indexOf("-") >= 0)
1518         {
1519           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1520
1521           int start = (Integer.parseInt(st3.nextToken()));
1522           int end = (Integer.parseInt(st3.nextToken()));
1523
1524           if (end > start)
1525           {
1526             for (int i = start; i <= end; i++)
1527             {
1528               sg.addSequence(al.getSequenceAt(i - 1), false);
1529             }
1530           }
1531         }
1532         else
1533         {
1534           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1535         }
1536       }
1537     }
1538
1539     if (refSeq != null)
1540     {
1541       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1542       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1543       sg.setSeqrep(refSeq);
1544     }
1545
1546     if (sg.getSize() > 0)
1547     {
1548       al.addGroup(sg);
1549     }
1550   }
1551
1552   void addRowProperties(AlignmentI al, StringTokenizer st)
1553   {
1554     String label = st.nextToken(), keyValue, key, value;
1555     boolean scaletofit = false, centerlab = false, showalllabs = false;
1556     while (st.hasMoreTokens())
1557     {
1558       keyValue = st.nextToken();
1559       key = keyValue.substring(0, keyValue.indexOf("="));
1560       value = keyValue.substring(keyValue.indexOf("=") + 1);
1561       if (key.equalsIgnoreCase("scaletofit"))
1562       {
1563         scaletofit = Boolean.valueOf(value).booleanValue();
1564       }
1565       if (key.equalsIgnoreCase("showalllabs"))
1566       {
1567         showalllabs = Boolean.valueOf(value).booleanValue();
1568       }
1569       if (key.equalsIgnoreCase("centrelabs"))
1570       {
1571         centerlab = Boolean.valueOf(value).booleanValue();
1572       }
1573       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1574       if (alr != null)
1575       {
1576         for (int i = 0; i < alr.length; i++)
1577         {
1578           if (alr[i].label.equalsIgnoreCase(label))
1579           {
1580             alr[i].centreColLabels = centerlab;
1581             alr[i].scaleColLabel = scaletofit;
1582             alr[i].showAllColLabels = showalllabs;
1583           }
1584         }
1585       }
1586     }
1587   }
1588
1589   void addProperties(AlignmentI al, StringTokenizer st)
1590   {
1591
1592     // So far we have only added groups to the annotationHash,
1593     // the idea is in the future properties can be added to
1594     // alignments, other annotations etc
1595     if (al.getGroups() == null)
1596     {
1597       return;
1598     }
1599
1600     String name = st.nextToken();
1601     SequenceGroup sg = null;
1602     for (SequenceGroup _sg : al.getGroups())
1603     {
1604       if ((sg = _sg).getName().equals(name))
1605       {
1606         break;
1607       }
1608       else
1609       {
1610         sg = null;
1611       }
1612     }
1613
1614     if (sg != null)
1615     {
1616       String keyValue, key, value;
1617       ColourSchemeI def = sg.cs;
1618       sg.cs = null;
1619       while (st.hasMoreTokens())
1620       {
1621         keyValue = st.nextToken();
1622         key = keyValue.substring(0, keyValue.indexOf("="));
1623         value = keyValue.substring(keyValue.indexOf("=") + 1);
1624
1625         if (key.equalsIgnoreCase("description"))
1626         {
1627           sg.setDescription(value);
1628         }
1629         else if (key.equalsIgnoreCase("colour"))
1630         {
1631           sg.cs = ColourSchemeProperty.getColour(al, value);
1632         }
1633         else if (key.equalsIgnoreCase("pidThreshold"))
1634         {
1635           sg.cs.setThreshold(Integer.parseInt(value), true);
1636
1637         }
1638         else if (key.equalsIgnoreCase("consThreshold"))
1639         {
1640           sg.cs.setConservationInc(Integer.parseInt(value));
1641           Conservation c = new Conservation("Group",
1642                   ResidueProperties.propHash, 3, sg.getSequences(null),
1643                   sg.getStartRes(), sg.getEndRes() + 1);
1644
1645           c.calculate();
1646           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1647
1648           sg.cs.setConservation(c);
1649
1650         }
1651         else if (key.equalsIgnoreCase("outlineColour"))
1652         {
1653           sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1654         }
1655         else if (key.equalsIgnoreCase("displayBoxes"))
1656         {
1657           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1658         }
1659         else if (key.equalsIgnoreCase("showUnconserved"))
1660         {
1661           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1662         }
1663         else if (key.equalsIgnoreCase("displayText"))
1664         {
1665           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1666         }
1667         else if (key.equalsIgnoreCase("colourText"))
1668         {
1669           sg.setColourText(Boolean.valueOf(value).booleanValue());
1670         }
1671         else if (key.equalsIgnoreCase("textCol1"))
1672         {
1673           sg.textColour = new UserColourScheme(value).findColour('A');
1674         }
1675         else if (key.equalsIgnoreCase("textCol2"))
1676         {
1677           sg.textColour2 = new UserColourScheme(value).findColour('A');
1678         }
1679         else if (key.equalsIgnoreCase("textColThreshold"))
1680         {
1681           sg.thresholdTextColour = Integer.parseInt(value);
1682         }
1683         else if (key.equalsIgnoreCase("idColour"))
1684         {
1685           // consider warning if colour doesn't resolve to a real colour
1686           sg.setIdColour((def = new UserColourScheme(value))
1687                   .findColour('A'));
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.cs == null)
1702       {
1703         sg.cs = 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     StringBuffer sp = new StringBuffer();
1764     for (int i = 0; i < annotations.length; i++)
1765     {
1766       String atos = annotations[i].toString();
1767       int p = 0;
1768       do
1769       {
1770         int cp = atos.indexOf("\n", p);
1771         sp.append(annotations[i].label);
1772         sp.append(",");
1773         if (cp > p)
1774         {
1775           sp.append(atos.substring(p, cp + 1));
1776         }
1777         else
1778         {
1779           sp.append(atos.substring(p));
1780           sp.append(newline);
1781         }
1782         p = cp + 1;
1783       } while (p > 0);
1784     }
1785     return sp.toString();
1786   }
1787
1788   public String printAnnotationsForView(AlignViewportI viewport)
1789   {
1790     return printAnnotations(viewport.isShowAnnotation() ? viewport
1791             .getAlignment().getAlignmentAnnotation() : null, viewport
1792             .getAlignment().getGroups(), viewport.getAlignment()
1793             .getProperties(), viewport.getColumnSelection(),
1794             viewport.getAlignment(), null);
1795   }
1796
1797   public String printAnnotationsForAlignment(AlignmentI al)
1798   {
1799     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1800             al.getProperties(), null, al, null);
1801   }
1802 }