Merge branch 'releases/Release_2_11_3_Branch'
[jalview.git] / examples / groovy / fileFormat.groovy
1 import jalview.datamodel.AlignmentI
2 import jalview.datamodel.SequenceI
3 import jalview.datamodel.Sequence
4 import jalview.io.FileFormatI
5 import jalview.io.FileFormats
6 import jalview.io.FileParse
7 import jalview.io.AlignFile
8
9 /*
10  * Example script that registers a new alignment file format 
11  * consisting of lines like
12  * !I=<sequence id>
13  * !S=<sequence string>
14  */
15
16 /*
17  * A parser class to read or write the format
18  */
19 class MyParser extends AlignFile 
20 {
21   /*
22    * Constructor for reading a file; the superclass
23    * constructor will call the parse() method
24    */
25   MyParser(FileParse src) 
26   {
27     super(src)
28   }
29
30   /*
31    * Constructor for writing out an alignment
32    */
33   MyParser(AlignmentI al) 
34   {
35   }
36   
37   /*
38    * Parse a formatted data file (with no error checking!)
39    */
40   void parse() 
41   {
42     String id
43     String line
44     while ((line = nextLine()) != null) 
45     {
46       if (line.startsWith('!I='))
47       {
48         int pos = line.indexOf('/')
49         id = line.substring(3, pos == -1 ? line.length() : pos)
50       } else if (line.startsWith('!S='))
51       {
52         String seq = line.substring(3)
53         addSequence(new Sequence(id, seq))
54       }
55     }
56   }
57   
58   /*
59    * Print the formatted sequences
60    * (addSuffix always defaults to true as no user preference for it)
61    */
62   String print(SequenceI[] seqs, boolean addSuffix) 
63   {
64       StringBuilder sb = new StringBuilder()
65       for (SequenceI seq : seqs) 
66       {
67           sb.append('!I=').append(seq.getDisplayId(addSuffix)).append('\n')
68           sb.append('!S=').append(seq.getSequenceAsString()).append('\n')
69       }
70       sb.toString()
71   }
72 }
73
74 /*
75  * A closure that defines the 'Groovy example' file format,
76  * delegating to MyParser for reading and writing
77  */
78 def myFormat = { ->
79   [
80     getName: { -> 'Groovy example' },
81     
82     toString: { -> getName() },
83     
84     getExtensions: { -> 'grv' },
85     
86     getReader: { FileParse source -> new MyParser(source) },
87     
88     getWriter: { AlignmentI al -> new MyParser(al) },
89     
90     isReadable: { -> true },
91     
92     isWritable: { -> true },
93     
94     isTextFormat: { -> true },
95     
96     isStructureFile: { -> false },
97     
98     isComplexAlignFile: { -> false },
99
100    ] as FileFormatI
101 }
102
103 /*
104  * Register the file format. After running this script in Jalview's
105  * Groovy console, the new format should be shown in open file,
106  * save file, and output to textbox menu options.
107  */
108 FileFormats.instance.registerFileFormat(myFormat())