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 // For compilers that support precompilation, includes "wx/wx.h".
12 #include "wx/wxprec.h"
18 // for all others, include the necessary headers
24 #include "wx/cmdline.h"
25 #include "wx/xml/xml.h"
27 #include "wx/filename.h"
28 #include "wx/wfstream.h"
35 XRCWidgetData(const wxString
& vname
,const wxString
& vclass
)
36 : m_class(vclass
), m_name(vname
) {}
37 const wxString
& GetName() const { return m_name
; }
38 const wxString
& GetClass() const { return m_class
; }
44 #include "wx/arrimpl.cpp"
45 WX_DECLARE_OBJARRAY(XRCWidgetData
,ArrayOfXRCWidgetData
);
46 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData
)
52 wxString m_parentClassName
;
53 ArrayOfXRCWidgetData m_wdata
;
55 void BrowseXmlNode(wxXmlNode
* node
)
62 if (node
->GetName() == _T("object")
63 && node
->GetPropVal(_T("class"),&classValue
)
64 && node
->GetPropVal(_T("name"),&nameValue
))
66 m_wdata
.Add(XRCWidgetData(nameValue
,classValue
));
68 children
= node
->GetChildren();
70 BrowseXmlNode(children
);
71 node
= node
->GetNext();
76 XRCWndClassData(const wxString
& className
,const wxString
& parentClassName
, const wxXmlNode
* node
) :
77 m_className(className
) , m_parentClassName(parentClassName
)
79 BrowseXmlNode(node
->GetChildren());
82 const ArrayOfXRCWidgetData
& GetWidgetData()
87 bool IsRealClass(const wxString
& name
)
89 if (name
== _T("tool") ||
90 name
== _T("unknown") ||
91 name
== _T("notebookpage") ||
92 name
== _T("separator") ||
93 name
== _T("sizeritem") ||
94 name
== _T("wxMenuItem"))
101 void GenerateHeaderCode(wxFFile
& file
)
104 file
.Write(_T("class ") + m_className
+ _T(" : public ") + m_parentClassName
105 + _T(" {\nprotected:\n"));
107 for(i
=0;i
<m_wdata
.Count();++i
)
109 const XRCWidgetData
& w
= m_wdata
.Item(i
);
110 if( !IsRealClass(w
.GetClass()) ) continue;
111 if( w
.GetName().Length() == 0 ) continue;
113 _T(" ") + w
.GetClass() + _T("* ") + w
.GetName()
116 file
.Write(_T("\nprivate:\n void InitWidgetsFromXRC(){\n")
117 _T(" wxXmlResource::Get()->LoadObject(this,NULL,_T(\"")
122 for(i
=0;i
<m_wdata
.Count();++i
)
124 const XRCWidgetData
& w
= m_wdata
.Item(i
);
125 if( !IsRealClass(w
.GetClass()) ) continue;
126 if( w
.GetName().Length() == 0 ) continue;
129 + _T(" = XRCCTRL(*this,\"")
136 file
.Write(_T(" }\n"));
144 + _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"), (wxCmdLineParamType
)0, 0 },
196 { wxCMD_LINE_SWITCH
, _T("e"), _T("extra-cpp-code"), _T("output C++ header file with XRC derived classes"), (wxCmdLineParamType
)0, 0 },
197 { wxCMD_LINE_SWITCH
, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file"), (wxCmdLineParamType
)0, 0 },
198 { wxCMD_LINE_SWITCH
, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file"), (wxCmdLineParamType
)0, 0 },
199 { wxCMD_LINE_SWITCH
, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)"), (wxCmdLineParamType
)0, 0 },
200 { wxCMD_LINE_OPTION
, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]"), (wxCmdLineParamType
)0, 0 },
201 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]"), (wxCmdLineParamType
)0, 0 },
202 #if 0 // not yet implemented
203 { wxCMD_LINE_OPTION
, _T("l"), _T("list-of-handlers"), _T("output list of necessary handlers to this file"), (wxCmdLineParamType
)0, 0 },
205 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file(s)"),
206 wxCMD_LINE_VAL_STRING
,
207 wxCMD_LINE_PARAM_MULTIPLE
| wxCMD_LINE_OPTION_MANDATORY
},
209 { wxCMD_LINE_NONE
, NULL
, NULL
, NULL
, (wxCmdLineParamType
)0, 0 }
212 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
214 switch (parser
.Parse())
234 void XmlResApp::ParseParams(const wxCmdLineParser
& cmdline
)
236 flagGettext
= cmdline
.Found(_T("g"));
237 flagVerbose
= cmdline
.Found(_T("v"));
238 flagCPP
= cmdline
.Found(_T("c"));
239 flagPython
= cmdline
.Found(_T("p"));
240 flagH
= flagCPP
&& cmdline
.Found(_T("e"));
243 if (!cmdline
.Found(_T("o"), &parOutput
))
246 parOutput
= wxEmptyString
;
250 parOutput
= _T("resource.cpp");
252 parOutput
= _T("resource.py");
254 parOutput
= _T("resource.xrs");
257 if (!parOutput
.empty())
259 wxFileName
fn(parOutput
);
261 parOutput
= fn
.GetFullPath();
262 parOutputPath
= wxPathOnly(parOutput
);
264 if (!parOutputPath
) parOutputPath
= _T(".");
266 if (!cmdline
.Found(_T("n"), &parFuncname
))
267 parFuncname
= _T("InitXmlResource");
269 for (size_t i
= 0; i
< cmdline
.GetParamCount(); i
++)
272 wxString fn
=wxFindFirstFile(cmdline
.GetParam(i
), wxFILE
);
279 parFiles
.Add(cmdline
.GetParam(i
));
287 void XmlResApp::CompileRes()
289 wxArrayString files
= PrepareTempFiles();
291 wxRemoveFile(parOutput
);
296 MakePackageCPP(files
);
301 MakePackagePython(files
);
303 MakePackageZIP(files
);
306 DeleteTempFiles(files
);
310 wxString
XmlResApp::GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
)
312 wxString name2
= name
;
313 name2
.Replace(_T(":"), _T("_"));
314 name2
.Replace(_T("/"), _T("_"));
315 name2
.Replace(_T("\\"), _T("_"));
316 name2
.Replace(_T("*"), _T("_"));
317 name2
.Replace(_T("?"), _T("_"));
319 wxString s
= wxFileNameFromPath(parOutput
) + _T("$") + name2
;
321 if (wxFileExists(s
) && flist
.Index(s
) == wxNOT_FOUND
)
323 for (int i
= 0;; i
++)
325 s
.Printf(wxFileNameFromPath(parOutput
) + _T("$%03i-") + name2
, i
);
326 if (!wxFileExists(s
) || flist
.Index(s
) != wxNOT_FOUND
)
333 wxArrayString
XmlResApp::PrepareTempFiles()
337 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
340 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
344 if (!doc
.Load(parFiles
[i
]))
346 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
351 wxString name
, ext
, path
;
352 wxSplitPath(parFiles
[i
], &path
, &name
, &ext
);
354 FindFilesInXML(doc
.GetRoot(), flist
, path
);
357 wxXmlNode
* node
= (doc
.GetRoot())->GetChildren();
358 wxString classValue
,nameValue
;
360 if(node
->GetName() == _T("object")
361 && node
->GetPropVal(_T("class"),&classValue
)
362 && node
->GetPropVal(_T("name"),&nameValue
)){
364 aXRCWndClassData
.Add(
365 XRCWndClassData(nameValue
,classValue
,node
)
368 node
= node
-> GetNext();
371 wxString internalName
= GetInternalFileName(parFiles
[i
], flist
);
373 doc
.Save(parOutputPath
+ wxFILE_SEP_PATH
+ internalName
);
374 flist
.Add(internalName
);
381 // Does 'node' contain filename information at all?
382 static bool NodeContainsFilename(wxXmlNode
*node
)
384 const wxString name
= node
->GetName();
386 // Any bitmaps (bitmap2 is used for disabled toolbar buttons):
387 if ( name
== _T("bitmap") || name
== _T("bitmap2") )
390 if ( name
== _T("icon") )
393 // URLs in wxHtmlWindow:
394 if ( name
== _T("url") )
398 wxXmlNode
*parent
= node
->GetParent();
399 if (parent
!= NULL
&&
400 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
401 (name
== _T("focus") ||
402 name
== _T("disabled") ||
403 name
== _T("selected")))
406 // wxBitmap or wxIcon toplevel resources:
407 if ( name
== _T("object") )
409 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
410 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
417 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
418 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
420 // Is 'node' XML node element?
421 if (node
== NULL
) return;
422 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
424 bool containsFilename
= NodeContainsFilename(node
);
426 wxXmlNode
*n
= node
->GetChildren();
429 if (containsFilename
&&
430 (n
->GetType() == wxXML_TEXT_NODE
||
431 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
434 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
435 fullname
= n
->GetContent();
437 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
440 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
442 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
443 n
->SetContent(filename
);
445 if (flist
.Index(filename
) == wxNOT_FOUND
)
448 wxFileInputStream
sin(fullname
);
449 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
450 sin
.Read(sout
); // copy the stream
454 if (n
->GetType() == wxXML_ELEMENT_NODE
)
455 FindFilesInXML(n
, flist
, inputPath
);
463 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
465 for (size_t i
= 0; i
< flist
.Count(); i
++)
466 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
471 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
475 for (size_t i
= 0; i
< flist
.Count(); i
++)
476 files
+= flist
[i
] + _T(" ");
480 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
482 wxString cwd
= wxGetCwd();
483 wxSetWorkingDirectory(parOutputPath
);
484 int execres
= wxExecute(_T("zip -9 -j ") +
485 wxString(flagVerbose
? _T("\"") : _T("-q \"")) +
486 parOutput
+ _T("\" ") + files
, true);
487 wxSetWorkingDirectory(cwd
);
490 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
491 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
499 static wxString
FileToCppArray(wxString filename
, int num
)
504 wxFFile
file(filename
, wxT("rb"));
505 wxFileOffset offset
= file
.Length();
506 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
508 const size_t lng
= wx_truncate_cast(size_t, offset
);
509 wxASSERT_MSG( lng
== offset
, wxT("Huge file not supported") );
511 snum
.Printf(_T("%i"), num
);
512 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
513 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
514 // we cannot use string literals because MSVC is dumb wannabe compiler
515 // with arbitrary limitation to 2048 strings :(
517 unsigned char *buffer
= new unsigned char[lng
];
518 file
.Read(buffer
, lng
);
520 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
522 tmp
.Printf(_T("%i"), buffer
[i
]);
523 if (i
!= 0) output
<< _T(',');
530 linelng
+= tmp
.Length()+1;
535 output
+= _T("};\n\n");
541 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
543 wxFFile
file(parOutput
, wxT("wt"));
547 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
551 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
553 _T("#include <wx/wxprec.h>\n")
555 _T("#ifdef __BORLANDC__\n")
556 _T(" #pragma hdrstop\n")
560 _T("#include <wx/filesys.h>\n")
561 _T("#include <wx/fs_mem.h>\n")
562 _T("#include <wx/xrc/xmlres.h>\n")
563 _T("#include <wx/xrc/xh_all.h>\n")
566 for (i
= 0; i
< flist
.Count(); i
++)
568 FileToCppArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
571 _T("void ") + parFuncname
+ wxT("()\n")
574 _T(" // Check for memory FS. If not present, load the handler:\n")
576 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
577 _T(" wxFileSystem fsys;\n")
578 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
579 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
580 _T(" if (f) delete f;\n")
581 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
585 for (i
= 0; i
< flist
.Count(); i
++)
588 s
.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist
[i
] +
589 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i
, i
);
593 for (i
= 0; i
< parFiles
.Count(); i
++)
595 file
.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
596 GetInternalFileName(parFiles
[i
], flist
) + _T("\"));\n"));
599 file
.Write(_T("}\n"));
604 void XmlResApp::GenCPPHeader()
606 wxString fileSpec
= ((parOutput
.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
607 wxString heaFileName
= fileSpec
+ _T(".h");
609 wxFFile
file(heaFileName
, wxT("wt"));
612 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
614 _T("#ifndef __") + fileSpec
+ _T("_h__\n")
615 _T("#define __") + fileSpec
+ _T("_h__\n")
617 for(size_t i
=0;i
<aXRCWndClassData
.Count();++i
){
618 aXRCWndClassData
.Item(i
).GenerateHeaderCode(file
);
623 + _T("();\n#endif\n"));
626 static wxString
FileToPythonArray(wxString filename
, int num
)
631 wxFFile
file(filename
, wxT("rb"));
632 wxFileOffset offset
= file
.Length();
633 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
635 const size_t lng
= wx_truncate_cast(size_t, offset
);
636 wxASSERT_MSG( offset
== lng
, wxT("Huge file not supported") );
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
);