1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik, Eduardo Marques <edrdo@netcabo.pt>
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 #if defined(__GNUG__) && !defined(__APPLE__)
12 #pragma implementation
16 // For compilers that support precompilation, includes "wx/wx.h".
17 #include "wx/wxprec.h"
23 // for all others, include the necessary headers
29 #include "wx/cmdline.h"
30 #include "wx/xml/xml.h"
32 #include "wx/filename.h"
33 #include "wx/wfstream.h"
39 XRCWidgetData(const wxString
& vname
,const wxString
& vclass
)
40 : m_class(vclass
), m_name(vname
) {}
41 const wxString
& GetName() const { return m_name
; }
42 const wxString
& GetClass() const { return m_class
; }
47 #include "wx/arrimpl.cpp"
48 WX_DECLARE_OBJARRAY(XRCWidgetData
,ArrayOfXRCWidgetData
);
49 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData
);
55 wxString m_parentClassName
;
56 ArrayOfXRCWidgetData m_wdata
;
58 void BrowseXmlNode(wxXmlNode
* node
)
65 if (node
->GetName() == _T("object")
66 && node
->GetPropVal(_T("class"),&classValue
)
67 && node
->GetPropVal(_T("name"),&nameValue
))
69 m_wdata
.Add(XRCWidgetData(nameValue
,classValue
));
71 children
= node
->GetChildren();
73 BrowseXmlNode(children
);
74 node
= node
->GetNext();
79 XRCWndClassData(const wxString
& className
,const wxString
& parentClassName
, const wxXmlNode
* node
) :
80 m_className(className
) , m_parentClassName(parentClassName
) {
82 BrowseXmlNode(node
->GetChildren());
86 const ArrayOfXRCWidgetData
& GetWidgetData(){
90 bool IsRealClass(const wxString
& name
)
92 if (name
== _T("tool") || name
== _T("unknown") ||
93 name
== _T("notebookpage") || name
== _T("separator") ||
94 name
== _T("sizeritem") ||
95 name
== _T("wxMenuItem"))
102 void GenerateHeaderCode(wxFFile
& file
)
105 file
.Write(_T("class ") + m_className
+ _T(" : public ") + m_parentClassName
106 + _T(" {\nprotected:\n"));
108 for(i
=0;i
<m_wdata
.Count();++i
)
110 const XRCWidgetData
& w
= m_wdata
.Item(i
);
111 if( !IsRealClass(w
.GetClass()) ) continue;
112 if( w
.GetName().Length() == 0 ) continue;
114 _T(" ") + w
.GetClass() + _T("* ") + w
.GetName()
117 file
.Write(_T("\nprivate:\n void InitWidgetsFromXRC(){\n")
118 _T(" wxXmlResource::Get()->LoadObject(this,NULL,_T(\"")
123 for(i
=0;i
<m_wdata
.Count();++i
)
125 const XRCWidgetData
& w
= m_wdata
.Item(i
);
126 if( !IsRealClass(w
.GetClass()) ) continue;
127 if( w
.GetName().Length() == 0 ) continue;
130 + _T(" = XRCCTRL(*this,\"")
137 file
.Write(_T(" }\n"));
145 + _T(" InitWidgetsFromXRC();\n")
150 WX_DECLARE_OBJARRAY(XRCWndClassData
,ArrayOfXRCWndClassData
);
151 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData
);
154 class XmlResApp
: public wxAppConsole
157 // don't use builtin cmd line parsing:
158 virtual bool OnInit() { return true; }
162 void ParseParams(const wxCmdLineParser
& cmdline
);
164 wxArrayString
PrepareTempFiles();
165 void FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
);
167 wxString
GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
);
168 void DeleteTempFiles(const wxArrayString
& flist
);
169 void MakePackageZIP(const wxArrayString
& flist
);
170 void MakePackageCPP(const wxArrayString
& flist
);
171 void MakePackagePython(const wxArrayString
& flist
);
173 void OutputGettext();
174 wxArrayString
FindStrings();
175 wxArrayString
FindStrings(wxXmlNode
*node
);
177 bool flagVerbose
, flagCPP
, flagPython
, flagGettext
;
178 wxString parOutput
, parFuncname
, parOutputPath
;
179 wxArrayString parFiles
;
182 ArrayOfXRCWndClassData aXRCWndClassData
;
187 IMPLEMENT_APP_CONSOLE(XmlResApp
)
189 int XmlResApp::OnRun()
191 static const wxCmdLineEntryDesc cmdLineDesc
[] =
193 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show help message"),
194 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
195 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
196 { wxCMD_LINE_SWITCH
, _T("e"), _T("extra-cpp-code"), _T("output C++ header file with XRC derived classes") },
197 { wxCMD_LINE_SWITCH
, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file") },
198 { wxCMD_LINE_SWITCH
, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file") },
199 { wxCMD_LINE_SWITCH
, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)") },
200 { wxCMD_LINE_OPTION
, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]") },
201 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]") },
202 #if 0 // not yet implemented
203 { wxCMD_LINE_OPTION
, _T("l"), _T("list-of-handlers", _T("output list of neccessary handlers to this file" },
205 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file(s)"),
206 wxCMD_LINE_VAL_STRING
,
207 wxCMD_LINE_PARAM_MULTIPLE
| wxCMD_LINE_OPTION_MANDATORY
},
212 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
214 switch (parser
.Parse())
219 // break is unreachable because of return earlier
232 // break is unreachable because of return earlier
237 // default return moved outside of switch to avoid warning about lack of return in function
249 void XmlResApp::ParseParams(const wxCmdLineParser
& cmdline
)
251 flagGettext
= cmdline
.Found(_T("g"));
252 flagVerbose
= cmdline
.Found(_T("v"));
253 flagCPP
= cmdline
.Found(_T("c"));
254 flagPython
= cmdline
.Found(_T("p"));
255 flagH
= flagCPP
&& cmdline
.Found(_T("e"));
258 if (!cmdline
.Found(_T("o"), &parOutput
))
261 parOutput
= wxEmptyString
;
265 parOutput
= _T("resource.cpp");
267 parOutput
= _T("resource.py");
269 parOutput
= _T("resource.xrs");
272 if (!parOutput
.empty())
274 wxFileName
fn(parOutput
);
276 parOutput
= fn
.GetFullPath();
277 parOutputPath
= wxPathOnly(parOutput
);
279 if (!parOutputPath
) parOutputPath
= _T(".");
281 if (!cmdline
.Found(_T("n"), &parFuncname
))
282 parFuncname
= _T("InitXmlResource");
284 for (size_t i
= 0; i
< cmdline
.GetParamCount(); i
++)
287 wxString fn
=wxFindFirstFile(cmdline
.GetParam(i
), wxFILE
);
288 while (!fn
.IsEmpty())
294 parFiles
.Add(cmdline
.GetParam(i
));
302 void XmlResApp::CompileRes()
304 wxArrayString files
= PrepareTempFiles();
306 wxRemoveFile(parOutput
);
311 MakePackageCPP(files
);
316 MakePackagePython(files
);
318 MakePackageZIP(files
);
321 DeleteTempFiles(files
);
325 wxString
XmlResApp::GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
)
327 wxString name2
= name
;
328 name2
.Replace(_T(":"), _T("_"));
329 name2
.Replace(_T("/"), _T("_"));
330 name2
.Replace(_T("\\"), _T("_"));
331 name2
.Replace(_T("*"), _T("_"));
332 name2
.Replace(_T("?"), _T("_"));
334 wxString s
= wxFileNameFromPath(parOutput
) + _T("$") + name2
;
336 if (wxFileExists(s
) && flist
.Index(s
) == wxNOT_FOUND
)
338 for (int i
= 0;; i
++)
340 s
.Printf(wxFileNameFromPath(parOutput
) + _T("$%03i-") + name2
, i
);
341 if (!wxFileExists(s
) || flist
.Index(s
) != wxNOT_FOUND
)
348 wxArrayString
XmlResApp::PrepareTempFiles()
352 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
355 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
359 if (!doc
.Load(parFiles
[i
]))
361 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
366 wxString name
, ext
, path
;
367 wxSplitPath(parFiles
[i
], &path
, &name
, &ext
);
369 FindFilesInXML(doc
.GetRoot(), flist
, path
);
372 wxXmlNode
* node
= (doc
.GetRoot())->GetChildren();
373 wxString classValue
,nameValue
;
375 if(node
->GetName() == _T("object")
376 && node
->GetPropVal(_T("class"),&classValue
)
377 && node
->GetPropVal(_T("name"),&nameValue
)){
379 aXRCWndClassData
.Add(
380 XRCWndClassData(nameValue
,classValue
,node
)
383 node
= node
-> GetNext();
386 wxString internalName
= GetInternalFileName(parFiles
[i
], flist
);
388 doc
.Save(parOutputPath
+ wxFILE_SEP_PATH
+ internalName
);
389 flist
.Add(internalName
);
396 // Does 'node' contain filename information at all?
397 static bool NodeContainsFilename(wxXmlNode
*node
)
400 if (node
->GetName() == _T("bitmap"))
403 if (node
->GetName() == _T("icon"))
406 // URLs in wxHtmlWindow:
407 if (node
->GetName() == _T("url"))
411 wxXmlNode
*parent
= node
->GetParent();
412 if (parent
!= NULL
&&
413 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
414 (node
->GetName() == _T("focus") ||
415 node
->GetName() == _T("disabled") ||
416 node
->GetName() == _T("selected")))
419 // wxBitmap or wxIcon toplevel resources:
420 if (node
->GetName() == _T("object"))
422 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
423 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
430 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
431 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
433 // Is 'node' XML node element?
434 if (node
== NULL
) return;
435 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
437 bool containsFilename
= NodeContainsFilename(node
);
439 wxXmlNode
*n
= node
->GetChildren();
442 if (containsFilename
&&
443 (n
->GetType() == wxXML_TEXT_NODE
||
444 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
447 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
448 fullname
= n
->GetContent();
450 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
453 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
455 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
456 n
->SetContent(filename
);
458 if (flist
.Index(filename
) == wxNOT_FOUND
)
461 wxFileInputStream
sin(fullname
);
462 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
463 sin
.Read(sout
); // copy the stream
467 if (n
->GetType() == wxXML_ELEMENT_NODE
)
468 FindFilesInXML(n
, flist
, inputPath
);
476 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
478 for (size_t i
= 0; i
< flist
.Count(); i
++)
479 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
484 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
488 for (size_t i
= 0; i
< flist
.Count(); i
++)
489 files
+= flist
[i
] + _T(" ");
493 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
495 wxString cwd
= wxGetCwd();
496 wxSetWorkingDirectory(parOutputPath
);
497 int execres
= wxExecute(_T("zip -9 -j ") +
498 wxString(flagVerbose
? _T("") : _T("-q ")) +
499 parOutput
+ _T(" ") + files
, true);
500 wxSetWorkingDirectory(cwd
);
503 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
504 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
512 static wxString
FileToCppArray(wxString filename
, int num
)
517 wxFFile
file(filename
, wxT("rb"));
518 size_t lng
= file
.Length();
520 snum
.Printf(_T("%i"), num
);
521 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
522 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
523 // we cannot use string literals because MSVC is dumb wannabe compiler
524 // with arbitrary limitation to 2048 strings :(
526 unsigned char *buffer
= new unsigned char[lng
];
527 file
.Read(buffer
, lng
);
529 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
531 tmp
.Printf(_T("%i"), buffer
[i
]);
532 if (i
!= 0) output
<< _T(',');
539 linelng
+= tmp
.Length()+1;
544 output
+= _T("};\n\n");
550 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
552 wxFFile
file(parOutput
, wxT("wt"));
556 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
560 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
562 _T("#include <wx/wxprec.h>\n")
564 _T("#ifdef __BORLANDC__\n")
565 _T(" #pragma hdrstop\n")
569 _T("#include <wx/filesys.h>\n")
570 _T("#include <wx/fs_mem.h>\n")
571 _T("#include <wx/xrc/xmlres.h>\n")
572 _T("#include <wx/xrc/xh_all.h>\n")
575 for (i
= 0; i
< flist
.Count(); i
++)
577 FileToCppArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
580 _T("void ") + parFuncname
+ wxT("()\n")
583 _T(" // Check for memory FS. If not present, load the handler:\n")
585 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
586 _T(" wxFileSystem fsys;\n")
587 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
588 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
589 _T(" if (f) delete f;\n")
590 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
594 for (i
= 0; i
< flist
.Count(); i
++)
597 s
.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist
[i
] +
598 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i
, i
);
602 for (i
= 0; i
< parFiles
.Count(); i
++)
604 file
.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
605 GetInternalFileName(parFiles
[i
], flist
) + _T("\"));\n"));
608 file
.Write(_T("}\n"));
613 void XmlResApp::GenCPPHeader()
615 wxString fileSpec
= ((parOutput
.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
616 wxString heaFileName
= fileSpec
+ _T(".h");
618 wxFFile
file(heaFileName
, wxT("wt"));
621 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
623 _T("#ifndef __") + fileSpec
+ _T("_h__\n")
624 _T("#define __") + fileSpec
+ _T("_h__\n")
626 for(size_t i
=0;i
<aXRCWndClassData
.Count();++i
){
627 aXRCWndClassData
.Item(i
).GenerateHeaderCode(file
);
632 + _T("();\n#endif\n"));
635 static wxString
FileToPythonArray(wxString filename
, int num
)
640 wxFFile
file(filename
, wxT("rb"));
641 size_t lng
= file
.Length();
643 snum
.Printf(_T("%i"), num
);
644 output
= _T(" xml_res_file_") + snum
+ _T(" = '''\\\n");
646 unsigned char *buffer
= new unsigned char[lng
];
647 file
.Read(buffer
, lng
);
649 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
651 unsigned char c
= buffer
[i
];
657 else if (c
< 32 || c
> 127 || c
== '\'')
658 tmp
.Printf(_T("\\x%02x"), c
);
666 output
<< _T("\\\n");
669 linelng
+= tmp
.Length();
674 output
+= _T("'''\n\n");
680 void XmlResApp::MakePackagePython(const wxArrayString
& flist
)
682 wxFFile
file(parOutput
, wxT("wt"));
686 wxPrintf(_T("creating Python source file ") + parOutput
+ _T("...\n"));
690 _T("# This file was automatically generated by wxrc, do not edit by hand.\n")
693 _T("import wx.xrc\n\n")
697 file
.Write(_T("def ") + parFuncname
+ _T("():\n"));
699 for (i
= 0; i
< flist
.Count(); i
++)
701 FileToPythonArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
704 _T(" # check if the memory filesystem handler has been loaded yet, and load it if not\n")
705 _T(" wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n")
706 _T(" fsys = wx.FileSystem()\n")
707 _T(" f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n")
708 _T(" wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n")
709 _T(" if f is not None:\n")
712 _T(" wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n")
714 _T(" # load all the strings as memory files and load into XmlRes\n")
718 for (i
= 0; i
< flist
.Count(); i
++)
721 s
.Printf(_T(" wx.MemoryFSHandler.AddFile('XRC_resource/") + flist
[i
] +
722 _T("', xml_res_file_%i)\n"), i
);
725 for (i
= 0; i
< parFiles
.Count(); i
++)
727 file
.Write(_T(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/") +
728 GetInternalFileName(parFiles
[i
], flist
) + _T("')\n"));
731 file
.Write(_T("\n"));
736 void XmlResApp::OutputGettext()
738 wxArrayString str
= FindStrings();
741 if (parOutput
.empty())
744 fout
.Open(parOutput
, wxT("wt"));
746 for (size_t i
= 0; i
< str
.GetCount(); i
++)
747 fout
.Write(_T("_(\"") + str
[i
] + _T("\");\n"));
749 if (!parOutput
) fout
.Detach();
754 wxArrayString
XmlResApp::FindStrings()
756 wxArrayString arr
, a2
;
758 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
761 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
764 if (!doc
.Load(parFiles
[i
]))
766 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
770 a2
= FindStrings(doc
.GetRoot());
771 WX_APPEND_ARRAY(arr
, a2
);
779 static wxString
ConvertText(const wxString
& str
)
784 for (dt
= str
.c_str(); *dt
; dt
++)
788 if ( *(++dt
) == wxT('_') )
791 str2
<< wxT('&') << *dt
;
797 case wxT('\n') : str2
<< wxT("\\n"); break;
798 case wxT('\t') : str2
<< wxT("\\t"); break;
799 case wxT('\r') : str2
<< wxT("\\r"); break;
800 case wxT('\\') : if ((*(dt
+1) != 'n') &&
807 case wxT('"') : str2
<< wxT("\\\""); break;
808 default : str2
<< *dt
; break;
817 wxArrayString
XmlResApp::FindStrings(wxXmlNode
*node
)
822 if (n
== NULL
) return arr
;
823 n
= n
->GetChildren();
827 if ((node
->GetType() == wxXML_ELEMENT_NODE
) &&
828 // parent is an element, i.e. has subnodes...
829 (n
->GetType() == wxXML_TEXT_NODE
||
830 n
->GetType() == wxXML_CDATA_SECTION_NODE
) &&
831 // ...it is textnode...
833 node
/*not n!*/->GetName() == _T("label") ||
834 (node
/*not n!*/->GetName() == _T("value") &&
835 !n
->GetContent().IsNumber()) ||
836 node
/*not n!*/->GetName() == _T("help") ||
837 node
/*not n!*/->GetName() == _T("longhelp") ||
838 node
/*not n!*/->GetName() == _T("tooltip") ||
839 node
/*not n!*/->GetName() == _T("htmlcode") ||
840 node
/*not n!*/->GetName() == _T("title") ||
841 node
/*not n!*/->GetName() == _T("item")
843 // ...and known to contain translatable string
846 node
->GetPropVal(_T("translate"), _T("1")) != _T("0"))
848 arr
.Add(ConvertText(n
->GetContent()));
853 if (n
->GetType() == wxXML_ELEMENT_NODE
)
855 wxArrayString a2
= FindStrings(n
);
856 WX_APPEND_ARRAY(arr
, a2
);