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,\"")
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 // URLs in wxHtmlWindow:
404 if (node
->GetName() == _T("url"))
408 wxXmlNode
*parent
= node
->GetParent();
409 if (parent
!= NULL
&&
410 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
411 (node
->GetName() == _T("focus") ||
412 node
->GetName() == _T("disabled") ||
413 node
->GetName() == _T("selected")))
416 // wxBitmap or wxIcon toplevel resources:
417 if (node
->GetName() == _T("object"))
419 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
420 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
427 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
428 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
430 // Is 'node' XML node element?
431 if (node
== NULL
) return;
432 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
434 bool containsFilename
= NodeContainsFilename(node
);
436 wxXmlNode
*n
= node
->GetChildren();
439 if (containsFilename
&&
440 (n
->GetType() == wxXML_TEXT_NODE
||
441 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
444 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
445 fullname
= n
->GetContent();
447 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
450 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
452 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
453 n
->SetContent(filename
);
455 if (flist
.Index(filename
) == wxNOT_FOUND
)
458 wxFileInputStream
sin(fullname
);
459 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
460 sin
.Read(sout
); // copy the stream
464 if (n
->GetType() == wxXML_ELEMENT_NODE
)
465 FindFilesInXML(n
, flist
, inputPath
);
473 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
475 for (size_t i
= 0; i
< flist
.Count(); i
++)
476 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
481 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
485 for (size_t i
= 0; i
< flist
.Count(); i
++)
486 files
+= flist
[i
] + _T(" ");
490 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
492 wxString cwd
= wxGetCwd();
493 wxSetWorkingDirectory(parOutputPath
);
494 int execres
= wxExecute(_T("zip -9 -j ") +
495 wxString(flagVerbose
? _T("") : _T("-q ")) +
496 parOutput
+ _T(" ") + files
, true);
497 wxSetWorkingDirectory(cwd
);
500 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
501 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
509 static wxString
FileToCppArray(wxString filename
, int num
)
514 wxFFile
file(filename
, wxT("rb"));
515 size_t lng
= file
.Length();
517 snum
.Printf(_T("%i"), num
);
518 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
519 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
520 // we cannot use string literals because MSVC is dumb wannabe compiler
521 // with arbitrary limitation to 2048 strings :(
523 unsigned char *buffer
= new unsigned char[lng
];
524 file
.Read(buffer
, lng
);
526 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
528 tmp
.Printf(_T("%i"), buffer
[i
]);
529 if (i
!= 0) output
<< _T(',');
536 linelng
+= tmp
.Length()+1;
541 output
+= _T("};\n\n");
547 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
549 wxFFile
file(parOutput
, wxT("wt"));
553 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
557 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
559 _T("#include <wx/wxprec.h>\n")
561 _T("#ifdef __BORLANDC__\n")
562 _T(" #pragma hdrstop\n")
565 _T("#ifndef WX_PRECOMP\n")
566 _T(" #include <wx/wx.h>\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)
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")
692 _T("from wxPython.wx import *\n")
693 _T("from wxPython.xrc import *\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
));
703 for (i
= 0; i
< flist
.Count(); i
++)
706 s
.Printf(_T(" wxXmlResource_Get().LoadFromString(xml_res_file_%i)\n"), i
);
713 void XmlResApp::OutputGettext()
715 wxArrayString str
= FindStrings();
718 if (parOutput
.empty())
721 fout
.Open(parOutput
, wxT("wt"));
723 for (size_t i
= 0; i
< str
.GetCount(); i
++)
724 fout
.Write(_T("_(\"") + str
[i
] + _T("\");\n"));
726 if (!parOutput
) fout
.Detach();
731 wxArrayString
XmlResApp::FindStrings()
733 wxArrayString arr
, a2
;
735 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
738 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
741 if (!doc
.Load(parFiles
[i
]))
743 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
747 a2
= FindStrings(doc
.GetRoot());
748 WX_APPEND_ARRAY(arr
, a2
);
756 static wxString
ConvertText(const wxString
& str
)
761 for (dt
= str
.c_str(); *dt
; dt
++)
765 if ( *(++dt
) == wxT('_') )
768 str2
<< wxT('&') << *dt
;
774 case wxT('\n') : str2
<< wxT("\\n"); break;
775 case wxT('\t') : str2
<< wxT("\\t"); break;
776 case wxT('\r') : str2
<< wxT("\\r"); break;
777 case wxT('\\') : if ((*(dt
+1) != 'n') &&
784 case wxT('"') : str2
<< wxT("\\\""); break;
785 default : str2
<< *dt
; break;
794 wxArrayString
XmlResApp::FindStrings(wxXmlNode
*node
)
799 if (n
== NULL
) return arr
;
800 n
= n
->GetChildren();
804 if ((node
->GetType() == wxXML_ELEMENT_NODE
) &&
805 // parent is an element, i.e. has subnodes...
806 (n
->GetType() == wxXML_TEXT_NODE
||
807 n
->GetType() == wxXML_CDATA_SECTION_NODE
) &&
808 // ...it is textnode...
810 node
/*not n!*/->GetName() == _T("label") ||
811 (node
/*not n!*/->GetName() == _T("value") &&
812 !n
->GetContent().IsNumber()) ||
813 node
/*not n!*/->GetName() == _T("help") ||
814 node
/*not n!*/->GetName() == _T("longhelp") ||
815 node
/*not n!*/->GetName() == _T("tooltip") ||
816 node
/*not n!*/->GetName() == _T("htmlcode") ||
817 node
/*not n!*/->GetName() == _T("title") ||
818 node
/*not n!*/->GetName() == _T("item")
820 // ...and known to contain translatable string
823 node
->GetPropVal(_T("translate"), _T("1")) != _T("0"))
825 arr
.Add(ConvertText(n
->GetContent()));
830 if (n
->GetType() == wxXML_ELEMENT_NODE
)
832 wxArrayString a2
= FindStrings(n
);
833 WX_APPEND_ARRAY(arr
, a2
);