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