b72184bf6f26cebdff01e05bea07d443cb13e122
[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.PDBEntry;
32 import jalview.datamodel.PDBEntry.Type;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.Desktop;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ColourSchemeProperty;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.ColorUtils;
40
41 import java.awt.Color;
42 import java.io.BufferedReader;
43 import java.io.File;
44 import java.io.FileReader;
45 import java.io.InputStreamReader;
46 import java.io.StringReader;
47 import java.net.URL;
48 import java.util.ArrayList;
49 import java.util.BitSet;
50 import java.util.Enumeration;
51 import java.util.Hashtable;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.StringTokenizer;
55 import java.util.Vector;
56
57 public class AnnotationFile
58 {
59   public AnnotationFile()
60   {
61     init();
62   }
63
64   /**
65    * character used to write newlines
66    */
67   protected String newline = System.getProperty("line.separator");
68
69   /**
70    * set new line string and reset the output buffer
71    * 
72    * @param nl
73    */
74   public void setNewlineString(String nl)
75   {
76     newline = nl;
77     init();
78   }
79
80   public String getNewlineString()
81   {
82     return newline;
83   }
84
85   StringBuffer text;
86
87   private void init()
88   {
89     text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
90             + new java.util.Date() + newline + newline);
91     refSeq = null;
92     refSeqId = null;
93   }
94
95   /**
96    * convenience method for pre-2.9 annotation files which have no view, hidden
97    * columns or hidden row keywords.
98    * 
99    * @param annotations
100    * @param list
101    * @param properties
102    * @return annotation file as a string.
103    */
104   public String printAnnotations(AlignmentAnnotation[] annotations,
105           List<SequenceGroup> list, Hashtable properties)
106   {
107     return printAnnotations(annotations, list, properties, null, null, null);
108
109   }
110
111   /**
112    * hold all the information about a particular view definition read from or
113    * written out in an annotations file.
114    */
115   public class ViewDef
116   {
117     public String viewname;
118
119     public HiddenSequences hidseqs;
120
121     public ColumnSelection hiddencols;
122
123     public Vector visibleGroups;
124
125     public Hashtable hiddenRepSeqs;
126
127     public ViewDef(String viewname, HiddenSequences hidseqs,
128             ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
129     {
130       this.viewname = viewname;
131       this.hidseqs = hidseqs;
132       this.hiddencols = hiddencols;
133       this.hiddenRepSeqs = hiddenRepSeqs;
134     }
135   }
136
137   /**
138    * Prepare an annotation file given a set of annotations, groups, alignment
139    * properties and views.
140    * 
141    * @param annotations
142    * @param list
143    * @param properties
144    * @param views
145    * @return annotation file
146    */
147   public String printAnnotations(AlignmentAnnotation[] annotations,
148           List<SequenceGroup> list, Hashtable properties,
149           ColumnSelection cs, AlignmentI al, ViewDef view)
150   {
151     if (view != null)
152     {
153       if (view.viewname != null)
154       {
155         text.append("VIEW_DEF\t" + view.viewname + "\n");
156       }
157       if (list == null)
158       {
159         list = view.visibleGroups;
160       }
161       if (cs == null)
162       {
163         cs = view.hiddencols;
164       }
165       if (al == null)
166       {
167         // add hidden rep sequences.
168       }
169     }
170     // first target - store and restore all settings for a view.
171     if (al != null && al.hasSeqrep())
172     {
173       text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
174     }
175     if (cs != null && cs.hasHiddenColumns())
176     {
177       text.append("VIEW_HIDECOLS\t");
178       List<int[]> hc = cs.getHiddenColumns();
179       boolean comma = false;
180       for (int[] r : hc)
181       {
182         if (!comma)
183         {
184           comma = true;
185         }
186         else
187         {
188           text.append(",");
189         }
190         text.append(r[0]);
191         text.append("-");
192         text.append(r[1]);
193       }
194       text.append("\n");
195     }
196     // TODO: allow efficient recovery of annotation data shown in several
197     // different views
198     if (annotations != null)
199     {
200       boolean oneColour = true;
201       AlignmentAnnotation row;
202       String comma;
203       SequenceI refSeq = null;
204       SequenceGroup refGroup = null;
205
206       StringBuffer colours = new StringBuffer();
207       StringBuffer graphLine = new StringBuffer();
208       StringBuffer rowprops = new StringBuffer();
209       Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
210       Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
211       BitSet graphGroupSeen = new BitSet();
212
213       java.awt.Color color;
214
215       for (int i = 0; i < annotations.length; i++)
216       {
217         row = annotations[i];
218
219         if (!row.visible
220                 && !row.hasScore()
221                 && !(row.graphGroup > -1 && graphGroupSeen
222                         .get(row.graphGroup)))
223         {
224           continue;
225         }
226
227         color = null;
228         oneColour = true;
229
230         // mark any sequence references for the row
231         writeSequence_Ref(refSeq, row.sequenceRef);
232         refSeq = row.sequenceRef;
233         // mark any group references for the row
234         writeGroup_Ref(refGroup, row.groupRef);
235         refGroup = row.groupRef;
236
237         boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
238         // lookahead to check what the annotation row object actually contains.
239         for (int j = 0; row.annotations != null
240                 && j < row.annotations.length
241                 && (!hasGlyphs || !hasLabels || !hasValues); j++)
242         {
243           if (row.annotations[j] != null)
244           {
245             hasLabels |= (row.annotations[j].displayCharacter != null
246                     && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
247                     .equals(" "));
248             hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
249             hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
250             // be
251             // rendered..
252             hasText |= (row.annotations[j].description != null && row.annotations[j].description
253                     .length() > 0);
254           }
255         }
256
257         if (row.graph == AlignmentAnnotation.NO_GRAPH)
258         {
259           text.append("NO_GRAPH\t");
260           hasValues = false; // only secondary structure
261           // hasLabels = false; // and annotation description string.
262         }
263         else
264         {
265           if (row.graph == AlignmentAnnotation.BAR_GRAPH)
266           {
267             text.append("BAR_GRAPH\t");
268             hasGlyphs = false; // no secondary structure
269
270           }
271           else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
272           {
273             hasGlyphs = false; // no secondary structure
274             text.append("LINE_GRAPH\t");
275           }
276
277           if (row.getThreshold() != null)
278           {
279             graphLine.append("GRAPHLINE\t");
280             graphLine.append(row.label);
281             graphLine.append("\t");
282             graphLine.append(row.getThreshold().value);
283             graphLine.append("\t");
284             graphLine.append(row.getThreshold().label);
285             graphLine.append("\t");
286             graphLine.append(jalview.util.Format.getHexString(row
287                     .getThreshold().colour));
288             graphLine.append(newline);
289           }
290
291           if (row.graphGroup > -1)
292           {
293             graphGroupSeen.set(row.graphGroup);
294             Integer key = new Integer(row.graphGroup);
295             if (graphGroup.containsKey(key))
296             {
297               graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
298
299             }
300             else
301             {
302               graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
303               graphGroup.put(key, row.label);
304             }
305           }
306         }
307
308         text.append(row.label + "\t");
309         if (row.description != null)
310         {
311           text.append(row.description + "\t");
312         }
313         for (int j = 0; row.annotations != null
314                 && j < row.annotations.length; j++)
315         {
316           if (refSeq != null
317                   && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
318           {
319             continue;
320           }
321
322           if (row.annotations[j] != null)
323           {
324             comma = "";
325             if (hasGlyphs) // could be also hasGlyphs || ...
326             {
327
328               text.append(comma);
329               if (row.annotations[j].secondaryStructure != ' ')
330               {
331                 // only write out the field if its not whitespace.
332                 text.append(row.annotations[j].secondaryStructure);
333               }
334               comma = ",";
335             }
336             if (hasValues)
337             {
338               if (!Float.isNaN(row.annotations[j].value))
339               {
340                 text.append(comma + row.annotations[j].value);
341               }
342               else
343               {
344                 // System.err.println("Skipping NaN - not valid value.");
345                 text.append(comma + 0f);// row.annotations[j].value);
346               }
347               comma = ",";
348             }
349             if (hasLabels)
350             {
351               // TODO: labels are emitted after values for bar graphs.
352               if // empty labels are allowed, so
353               (row.annotations[j].displayCharacter != null
354                       && row.annotations[j].displayCharacter.length() > 0
355                       && !row.annotations[j].displayCharacter.equals(" "))
356               {
357                 text.append(comma + row.annotations[j].displayCharacter);
358                 comma = ",";
359               }
360             }
361             if (hasText)
362             {
363               if (row.annotations[j].description != null
364                       && row.annotations[j].description.length() > 0
365                       && !row.annotations[j].description
366                               .equals(row.annotations[j].displayCharacter))
367               {
368                 text.append(comma + row.annotations[j].description);
369                 comma = ",";
370               }
371             }
372             if (color != null && !color.equals(row.annotations[j].colour))
373             {
374               oneColour = false;
375             }
376
377             color = row.annotations[j].colour;
378
379             if (row.annotations[j].colour != null
380                     && row.annotations[j].colour != java.awt.Color.black)
381             {
382               text.append(comma
383                       + "["
384                       + jalview.util.Format
385                               .getHexString(row.annotations[j].colour)
386                       + "]");
387               comma = ",";
388             }
389           }
390           text.append("|");
391         }
392
393         if (row.hasScore())
394         {
395           text.append("\t" + row.score);
396         }
397
398         text.append(newline);
399
400         if (color != null && color != java.awt.Color.black && oneColour)
401         {
402           colours.append("COLOUR\t");
403           colours.append(row.label);
404           colours.append("\t");
405           colours.append(jalview.util.Format.getHexString(color));
406           colours.append(newline);
407         }
408         if (row.scaleColLabel || row.showAllColLabels
409                 || row.centreColLabels)
410         {
411           rowprops.append("ROWPROPERTIES\t");
412           rowprops.append(row.label);
413           rowprops.append("\tscaletofit=");
414           rowprops.append(row.scaleColLabel);
415           rowprops.append("\tshowalllabs=");
416           rowprops.append(row.showAllColLabels);
417           rowprops.append("\tcentrelabs=");
418           rowprops.append(row.centreColLabels);
419           rowprops.append(newline);
420         }
421         if (graphLine.length() > 0)
422         {
423           text.append(graphLine.toString());
424           graphLine.setLength(0);
425         }
426       }
427
428       text.append(newline);
429
430       text.append(colours.toString());
431       if (graphGroup.size() > 0)
432       {
433         SequenceI oldRefSeq = refSeq;
434         SequenceGroup oldRefGroup = refGroup;
435         for (Map.Entry<Integer, String> combine_statement : graphGroup
436                 .entrySet())
437         {
438           Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
439                   .getKey());
440
441           writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
442           refSeq = (SequenceI) seqRefAndGroup[0];
443
444           writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
445           refGroup = (SequenceGroup) seqRefAndGroup[1];
446           text.append("COMBINE\t");
447           text.append(combine_statement.getValue());
448           text.append(newline);
449         }
450         writeSequence_Ref(refSeq, oldRefSeq);
451         refSeq = oldRefSeq;
452
453         writeGroup_Ref(refGroup, oldRefGroup);
454         refGroup = oldRefGroup;
455       }
456       text.append(rowprops.toString());
457     }
458
459     if (list != null)
460     {
461       printGroups(list);
462     }
463
464     if (properties != null)
465     {
466       text.append(newline);
467       text.append(newline);
468       text.append("ALIGNMENT");
469       Enumeration en = properties.keys();
470       while (en.hasMoreElements())
471       {
472         String key = en.nextElement().toString();
473         text.append("\t");
474         text.append(key);
475         text.append("=");
476         text.append(properties.get(key));
477       }
478       // TODO: output alignment visualization settings here if required
479       // iterate through one or more views, defining, marking columns and rows
480       // as visible/hidden, and emmitting view properties.
481       // View specific annotation is
482     }
483
484     return text.toString();
485   }
486
487   private Object writeGroup_Ref(SequenceGroup refGroup,
488           SequenceGroup next_refGroup)
489   {
490     if (next_refGroup == null)
491     {
492
493       if (refGroup != null)
494       {
495         text.append(newline);
496         text.append("GROUP_REF\t");
497         text.append("ALIGNMENT");
498         text.append(newline);
499       }
500       return true;
501     }
502     else
503     {
504       if (refGroup == null || refGroup != next_refGroup)
505       {
506         text.append(newline);
507         text.append("GROUP_REF\t");
508         text.append(next_refGroup.getName());
509         text.append(newline);
510         return true;
511       }
512     }
513     return false;
514   }
515
516   private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
517   {
518
519     if (next_refSeq == null)
520     {
521       if (refSeq != null)
522       {
523         text.append(newline);
524         text.append("SEQUENCE_REF\t");
525         text.append("ALIGNMENT");
526         text.append(newline);
527         return true;
528       }
529     }
530     else
531     {
532       if (refSeq == null || refSeq != next_refSeq)
533       {
534         text.append(newline);
535         text.append("SEQUENCE_REF\t");
536         text.append(next_refSeq.getName());
537         text.append(newline);
538         return true;
539       }
540     }
541     return false;
542   }
543
544   public void printGroups(List<SequenceGroup> list)
545   {
546     SequenceI seqrep = null;
547     for (SequenceGroup sg : list)
548     {
549       if (!sg.hasSeqrep())
550       {
551         text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
552                 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
553                 + "\t" + "-1\t");
554         seqrep = null;
555       }
556       else
557       {
558         seqrep = sg.getSeqrep();
559         text.append("SEQUENCE_REF\t");
560         text.append(seqrep.getName());
561         text.append(newline);
562         text.append("SEQUENCE_GROUP\t");
563         text.append(sg.getName());
564         text.append("\t");
565         text.append((seqrep.findPosition(sg.getStartRes())));
566         text.append("\t");
567         text.append((seqrep.findPosition(sg.getEndRes())));
568         text.append("\t");
569         text.append("-1\t");
570       }
571       for (int s = 0; s < sg.getSize(); s++)
572       {
573         text.append(sg.getSequenceAt(s).getName());
574         text.append("\t");
575       }
576       text.append(newline);
577       text.append("PROPERTIES\t");
578       text.append(sg.getName());
579       text.append("\t");
580
581       if (sg.getDescription() != null)
582       {
583         text.append("description=");
584         text.append(sg.getDescription());
585         text.append("\t");
586       }
587       if (sg.cs != null)
588       {
589         text.append("colour=");
590         text.append(sg.cs.toString());
591         text.append("\t");
592         if (sg.cs.getThreshold() != 0)
593         {
594           text.append("pidThreshold=");
595           text.append(sg.cs.getThreshold());
596         }
597         if (sg.cs.conservationApplied())
598         {
599           text.append("consThreshold=");
600           text.append(sg.cs.getConservationInc());
601           text.append("\t");
602         }
603       }
604       text.append("outlineColour=");
605       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
606       text.append("\t");
607
608       text.append("displayBoxes=");
609       text.append(sg.getDisplayBoxes());
610       text.append("\t");
611       text.append("displayText=");
612       text.append(sg.getDisplayText());
613       text.append("\t");
614       text.append("colourText=");
615       text.append(sg.getColourText());
616       text.append("\t");
617       text.append("showUnconserved=");
618       text.append(sg.getShowNonconserved());
619       text.append("\t");
620       if (sg.textColour != java.awt.Color.black)
621       {
622         text.append("textCol1=");
623         text.append(jalview.util.Format.getHexString(sg.textColour));
624         text.append("\t");
625       }
626       if (sg.textColour2 != java.awt.Color.white)
627       {
628         text.append("textCol2=");
629         text.append(jalview.util.Format.getHexString(sg.textColour2));
630         text.append("\t");
631       }
632       if (sg.thresholdTextColour != 0)
633       {
634         text.append("textColThreshold=");
635         text.append(sg.thresholdTextColour);
636         text.append("\t");
637       }
638       if (sg.idColour != null)
639       {
640         text.append("idColour=");
641         text.append(jalview.util.Format.getHexString(sg.idColour));
642         text.append("\t");
643       }
644       if (sg.isHidereps())
645       {
646         text.append("hide=true\t");
647       }
648       if (sg.isHideCols())
649       {
650         text.append("hidecols=true\t");
651       }
652       if (seqrep != null)
653       {
654         // terminate the last line and clear the sequence ref for the group
655         text.append(newline);
656         text.append("SEQUENCE_REF");
657       }
658       text.append(newline);
659       text.append(newline);
660
661     }
662   }
663
664   SequenceI refSeq = null;
665
666   String refSeqId = null;
667
668   public boolean annotateAlignmentView(AlignViewportI viewport,
669           String file, DataSourceType protocol)
670   {
671     ColumnSelection colSel = viewport.getColumnSelection();
672     if (colSel == null)
673     {
674       colSel = new ColumnSelection();
675     }
676     boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
677             file, protocol);
678     if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
679     {
680       viewport.setColumnSelection(colSel);
681     }
682
683     return rslt;
684   }
685
686   public boolean readAnnotationFile(AlignmentI al, String file,
687           DataSourceType sourceType)
688   {
689     return readAnnotationFile(al, null, file, sourceType);
690   }
691
692   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
693           String file, DataSourceType sourceType)
694   {
695     baseUri = "";
696     BufferedReader in = null;
697     try
698     {
699       if (sourceType == DataSourceType.FILE)
700       {
701         in = new BufferedReader(new FileReader(file));
702         baseUri = new File(file).getParent();
703         if (baseUri == null)
704         {
705           baseUri = "";
706         }
707         else
708         {
709           baseUri += "/";
710         }
711       }
712       else if (sourceType == DataSourceType.URL)
713       {
714         URL url = new URL(file);
715         in = new BufferedReader(new InputStreamReader(url.openStream()));
716         String bs = url.toExternalForm();
717         baseUri = bs.substring(0, bs.indexOf(url.getHost())
718                 + url.getHost().length());
719         baseUri += url.toURI().getPath();
720         if (baseUri.lastIndexOf("/") > -1)
721         {
722           baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
723         }
724       }
725       else if (sourceType == DataSourceType.PASTE)
726       {
727         in = new BufferedReader(new StringReader(file));
728         // TODO - support mimencoded PDBs for a paste.. ?
729         baseUri = "";
730       }
731       else if (sourceType == DataSourceType.CLASSLOADER)
732       {
733         java.io.InputStream is = getClass().getResourceAsStream("/" + file);
734         if (is != null)
735         {
736           in = new BufferedReader(new java.io.InputStreamReader(is));
737           // TODO: this probably doesn't work for classloader - needs a test
738           baseUri = new File("/" + file).getParent() + "/";
739         }
740       }
741       if (in != null)
742       {
743         return parseAnnotationFrom(al, colSel, in);
744       }
745
746     } catch (Exception ex)
747     {
748       ex.printStackTrace();
749       System.out.println("Problem reading annotation file: " + ex);
750       if (nlinesread > 0)
751       {
752         System.out.println("Last read line " + nlinesread + ": '"
753                 + lastread + "' (first 80 chars) ...");
754       }
755       return false;
756     }
757     return false;
758   }
759
760   long nlinesread = 0;
761
762   String lastread = "";
763
764   /**
765    * used for resolving absolute references to resources relative to
766    * annotationFile location
767    */
768   String baseUri = "";
769
770   private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
771           STRUCTMODEL = "STRUCTMODEL";
772
773   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
774           BufferedReader in) throws Exception
775   {
776     nlinesread = 0;
777     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
778     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
779     boolean modified = false;
780     String groupRef = null;
781     Hashtable groupRefRows = new Hashtable();
782
783     Hashtable autoAnnots = new Hashtable();
784     {
785       String line, label, description, token;
786       int graphStyle, index;
787       int refSeqIndex = 1;
788       int existingAnnotations = 0;
789       // when true - will add new rows regardless of whether they are duplicate
790       // auto-annotation like consensus or conservation graphs
791       boolean overrideAutoAnnot = false;
792       if (al.getAlignmentAnnotation() != null)
793       {
794         existingAnnotations = al.getAlignmentAnnotation().length;
795         if (existingAnnotations > 0)
796         {
797           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
798           for (int aai = 0; aai < aa.length; aai++)
799           {
800             if (aa[aai].autoCalculated)
801             {
802               // make a note of the name and description
803               autoAnnots.put(
804                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
805                               (aa[aai].groupRef == null ? null
806                                       : aa[aai].groupRef.getName())),
807                       new Integer(1));
808             }
809           }
810         }
811       }
812
813       int alWidth = al.getWidth();
814
815       StringTokenizer st;
816       Annotation[] annotations;
817       AlignmentAnnotation annotation = null;
818
819       // First confirm this is an Annotation file
820       boolean jvAnnotationFile = false;
821       while ((line = in.readLine()) != null)
822       {
823         nlinesread++;
824         lastread = new String(line);
825         if (line.indexOf("#") == 0)
826         {
827           continue;
828         }
829
830         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
831         {
832           jvAnnotationFile = true;
833           break;
834         }
835       }
836
837       if (!jvAnnotationFile)
838       {
839         in.close();
840         return false;
841       }
842
843       while ((line = in.readLine()) != null)
844       {
845         nlinesread++;
846         lastread = new String(line);
847         if (line.indexOf("#") == 0
848                 || line.indexOf("JALVIEW_ANNOTATION") > -1
849                 || line.length() == 0)
850         {
851           continue;
852         }
853
854         st = new StringTokenizer(line, "\t");
855         token = st.nextToken();
856         if (token.equalsIgnoreCase("COLOUR"))
857         {
858           // TODO: use graduated colour def'n here too
859           colourAnnotations(al, st.nextToken(), st.nextToken());
860           modified = true;
861           continue;
862         }
863
864         else if (token.equalsIgnoreCase(COMBINE))
865         {
866           // keep a record of current state and resolve groupRef at end
867           combineAnnotation_calls
868                   .add(new Object[] { st, refSeq, groupRef });
869           modified = true;
870           continue;
871         }
872         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
873         {
874           addRowProperties(al, st);
875           modified = true;
876           continue;
877         }
878         else if (token.equalsIgnoreCase(GRAPHLINE))
879         {
880           // resolve at end
881           deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
882               refSeq, groupRef });
883           modified = true;
884           continue;
885         }
886
887         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
888         {
889           if (st.hasMoreTokens())
890           {
891             refSeq = al.findName(refSeqId = st.nextToken());
892             if (refSeq == null)
893             {
894               refSeqId = null;
895             }
896             try
897             {
898               refSeqIndex = Integer.parseInt(st.nextToken());
899               if (refSeqIndex < 1)
900               {
901                 refSeqIndex = 1;
902                 System.out
903                         .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
904               }
905             } catch (Exception ex)
906             {
907               refSeqIndex = 1;
908             }
909           }
910           else
911           {
912             refSeq = null;
913             refSeqId = null;
914           }
915           continue;
916         }
917         else if (token.equalsIgnoreCase("GROUP_REF"))
918         {
919           // Group references could be forward or backwards, so they are
920           // resolved after the whole file is read in
921           groupRef = null;
922           if (st.hasMoreTokens())
923           {
924             groupRef = st.nextToken();
925             if (groupRef.length() < 1)
926             {
927               groupRef = null; // empty string
928             }
929             else
930             {
931               if (groupRefRows.get(groupRef) == null)
932               {
933                 groupRefRows.put(groupRef, new Vector());
934               }
935             }
936           }
937           continue;
938         }
939         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
940         {
941           addGroup(al, st);
942           modified = true;
943           continue;
944         }
945
946         else if (token.equalsIgnoreCase("PROPERTIES"))
947         {
948           addProperties(al, st);
949           modified = true;
950           continue;
951         }
952
953         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
954         {
955           setBelowAlignment(al, st);
956           modified = true;
957           continue;
958         }
959         else if (token.equalsIgnoreCase("ALIGNMENT"))
960         {
961           addAlignmentDetails(al, st);
962           modified = true;
963           continue;
964         }
965         // else if (token.equalsIgnoreCase("VIEW_DEF"))
966         // {
967         // addOrSetView(al,st);
968         // modified = true;
969         // continue;
970         // }
971         else if (token.equalsIgnoreCase("VIEW_SETREF"))
972         {
973           if (refSeq != null)
974           {
975             al.setSeqrep(refSeq);
976           }
977           modified = true;
978           continue;
979         }
980         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
981         {
982           if (st.hasMoreTokens())
983           {
984             if (colSel == null)
985             {
986               colSel = new ColumnSelection();
987             }
988             parseHideCols(colSel, st.nextToken());
989           }
990           modified = true;
991           continue;
992         }
993         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
994         {
995           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
996           if (sr == null)
997           {
998             sr = al.getSequenceAt(0);
999           }
1000           if (sr != null)
1001           {
1002             if (colSel == null)
1003             {
1004               System.err
1005                       .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1006                               + line);
1007             }
1008             else
1009             {
1010               // consider deferring this till after the file has been parsed ?
1011               colSel.hideInsertionsFor(sr);
1012             }
1013           }
1014           modified = true;
1015           continue;
1016         }
1017         else if (token.equalsIgnoreCase(STRUCTMODEL))
1018         {
1019           boolean failedtoadd = true;
1020           // expect
1021           // STRUCTMODEL <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile>
1022           // <Confidence> <%.I.D>
1023           // <MatchStart> <MatchEnd> <Coverage> [<Other Information>]
1024           String querySeqId = !st.hasMoreTokens() ? "" : st.nextToken();
1025           SequenceI querySeq = al.findName(querySeqId);
1026           if (st.hasMoreTokens()) {
1027             refSeq = al.findName(refSeqId = st.nextToken());
1028             if (refSeq == null)
1029             {
1030               System.err.println("Couldn't locate " + refSeqId
1031                       + " in the alignment for STRUCTMODEL");
1032               refSeqId = null;
1033             }
1034             else
1035             {
1036               String tempId = st.nextToken();
1037               String fastaMapping = st.nextToken();
1038               String confidence = !st.hasMoreTokens() ? "" : 100
1039                       * Double.valueOf(st.nextToken()) + "";
1040               String pid = !st.hasMoreTokens() ? "" : st.nextToken();
1041               String alignRange = !st.hasMoreTokens() ? "" : st.nextToken()
1042                       + "-" + st.nextToken();
1043               String otherInfo = !st.hasMoreTokens() ? "" : st.nextToken();
1044               String coverage = "";
1045               if (add_structmodel(al, querySeq, refSeq, tempId,
1046                       fastaMapping,
1047                       alignRange, coverage,
1048                       confidence, pid, otherInfo))
1049               {
1050                 failedtoadd = false;
1051               }
1052             }
1053           }
1054           if (failedtoadd)
1055           {
1056             System.err
1057                     .println("Need <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile> <Confidence> <%.I.D> <MatchStart> <MatchEnd> <Coverage> [<Other Information>] as tab separated fields after"
1058                             + STRUCTMODEL
1059                             + ".\nNote: other information could be provided in html format ");
1060           } else {
1061             modified = true;
1062           }
1063           continue;
1064         }
1065         // Parse out the annotation row
1066         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1067         label = st.nextToken();
1068
1069         index = 0;
1070         annotations = new Annotation[alWidth];
1071         description = null;
1072         float score = Float.NaN;
1073
1074         if (st.hasMoreTokens())
1075         {
1076           line = st.nextToken();
1077
1078           if (line.indexOf("|") == -1)
1079           {
1080             description = line;
1081             if (st.hasMoreTokens())
1082             {
1083               line = st.nextToken();
1084             }
1085           }
1086
1087           if (st.hasMoreTokens())
1088           {
1089             // This must be the score
1090             score = Float.valueOf(st.nextToken()).floatValue();
1091           }
1092
1093           st = new StringTokenizer(line, "|", true);
1094
1095           boolean emptyColumn = true;
1096           boolean onlyOneElement = (st.countTokens() == 1);
1097
1098           while (st.hasMoreElements() && index < alWidth)
1099           {
1100             token = st.nextToken().trim();
1101
1102             if (onlyOneElement)
1103             {
1104               try
1105               {
1106                 score = Float.valueOf(token).floatValue();
1107                 break;
1108               } catch (NumberFormatException ex)
1109               {
1110               }
1111             }
1112
1113             if (token.equals("|"))
1114             {
1115               if (emptyColumn)
1116               {
1117                 index++;
1118               }
1119
1120               emptyColumn = true;
1121             }
1122             else
1123             {
1124               annotations[index++] = parseAnnotation(token, graphStyle);
1125               emptyColumn = false;
1126             }
1127           }
1128
1129         }
1130
1131         annotation = new AlignmentAnnotation(label, description,
1132                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1133
1134         annotation.score = score;
1135         if (!overrideAutoAnnot
1136                 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1137                         groupRef)))
1138         {
1139           // skip - we've already got an automatic annotation of this type.
1140           continue;
1141         }
1142         // otherwise add it!
1143         if (refSeq != null)
1144         {
1145
1146           annotation.belowAlignment = false;
1147           // make a copy of refSeq so we can find other matches in the alignment
1148           SequenceI referedSeq = refSeq;
1149           do
1150           {
1151             // copy before we do any mapping business.
1152             // TODO: verify that undo/redo with 1:many sequence associated
1153             // annotations can be undone correctly
1154             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1155             annotation
1156                     .createSequenceMapping(referedSeq, refSeqIndex, false);
1157             annotation.adjustForAlignment();
1158             referedSeq.addAlignmentAnnotation(annotation);
1159             al.addAnnotation(annotation);
1160             al.setAnnotationIndex(annotation,
1161                     al.getAlignmentAnnotation().length
1162                             - existingAnnotations - 1);
1163             if (groupRef != null)
1164             {
1165               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1166             }
1167             // and recover our virgin copy to use again if necessary.
1168             annotation = ann;
1169
1170           } while (refSeqId != null
1171                   && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1172         }
1173         else
1174         {
1175           al.addAnnotation(annotation);
1176           al.setAnnotationIndex(annotation,
1177                   al.getAlignmentAnnotation().length - existingAnnotations
1178                           - 1);
1179           if (groupRef != null)
1180           {
1181             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1182           }
1183         }
1184         // and set modification flag
1185         modified = true;
1186       }
1187       // Resolve the groupRefs
1188       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1189       Enumeration en = groupRefRows.keys();
1190
1191       while (en.hasMoreElements())
1192       {
1193         groupRef = (String) en.nextElement();
1194         boolean matched = false;
1195         // Resolve group: TODO: add a getGroupByName method to alignments
1196         for (SequenceGroup theGroup : al.getGroups())
1197         {
1198           if (theGroup.getName().equals(groupRef))
1199           {
1200             if (matched)
1201             {
1202               // TODO: specify and implement duplication of alignment annotation
1203               // for multiple group references.
1204               System.err
1205                       .println("Ignoring 1:many group reference mappings for group name '"
1206                               + groupRef + "'");
1207             }
1208             else
1209             {
1210               matched = true;
1211               Vector rowset = (Vector) groupRefRows.get(groupRef);
1212               groupRefLookup.put(groupRef, theGroup);
1213               if (rowset != null && rowset.size() > 0)
1214               {
1215                 AlignmentAnnotation alan = null;
1216                 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1217                 {
1218                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1219                   alan.groupRef = theGroup;
1220                 }
1221               }
1222             }
1223           }
1224         }
1225         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1226       }
1227       // process any deferred attribute settings for each context
1228       for (Object[] _deferred_args : deferredAnnotation_calls)
1229       {
1230         if (_deferred_args[0] == GRAPHLINE)
1231         {
1232           addLine(al,
1233                   (StringTokenizer) _deferred_args[1], // st
1234                   (SequenceI) _deferred_args[2], // refSeq
1235                   (_deferred_args[3] == null) ? null : groupRefLookup
1236                           .get(_deferred_args[3]) // the reference
1237                                                   // group, or null
1238           );
1239         }
1240       }
1241
1242       // finally, combine all the annotation rows within each context.
1243       /**
1244        * number of combine statements in this annotation file. Used to create
1245        * new groups for combined annotation graphs without disturbing existing
1246        * ones
1247        */
1248       int combinecount = 0;
1249       for (Object[] _combine_args : combineAnnotation_calls)
1250       {
1251         combineAnnotations(al,
1252                 ++combinecount,
1253                 (StringTokenizer) _combine_args[0], // st
1254                 (SequenceI) _combine_args[1], // refSeq
1255                 (_combine_args[2] == null) ? null : groupRefLookup
1256                         .get(_combine_args[2]) // the reference group,
1257                                                // or null
1258         );
1259       }
1260     }
1261     return modified;
1262   }
1263
1264   /**
1265    * resolve a structural model and generate and add an alignment sequence for
1266    * it
1267    * 
1268    * @param refSeq2
1269    * @param tempId
1270    * @param urlToModel
1271    * @param urlToPairwise
1272    * @return true if model and sequence was added
1273    */
1274   private boolean add_structmodel(AlignmentI al, SequenceI querySequence,
1275           SequenceI templateSeq,
1276           String modelFile, String fastaFile, String aRange,
1277           String coverage, String confidence,
1278           String pid, String otherInfo)
1279   {
1280     String warningMessage = null;
1281     boolean added = false;
1282     try {
1283       String structureModelFile = resolveAbsolute(modelFile);
1284       String fastaMappingFile = resolveAbsolute(fastaFile.replaceAll(
1285               ".fasta.jal", ".fasta"));
1286       // System.out.println("Model File >> " + structureModelFile);
1287       // System.out.println("Fasta File >> " + fastaMappingFile);
1288       PDBEntry phyre2PDBEntry = new PDBEntry(modelFile, null, Type.FILE,
1289               structureModelFile);
1290       String phyre2ModelDesc = generatePhyre2InfoHTMLTable(aRange,
1291               coverage, confidence, pid, otherInfo);
1292       phyre2PDBEntry.setProperty("PHYRE2_MODEL_INFO", phyre2ModelDesc);
1293       templateSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
1294       if (querySequence != null)
1295       {
1296         querySequence.getDatasetSequence().addPDBId(phyre2PDBEntry);
1297       }
1298       StructureSelectionManager ssm = StructureSelectionManager
1299               .getStructureSelectionManager(Desktop.instance);
1300       ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
1301       added = true;
1302
1303     } catch (Exception x)
1304     {
1305       warningMessage = x.toString();
1306     } finally {
1307       if (warningMessage !=null)
1308       {
1309         System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1310       }
1311     }
1312     return added;
1313   }
1314
1315   private String generatePhyre2InfoHTMLTable(String aRange,
1316           String coverage, String confidence, String pid, String otherInfo)
1317   {
1318     StringBuilder phyre2InfoBuilder = new StringBuilder();
1319     phyre2InfoBuilder.append("<html><table border=\"1\" width=100%>");
1320     phyre2InfoBuilder
1321             .append("<tr><td colspan=\"2\"><strong>Phyre2 Template Info</strong></td></tr>");
1322     if (aRange != null && !aRange.isEmpty())
1323     {
1324       phyre2InfoBuilder.append("<tr><td>").append("Aligned range")
1325               .append("</td><td>").append(aRange).append("</td></tr>");
1326     }
1327     if (coverage != null && !coverage.isEmpty())
1328     {
1329       phyre2InfoBuilder.append("<tr><td>").append("Coverage")
1330               .append("</td><td>").append(coverage).append("</td></tr>");
1331     }
1332     if (confidence != null && !confidence.isEmpty())
1333     {
1334       phyre2InfoBuilder.append("<tr><td>").append("Confidence")
1335               .append("</td><td>").append(confidence).append("</td></tr>");
1336     }
1337     if (pid != null && !pid.isEmpty())
1338     {
1339       phyre2InfoBuilder.append("<tr><td>").append("%.i.d")
1340               .append("</td><td>").append(pid).append("</td></tr>");
1341     }
1342     if (otherInfo != null && !otherInfo.isEmpty())
1343     {
1344       phyre2InfoBuilder.append("<tr><td>").append("Other information")
1345               .append("</td><td>").append(otherInfo).append("</td></tr>");
1346     }
1347     phyre2InfoBuilder.append("</table></html>");
1348     return phyre2InfoBuilder.toString();
1349   }
1350
1351   private String resolveAbsolute(String relURI)
1352   {
1353     if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1354             || "".equals(baseUri) || relURI.startsWith(baseUri))
1355     {
1356       return relURI;
1357     }
1358     return baseUri + relURI;
1359   }
1360
1361   private void parseHideCols(ColumnSelection colSel, String nextToken)
1362   {
1363     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1364     while (inval.hasMoreTokens())
1365     {
1366       String range = inval.nextToken().trim();
1367       int from, to = range.indexOf("-");
1368       if (to == -1)
1369       {
1370         from = to = Integer.parseInt(range);
1371         if (from >= 0)
1372         {
1373           colSel.hideColumns(from, to);
1374         }
1375       }
1376       else
1377       {
1378         from = Integer.parseInt(range.substring(0, to));
1379         if (to < range.length() - 1)
1380         {
1381           to = Integer.parseInt(range.substring(to + 1));
1382         }
1383         else
1384         {
1385           to = from;
1386         }
1387         if (from > 0 && to >= from)
1388         {
1389           colSel.hideColumns(from, to);
1390         }
1391       }
1392     }
1393   }
1394
1395   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1396           SequenceI refSeq, String groupRef)
1397   {
1398     return annotation.graph + "\t" + annotation.label + "\t"
1399             + annotation.description + "\t"
1400             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1401   }
1402
1403   Annotation parseAnnotation(String string, int graphStyle)
1404   {
1405     // don't do the glyph test if we don't want secondary structure
1406     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1407     String desc = null, displayChar = null;
1408     char ss = ' '; // secondaryStructure
1409     float value = 0;
1410     boolean parsedValue = false, dcset = false;
1411
1412     // find colour here
1413     Color colour = null;
1414     int i = string.indexOf("[");
1415     int j = string.indexOf("]");
1416     if (i > -1 && j > -1)
1417     {
1418       colour = ColorUtils.parseColourString(string.substring(i + 1,
1419               j));
1420       if (i > 0 && string.charAt(i - 1) == ',')
1421       {
1422         // clip the preceding comma as well
1423         i--;
1424       }
1425       string = string.substring(0, i) + string.substring(j + 1);
1426     }
1427
1428     StringTokenizer st = new StringTokenizer(string, ",", true);
1429     String token;
1430     boolean seenContent = false;
1431     int pass = 0;
1432     while (st.hasMoreTokens())
1433     {
1434       pass++;
1435       token = st.nextToken().trim();
1436       if (token.equals(","))
1437       {
1438         if (!seenContent && parsedValue && !dcset)
1439         {
1440           // allow the value below the bar/line to be empty
1441           dcset = true;
1442           displayChar = " ";
1443         }
1444         seenContent = false;
1445         continue;
1446       }
1447       else
1448       {
1449         seenContent = true;
1450       }
1451
1452       if (!parsedValue)
1453       {
1454         try
1455         {
1456           displayChar = token;
1457           // foo
1458           value = new Float(token).floatValue();
1459           parsedValue = true;
1460           continue;
1461         } catch (NumberFormatException ex)
1462         {
1463         }
1464       }
1465       else
1466       {
1467         if (token.length() == 1)
1468         {
1469           displayChar = token;
1470         }
1471       }
1472       if (hasSymbols
1473               && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1474                       .contains(token)))
1475       {
1476         // Either this character represents a helix or sheet
1477         // or an integer which can be displayed
1478         ss = token.charAt(0);
1479         if (displayChar.equals(token.substring(0, 1)))
1480         {
1481           displayChar = "";
1482         }
1483       }
1484       else if (desc == null || (parsedValue && pass > 2))
1485       {
1486         desc = token;
1487       }
1488
1489     }
1490     // if (!dcset && string.charAt(string.length() - 1) == ',')
1491     // {
1492     // displayChar = " "; // empty display char symbol.
1493     // }
1494     if (displayChar != null && desc != null && desc.length() == 1)
1495     {
1496       if (displayChar.length() > 1)
1497       {
1498         // switch desc and displayChar - legacy support
1499         String tmp = displayChar;
1500         displayChar = desc;
1501         desc = tmp;
1502       }
1503       else
1504       {
1505         if (displayChar.equals(desc))
1506         {
1507           // duplicate label - hangover from the 'robust parser' above
1508           desc = null;
1509         }
1510       }
1511     }
1512     Annotation anot = new Annotation(displayChar, desc, ss, value);
1513
1514     anot.colour = colour;
1515
1516     return anot;
1517   }
1518
1519   void colourAnnotations(AlignmentI al, String label, String colour)
1520   {
1521     Color awtColour = ColorUtils.parseColourString(colour);
1522     Annotation[] annotations;
1523     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1524     {
1525       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1526       {
1527         annotations = al.getAlignmentAnnotation()[i].annotations;
1528         for (int j = 0; j < annotations.length; j++)
1529         {
1530           if (annotations[j] != null)
1531           {
1532             annotations[j].colour = awtColour;
1533           }
1534         }
1535       }
1536     }
1537   }
1538
1539   void combineAnnotations(AlignmentI al, int combineCount,
1540           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1541   {
1542     String group = st.nextToken();
1543     // First make sure we are not overwriting the graphIndex
1544     int graphGroup = 0;
1545     if (al.getAlignmentAnnotation() != null)
1546     {
1547       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1548       {
1549         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1550
1551         if (aa.graphGroup > graphGroup)
1552         {
1553           // try to number graphGroups in order of occurence.
1554           graphGroup = aa.graphGroup + 1;
1555         }
1556         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1557                 && aa.label.equalsIgnoreCase(group))
1558         {
1559           if (aa.graphGroup > -1)
1560           {
1561             graphGroup = aa.graphGroup;
1562           }
1563           else
1564           {
1565             if (graphGroup <= combineCount)
1566             {
1567               graphGroup = combineCount + 1;
1568             }
1569             aa.graphGroup = graphGroup;
1570           }
1571           break;
1572         }
1573       }
1574
1575       // Now update groups
1576       while (st.hasMoreTokens())
1577       {
1578         group = st.nextToken();
1579         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1580         {
1581           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1582           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1583                   && aa.label.equalsIgnoreCase(group))
1584           {
1585             aa.graphGroup = graphGroup;
1586             break;
1587           }
1588         }
1589       }
1590     }
1591     else
1592     {
1593       System.err
1594               .println("Couldn't combine annotations. None are added to alignment yet!");
1595     }
1596   }
1597
1598   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1599           SequenceGroup groupRef)
1600   {
1601     String group = st.nextToken();
1602     AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1603     String nextToken = st.nextToken();
1604     float value = 0f;
1605     try
1606     {
1607       value = Float.valueOf(nextToken);
1608     } catch (NumberFormatException e)
1609     {
1610       System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1611               + "' invalid, setting to zero");
1612     }
1613     String label = st.hasMoreTokens() ? st.nextToken() : null;
1614     Color colour = null;
1615     if (st.hasMoreTokens())
1616     {
1617       colour = ColorUtils.parseColourString(st.nextToken());
1618     }
1619     if (alannot != null)
1620     {
1621       for (int i = 0; i < alannot.length; i++)
1622       {
1623         if (alannot[i].label.equalsIgnoreCase(group)
1624                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1625                 && (groupRef == null || alannot[i].groupRef == groupRef))
1626         {
1627           alannot[i].setThreshold(new GraphLine(value, label, colour));
1628         }
1629       }
1630     }
1631   }
1632
1633   void addGroup(AlignmentI al, StringTokenizer st)
1634   {
1635     SequenceGroup sg = new SequenceGroup();
1636     sg.setName(st.nextToken());
1637     String rng = "";
1638     try
1639     {
1640       rng = st.nextToken();
1641       if (rng.length() > 0 && !rng.startsWith("*"))
1642       {
1643         sg.setStartRes(Integer.parseInt(rng) - 1);
1644       }
1645       else
1646       {
1647         sg.setStartRes(0);
1648       }
1649       rng = st.nextToken();
1650       if (rng.length() > 0 && !rng.startsWith("*"))
1651       {
1652         sg.setEndRes(Integer.parseInt(rng) - 1);
1653       }
1654       else
1655       {
1656         sg.setEndRes(al.getWidth() - 1);
1657       }
1658     } catch (Exception e)
1659     {
1660       System.err
1661               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1662                       + rng + "' - assuming alignment width for group.");
1663       // assume group is full width
1664       sg.setStartRes(0);
1665       sg.setEndRes(al.getWidth() - 1);
1666     }
1667
1668     String index = st.nextToken();
1669     if (index.equals("-1"))
1670     {
1671       while (st.hasMoreElements())
1672       {
1673         sg.addSequence(al.findName(st.nextToken()), false);
1674       }
1675     }
1676     else
1677     {
1678       StringTokenizer st2 = new StringTokenizer(index, ",");
1679
1680       while (st2.hasMoreTokens())
1681       {
1682         String tmp = st2.nextToken();
1683         if (tmp.equals("*"))
1684         {
1685           for (int i = 0; i < al.getHeight(); i++)
1686           {
1687             sg.addSequence(al.getSequenceAt(i), false);
1688           }
1689         }
1690         else if (tmp.indexOf("-") >= 0)
1691         {
1692           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1693
1694           int start = (Integer.parseInt(st3.nextToken()));
1695           int end = (Integer.parseInt(st3.nextToken()));
1696
1697           if (end > start)
1698           {
1699             for (int i = start; i <= end; i++)
1700             {
1701               sg.addSequence(al.getSequenceAt(i - 1), false);
1702             }
1703           }
1704         }
1705         else
1706         {
1707           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1708         }
1709       }
1710     }
1711
1712     if (refSeq != null)
1713     {
1714       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1715       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1716       sg.setSeqrep(refSeq);
1717     }
1718
1719     if (sg.getSize() > 0)
1720     {
1721       al.addGroup(sg);
1722     }
1723   }
1724
1725   void addRowProperties(AlignmentI al, StringTokenizer st)
1726   {
1727     String label = st.nextToken(), keyValue, key, value;
1728     boolean scaletofit = false, centerlab = false, showalllabs = false;
1729     while (st.hasMoreTokens())
1730     {
1731       keyValue = st.nextToken();
1732       key = keyValue.substring(0, keyValue.indexOf("="));
1733       value = keyValue.substring(keyValue.indexOf("=") + 1);
1734       if (key.equalsIgnoreCase("scaletofit"))
1735       {
1736         scaletofit = Boolean.valueOf(value).booleanValue();
1737       }
1738       if (key.equalsIgnoreCase("showalllabs"))
1739       {
1740         showalllabs = Boolean.valueOf(value).booleanValue();
1741       }
1742       if (key.equalsIgnoreCase("centrelabs"))
1743       {
1744         centerlab = Boolean.valueOf(value).booleanValue();
1745       }
1746       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1747       if (alr != null)
1748       {
1749         for (int i = 0; i < alr.length; i++)
1750         {
1751           if (alr[i].label.equalsIgnoreCase(label))
1752           {
1753             alr[i].centreColLabels = centerlab;
1754             alr[i].scaleColLabel = scaletofit;
1755             alr[i].showAllColLabels = showalllabs;
1756           }
1757         }
1758       }
1759     }
1760   }
1761
1762   void addProperties(AlignmentI al, StringTokenizer st)
1763   {
1764
1765     // So far we have only added groups to the annotationHash,
1766     // the idea is in the future properties can be added to
1767     // alignments, other annotations etc
1768     if (al.getGroups() == null)
1769     {
1770       return;
1771     }
1772
1773     String name = st.nextToken();
1774     SequenceGroup sg = null;
1775     for (SequenceGroup _sg : al.getGroups())
1776     {
1777       if ((sg = _sg).getName().equals(name))
1778       {
1779         break;
1780       }
1781       else
1782       {
1783         sg = null;
1784       }
1785     }
1786
1787     if (sg != null)
1788     {
1789       String keyValue, key, value;
1790       ColourSchemeI def = sg.getColourScheme();
1791       while (st.hasMoreTokens())
1792       {
1793         keyValue = st.nextToken();
1794         key = keyValue.substring(0, keyValue.indexOf("="));
1795         value = keyValue.substring(keyValue.indexOf("=") + 1);
1796
1797         if (key.equalsIgnoreCase("description"))
1798         {
1799           sg.setDescription(value);
1800         }
1801         else if (key.equalsIgnoreCase("colour"))
1802         {
1803           sg.cs.setColourScheme(ColourSchemeProperty
1804                   .getColourScheme(al, value));
1805         }
1806         else if (key.equalsIgnoreCase("pidThreshold"))
1807         {
1808           sg.cs.setThreshold(Integer.parseInt(value), true);
1809
1810         }
1811         else if (key.equalsIgnoreCase("consThreshold"))
1812         {
1813           sg.cs.setConservationInc(Integer.parseInt(value));
1814           Conservation c = new Conservation("Group", sg.getSequences(null),
1815                   sg.getStartRes(), sg.getEndRes() + 1);
1816
1817           c.calculate();
1818           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1819
1820           sg.cs.setConservation(c);
1821
1822         }
1823         else if (key.equalsIgnoreCase("outlineColour"))
1824         {
1825           sg.setOutlineColour(ColorUtils.parseColourString(value));
1826         }
1827         else if (key.equalsIgnoreCase("displayBoxes"))
1828         {
1829           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1830         }
1831         else if (key.equalsIgnoreCase("showUnconserved"))
1832         {
1833           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1834         }
1835         else if (key.equalsIgnoreCase("displayText"))
1836         {
1837           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1838         }
1839         else if (key.equalsIgnoreCase("colourText"))
1840         {
1841           sg.setColourText(Boolean.valueOf(value).booleanValue());
1842         }
1843         else if (key.equalsIgnoreCase("textCol1"))
1844         {
1845           sg.textColour = ColorUtils.parseColourString(value);
1846         }
1847         else if (key.equalsIgnoreCase("textCol2"))
1848         {
1849           sg.textColour2 = ColorUtils.parseColourString(value);
1850         }
1851         else if (key.equalsIgnoreCase("textColThreshold"))
1852         {
1853           sg.thresholdTextColour = Integer.parseInt(value);
1854         }
1855         else if (key.equalsIgnoreCase("idColour"))
1856         {
1857           Color idColour = ColorUtils.parseColourString(value);
1858           sg.setIdColour(idColour == null ? Color.black : idColour);
1859         }
1860         else if (key.equalsIgnoreCase("hide"))
1861         {
1862           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1863           sg.setHidereps(true);
1864         }
1865         else if (key.equalsIgnoreCase("hidecols"))
1866         {
1867           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1868           sg.setHideCols(true);
1869         }
1870         sg.recalcConservation();
1871       }
1872       if (sg.getColourScheme() == null)
1873       {
1874         sg.setColourScheme(def);
1875       }
1876     }
1877   }
1878
1879   void setBelowAlignment(AlignmentI al, StringTokenizer st)
1880   {
1881     String token;
1882     AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1883     if (ala == null)
1884     {
1885       System.err
1886               .print("Warning - no annotation to set below for sequence associated annotation:");
1887     }
1888     while (st.hasMoreTokens())
1889     {
1890       token = st.nextToken();
1891       if (ala == null)
1892       {
1893         System.err.print(" " + token);
1894       }
1895       else
1896       {
1897         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1898         {
1899           aa = al.getAlignmentAnnotation()[i];
1900           if (aa.sequenceRef == refSeq && aa.label.equals(token))
1901           {
1902             aa.belowAlignment = true;
1903           }
1904         }
1905       }
1906     }
1907     if (ala == null)
1908     {
1909       System.err.print("\n");
1910     }
1911   }
1912
1913   void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1914   {
1915     String keyValue, key, value;
1916     while (st.hasMoreTokens())
1917     {
1918       keyValue = st.nextToken();
1919       key = keyValue.substring(0, keyValue.indexOf("="));
1920       value = keyValue.substring(keyValue.indexOf("=") + 1);
1921       al.setProperty(key, value);
1922     }
1923   }
1924
1925   /**
1926    * Write annotations as a CSV file of the form 'label, value, value, ...' for
1927    * each row.
1928    * 
1929    * @param annotations
1930    * @return CSV file as a string.
1931    */
1932   public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1933   {
1934     if (annotations == null)
1935     {
1936       return "";
1937     }
1938     StringBuffer sp = new StringBuffer();
1939     for (int i = 0; i < annotations.length; i++)
1940     {
1941       String atos = annotations[i].toString();
1942       int p = 0;
1943       do
1944       {
1945         int cp = atos.indexOf("\n", p);
1946         sp.append(annotations[i].label);
1947         sp.append(",");
1948         if (cp > p)
1949         {
1950           sp.append(atos.substring(p, cp + 1));
1951         }
1952         else
1953         {
1954           sp.append(atos.substring(p));
1955           sp.append(newline);
1956         }
1957         p = cp + 1;
1958       } while (p > 0);
1959     }
1960     return sp.toString();
1961   }
1962
1963   public String printAnnotationsForView(AlignViewportI viewport)
1964   {
1965     return printAnnotations(viewport.isShowAnnotation() ? viewport
1966             .getAlignment().getAlignmentAnnotation() : null, viewport
1967             .getAlignment().getGroups(), viewport.getAlignment()
1968             .getProperties(), viewport.getColumnSelection(),
1969             viewport.getAlignment(), null);
1970   }
1971
1972   public String printAnnotationsForAlignment(AlignmentI al)
1973   {
1974     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1975             al.getProperties(), null, al, null);
1976   }
1977 }