]> git.saurik.com Git - wxWidgets.git/blob - utils/wxrc/wxrc.cpp
BIG CHANGE: added parsing of base classes; now CompareClasses() is much smarter since...
[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( wx_static_cast(wxFileOffset, lng) == offset,
585 wxT("Huge file not supported") );
586
587 snum.Printf(_T("%i"), num);
588 output.Printf(_T("static size_t xml_res_size_") + snum + _T(" = %i;\n"), lng);
589 output += _T("static unsigned char xml_res_file_") + snum + _T("[] = {\n");
590 // we cannot use string literals because MSVC is dumb wannabe compiler
591 // with arbitrary limitation to 2048 strings :(
592
593 unsigned char *buffer = new unsigned char[lng];
594 file.Read(buffer, lng);
595
596 for (size_t i = 0, linelng = 0; i < lng; i++)
597 {
598 tmp.Printf(_T("%i"), buffer[i]);
599 if (i != 0) output << _T(',');
600 if (linelng > 70)
601 {
602 linelng = 0;
603 output << _T("\n");
604 }
605 output << tmp;
606 linelng += tmp.Length()+1;
607 }
608
609 delete[] buffer;
610
611 output += _T("};\n\n");
612
613 return output;
614 }
615
616
617 void XmlResApp::MakePackageCPP(const wxArrayString& flist)
618 {
619 wxFFile file(parOutput, wxT("wt"));
620 size_t i;
621
622 if (flagVerbose)
623 wxPrintf(_T("creating C++ source file ") + parOutput + _T("...\n"));
624
625 file.Write(""
626 "//\n"
627 "// This file was automatically generated by wxrc, do not edit by hand.\n"
628 "//\n\n"
629 "#include <wx/wxprec.h>\n"
630 "\n"
631 "#ifdef __BORLANDC__\n"
632 " #pragma hdrstop\n"
633 "#endif\n"
634 "\n"
635 ""
636 "#include <wx/filesys.h>\n"
637 "#include <wx/fs_mem.h>\n"
638 "#include <wx/xrc/xmlres.h>\n"
639 "#include <wx/xrc/xh_all.h>\n"
640 "\n"
641 "#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805\n"
642 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
643 " wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)\n"
644 "#else\n"
645 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
646 " wxMemoryFSHandler::AddFile(name, data, size)\n"
647 "#endif\n"
648 "\n");
649
650 for (i = 0; i < flist.GetCount(); i++)
651 file.Write(
652 FileToCppArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
653
654 file.Write(""
655 "void " + parFuncname + "()\n"
656 "{\n"
657 "\n"
658 " // Check for memory FS. If not present, load the handler:\n"
659 " {\n"
660 " wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n"
661 " wxFileSystem fsys;\n"
662 " wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n"
663 " wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n"
664 " if (f) delete f;\n"
665 " else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n"
666 " }\n"
667 "\n");
668
669 for (i = 0; i < flist.GetCount(); i++)
670 {
671 wxString s;
672
673 wxString mime;
674 wxString ext = wxFileName(flist[i]).GetExt();
675 if ( ext.Lower() == _T("xrc") )
676 mime = _T("text/xml");
677 #if wxUSE_MIMETYPE
678 else
679 {
680 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
681 if ( ft )
682 {
683 ft->GetMimeType(&mime);
684 delete ft;
685 }
686 }
687 #endif // wxUSE_MIMETYPE
688
689 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
690 "\"), xml_res_file_%i, xml_res_size_%i, _T(\"%s\"));\n",
691 i, i, mime.c_str());
692 file.Write(s);
693 }
694
695 for (i = 0; i < parFiles.GetCount(); i++)
696 {
697 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" +
698 GetInternalFileName(parFiles[i], flist) + "\"));\n");
699 }
700
701 file.Write("}\n");
702
703
704 }
705
706 void XmlResApp::GenCPPHeader()
707 {
708 wxString fileSpec = ((parOutput.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
709 wxString heaFileName = fileSpec + _T(".h");
710
711 wxFFile file(heaFileName, wxT("wt"));
712 file.Write(
713 "//\n"
714 "// This file was automatically generated by wxrc, do not edit by hand.\n"
715 "//\n\n"
716 "#ifndef __" + fileSpec + "_h__\n"
717 "#define __" + fileSpec + "_h__\n"
718 );
719 for(size_t i=0;i<aXRCWndClassData.GetCount();++i){
720 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
721 }
722 file.Write(
723 "\nvoid \n"
724 + parFuncname
725 + "();\n#endif\n");
726 }
727
728 static wxString FileToPythonArray(wxString filename, int num)
729 {
730 wxString output;
731 wxString tmp;
732 wxString snum;
733 wxFFile file(filename, wxT("rb"));
734 wxFileOffset offset = file.Length();
735 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
736
737 const size_t lng = wx_truncate_cast(size_t, offset);
738 wxASSERT_MSG( wx_static_cast(wxFileOffset, lng) == offset,
739 wxT("Huge file not supported") );
740
741 snum.Printf(_T("%i"), num);
742 output = " xml_res_file_" + snum + " = '''\\\n";
743
744 unsigned char *buffer = new unsigned char[lng];
745 file.Read(buffer, lng);
746
747 for (size_t i = 0, linelng = 0; i < lng; i++)
748 {
749 unsigned char c = buffer[i];
750 if (c == '\n')
751 {
752 tmp = (wxChar)c;
753 linelng = 0;
754 }
755 else if (c < 32 || c > 127 || c == '\'')
756 tmp.Printf(_T("\\x%02x"), c);
757 else if (c == '\\')
758 tmp = _T("\\\\");
759 else
760 tmp = (wxChar)c;
761 if (linelng > 70)
762 {
763 linelng = 0;
764 output << _T("\\\n");
765 }
766 output << tmp;
767 linelng += tmp.Length();
768 }
769
770 delete[] buffer;
771
772 output += _T("'''\n\n");
773
774 return output;
775 }
776
777
778 void XmlResApp::MakePackagePython(const wxArrayString& flist)
779 {
780 wxFFile file(parOutput, wxT("wt"));
781 size_t i;
782
783 if (flagVerbose)
784 wxPrintf(_T("creating Python source file ") + parOutput + _T("...\n"));
785
786 file.Write(
787 "#\n"
788 "# This file was automatically generated by wxrc, do not edit by hand.\n"
789 "#\n\n"
790 "import wx\n"
791 "import wx.xrc\n\n"
792 );
793
794
795 file.Write("def " + parFuncname + "():\n");
796
797 for (i = 0; i < flist.GetCount(); i++)
798 file.Write(
799 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
800
801 file.Write(
802 " # check if the memory filesystem handler has been loaded yet, and load it if not\n"
803 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
804 " fsys = wx.FileSystem()\n"
805 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
806 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
807 " if f is not None:\n"
808 " f.Destroy()\n"
809 " else:\n"
810 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
811 "\n"
812 " # load all the strings as memory files and load into XmlRes\n"
813 );
814
815
816 for (i = 0; i < flist.GetCount(); i++)
817 {
818 wxString s;
819 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] +
820 "', xml_res_file_%i)\n", i);
821 file.Write(s);
822 }
823 for (i = 0; i < parFiles.GetCount(); i++)
824 {
825 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" +
826 GetInternalFileName(parFiles[i], flist) + "')\n");
827 }
828
829 file.Write("\n");
830 }
831
832
833
834 void XmlResApp::OutputGettext()
835 {
836 ExtractedStrings str = FindStrings();
837
838 wxFFile fout;
839 if (parOutput.empty())
840 fout.Attach(stdout);
841 else
842 fout.Open(parOutput, wxT("wt"));
843
844 for (ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i)
845 {
846 wxString s;
847
848 s.Printf("#line %d \"%s\"\n", i->lineNo, i->filename);
849 fout.Write(s);
850 fout.Write("_(\"" + i->str + "\");\n");
851 }
852
853 if (!parOutput) fout.Detach();
854 }
855
856
857
858 ExtractedStrings XmlResApp::FindStrings()
859 {
860 ExtractedStrings arr, a2;
861
862 for (size_t i = 0; i < parFiles.GetCount(); i++)
863 {
864 if (flagVerbose)
865 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
866
867 wxXmlDocument doc;
868 if (!doc.Load(parFiles[i]))
869 {
870 wxLogError(_T("Error parsing file ") + parFiles[i]);
871 retCode = 1;
872 continue;
873 }
874 a2 = FindStrings(parFiles[i], doc.GetRoot());
875
876 WX_APPEND_ARRAY(arr, a2);
877 }
878
879 return arr;
880 }
881
882
883
884 static wxString ConvertText(const wxString& str)
885 {
886 wxString str2;
887 const wxChar *dt;
888
889 for (dt = str.c_str(); *dt; dt++)
890 {
891 if (*dt == wxT('_'))
892 {
893 if ( *(++dt) == wxT('_') )
894 str2 << wxT('_');
895 else
896 str2 << wxT('&') << *dt;
897 }
898 else
899 {
900 switch (*dt)
901 {
902 case wxT('\n') : str2 << wxT("\\n"); break;
903 case wxT('\t') : str2 << wxT("\\t"); break;
904 case wxT('\r') : str2 << wxT("\\r"); break;
905 case wxT('\\') : if ((*(dt+1) != 'n') &&
906 (*(dt+1) != 't') &&
907 (*(dt+1) != 'r'))
908 str2 << wxT("\\\\");
909 else
910 str2 << wxT("\\");
911 break;
912 case wxT('"') : str2 << wxT("\\\""); break;
913 default : str2 << *dt; break;
914 }
915 }
916 }
917
918 return str2;
919 }
920
921
922 ExtractedStrings
923 XmlResApp::FindStrings(const wxString& filename, wxXmlNode *node)
924 {
925 ExtractedStrings arr;
926
927 wxXmlNode *n = node;
928 if (n == NULL) return arr;
929 n = n->GetChildren();
930
931 while (n)
932 {
933 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
934 // parent is an element, i.e. has subnodes...
935 (n->GetType() == wxXML_TEXT_NODE ||
936 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
937 // ...it is textnode...
938 (
939 node/*not n!*/->GetName() == _T("label") ||
940 (node/*not n!*/->GetName() == _T("value") &&
941 !n->GetContent().IsNumber()) ||
942 node/*not n!*/->GetName() == _T("help") ||
943 node/*not n!*/->GetName() == _T("longhelp") ||
944 node/*not n!*/->GetName() == _T("tooltip") ||
945 node/*not n!*/->GetName() == _T("htmlcode") ||
946 node/*not n!*/->GetName() == _T("title") ||
947 node/*not n!*/->GetName() == _T("item")
948 ))
949 // ...and known to contain translatable string
950 {
951 if (!flagGettext ||
952 node->GetAttribute(_T("translate"), _T("1")) != _T("0"))
953 {
954 arr.push_back
955 (
956 ExtractedString
957 (
958 ConvertText(n->GetContent()),
959 filename,
960 n->GetLineNumber()
961 )
962 );
963 }
964 }
965
966 // subnodes:
967 if (n->GetType() == wxXML_ELEMENT_NODE)
968 {
969 ExtractedStrings a2 = FindStrings(filename, n);
970 WX_APPEND_ARRAY(arr, a2);
971 }
972
973 n = n->GetNext();
974 }
975 return arr;
976 }