generate #line references to source .xrc files in wxrc --gettext (patch #1803492...
[wxWidgets.git] / utils / wxrc / wxrc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wxrc.cpp
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik, Eduardo Marques <edrdo@netcabo.pt>
5 // Created: 2000/03/05
6 // RCS-ID: $Id$
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx/wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 // for all others, include the necessary headers
19 #ifndef WX_PRECOMP
20 #include "wx/app.h"
21 #include "wx/log.h"
22 #include "wx/wxcrtvararg.h"
23 #endif
24
25 #include "wx/cmdline.h"
26 #include "wx/xml/xml.h"
27 #include "wx/ffile.h"
28 #include "wx/filename.h"
29 #include "wx/wfstream.h"
30 #include "wx/utils.h"
31 #include "wx/hashset.h"
32 #include "wx/mimetype.h"
33 #include "wx/vector.h"
34
35 WX_DECLARE_HASH_SET(wxString, wxStringHash, wxStringEqual, StringSet);
36
37 class XRCWidgetData
38 {
39 public:
40 XRCWidgetData(const wxString& vname,const wxString& vclass)
41 : m_class(vclass), m_name(vname) {}
42 const wxString& GetName() const { return m_name; }
43 const wxString& GetClass() const { return m_class; }
44 private:
45 wxString m_class;
46 wxString m_name;
47 };
48
49 #include "wx/arrimpl.cpp"
50 WX_DECLARE_OBJARRAY(XRCWidgetData,ArrayOfXRCWidgetData);
51 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData)
52
53 class XRCWndClassData
54 {
55 private:
56 wxString m_className;
57 wxString m_parentClassName;
58 StringSet m_ancestorClassNames;
59 ArrayOfXRCWidgetData m_wdata;
60
61 void BrowseXmlNode(wxXmlNode* node)
62 {
63 wxString classValue;
64 wxString nameValue;
65 wxXmlNode* children;
66 while (node)
67 {
68 if (node->GetName() == _T("object")
69 && node->GetAttribute(_T("class"),&classValue)
70 && node->GetAttribute(_T("name"),&nameValue))
71 {
72 m_wdata.Add(XRCWidgetData(nameValue,classValue));
73 }
74 children = node->GetChildren();
75 if (children)
76 BrowseXmlNode(children);
77 node = node->GetNext();
78 }
79 }
80
81 public:
82 XRCWndClassData(const wxString& className,
83 const wxString& parentClassName,
84 const wxXmlNode* node) :
85 m_className(className) , m_parentClassName(parentClassName)
86 {
87 if ( className == _T("wxMenu") )
88 {
89 m_ancestorClassNames.insert(_T("wxMenu"));
90 m_ancestorClassNames.insert(_T("wxMenuBar"));
91 }
92 else if ( className == _T("wxMDIChildFrame") )
93 {
94 m_ancestorClassNames.insert(_T("wxMDIParentFrame"));
95 }
96 else if( className == _T("wxMenuBar") ||
97 className == _T("wxStatusBar") ||
98 className == _T("wxToolBar") )
99 {
100 m_ancestorClassNames.insert(_T("wxFrame"));
101 }
102 else
103 {
104 m_ancestorClassNames.insert(_T("wxWindow"));
105 }
106
107 BrowseXmlNode(node->GetChildren());
108 }
109
110 const ArrayOfXRCWidgetData& GetWidgetData()
111 {
112 return m_wdata;
113 }
114
115 bool CanBeUsedWithXRCCTRL(const wxString& name)
116 {
117 if (name == _T("tool") ||
118 name == _T("data") ||
119 name == _T("unknown") ||
120 name == _T("notebookpage") ||
121 name == _T("separator") ||
122 name == _T("sizeritem") ||
123 name == _T("wxMenuBar") ||
124 name == _T("wxMenuItem") ||
125 name == _T("wxStaticBoxSizer") )
126 {
127 return false;
128 }
129 return true;
130 }
131
132 void GenerateHeaderCode(wxFFile& file)
133 {
134
135 file.Write(_T("class ") + m_className + _T(" : public ") + m_parentClassName
136 + _T(" {\nprotected:\n"));
137 size_t i;
138 for(i=0;i<m_wdata.GetCount();++i)
139 {
140 const XRCWidgetData& w = m_wdata.Item(i);
141 if( !CanBeUsedWithXRCCTRL(w.GetClass()) ) continue;
142 if( w.GetName().Length() == 0 ) continue;
143 file.Write(
144 _T(" ") + w.GetClass() + _T("* ") + w.GetName()
145 + _T(";\n"));
146 }
147 file.Write(_T("\nprivate:\n void InitWidgetsFromXRC(wxWindow *parent){\n")
148 _T(" wxXmlResource::Get()->LoadObject(this,parent,_T(\"")
149 + m_className
150 + _T("\"), _T(\"")
151 + m_parentClassName
152 + _T("\"));\n"));
153 for(i=0;i<m_wdata.GetCount();++i)
154 {
155 const XRCWidgetData& w = m_wdata.Item(i);
156 if( !CanBeUsedWithXRCCTRL(w.GetClass()) ) continue;
157 if( w.GetName().Length() == 0 ) continue;
158 file.Write( _T(" ")
159 + w.GetName()
160 + _T(" = XRCCTRL(*this,\"")
161 + w.GetName()
162 + _T("\",")
163 + w.GetClass()
164 + _T(");\n"));
165 }
166 file.Write(_T(" }\n"));
167
168 file.Write( _T("public:\n"));
169
170 if ( m_ancestorClassNames.size() == 1 )
171 {
172 file.Write
173 (
174 m_className +
175 _T("(") +
176 *m_ancestorClassNames.begin() +
177 _T(" *parent=NULL){\n") +
178 _T(" InitWidgetsFromXRC((wxWindow *)parent);\n")
179 _T(" }\n")
180 _T("};\n")
181 );
182 }
183 else
184 {
185 file.Write(m_className + _T("(){\n") +
186 _T(" InitWidgetsFromXRC(NULL);\n")
187 _T(" }\n")
188 _T("};\n"));
189
190 for ( StringSet::const_iterator it = m_ancestorClassNames.begin();
191 it != m_ancestorClassNames.end();
192 ++it )
193 {
194 file.Write(m_className + _T("(") + *it + _T(" *parent){\n") +
195 _T(" InitWidgetsFromXRC((wxWindow *)parent);\n")
196 _T(" }\n")
197 _T("};\n"));
198 }
199 }
200 }
201 };
202 WX_DECLARE_OBJARRAY(XRCWndClassData,ArrayOfXRCWndClassData);
203 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData)
204
205 struct ExtractedString
206 {
207 ExtractedString() : lineNo(-1) {}
208 ExtractedString(const wxString& str_,
209 const wxString& filename_, int lineNo_)
210 : str(str_), filename(filename_), lineNo(lineNo_)
211 {}
212
213 wxString str;
214
215 wxString filename;
216 int lineNo;
217 };
218
219 typedef wxVector<ExtractedString> ExtractedStrings;
220
221
222 class XmlResApp : public wxAppConsole
223 {
224 public:
225 // don't use builtin cmd line parsing:
226 virtual bool OnInit() { return true; }
227 virtual int OnRun();
228
229 private:
230 void ParseParams(const wxCmdLineParser& cmdline);
231 void CompileRes();
232 wxArrayString PrepareTempFiles();
233 void FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath);
234
235 wxString GetInternalFileName(const wxString& name, const wxArrayString& flist);
236 void DeleteTempFiles(const wxArrayString& flist);
237 void MakePackageZIP(const wxArrayString& flist);
238 void MakePackageCPP(const wxArrayString& flist);
239 void MakePackagePython(const wxArrayString& flist);
240
241 void OutputGettext();
242 ExtractedStrings FindStrings();
243 ExtractedStrings FindStrings(const wxString& filename, wxXmlNode *node);
244
245 bool flagVerbose, flagCPP, flagPython, flagGettext;
246 wxString parOutput, parFuncname, parOutputPath;
247 wxArrayString parFiles;
248 int retCode;
249
250 ArrayOfXRCWndClassData aXRCWndClassData;
251 bool flagH;
252 void GenCPPHeader();
253 };
254
255 IMPLEMENT_APP_CONSOLE(XmlResApp)
256
257 int XmlResApp::OnRun()
258 {
259 static const wxCmdLineEntryDesc cmdLineDesc[] =
260 {
261 { wxCMD_LINE_SWITCH, "h", "help", "show help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
262 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
263 { wxCMD_LINE_SWITCH, "e", "extra-cpp-code", "output C++ header file with XRC derived classes" },
264 { wxCMD_LINE_SWITCH, "c", "cpp-code", "output C++ source rather than .rsc file" },
265 { wxCMD_LINE_SWITCH, "p", "python-code", "output wxPython source rather than .rsc file" },
266 { wxCMD_LINE_SWITCH, "g", "gettext", "output list of translatable strings (to stdout or file if -o used)" },
267 { wxCMD_LINE_OPTION, "n", "function", "C++/Python function name (with -c or -p) [InitXmlResource]" },
268 { wxCMD_LINE_OPTION, "o", "output", "output file [resource.xrs/cpp]" },
269 #if 0 // not yet implemented
270 { wxCMD_LINE_OPTION, "l", "list-of-handlers", "output list of necessary handlers to this file" },
271 #endif
272 { wxCMD_LINE_PARAM, NULL, NULL, "input file(s)",
273 wxCMD_LINE_VAL_STRING,
274 wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_OPTION_MANDATORY },
275
276 wxCMD_LINE_DESC_END
277 };
278
279 wxCmdLineParser parser(cmdLineDesc, argc, argv);
280
281 switch (parser.Parse())
282 {
283 case -1:
284 return 0;
285
286 case 0:
287 retCode = 0;
288 ParseParams(parser);
289 if (flagGettext)
290 OutputGettext();
291 else
292 CompileRes();
293 return retCode;
294 }
295 return 1;
296 }
297
298
299
300
301 void XmlResApp::ParseParams(const wxCmdLineParser& cmdline)
302 {
303 flagGettext = cmdline.Found("g");
304 flagVerbose = cmdline.Found("v");
305 flagCPP = cmdline.Found("c");
306 flagPython = cmdline.Found("p");
307 flagH = flagCPP && cmdline.Found("e");
308
309
310 if (!cmdline.Found("o", &parOutput))
311 {
312 if (flagGettext)
313 parOutput = wxEmptyString;
314 else
315 {
316 if (flagCPP)
317 parOutput = _T("resource.cpp");
318 else if (flagPython)
319 parOutput = _T("resource.py");
320 else
321 parOutput = _T("resource.xrs");
322 }
323 }
324 if (!parOutput.empty())
325 {
326 wxFileName fn(parOutput);
327 fn.Normalize();
328 parOutput = fn.GetFullPath();
329 parOutputPath = wxPathOnly(parOutput);
330 }
331 if (!parOutputPath) parOutputPath = _T(".");
332
333 if (!cmdline.Found("n", &parFuncname))
334 parFuncname = _T("InitXmlResource");
335
336 for (size_t i = 0; i < cmdline.GetParamCount(); i++)
337 {
338 #ifdef __WINDOWS__
339 wxString fn=wxFindFirstFile(cmdline.GetParam(i), wxFILE);
340 while (!fn.empty())
341 {
342 parFiles.Add(fn);
343 fn=wxFindNextFile();
344 }
345 #else
346 parFiles.Add(cmdline.GetParam(i));
347 #endif
348 }
349 }
350
351
352
353
354 void XmlResApp::CompileRes()
355 {
356 wxArrayString files = PrepareTempFiles();
357
358 wxRemoveFile(parOutput);
359
360 if (!retCode)
361 {
362 if (flagCPP){
363 MakePackageCPP(files);
364 if (flagH)
365 GenCPPHeader();
366 }
367 else if (flagPython)
368 MakePackagePython(files);
369 else
370 MakePackageZIP(files);
371 }
372
373 DeleteTempFiles(files);
374 }
375
376
377 wxString XmlResApp::GetInternalFileName(const wxString& name, const wxArrayString& flist)
378 {
379 wxString name2 = name;
380 name2.Replace(_T(":"), _T("_"));
381 name2.Replace(_T("/"), _T("_"));
382 name2.Replace(_T("\\"), _T("_"));
383 name2.Replace(_T("*"), _T("_"));
384 name2.Replace(_T("?"), _T("_"));
385
386 wxString s = wxFileNameFromPath(parOutput) + _T("$") + name2;
387
388 if (wxFileExists(s) && flist.Index(s) == wxNOT_FOUND)
389 {
390 for (int i = 0;; i++)
391 {
392 s.Printf(wxFileNameFromPath(parOutput) + _T("$%03i-") + name2, i);
393 if (!wxFileExists(s) || flist.Index(s) != wxNOT_FOUND)
394 break;
395 }
396 }
397 return s;
398 }
399
400 wxArrayString XmlResApp::PrepareTempFiles()
401 {
402 wxArrayString flist;
403
404 for (size_t i = 0; i < parFiles.GetCount(); i++)
405 {
406 if (flagVerbose)
407 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
408
409 wxXmlDocument doc;
410
411 if (!doc.Load(parFiles[i]))
412 {
413 wxLogError(_T("Error parsing file ") + parFiles[i]);
414 retCode = 1;
415 continue;
416 }
417
418 wxString name, ext, path;
419 wxSplitPath(parFiles[i], &path, &name, &ext);
420
421 FindFilesInXML(doc.GetRoot(), flist, path);
422 if (flagH)
423 {
424 wxXmlNode* node = (doc.GetRoot())->GetChildren();
425 wxString classValue,nameValue;
426 while(node){
427 if(node->GetName() == _T("object")
428 && node->GetAttribute(_T("class"),&classValue)
429 && node->GetAttribute(_T("name"),&nameValue)){
430
431 aXRCWndClassData.Add(
432 XRCWndClassData(nameValue,classValue,node)
433 );
434 }
435 node = node -> GetNext();
436 }
437 }
438 wxString internalName = GetInternalFileName(parFiles[i], flist);
439
440 doc.Save(parOutputPath + wxFILE_SEP_PATH + internalName);
441 flist.Add(internalName);
442 }
443
444 return flist;
445 }
446
447
448 // Does 'node' contain filename information at all?
449 static bool NodeContainsFilename(wxXmlNode *node)
450 {
451 const wxString name = node->GetName();
452
453 // Any bitmaps (bitmap2 is used for disabled toolbar buttons):
454 if ( name == _T("bitmap") || name == _T("bitmap2") )
455 return true;
456
457 if ( name == _T("icon") )
458 return true;
459
460 // wxBitmapButton:
461 wxXmlNode *parent = node->GetParent();
462 if (parent != NULL &&
463 parent->GetAttribute(_T("class"), _T("")) == _T("wxBitmapButton") &&
464 (name == _T("focus") ||
465 name == _T("disabled") ||
466 name == _T("hover") ||
467 name == _T("selected")))
468 return true;
469
470 // wxBitmap or wxIcon toplevel resources:
471 if ( name == _T("object") )
472 {
473 wxString klass = node->GetAttribute(_T("class"), wxEmptyString);
474 if (klass == _T("wxBitmap") ||
475 klass == _T("wxIcon") ||
476 klass == _T("data") )
477 return true;
478 }
479
480 // URLs in wxHtmlWindow:
481 if ( name == _T("url") &&
482 parent != NULL &&
483 parent->GetAttribute(_T("class"), _T("")) == _T("wxHtmlWindow") )
484 {
485 // FIXME: this is wrong for e.g. http:// URLs
486 return true;
487 }
488
489 return false;
490 }
491
492 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
493 void XmlResApp::FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath)
494 {
495 // Is 'node' XML node element?
496 if (node == NULL) return;
497 if (node->GetType() != wxXML_ELEMENT_NODE) return;
498
499 bool containsFilename = NodeContainsFilename(node);
500
501 wxXmlNode *n = node->GetChildren();
502 while (n)
503 {
504 if (containsFilename &&
505 (n->GetType() == wxXML_TEXT_NODE ||
506 n->GetType() == wxXML_CDATA_SECTION_NODE))
507 {
508 wxString fullname;
509 if (wxIsAbsolutePath(n->GetContent()) || inputPath.empty())
510 fullname = n->GetContent();
511 else
512 fullname = inputPath + wxFILE_SEP_PATH + n->GetContent();
513
514 if (flagVerbose)
515 wxPrintf(_T("adding ") + fullname + _T("...\n"));
516
517 wxString filename = GetInternalFileName(n->GetContent(), flist);
518 n->SetContent(filename);
519
520 if (flist.Index(filename) == wxNOT_FOUND)
521 flist.Add(filename);
522
523 wxFileInputStream sin(fullname);
524 wxFileOutputStream sout(parOutputPath + wxFILE_SEP_PATH + filename);
525 sin.Read(sout); // copy the stream
526 }
527
528 // subnodes:
529 if (n->GetType() == wxXML_ELEMENT_NODE)
530 FindFilesInXML(n, flist, inputPath);
531
532 n = n->GetNext();
533 }
534 }
535
536
537
538 void XmlResApp::DeleteTempFiles(const wxArrayString& flist)
539 {
540 for (size_t i = 0; i < flist.GetCount(); i++)
541 wxRemoveFile(parOutputPath + wxFILE_SEP_PATH + flist[i]);
542 }
543
544
545
546 void XmlResApp::MakePackageZIP(const wxArrayString& flist)
547 {
548 wxString files;
549
550 for (size_t i = 0; i < flist.GetCount(); i++)
551 files += flist[i] + _T(" ");
552 files.RemoveLast();
553
554 if (flagVerbose)
555 wxPrintf(_T("compressing ") + parOutput + _T("...\n"));
556
557 wxString cwd = wxGetCwd();
558 wxSetWorkingDirectory(parOutputPath);
559 int execres = wxExecute(_T("zip -9 -j ") +
560 wxString(flagVerbose ? _T("\"") : _T("-q \"")) +
561 parOutput + _T("\" ") + files, true);
562 wxSetWorkingDirectory(cwd);
563 if (execres == -1)
564 {
565 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
566 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
567 retCode = 1;
568 return;
569 }
570 }
571
572
573
574 static wxString FileToCppArray(wxString filename, int num)
575 {
576 wxString output;
577 wxString tmp;
578 wxString snum;
579 wxFFile file(filename, wxT("rb"));
580 wxFileOffset offset = file.Length();
581 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
582
583 const size_t lng = wx_truncate_cast(size_t, offset);
584 wxASSERT_MSG( lng == offset, wxT("Huge file not supported") );
585
586 snum.Printf(_T("%i"), num);
587 output.Printf(_T("static size_t xml_res_size_") + snum + _T(" = %i;\n"), lng);
588 output += _T("static unsigned char xml_res_file_") + snum + _T("[] = {\n");
589 // we cannot use string literals because MSVC is dumb wannabe compiler
590 // with arbitrary limitation to 2048 strings :(
591
592 unsigned char *buffer = new unsigned char[lng];
593 file.Read(buffer, lng);
594
595 for (size_t i = 0, linelng = 0; i < lng; i++)
596 {
597 tmp.Printf(_T("%i"), buffer[i]);
598 if (i != 0) output << _T(',');
599 if (linelng > 70)
600 {
601 linelng = 0;
602 output << _T("\n");
603 }
604 output << tmp;
605 linelng += tmp.Length()+1;
606 }
607
608 delete[] buffer;
609
610 output += _T("};\n\n");
611
612 return output;
613 }
614
615
616 void XmlResApp::MakePackageCPP(const wxArrayString& flist)
617 {
618 wxFFile file(parOutput, wxT("wt"));
619 size_t i;
620
621 if (flagVerbose)
622 wxPrintf(_T("creating C++ source file ") + parOutput + _T("...\n"));
623
624 file.Write(""
625 "//\n"
626 "// This file was automatically generated by wxrc, do not edit by hand.\n"
627 "//\n\n"
628 "#include <wx/wxprec.h>\n"
629 "\n"
630 "#ifdef __BORLANDC__\n"
631 " #pragma hdrstop\n"
632 "#endif\n"
633 "\n"
634 ""
635 "#include <wx/filesys.h>\n"
636 "#include <wx/fs_mem.h>\n"
637 "#include <wx/xrc/xmlres.h>\n"
638 "#include <wx/xrc/xh_all.h>\n"
639 "\n"
640 "#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805\n"
641 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
642 " wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)\n"
643 "#else\n"
644 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
645 " wxMemoryFSHandler::AddFile(name, data, size)\n"
646 "#endif\n"
647 "\n");
648
649 for (i = 0; i < flist.GetCount(); i++)
650 file.Write(
651 FileToCppArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
652
653 file.Write(""
654 "void " + parFuncname + "()\n"
655 "{\n"
656 "\n"
657 " // Check for memory FS. If not present, load the handler:\n"
658 " {\n"
659 " wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n"
660 " wxFileSystem fsys;\n"
661 " wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n"
662 " wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n"
663 " if (f) delete f;\n"
664 " else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n"
665 " }\n"
666 "\n");
667
668 for (i = 0; i < flist.GetCount(); i++)
669 {
670 wxString s;
671
672 wxString mime;
673 wxString ext = wxFileName(flist[i]).GetExt();
674 if ( ext.Lower() == _T("xrc") )
675 mime = _T("text/xml");
676 else
677 {
678 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
679 if ( ft )
680 ft->GetMimeType(&mime);
681 }
682
683 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
684 "\"), xml_res_file_%i, xml_res_size_%i, _T(\"%s\"));\n",
685 i, i, mime.c_str());
686 file.Write(s);
687 }
688
689 for (i = 0; i < parFiles.GetCount(); i++)
690 {
691 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" +
692 GetInternalFileName(parFiles[i], flist) + "\"));\n");
693 }
694
695 file.Write("}\n");
696
697
698 }
699
700 void XmlResApp::GenCPPHeader()
701 {
702 wxString fileSpec = ((parOutput.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
703 wxString heaFileName = fileSpec + _T(".h");
704
705 wxFFile file(heaFileName, wxT("wt"));
706 file.Write(
707 "//\n"
708 "// This file was automatically generated by wxrc, do not edit by hand.\n"
709 "//\n\n"
710 "#ifndef __" + fileSpec + "_h__\n"
711 "#define __" + fileSpec + "_h__\n"
712 );
713 for(size_t i=0;i<aXRCWndClassData.GetCount();++i){
714 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
715 }
716 file.Write(
717 "\nvoid \n"
718 + parFuncname
719 + "();\n#endif\n");
720 }
721
722 static wxString FileToPythonArray(wxString filename, int num)
723 {
724 wxString output;
725 wxString tmp;
726 wxString snum;
727 wxFFile file(filename, wxT("rb"));
728 wxFileOffset offset = file.Length();
729 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
730
731 const size_t lng = wx_truncate_cast(size_t, offset);
732 wxASSERT_MSG( offset == lng, wxT("Huge file not supported") );
733
734 snum.Printf(_T("%i"), num);
735 output = " xml_res_file_" + snum + " = '''\\\n";
736
737 unsigned char *buffer = new unsigned char[lng];
738 file.Read(buffer, lng);
739
740 for (size_t i = 0, linelng = 0; i < lng; i++)
741 {
742 unsigned char c = buffer[i];
743 if (c == '\n')
744 {
745 tmp = (wxChar)c;
746 linelng = 0;
747 }
748 else if (c < 32 || c > 127 || c == '\'')
749 tmp.Printf(_T("\\x%02x"), c);
750 else if (c == '\\')
751 tmp = _T("\\\\");
752 else
753 tmp = (wxChar)c;
754 if (linelng > 70)
755 {
756 linelng = 0;
757 output << _T("\\\n");
758 }
759 output << tmp;
760 linelng += tmp.Length();
761 }
762
763 delete[] buffer;
764
765 output += _T("'''\n\n");
766
767 return output;
768 }
769
770
771 void XmlResApp::MakePackagePython(const wxArrayString& flist)
772 {
773 wxFFile file(parOutput, wxT("wt"));
774 size_t i;
775
776 if (flagVerbose)
777 wxPrintf(_T("creating Python source file ") + parOutput + _T("...\n"));
778
779 file.Write(
780 "#\n"
781 "# This file was automatically generated by wxrc, do not edit by hand.\n"
782 "#\n\n"
783 "import wx\n"
784 "import wx.xrc\n\n"
785 );
786
787
788 file.Write("def " + parFuncname + "():\n");
789
790 for (i = 0; i < flist.GetCount(); i++)
791 file.Write(
792 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
793
794 file.Write(
795 " # check if the memory filesystem handler has been loaded yet, and load it if not\n"
796 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
797 " fsys = wx.FileSystem()\n"
798 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
799 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
800 " if f is not None:\n"
801 " f.Destroy()\n"
802 " else:\n"
803 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
804 "\n"
805 " # load all the strings as memory files and load into XmlRes\n"
806 );
807
808
809 for (i = 0; i < flist.GetCount(); i++)
810 {
811 wxString s;
812 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] +
813 "', xml_res_file_%i)\n", i);
814 file.Write(s);
815 }
816 for (i = 0; i < parFiles.GetCount(); i++)
817 {
818 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" +
819 GetInternalFileName(parFiles[i], flist) + "')\n");
820 }
821
822 file.Write("\n");
823 }
824
825
826
827 void XmlResApp::OutputGettext()
828 {
829 ExtractedStrings str = FindStrings();
830
831 wxFFile fout;
832 if (parOutput.empty())
833 fout.Attach(stdout);
834 else
835 fout.Open(parOutput, wxT("wt"));
836
837 for (ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i)
838 {
839 wxString s;
840
841 s.Printf("#line %d \"%s\"\n", i->lineNo, i->filename);
842 fout.Write(s);
843 fout.Write("_(\"" + i->str + "\");\n");
844 }
845
846 if (!parOutput) fout.Detach();
847 }
848
849
850
851 ExtractedStrings XmlResApp::FindStrings()
852 {
853 ExtractedStrings arr, a2;
854
855 for (size_t i = 0; i < parFiles.GetCount(); i++)
856 {
857 if (flagVerbose)
858 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
859
860 wxXmlDocument doc;
861 if (!doc.Load(parFiles[i]))
862 {
863 wxLogError(_T("Error parsing file ") + parFiles[i]);
864 retCode = 1;
865 continue;
866 }
867 a2 = FindStrings(parFiles[i], doc.GetRoot());
868
869 WX_APPEND_ARRAY(arr, a2);
870 }
871
872 return arr;
873 }
874
875
876
877 static wxString ConvertText(const wxString& str)
878 {
879 wxString str2;
880 const wxChar *dt;
881
882 for (dt = str.c_str(); *dt; dt++)
883 {
884 if (*dt == wxT('_'))
885 {
886 if ( *(++dt) == wxT('_') )
887 str2 << wxT('_');
888 else
889 str2 << wxT('&') << *dt;
890 }
891 else
892 {
893 switch (*dt)
894 {
895 case wxT('\n') : str2 << wxT("\\n"); break;
896 case wxT('\t') : str2 << wxT("\\t"); break;
897 case wxT('\r') : str2 << wxT("\\r"); break;
898 case wxT('\\') : if ((*(dt+1) != 'n') &&
899 (*(dt+1) != 't') &&
900 (*(dt+1) != 'r'))
901 str2 << wxT("\\\\");
902 else
903 str2 << wxT("\\");
904 break;
905 case wxT('"') : str2 << wxT("\\\""); break;
906 default : str2 << *dt; break;
907 }
908 }
909 }
910
911 return str2;
912 }
913
914
915 ExtractedStrings
916 XmlResApp::FindStrings(const wxString& filename, wxXmlNode *node)
917 {
918 ExtractedStrings arr;
919
920 wxXmlNode *n = node;
921 if (n == NULL) return arr;
922 n = n->GetChildren();
923
924 while (n)
925 {
926 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
927 // parent is an element, i.e. has subnodes...
928 (n->GetType() == wxXML_TEXT_NODE ||
929 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
930 // ...it is textnode...
931 (
932 node/*not n!*/->GetName() == _T("label") ||
933 (node/*not n!*/->GetName() == _T("value") &&
934 !n->GetContent().IsNumber()) ||
935 node/*not n!*/->GetName() == _T("help") ||
936 node/*not n!*/->GetName() == _T("longhelp") ||
937 node/*not n!*/->GetName() == _T("tooltip") ||
938 node/*not n!*/->GetName() == _T("htmlcode") ||
939 node/*not n!*/->GetName() == _T("title") ||
940 node/*not n!*/->GetName() == _T("item")
941 ))
942 // ...and known to contain translatable string
943 {
944 if (!flagGettext ||
945 node->GetAttribute(_T("translate"), _T("1")) != _T("0"))
946 {
947 arr.push_back
948 (
949 ExtractedString
950 (
951 ConvertText(n->GetContent()),
952 filename,
953 n->GetLineNumber()
954 )
955 );
956 }
957 }
958
959 // subnodes:
960 if (n->GetType() == wxXML_ELEMENT_NODE)
961 {
962 ExtractedStrings a2 = FindStrings(filename, n);
963 WX_APPEND_ARRAY(arr, a2);
964 }
965
966 n = n->GetNext();
967 }
968 return arr;
969 }