]> git.saurik.com Git - wxWidgets.git/blob - utils/wxrc/wxrc.cpp
cleanup
[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 #if wxUSE_MIMETYPE
677 else
678 {
679 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
680 if ( ft )
681 {
682 ft->GetMimeType(&mime);
683 delete ft;
684 }
685 }
686 #endif // wxUSE_MIMETYPE
687
688 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
689 "\"), xml_res_file_%i, xml_res_size_%i, _T(\"%s\"));\n",
690 i, i, mime.c_str());
691 file.Write(s);
692 }
693
694 for (i = 0; i < parFiles.GetCount(); i++)
695 {
696 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" +
697 GetInternalFileName(parFiles[i], flist) + "\"));\n");
698 }
699
700 file.Write("}\n");
701
702
703 }
704
705 void XmlResApp::GenCPPHeader()
706 {
707 wxString fileSpec = ((parOutput.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
708 wxString heaFileName = fileSpec + _T(".h");
709
710 wxFFile file(heaFileName, wxT("wt"));
711 file.Write(
712 "//\n"
713 "// This file was automatically generated by wxrc, do not edit by hand.\n"
714 "//\n\n"
715 "#ifndef __" + fileSpec + "_h__\n"
716 "#define __" + fileSpec + "_h__\n"
717 );
718 for(size_t i=0;i<aXRCWndClassData.GetCount();++i){
719 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
720 }
721 file.Write(
722 "\nvoid \n"
723 + parFuncname
724 + "();\n#endif\n");
725 }
726
727 static wxString FileToPythonArray(wxString filename, int num)
728 {
729 wxString output;
730 wxString tmp;
731 wxString snum;
732 wxFFile file(filename, wxT("rb"));
733 wxFileOffset offset = file.Length();
734 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
735
736 const size_t lng = wx_truncate_cast(size_t, offset);
737 wxASSERT_MSG( offset == lng, wxT("Huge file not supported") );
738
739 snum.Printf(_T("%i"), num);
740 output = " xml_res_file_" + snum + " = '''\\\n";
741
742 unsigned char *buffer = new unsigned char[lng];
743 file.Read(buffer, lng);
744
745 for (size_t i = 0, linelng = 0; i < lng; i++)
746 {
747 unsigned char c = buffer[i];
748 if (c == '\n')
749 {
750 tmp = (wxChar)c;
751 linelng = 0;
752 }
753 else if (c < 32 || c > 127 || c == '\'')
754 tmp.Printf(_T("\\x%02x"), c);
755 else if (c == '\\')
756 tmp = _T("\\\\");
757 else
758 tmp = (wxChar)c;
759 if (linelng > 70)
760 {
761 linelng = 0;
762 output << _T("\\\n");
763 }
764 output << tmp;
765 linelng += tmp.Length();
766 }
767
768 delete[] buffer;
769
770 output += _T("'''\n\n");
771
772 return output;
773 }
774
775
776 void XmlResApp::MakePackagePython(const wxArrayString& flist)
777 {
778 wxFFile file(parOutput, wxT("wt"));
779 size_t i;
780
781 if (flagVerbose)
782 wxPrintf(_T("creating Python source file ") + parOutput + _T("...\n"));
783
784 file.Write(
785 "#\n"
786 "# This file was automatically generated by wxrc, do not edit by hand.\n"
787 "#\n\n"
788 "import wx\n"
789 "import wx.xrc\n\n"
790 );
791
792
793 file.Write("def " + parFuncname + "():\n");
794
795 for (i = 0; i < flist.GetCount(); i++)
796 file.Write(
797 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
798
799 file.Write(
800 " # check if the memory filesystem handler has been loaded yet, and load it if not\n"
801 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
802 " fsys = wx.FileSystem()\n"
803 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
804 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
805 " if f is not None:\n"
806 " f.Destroy()\n"
807 " else:\n"
808 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
809 "\n"
810 " # load all the strings as memory files and load into XmlRes\n"
811 );
812
813
814 for (i = 0; i < flist.GetCount(); i++)
815 {
816 wxString s;
817 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] +
818 "', xml_res_file_%i)\n", i);
819 file.Write(s);
820 }
821 for (i = 0; i < parFiles.GetCount(); i++)
822 {
823 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" +
824 GetInternalFileName(parFiles[i], flist) + "')\n");
825 }
826
827 file.Write("\n");
828 }
829
830
831
832 void XmlResApp::OutputGettext()
833 {
834 ExtractedStrings str = FindStrings();
835
836 wxFFile fout;
837 if (parOutput.empty())
838 fout.Attach(stdout);
839 else
840 fout.Open(parOutput, wxT("wt"));
841
842 for (ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i)
843 {
844 wxString s;
845
846 s.Printf("#line %d \"%s\"\n", i->lineNo, i->filename);
847 fout.Write(s);
848 fout.Write("_(\"" + i->str + "\");\n");
849 }
850
851 if (!parOutput) fout.Detach();
852 }
853
854
855
856 ExtractedStrings XmlResApp::FindStrings()
857 {
858 ExtractedStrings arr, a2;
859
860 for (size_t i = 0; i < parFiles.GetCount(); i++)
861 {
862 if (flagVerbose)
863 wxPrintf(_T("processing ") + parFiles[i] + _T("...\n"));
864
865 wxXmlDocument doc;
866 if (!doc.Load(parFiles[i]))
867 {
868 wxLogError(_T("Error parsing file ") + parFiles[i]);
869 retCode = 1;
870 continue;
871 }
872 a2 = FindStrings(parFiles[i], doc.GetRoot());
873
874 WX_APPEND_ARRAY(arr, a2);
875 }
876
877 return arr;
878 }
879
880
881
882 static wxString ConvertText(const wxString& str)
883 {
884 wxString str2;
885 const wxChar *dt;
886
887 for (dt = str.c_str(); *dt; dt++)
888 {
889 if (*dt == wxT('_'))
890 {
891 if ( *(++dt) == wxT('_') )
892 str2 << wxT('_');
893 else
894 str2 << wxT('&') << *dt;
895 }
896 else
897 {
898 switch (*dt)
899 {
900 case wxT('\n') : str2 << wxT("\\n"); break;
901 case wxT('\t') : str2 << wxT("\\t"); break;
902 case wxT('\r') : str2 << wxT("\\r"); break;
903 case wxT('\\') : if ((*(dt+1) != 'n') &&
904 (*(dt+1) != 't') &&
905 (*(dt+1) != 'r'))
906 str2 << wxT("\\\\");
907 else
908 str2 << wxT("\\");
909 break;
910 case wxT('"') : str2 << wxT("\\\""); break;
911 default : str2 << *dt; break;
912 }
913 }
914 }
915
916 return str2;
917 }
918
919
920 ExtractedStrings
921 XmlResApp::FindStrings(const wxString& filename, wxXmlNode *node)
922 {
923 ExtractedStrings arr;
924
925 wxXmlNode *n = node;
926 if (n == NULL) return arr;
927 n = n->GetChildren();
928
929 while (n)
930 {
931 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
932 // parent is an element, i.e. has subnodes...
933 (n->GetType() == wxXML_TEXT_NODE ||
934 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
935 // ...it is textnode...
936 (
937 node/*not n!*/->GetName() == _T("label") ||
938 (node/*not n!*/->GetName() == _T("value") &&
939 !n->GetContent().IsNumber()) ||
940 node/*not n!*/->GetName() == _T("help") ||
941 node/*not n!*/->GetName() == _T("longhelp") ||
942 node/*not n!*/->GetName() == _T("tooltip") ||
943 node/*not n!*/->GetName() == _T("htmlcode") ||
944 node/*not n!*/->GetName() == _T("title") ||
945 node/*not n!*/->GetName() == _T("item")
946 ))
947 // ...and known to contain translatable string
948 {
949 if (!flagGettext ||
950 node->GetAttribute(_T("translate"), _T("1")) != _T("0"))
951 {
952 arr.push_back
953 (
954 ExtractedString
955 (
956 ConvertText(n->GetContent()),
957 filename,
958 n->GetLineNumber()
959 )
960 );
961 }
962 }
963
964 // subnodes:
965 if (n->GetType() == wxXML_ELEMENT_NODE)
966 {
967 ExtractedStrings a2 = FindStrings(filename, n);
968 WX_APPEND_ARRAY(arr, a2);
969 }
970
971 n = n->GetNext();
972 }
973 return arr;
974 }