Debian Codegraph @

scripts/localize/pvpgn_localize_generator.cs

raw symbols SCIP
1 /*
2 Copyright (c) 2014 HarpyWar ([email protected])
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy
5 of this software and associated documentation files (the "Software"), to deal
6 in the Software without restriction, including without limitation the rights
7 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 copies of the Software, and to permit persons to whom the Software is
9 furnished to do so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in
12 all copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE.
21 */
22
23 using System;
24 using System.Collections.Generic;
25 using System.ComponentModel;
26 using System.IO;
27 using System.Text;
28 using System.Linq;
29 using System.Xml.Serialization;
30
31 namespace pvpgn_localize_generator
32 {
33 class Program
34 {
35 /// <summary>
36 /// C++ localization function name
37 /// </summary>
38 const string func_name = "localize";
39 static string outfile = "output.xml";
40 static string dirpath;
41
42 static Root _data = new Root();
43
44 static void Main(string[] args)
45 {
46 if (args.Length == 0 || args.Length > 2)
47 {
48 Console.WriteLine("This utility generates XML file for next translation from hardcoded text arguments in function {0}(...) that in *.cpp, *.h, *.lua files\n(c) 2014 HarpyWar ([email protected])", func_name);
49 Console.WriteLine("\nUsage: {0} [path to 'pvpgn' repository directory] {{output.xml}}", AppDomain.CurrentDomain.FriendlyName);
50 Console.WriteLine(" (to make update of existing xml file, pass it in a second parameter)\n", AppDomain.CurrentDomain.FriendlyName);
51
52 Environment.Exit(0);
53 }
54 dirpath = args[0];
55 if (args.Length == 2)
56 outfile = args[1];
57
58
59 if (File.Exists(outfile))
60 {
61 // deserialize xml to data
62 var xsr = new XmlSerializer(typeof(Root));
63 var reader = new StreamReader(outfile);
64 _data = (Root)xsr.Deserialize(reader);
65 reader.Close();
66 }
67
68 string[] cppfiles = Directory.GetFiles(dirpath, "*.cpp", SearchOption.AllDirectories);
69 string[] hfiles = Directory.GetFiles(dirpath, "*.h", SearchOption.AllDirectories);
70 string[] luafiles = Directory.GetFiles(dirpath, "*.lua", SearchOption.AllDirectories);
71 string[] allfiles = cppfiles.Concat(hfiles).Concat(luafiles).ToArray();
72
73 // process each file
74 foreach (var f in allfiles)
75 {
76 parse_file(f);
77 }
78
79 // sort items by file -> function
80 _data.Items = _data.Items.OrderBy(x => x.Function).OrderBy(x => x.File).OrderBy(x => Path.GetExtension(x.File)).ToList();
81
82 // serialize data to xml
83 var xsw = new XmlSerializer(typeof(Root));
84 using (var fs = new FileStream(outfile, FileMode.Create))
85 {
86 xsw.Serialize(fs, _data);
87 }
88
89 // replace empty "<translate />" strings (for comfort further translation)
90 var data = File.ReadAllText(outfile);
91 data = data.Replace("<translate />", "<translate></translate>");
92 File.WriteAllText(outfile, data);
93
94 Console.WriteLine("\n{0} items saved in {1}: ", _data.Items.Count, outfile);
95 //Console.WriteLine("\nPress any key to exit...");
96 //Console.ReadKey();
97 }
98
99 /// <summary>
100 /// Parse a single file
101 /// </summary>
102 /// <param name="filepath"></param>
103 private static void parse_file(string filepath)
104 {
105 string[] lines = File.ReadAllLines(filepath);
106 string filename = Path.GetFileName(filepath);
107
108 string text, f, function = string.Empty;
109 int ln = 0; // line number
110 int uid = 1;
111 foreach (string l in lines)
112 {
113 ln++;
114 try
115 {
116 if ((f = is_function(l)) != null)
117 function = f; // remember last function
118
119 if ((text = find_localize_text(l)) == null)
120 continue;
121
122 // ignore duplicate strings in the same file and function
123 if (_data.Items.Find(x => x.Original == text && x.File == filename && x.Function == function) != null)
124 continue;
125
126 // find the original text in list for reference
127 var reference = _data.Items.Find(x => x.Original == text && x.Translate.RefId == null);
128
129 // set unique Id
130 while (_data.Items.Find(x => x.Id == uid.ToString()) != null)
131 {
132 uid++;
133 }
134
135 _data.Items.Add(new Root.StringItem()
136 {
137 Id = uid.ToString(),
138 File = filename,
139 Function = function,
140 Original = text,
141 Translate = new Root.StringItem.TranslateItem()
142 {
143 // reference to exist translation
144 RefId = (reference != null) ? reference.Id : null,
145 }
146 });
147 // insert example author
148 if (_data.meta.Authors.Count == 0)
149 _data.meta.Authors.Add(new Root.Meta.AuthorItem() { Name = "nomad" , Email = "[email protected]"});
150
151 Console.WriteLine("{0}, {1}(): {2}", filename, function, text);
152 }
153 catch (Exception e)
154 {
155 Console.WriteLine("Error on parse file \"{0}\" on line #{1}: {2}", filename, ln, l);
156 Console.WriteLine(e.Message);
157 }
158 }
159 }
160
161 /// <summary>
162 /// Return a text from the first string argument of the func_name
163 /// </summary>
164 /// <param name="line"></param>
165 /// <returns>text or null</returns>
166 private static string find_localize_text(string line)
167 {
168 int func_pos, bracket1_pos, quote1_pos, quote2_pos;
169 func_pos = bracket1_pos = quote1_pos = quote2_pos = -1;
170
171 string text = null;
172
173 for (int i = 0; i < line.Length; i++)
174 {
175 if (func_pos >= 0)
176 {
177 if (bracket1_pos > 0)
178 {
179 if (quote1_pos > 0)
180 {
181 if (quote2_pos > 0)
182 {
183 text = line.Substring(quote1_pos, quote2_pos - quote1_pos);
184 break;
185 }
186 // 3) find last quote
187 if (line.Substring(i, 1) == "\"" && line.Substring(i - 1, 1) != "\\")
188 quote2_pos = i;
189 continue;
190 }
191 // 3) find first quote
192 if (line.Substring(i, 1) == "\"")
193 quote1_pos = ++i;
194 continue;
195 }
196 // 2) find first bracket
197 if (line.Substring(i, 1) == "(")
198 bracket1_pos = i;
199 continue;
200 }
201 // 1) find function name
202 if (line.Substring(i, (i + func_name.Length > line.Length) ? line.Length - i : func_name.Length) == func_name)
203 func_pos = i;
204 }
205 return escape_text(text);
206 }
207
208 /// <summary>
209 /// Filter text corresponding to XML rules
210 /// </summary>
211 /// <param name="text"></param>
212 /// <returns>text or null (if null passed)</returns>
213 private static string escape_text(string text)
214 {
215 if (text == null)
216 return null;
217
218 text = text.Replace("\\\"", "\"");
219 text = text.Replace("<", "&lt;");
220 text = text.Replace(">", "&gt;");
221 return text;
222 }
223
224
225 /// <summary>
226 /// Is word a function?
227 /// </summary>
228 /// <param name="line"></param>
229 /// <returns>string or null</returns>
230 private static string is_function(string line)
231 {
232 int j;
233 line = line.Trim();
234 if (line.Length == 0)
235 return null;
236
237 // last line must have ) or {
238 if (!line.Contains(";") && line[line.Length - 1] == ')' || line[line.Length - 1] == '{')
239 {
240 string[] words = line.Split();
241 if (words.Length > 0)
242 {
243 bool bad = false;
244 // exclude small words and reserved words that can not be at the beginning of the function definition
245 foreach (string r in reserved_words)
246 if (r.Length > words[0].Length)
247 continue;
248 else if (words[0].Substring(0, r.Length) == r)
249 bad = true;
250
251 if (!bad)
252 {
253 // find function name in words
254 for (int i = 0; i < words.Length; i++)
255 {
256 if (words[i].Trim() == string.Empty)
257 continue;
258
259 if (words[i][0] == '(')
260 return words[i - 1];
261 else if ((j = words[i].IndexOf("(", 0)) != -1)
262 return words[i].Substring(0, j);
263 }
264
265 }
266 }
267 }
268 return null;
269 }
270
271 /// <summary>
272 /// Ignore these words when find a function name
273 /// </summary>
274 static string[] reserved_words = new string[]
275 {
276 func_name, // function definition
277 "LIST_TRAVERSE",
278 "type",
279 "while",
280 "switch",
281 "class",
282 "new",
283 "goto",
284 "for",
285 "sizeof",
286 "struct",
287 "throw",
288 "try",
289 "catch",
290 "typedef",
291 "enum",
292 "if", "else",
293 "{","}",
294 "(",")",
295 "<<",">>",
296 "||","|",
297 "&&","&",
298 "//", "/", "*", // comments
299 "!",
300 };
301 }
302
303 #region Serializer Class
304
305 [XmlRoot("root")]
306 public class Root
307 {
308 public Root()
309 {
310 Items = new List<StringItem>();
311 }
312
313 [XmlElement("meta")]
314 public Meta meta = new Meta();
315
316 [XmlArray("items"), XmlArrayItem(typeof(StringItem), ElementName = "item")]
317 public List<StringItem> Items { get; set; }
318
319 public class Meta
320 {
321 public Meta()
322 {
323 language = new LanguageItem();
324 Authors = new List<AuthorItem>();
325 }
326
327 [XmlElement("language"), DefaultValue("change_me")]
328 public LanguageItem language { get; set; }
329
330 [XmlArray("authors"), XmlArrayItem(typeof(AuthorItem), ElementName = "author")]
331 public List<AuthorItem> Authors { get; set; }
332
333 public class LanguageItem
334 {
335 [XmlAttribute("tag")]
336 public string Tag = "enUS";
337 [XmlText]
338 public string InnerText = "English";
339 }
340 public class AuthorItem
341 {
342 [XmlAttribute("name")]
343 public string Name;
344 [XmlAttribute("email")]
345 public string Email;
346 }
347 }
348
349
350 public class StringItem
351 {
352 [XmlAttribute("id")]
353 public string Id;
354 [XmlAttribute("file")]
355 public string File;
356 [XmlAttribute("function")]
357 public string Function;
358 [XmlElement("original")]
359 public string Original;
360 [XmlElement("translate")]
361 public TranslateItem Translate;
362
363 public class TranslateItem
364 {
365 [XmlAttribute("refid")]
366 public string RefId;
367 [XmlText]
368 public string InnerText;
369 }
370 }
371
372 #endregion
373
374 }
375 }