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