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
; }
48 #include "wx/arrimpl.cpp"
49 WX_DECLARE_OBJARRAY(XRCWidgetData
,ArrayOfXRCWidgetData
);
50 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData
);
56 wxString m_parentClassName
;
57 ArrayOfXRCWidgetData m_wdata
;
59 void BrowseXmlNode(wxXmlNode
* node
)
66 if (node
->GetName() == _T("object")
67 && node
->GetPropVal(_T("class"),&classValue
)
68 && node
->GetPropVal(_T("name"),&nameValue
))
70 m_wdata
.Add(XRCWidgetData(nameValue
,classValue
));
72 children
= node
->GetChildren();
74 BrowseXmlNode(children
);
75 node
= node
->GetNext();
80 XRCWndClassData(const wxString
& className
,const wxString
& parentClassName
, const wxXmlNode
* node
) :
81 m_className(className
) , m_parentClassName(parentClassName
)
83 BrowseXmlNode(node
->GetChildren());
86 const ArrayOfXRCWidgetData
& GetWidgetData()
91 bool IsRealClass(const wxString
& name
)
93 if (name
== _T("tool") ||
94 name
== _T("unknown") ||
95 name
== _T("notebookpage") ||
96 name
== _T("separator") ||
97 name
== _T("sizeritem") ||
98 name
== _T("wxMenuItem"))
105 void GenerateHeaderCode(wxFFile
& file
)
108 file
.Write(_T("class ") + m_className
+ _T(" : public ") + m_parentClassName
109 + _T(" {\nprotected:\n"));
111 for(i
=0;i
<m_wdata
.Count();++i
)
113 const XRCWidgetData
& w
= m_wdata
.Item(i
);
114 if( !IsRealClass(w
.GetClass()) ) continue;
115 if( w
.GetName().Length() == 0 ) continue;
117 _T(" ") + w
.GetClass() + _T("* ") + w
.GetName()
120 file
.Write(_T("\nprivate:\n void InitWidgetsFromXRC(){\n")
121 _T(" wxXmlResource::Get()->LoadObject(this,NULL,_T(\"")
126 for(i
=0;i
<m_wdata
.Count();++i
)
128 const XRCWidgetData
& w
= m_wdata
.Item(i
);
129 if( !IsRealClass(w
.GetClass()) ) continue;
130 if( w
.GetName().Length() == 0 ) continue;
133 + _T(" = XRCCTRL(*this,\"")
140 file
.Write(_T(" }\n"));
148 + _T(" InitWidgetsFromXRC();\n")
154 WX_DECLARE_OBJARRAY(XRCWndClassData
,ArrayOfXRCWndClassData
);
155 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData
);
158 class XmlResApp
: public wxAppConsole
161 // don't use builtin cmd line parsing:
162 virtual bool OnInit() { return true; }
166 void ParseParams(const wxCmdLineParser
& cmdline
);
168 wxArrayString
PrepareTempFiles();
169 void FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
);
171 wxString
GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
);
172 void DeleteTempFiles(const wxArrayString
& flist
);
173 void MakePackageZIP(const wxArrayString
& flist
);
174 void MakePackageCPP(const wxArrayString
& flist
);
175 void MakePackagePython(const wxArrayString
& flist
);
177 void OutputGettext();
178 wxArrayString
FindStrings();
179 wxArrayString
FindStrings(wxXmlNode
*node
);
181 bool flagVerbose
, flagCPP
, flagPython
, flagGettext
;
182 wxString parOutput
, parFuncname
, parOutputPath
;
183 wxArrayString parFiles
;
186 ArrayOfXRCWndClassData aXRCWndClassData
;
191 IMPLEMENT_APP_CONSOLE(XmlResApp
)
193 int XmlResApp::OnRun()
195 static const wxCmdLineEntryDesc cmdLineDesc
[] =
197 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show help message"),
198 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
199 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
200 { wxCMD_LINE_SWITCH
, _T("e"), _T("extra-cpp-code"), _T("output C++ header file with XRC derived classes") },
201 { wxCMD_LINE_SWITCH
, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file") },
202 { wxCMD_LINE_SWITCH
, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file") },
203 { wxCMD_LINE_SWITCH
, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)") },
204 { wxCMD_LINE_OPTION
, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]") },
205 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]") },
206 #if 0 // not yet implemented
207 { wxCMD_LINE_OPTION
, _T("l"), _T("list-of-handlers", _T("output list of neccessary handlers to this file" },
209 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file(s)"),
210 wxCMD_LINE_VAL_STRING
,
211 wxCMD_LINE_PARAM_MULTIPLE
| wxCMD_LINE_OPTION_MANDATORY
},
216 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
218 switch (parser
.Parse())
238 void XmlResApp::ParseParams(const wxCmdLineParser
& cmdline
)
240 flagGettext
= cmdline
.Found(_T("g"));
241 flagVerbose
= cmdline
.Found(_T("v"));
242 flagCPP
= cmdline
.Found(_T("c"));
243 flagPython
= cmdline
.Found(_T("p"));
244 flagH
= flagCPP
&& cmdline
.Found(_T("e"));
247 if (!cmdline
.Found(_T("o"), &parOutput
))
250 parOutput
= wxEmptyString
;
254 parOutput
= _T("resource.cpp");
256 parOutput
= _T("resource.py");
258 parOutput
= _T("resource.xrs");
261 if (!parOutput
.empty())
263 wxFileName
fn(parOutput
);
265 parOutput
= fn
.GetFullPath();
266 parOutputPath
= wxPathOnly(parOutput
);
268 if (!parOutputPath
) parOutputPath
= _T(".");
270 if (!cmdline
.Found(_T("n"), &parFuncname
))
271 parFuncname
= _T("InitXmlResource");
273 for (size_t i
= 0; i
< cmdline
.GetParamCount(); i
++)
276 wxString fn
=wxFindFirstFile(cmdline
.GetParam(i
), wxFILE
);
283 parFiles
.Add(cmdline
.GetParam(i
));
291 void XmlResApp::CompileRes()
293 wxArrayString files
= PrepareTempFiles();
295 wxRemoveFile(parOutput
);
300 MakePackageCPP(files
);
305 MakePackagePython(files
);
307 MakePackageZIP(files
);
310 DeleteTempFiles(files
);
314 wxString
XmlResApp::GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
)
316 wxString name2
= name
;
317 name2
.Replace(_T(":"), _T("_"));
318 name2
.Replace(_T("/"), _T("_"));
319 name2
.Replace(_T("\\"), _T("_"));
320 name2
.Replace(_T("*"), _T("_"));
321 name2
.Replace(_T("?"), _T("_"));
323 wxString s
= wxFileNameFromPath(parOutput
) + _T("$") + name2
;
325 if (wxFileExists(s
) && flist
.Index(s
) == wxNOT_FOUND
)
327 for (int i
= 0;; i
++)
329 s
.Printf(wxFileNameFromPath(parOutput
) + _T("$%03i-") + name2
, i
);
330 if (!wxFileExists(s
) || flist
.Index(s
) != wxNOT_FOUND
)
337 wxArrayString
XmlResApp::PrepareTempFiles()
341 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
344 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
348 if (!doc
.Load(parFiles
[i
]))
350 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
355 wxString name
, ext
, path
;
356 wxSplitPath(parFiles
[i
], &path
, &name
, &ext
);
358 FindFilesInXML(doc
.GetRoot(), flist
, path
);
361 wxXmlNode
* node
= (doc
.GetRoot())->GetChildren();
362 wxString classValue
,nameValue
;
364 if(node
->GetName() == _T("object")
365 && node
->GetPropVal(_T("class"),&classValue
)
366 && node
->GetPropVal(_T("name"),&nameValue
)){
368 aXRCWndClassData
.Add(
369 XRCWndClassData(nameValue
,classValue
,node
)
372 node
= node
-> GetNext();
375 wxString internalName
= GetInternalFileName(parFiles
[i
], flist
);
377 doc
.Save(parOutputPath
+ wxFILE_SEP_PATH
+ internalName
);
378 flist
.Add(internalName
);
385 // Does 'node' contain filename information at all?
386 static bool NodeContainsFilename(wxXmlNode
*node
)
389 if (node
->GetName() == _T("bitmap"))
392 if (node
->GetName() == _T("icon"))
395 // URLs in wxHtmlWindow:
396 if (node
->GetName() == _T("url"))
400 wxXmlNode
*parent
= node
->GetParent();
401 if (parent
!= NULL
&&
402 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
403 (node
->GetName() == _T("focus") ||
404 node
->GetName() == _T("disabled") ||
405 node
->GetName() == _T("selected")))
408 // wxBitmap or wxIcon toplevel resources:
409 if (node
->GetName() == _T("object"))
411 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
412 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
419 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
420 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
422 // Is 'node' XML node element?
423 if (node
== NULL
) return;
424 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
426 bool containsFilename
= NodeContainsFilename(node
);
428 wxXmlNode
*n
= node
->GetChildren();
431 if (containsFilename
&&
432 (n
->GetType() == wxXML_TEXT_NODE
||
433 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
436 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
437 fullname
= n
->GetContent();
439 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
442 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
444 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
445 n
->SetContent(filename
);
447 if (flist
.Index(filename
) == wxNOT_FOUND
)
450 wxFileInputStream
sin(fullname
);
451 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
452 sin
.Read(sout
); // copy the stream
456 if (n
->GetType() == wxXML_ELEMENT_NODE
)
457 FindFilesInXML(n
, flist
, inputPath
);
465 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
467 for (size_t i
= 0; i
< flist
.Count(); i
++)
468 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
473 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
477 for (size_t i
= 0; i
< flist
.Count(); i
++)
478 files
+= flist
[i
] + _T(" ");
482 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
484 wxString cwd
= wxGetCwd();
485 wxSetWorkingDirectory(parOutputPath
);
486 int execres
= wxExecute(_T("zip -9 -j ") +
487 wxString(flagVerbose
? _T("") : _T("-q ")) +
488 parOutput
+ _T(" ") + files
, true);
489 wxSetWorkingDirectory(cwd
);
492 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
493 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
501 static wxString
FileToCppArray(wxString filename
, int num
)
506 wxFFile
file(filename
, wxT("rb"));
507 wxFileOffset offset
= file
.Length();
508 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
509 wxASSERT_MSG( offset
== wxFileOffset(size_t(offset
)) , wxT("Huge file not supported") );
510 size_t lng
= (size_t)offset
;
512 snum
.Printf(_T("%i"), num
);
513 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
514 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
515 // we cannot use string literals because MSVC is dumb wannabe compiler
516 // with arbitrary limitation to 2048 strings :(
518 unsigned char *buffer
= new unsigned char[lng
];
519 file
.Read(buffer
, lng
);
521 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
523 tmp
.Printf(_T("%i"), buffer
[i
]);
524 if (i
!= 0) output
<< _T(',');
531 linelng
+= tmp
.Length()+1;
536 output
+= _T("};\n\n");
542 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
544 wxFFile
file(parOutput
, wxT("wt"));
548 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
552 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
554 _T("#include <wx/wxprec.h>\n")
556 _T("#ifdef __BORLANDC__\n")
557 _T(" #pragma hdrstop\n")
561 _T("#include <wx/filesys.h>\n")
562 _T("#include <wx/fs_mem.h>\n")
563 _T("#include <wx/xrc/xmlres.h>\n")
564 _T("#include <wx/xrc/xh_all.h>\n")
567 for (i
= 0; i
< flist
.Count(); i
++)
569 FileToCppArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
572 _T("void ") + parFuncname
+ wxT("()\n")
575 _T(" // Check for memory FS. If not present, load the handler:\n")
577 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
578 _T(" wxFileSystem fsys;\n")
579 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
580 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
581 _T(" if (f) delete f;\n")
582 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
586 for (i
= 0; i
< flist
.Count(); i
++)
589 s
.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist
[i
] +
590 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i
, i
);
594 for (i
= 0; i
< parFiles
.Count(); i
++)
596 file
.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
597 GetInternalFileName(parFiles
[i
], flist
) + _T("\"));\n"));
600 file
.Write(_T("}\n"));
605 void XmlResApp::GenCPPHeader()
607 wxString fileSpec
= ((parOutput
.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
608 wxString heaFileName
= fileSpec
+ _T(".h");
610 wxFFile
file(heaFileName
, wxT("wt"));
613 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
615 _T("#ifndef __") + fileSpec
+ _T("_h__\n")
616 _T("#define __") + fileSpec
+ _T("_h__\n")
618 for(size_t i
=0;i
<aXRCWndClassData
.Count();++i
){
619 aXRCWndClassData
.Item(i
).GenerateHeaderCode(file
);
624 + _T("();\n#endif\n"));
627 static wxString
FileToPythonArray(wxString filename
, int num
)
632 wxFFile
file(filename
, wxT("rb"));
633 wxFileOffset offset
= file
.Length();
634 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
635 wxASSERT_MSG( offset
== wxFileOffset(size_t(offset
)) , wxT("Huge file not supported") );
636 size_t lng
= (size_t)offset
;
638 snum
.Printf(_T("%i"), num
);
639 output
= _T(" xml_res_file_") + snum
+ _T(" = '''\\\n");
641 unsigned char *buffer
= new unsigned char[lng
];
642 file
.Read(buffer
, lng
);
644 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
646 unsigned char c
= buffer
[i
];
652 else if (c
< 32 || c
> 127 || c
== '\'')
653 tmp
.Printf(_T("\\x%02x"), c
);
661 output
<< _T("\\\n");
664 linelng
+= tmp
.Length();
669 output
+= _T("'''\n\n");
675 void XmlResApp::MakePackagePython(const wxArrayString
& flist
)
677 wxFFile
file(parOutput
, wxT("wt"));
681 wxPrintf(_T("creating Python source file ") + parOutput
+ _T("...\n"));
685 _T("# This file was automatically generated by wxrc, do not edit by hand.\n")
688 _T("import wx.xrc\n\n")
692 file
.Write(_T("def ") + parFuncname
+ _T("():\n"));
694 for (i
= 0; i
< flist
.Count(); i
++)
696 FileToPythonArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
699 _T(" # check if the memory filesystem handler has been loaded yet, and load it if not\n")
700 _T(" wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n")
701 _T(" fsys = wx.FileSystem()\n")
702 _T(" f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n")
703 _T(" wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n")
704 _T(" if f is not None:\n")
707 _T(" wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n")
709 _T(" # load all the strings as memory files and load into XmlRes\n")
713 for (i
= 0; i
< flist
.Count(); i
++)
716 s
.Printf(_T(" wx.MemoryFSHandler.AddFile('XRC_resource/") + flist
[i
] +
717 _T("', xml_res_file_%i)\n"), i
);
720 for (i
= 0; i
< parFiles
.Count(); i
++)
722 file
.Write(_T(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/") +
723 GetInternalFileName(parFiles
[i
], flist
) + _T("')\n"));
726 file
.Write(_T("\n"));
731 void XmlResApp::OutputGettext()
733 wxArrayString str
= FindStrings();
736 if (parOutput
.empty())
739 fout
.Open(parOutput
, wxT("wt"));
741 for (size_t i
= 0; i
< str
.GetCount(); i
++)
742 fout
.Write(_T("_(\"") + str
[i
] + _T("\");\n"));
744 if (!parOutput
) fout
.Detach();
749 wxArrayString
XmlResApp::FindStrings()
751 wxArrayString arr
, a2
;
753 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
756 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
759 if (!doc
.Load(parFiles
[i
]))
761 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
765 a2
= FindStrings(doc
.GetRoot());
766 WX_APPEND_ARRAY(arr
, a2
);
774 static wxString
ConvertText(const wxString
& str
)
779 for (dt
= str
.c_str(); *dt
; dt
++)
783 if ( *(++dt
) == wxT('_') )
786 str2
<< wxT('&') << *dt
;
792 case wxT('\n') : str2
<< wxT("\\n"); break;
793 case wxT('\t') : str2
<< wxT("\\t"); break;
794 case wxT('\r') : str2
<< wxT("\\r"); break;
795 case wxT('\\') : if ((*(dt
+1) != 'n') &&
802 case wxT('"') : str2
<< wxT("\\\""); break;
803 default : str2
<< *dt
; break;
812 wxArrayString
XmlResApp::FindStrings(wxXmlNode
*node
)
817 if (n
== NULL
) return arr
;
818 n
= n
->GetChildren();
822 if ((node
->GetType() == wxXML_ELEMENT_NODE
) &&
823 // parent is an element, i.e. has subnodes...
824 (n
->GetType() == wxXML_TEXT_NODE
||
825 n
->GetType() == wxXML_CDATA_SECTION_NODE
) &&
826 // ...it is textnode...
828 node
/*not n!*/->GetName() == _T("label") ||
829 (node
/*not n!*/->GetName() == _T("value") &&
830 !n
->GetContent().IsNumber()) ||
831 node
/*not n!*/->GetName() == _T("help") ||
832 node
/*not n!*/->GetName() == _T("longhelp") ||
833 node
/*not n!*/->GetName() == _T("tooltip") ||
834 node
/*not n!*/->GetName() == _T("htmlcode") ||
835 node
/*not n!*/->GetName() == _T("title") ||
836 node
/*not n!*/->GetName() == _T("item")
838 // ...and known to contain translatable string
841 node
->GetPropVal(_T("translate"), _T("1")) != _T("0"))
843 arr
.Add(ConvertText(n
->GetContent()));
848 if (n
->GetType() == wxXML_ELEMENT_NODE
)
850 wxArrayString a2
= FindStrings(n
);
851 WX_APPEND_ARRAY(arr
, a2
);