]> git.saurik.com Git - wxWidgets.git/blob - contrib/utils/wxrc/wxrc.cpp
Clear -> ClearBackground
[wxWidgets.git] / contrib / utils / wxrc / wxrc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wxrc.cpp
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik
5 // Created: 2000/03/05
6 // RCS-ID: $Id$
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 #if defined(__GNUG__) && !defined(__APPLE__)
12 #pragma implementation
13 #pragma interface
14 #endif
15
16 // For compilers that support precompilation, includes "wx/wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 // for all others, include the necessary headers (this file is usually all you
24 // need because it includes almost all "standard" wxWindows headers
25 #ifndef WX_PRECOMP
26 #include "wx/wx.h"
27 #endif
28
29 #include "wx/cmdline.h"
30 #include "wx/xml/xml.h"
31 #include "wx/ffile.h"
32 #include "wx/filename.h"
33 #include "wx/wfstream.h"
34
35
36 class XmlResApp : public wxAppConsole
37 {
38 public:
39 // don't use builtin cmd line parsing:
40 virtual bool OnInit() { return true; }
41
42 virtual int OnRun();
43
44 private:
45
46 void ParseParams(const wxCmdLineParser& cmdline);
47 void CompileRes();
48 wxArrayString PrepareTempFiles();
49 void FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath);
50
51 wxString GetInternalFileName(const wxString& name, const wxArrayString& flist);
52 void DeleteTempFiles(const wxArrayString& flist);
53 void MakePackageZIP(const wxArrayString& flist);
54 void MakePackageCPP(const wxArrayString& flist);
55 void MakePackagePython(const wxArrayString& flist);
56
57 void OutputGettext();
58 wxArrayString FindStrings();
59 wxArrayString FindStrings(wxXmlNode *node);
60
61 bool flagVerbose, flagCPP, flagPython, flagGettext;
62 wxString parOutput, parFuncname, parOutputPath;
63 wxArrayString parFiles;
64 int retCode;
65 };
66
67 IMPLEMENT_APP(XmlResApp)
68
69 int XmlResApp::OnRun()
70 {
71 static const wxCmdLineEntryDesc cmdLineDesc[] =
72 {
73 { wxCMD_LINE_SWITCH, _T("h"), _T("help"), _T("show help message"),
74 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
75 { wxCMD_LINE_SWITCH, _T("v"), _T("verbose"), _T("be verbose") },
76 { wxCMD_LINE_SWITCH, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file") },
77 { wxCMD_LINE_SWITCH, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file") },
78 { wxCMD_LINE_SWITCH, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)") },
79 { wxCMD_LINE_OPTION, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]") },
80 { wxCMD_LINE_OPTION, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]") },
81 #if 0 // not yet implemented
82 { wxCMD_LINE_OPTION, _T("l"), _T("list-of-handlers", _T("output list of neccessary handlers to this file" },
83 #endif
84 { wxCMD_LINE_PARAM, NULL, NULL, _T("input file(s)"),
85 wxCMD_LINE_VAL_STRING,
86 wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_OPTION_MANDATORY },
87
88 { wxCMD_LINE_NONE }
89 };
90
91 wxCmdLineParser parser(cmdLineDesc, argc, argv);
92
93 switch (parser.Parse())
94 {
95 case -1:
96 return 0;
97 break;
98
99 case 0:
100 retCode = 0;
101 ParseParams(parser);
102 if (flagGettext)
103 OutputGettext();
104 else
105 CompileRes();
106 return retCode;
107 break;
108
109 default:
110 return 1;
111 break;
112 }
113 }
114
115
116
117
118 void XmlResApp::ParseParams(const wxCmdLineParser& cmdline)
119 {
120 flagGettext = cmdline.Found(_T("g"));
121 flagVerbose = cmdline.Found(_T("v"));
122 flagCPP = cmdline.Found(_T("c"));
123 flagPython = cmdline.Found(_T("p"));
124
125 if (!cmdline.Found(_T("o"), &parOutput))
126 {
127 if (flagGettext)
128 parOutput = wxEmptyString;
129 else
130 {
131 if (flagCPP)
132 parOutput = _T("resource.cpp");
133 else if (flagPython)
134 parOutput = _T("resource.py");
135 else
136 parOutput = _T("resource.xrs");
137 }
138 }
139 wxFileName fn(parOutput);
140 fn.Normalize();
141 parOutput = fn.GetFullPath();
142 parOutputPath = wxPathOnly(parOutput);
143 if (!parOutputPath) parOutputPath = _T(".");
144
145 if (!cmdline.Found(_T("n"), &parFuncname))
146 parFuncname = _T("InitXmlResource");
147
148 for (size_t i = 0; i < cmdline.GetParamCount(); i++)
149 {
150 #ifdef __WINDOWS__
151 wxString fn=wxFindFirstFile(cmdline.GetParam(i), wxFILE);
152 while (!fn.IsEmpty())
153 {
154 parFiles.Add(fn);
155 fn=wxFindNextFile();
156 }
157 #else
158 parFiles.Add(cmdline.GetParam(i));
159 #endif
160 }
161 }
162
163
164
165
166 void XmlResApp::CompileRes()
167 {
168 wxArrayString files = PrepareTempFiles();
169
170 wxRemoveFile(parOutput);
171
172 if (!retCode)
173 {
174 if (flagCPP)
175 MakePackageCPP(files);
176 else if (flagPython)
177 MakePackagePython(files);
178 else
179 MakePackageZIP(files);
180 }
181
182 DeleteTempFiles(files);
183 }
184
185
186 wxString XmlResApp::GetInternalFileName(const wxString& name, const wxArrayString& flist)
187 {
188 wxString name2 = name;
189 name2.Replace(_T(":"), _T("_"));
190 name2.Replace(_T("/"), _T("_"));
191 name2.Replace(_T("\\"), _T("_"));
192 name2.Replace(_T("*"), _T("_"));
193 name2.Replace(_T("?"), _T("_"));
194
195 wxString s = wxFileNameFromPath(parOutput) + _T("$") + name2;
196
197 if (wxFileExists(s) && flist.Index(s) == wxNOT_FOUND)
198 {
199 for (int i = 0;; i++)
200 {
201 s.Printf(wxFileNameFromPath(parOutput) + _T("$%03i-") + name2, i);
202 if (!wxFileExists(s) || flist.Index(s) != wxNOT_FOUND)
203 break;
204 }
205 }
206 return s;
207 }
208
209 wxArrayString XmlResApp::PrepareTempFiles()
210 {
211 wxArrayString flist;
212
213 for (size_t i = 0; i < parFiles.Count(); i++)
214 {
215 if (flagVerbose)
216 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
217
218 wxXmlDocument doc;
219
220 if (!doc.Load(parFiles[i]))
221 {
222 wxLogError(_T("Error parsing file ") + parFiles[i]);
223 retCode = 1;
224 continue;
225 }
226
227 wxString name, ext, path;
228 wxSplitPath(parFiles[i], &path, &name, &ext);
229
230 FindFilesInXML(doc.GetRoot(), flist, path);
231
232 wxString internalName = GetInternalFileName(parFiles[i], flist);
233
234 doc.Save(parOutputPath + wxFILE_SEP_PATH + internalName);
235 flist.Add(internalName);
236 }
237
238 return flist;
239 }
240
241
242 // Does 'node' contain filename information at all?
243 static bool NodeContainsFilename(wxXmlNode *node)
244 {
245 // Any bitmaps:
246 if (node->GetName() == _T("bitmap"))
247 return TRUE;
248
249 // URLs in wxHtmlWindow:
250 if (node->GetName() == _T("url"))
251 return TRUE;
252
253 // wxBitmapButton:
254 wxXmlNode *parent = node->GetParent();
255 if (parent != NULL &&
256 parent->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
257 (node->GetName() == _T("focus") ||
258 node->GetName() == _T("disabled") ||
259 node->GetName() == _T("selected")))
260 return TRUE;
261
262 // wxBitmap or wxIcon toplevel resources:
263 if (node->GetName() == _T("object"))
264 {
265 wxString klass = node->GetPropVal(_T("class"), wxEmptyString);
266 if (klass == _T("wxBitmap") || klass == _T("wxIcon"))
267 return TRUE;
268 }
269
270 return FALSE;
271 }
272
273 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
274 void XmlResApp::FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath)
275 {
276 // Is 'node' XML node element?
277 if (node == NULL) return;
278 if (node->GetType() != wxXML_ELEMENT_NODE) return;
279
280 bool containsFilename = NodeContainsFilename(node);
281
282 wxXmlNode *n = node->GetChildren();
283 while (n)
284 {
285 if (containsFilename &&
286 (n->GetType() == wxXML_TEXT_NODE ||
287 n->GetType() == wxXML_CDATA_SECTION_NODE))
288 {
289 wxString fullname;
290 if (wxIsAbsolutePath(n->GetContent()) || inputPath.empty())
291 fullname = n->GetContent();
292 else
293 fullname = inputPath + wxFILE_SEP_PATH + n->GetContent();
294
295 if (flagVerbose)
296 wxPrintf(_T("adding ") + fullname + _T("...\n"));
297
298 wxString filename = GetInternalFileName(n->GetContent(), flist);
299 n->SetContent(filename);
300
301 if (flist.Index(filename) == wxNOT_FOUND)
302 flist.Add(filename);
303
304 wxFileInputStream sin(fullname);
305 wxFileOutputStream sout(parOutputPath + wxFILE_SEP_PATH + filename);
306 sin.Read(sout); // copy the stream
307 }
308
309 // subnodes:
310 if (n->GetType() == wxXML_ELEMENT_NODE)
311 FindFilesInXML(n, flist, inputPath);
312
313 n = n->GetNext();
314 }
315 }
316
317
318
319 void XmlResApp::DeleteTempFiles(const wxArrayString& flist)
320 {
321 for (size_t i = 0; i < flist.Count(); i++)
322 wxRemoveFile(parOutputPath + wxFILE_SEP_PATH + flist[i]);
323 }
324
325
326
327 void XmlResApp::MakePackageZIP(const wxArrayString& flist)
328 {
329 wxString files;
330
331 for (size_t i = 0; i < flist.Count(); i++)
332 files += flist[i] + _T(" ");
333 files.RemoveLast();
334
335 if (flagVerbose)
336 wxPrintf(_T("compressing ") + parOutput + _T("...\n"));
337
338 wxString cwd = wxGetCwd();
339 wxSetWorkingDirectory(parOutputPath);
340 int execres = wxExecute(_T("zip -9 -j ") +
341 wxString(flagVerbose ? _T("") : _T("-q ")) +
342 parOutput + _T(" ") + files, TRUE);
343 wxSetWorkingDirectory(cwd);
344 if (execres == -1)
345 {
346 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
347 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
348 retCode = 1;
349 return;
350 }
351 }
352
353
354
355
356 static wxString FileToCppArray(wxString filename, int num)
357 {
358 wxString output;
359 wxString tmp;
360 wxString snum;
361 wxFFile file(filename, wxT("rb"));
362 size_t lng = file.Length();
363
364 snum.Printf(_T("%i"), num);
365 output.Printf(_T("static size_t xml_res_size_") + snum + _T(" = %i;\n"), lng);
366 output += _T("static unsigned char xml_res_file_") + snum + _T("[] = {\n");
367 // we cannot use string literals because MSVC is dumb wannabe compiler
368 // with arbitrary limitation to 2048 strings :(
369
370 unsigned char *buffer = new unsigned char[lng];
371 file.Read(buffer, lng);
372
373 for (size_t i = 0, linelng = 0; i < lng; i++)
374 {
375 tmp.Printf(_T("%i"), buffer[i]);
376 if (i != 0) output << _T(',');
377 if (linelng > 70)
378 {
379 linelng = 0;
380 output << _T("\n");
381 }
382 output << tmp;
383 linelng += tmp.Length()+1;
384 }
385
386 delete[] buffer;
387
388 output += _T("};\n\n");
389
390 return output;
391 }
392
393
394 void XmlResApp::MakePackageCPP(const wxArrayString& flist)
395 {
396 wxFFile file(parOutput, wxT("wt"));
397 size_t i;
398
399 if (flagVerbose)
400 wxPrintf(_T("creating C++ source file ") + parOutput + _T("...\n"));
401
402 file.Write(_T("")
403 _T("//\n")
404 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
405 _T("//\n\n")
406 _T("#include <wx/wxprec.h>\n")
407 _T("\n")
408 _T("#ifdef __BORLANDC__\n")
409 _T(" #pragma hdrstop\n")
410 _T("#endif\n")
411 _T("\n")
412 _T("#ifndef WX_PRECOMP\n")
413 _T(" #include <wx/wx.h>\n")
414 _T("#endif\n")
415 _T("")
416 _T("#include <wx/filesys.h>\n")
417 _T("#include <wx/fs_mem.h>\n")
418 _T("#include <wx/xrc/xmlres.h>\n")
419 _T("#include <wx/xrc/xh_all.h>\n")
420 _T("\n"));
421
422 for (i = 0; i < flist.Count(); i++)
423 file.Write(
424 FileToCppArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
425
426 file.Write(_T("")
427 _T("void ") + parFuncname + wxT("()\n")
428 _T("{\n")
429 _T("\n")
430 _T(" // Check for memory FS. If not present, load the handler:\n")
431 _T(" {\n")
432 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
433 _T(" wxFileSystem fsys;\n")
434 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
435 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
436 _T(" if (f) delete f;\n")
437 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
438 _T(" }\n")
439 _T("\n"));
440
441 for (i = 0; i < flist.Count(); i++)
442 {
443 wxString s;
444 s.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist[i] +
445 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i, i);
446 file.Write(s);
447 }
448
449 for (i = 0; i < parFiles.Count(); i++)
450 {
451 file.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
452 GetInternalFileName(parFiles[i], flist) + _T("\"));\n"));
453 }
454
455 file.Write(_T("}\n"));
456
457
458 }
459
460 static wxString FileToPythonArray(wxString filename, int num)
461 {
462 wxString output;
463 wxString tmp;
464 wxString snum;
465 wxFFile file(filename, wxT("rb"));
466 size_t lng = file.Length();
467
468 snum.Printf(_T("%i"), num);
469 output = _T(" xml_res_file_") + snum + _T(" = \"\"\"\\\n");
470
471 unsigned char *buffer = new unsigned char[lng];
472 file.Read(buffer, lng);
473
474 for (size_t i = 0, linelng = 0; i < lng; i++)
475 {
476 unsigned char c = buffer[i];
477 if (c == '\n')
478 {
479 tmp = (wxChar)c;
480 linelng = 0;
481 }
482 else if (c < 32 || c > 127)
483 tmp.Printf(_T("\\x%02x"), c);
484 else if (c == '\\')
485 tmp = _T("\\\\");
486 else
487 tmp = (wxChar)c;
488 if (linelng > 70)
489 {
490 linelng = 0;
491 output << _T("\\\n");
492 }
493 output << tmp;
494 linelng += tmp.Length();
495 }
496
497 delete[] buffer;
498
499 output += _T("\"\"\"\n\n");
500
501 return output;
502 }
503
504
505 void XmlResApp::MakePackagePython(const wxArrayString& flist)
506 {
507 wxFFile file(parOutput, wxT("wt"));
508 size_t i;
509
510 if (flagVerbose)
511 wxPrintf(_T("creating Python source file ") + parOutput + _T("...\n"));
512
513 file.Write(
514 _T("#\n")
515 _T("# This file was automatically generated by wxrc, do not edit by hand.\n")
516 _T("#\n\n")
517 _T("from wxPython.wx import *\n")
518 _T("from wxPython.xrc import *\n\n")
519 );
520
521
522 file.Write(_T("def ") + parFuncname + _T("():\n"));
523
524 for (i = 0; i < flist.Count(); i++)
525 file.Write(
526 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
527
528 for (i = 0; i < flist.Count(); i++)
529 {
530 wxString s;
531 s.Printf(_T(" wxXmlResource_Get().LoadFromString(xml_res_file_%i)\n"), i);
532 file.Write(s);
533 }
534 }
535
536
537
538 void XmlResApp::OutputGettext()
539 {
540 wxArrayString str = FindStrings();
541
542 wxFFile fout;
543 if (!parOutput) fout.Attach(stdout);
544 else fout.Open(parOutput, wxT("wt"));
545
546 for (size_t i = 0; i < str.GetCount(); i++)
547 fout.Write(_T("_(\"") + str[i] + _T("\");\n"));
548
549 if (!parOutput) fout.Detach();
550 }
551
552
553
554 wxArrayString XmlResApp::FindStrings()
555 {
556 wxArrayString arr, a2;
557
558 for (size_t i = 0; i < parFiles.Count(); i++)
559 {
560 if (flagVerbose)
561 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
562
563 wxXmlDocument doc;
564 if (!doc.Load(parFiles[i]))
565 {
566 wxLogError(_T("Error parsing file ") + parFiles[i]);
567 retCode = 1;
568 continue;
569 }
570 a2 = FindStrings(doc.GetRoot());
571 WX_APPEND_ARRAY(arr, a2);
572 }
573
574 return arr;
575 }
576
577
578
579 static wxString ConvertText(const wxString& str)
580 {
581 wxString str2;
582 const wxChar *dt;
583
584 for (dt = str.c_str(); *dt; dt++)
585 {
586 if (*dt == wxT('_'))
587 {
588 if ( *(++dt) == wxT('_') )
589 str2 << wxT('_');
590 else
591 str2 << wxT('&') << *dt;
592 }
593 else
594 {
595 switch (*dt)
596 {
597 case wxT('\n') : str2 << wxT("\\n"); break;
598 case wxT('\t') : str2 << wxT("\\t"); break;
599 case wxT('\r') : str2 << wxT("\\r"); break;
600 case wxT('\\') : if ((*(dt+1) != 'n') &&
601 (*(dt+1) != 't') &&
602 (*(dt+1) != 'r'))
603 str2 << wxT("\\\\");
604 else
605 str2 << wxT("\\");
606 break;
607 case wxT('"') : str2 << wxT("\\\""); break;
608 default : str2 << *dt; break;
609 }
610 }
611 }
612
613 return str2;
614 }
615
616
617 wxArrayString XmlResApp::FindStrings(wxXmlNode *node)
618 {
619 wxArrayString arr;
620
621 wxXmlNode *n = node;
622 if (n == NULL) return arr;
623 n = n->GetChildren();
624
625 while (n)
626 {
627 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
628 // parent is an element, i.e. has subnodes...
629 (n->GetType() == wxXML_TEXT_NODE ||
630 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
631 // ...it is textnode...
632 (
633 node/*not n!*/->GetName() == _T("label") ||
634 (node/*not n!*/->GetName() == _T("value") &&
635 !n->GetContent().IsNumber()) ||
636 node/*not n!*/->GetName() == _T("help") ||
637 node/*not n!*/->GetName() == _T("longhelp") ||
638 node/*not n!*/->GetName() == _T("tooltip") ||
639 node/*not n!*/->GetName() == _T("htmlcode") ||
640 node/*not n!*/->GetName() == _T("title") ||
641 node/*not n!*/->GetName() == _T("item")
642 ))
643 // ...and known to contain translatable string
644 {
645 arr.Add(ConvertText(n->GetContent()));
646 }
647
648 // subnodes:
649 if (n->GetType() == wxXML_ELEMENT_NODE)
650 {
651 wxArrayString a2 = FindStrings(n);
652 WX_APPEND_ARRAY(arr, a2);
653 }
654
655 n = n->GetNext();
656 }
657 return arr;
658 }