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"
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
; }
49 #include "wx/arrimpl.cpp"
50 WX_DECLARE_OBJARRAY(XRCWidgetData
,ArrayOfXRCWidgetData
);
51 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData
);
57 wxString m_parentClassName
;
58 ArrayOfXRCWidgetData m_wdata
;
60 void BrowseXmlNode(wxXmlNode
* node
)
67 if (node
->GetName() == _T("object")
68 && node
->GetPropVal(_T("class"),&classValue
)
69 && node
->GetPropVal(_T("name"),&nameValue
))
71 m_wdata
.Add(XRCWidgetData(nameValue
,classValue
));
73 children
= node
->GetChildren();
75 BrowseXmlNode(children
);
76 node
= node
->GetNext();
81 XRCWndClassData(const wxString
& className
,const wxString
& parentClassName
, const wxXmlNode
* node
) :
82 m_className(className
) , m_parentClassName(parentClassName
)
84 BrowseXmlNode(node
->GetChildren());
87 const ArrayOfXRCWidgetData
& GetWidgetData()
92 bool IsRealClass(const wxString
& name
)
94 if (name
== _T("tool") ||
95 name
== _T("unknown") ||
96 name
== _T("notebookpage") ||
97 name
== _T("separator") ||
98 name
== _T("sizeritem") ||
99 name
== _T("wxMenuItem"))
106 void GenerateHeaderCode(wxFFile
& file
)
109 file
.Write(_T("class ") + m_className
+ _T(" : public ") + m_parentClassName
110 + _T(" {\nprotected:\n"));
112 for(i
=0;i
<m_wdata
.Count();++i
)
114 const XRCWidgetData
& w
= m_wdata
.Item(i
);
115 if( !IsRealClass(w
.GetClass()) ) continue;
116 if( w
.GetName().Length() == 0 ) continue;
118 _T(" ") + w
.GetClass() + _T("* ") + w
.GetName()
121 file
.Write(_T("\nprivate:\n void InitWidgetsFromXRC(){\n")
122 _T(" wxXmlResource::Get()->LoadObject(this,NULL,_T(\"")
127 for(i
=0;i
<m_wdata
.Count();++i
)
129 const XRCWidgetData
& w
= m_wdata
.Item(i
);
130 if( !IsRealClass(w
.GetClass()) ) continue;
131 if( w
.GetName().Length() == 0 ) continue;
134 + _T(" = XRCCTRL(*this,\"")
141 file
.Write(_T(" }\n"));
149 + _T(" InitWidgetsFromXRC();\n")
155 WX_DECLARE_OBJARRAY(XRCWndClassData
,ArrayOfXRCWndClassData
);
156 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData
);
159 class XmlResApp
: public wxAppConsole
162 // don't use builtin cmd line parsing:
163 virtual bool OnInit() { return true; }
167 void ParseParams(const wxCmdLineParser
& cmdline
);
169 wxArrayString
PrepareTempFiles();
170 void FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
);
172 wxString
GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
);
173 void DeleteTempFiles(const wxArrayString
& flist
);
174 void MakePackageZIP(const wxArrayString
& flist
);
175 void MakePackageCPP(const wxArrayString
& flist
);
176 void MakePackagePython(const wxArrayString
& flist
);
178 void OutputGettext();
179 wxArrayString
FindStrings();
180 wxArrayString
FindStrings(wxXmlNode
*node
);
182 bool flagVerbose
, flagCPP
, flagPython
, flagGettext
;
183 wxString parOutput
, parFuncname
, parOutputPath
;
184 wxArrayString parFiles
;
187 ArrayOfXRCWndClassData aXRCWndClassData
;
192 IMPLEMENT_APP_CONSOLE(XmlResApp
)
194 int XmlResApp::OnRun()
196 static const wxCmdLineEntryDesc cmdLineDesc
[] =
198 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show help message"),
199 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
200 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose"), (wxCmdLineParamType
)0, 0 },
201 { wxCMD_LINE_SWITCH
, _T("e"), _T("extra-cpp-code"), _T("output C++ header file with XRC derived classes"), (wxCmdLineParamType
)0, 0 },
202 { wxCMD_LINE_SWITCH
, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file"), (wxCmdLineParamType
)0, 0 },
203 { wxCMD_LINE_SWITCH
, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file"), (wxCmdLineParamType
)0, 0 },
204 { wxCMD_LINE_SWITCH
, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)"), (wxCmdLineParamType
)0, 0 },
205 { wxCMD_LINE_OPTION
, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]"), (wxCmdLineParamType
)0, 0 },
206 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]"), (wxCmdLineParamType
)0, 0 },
207 #if 0 // not yet implemented
208 { wxCMD_LINE_OPTION
, _T("l"), _T("list-of-handlers"), _T("output list of neccessary handlers to this file"), (wxCmdLineParamType
)0, 0 },
210 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file(s)"),
211 wxCMD_LINE_VAL_STRING
,
212 wxCMD_LINE_PARAM_MULTIPLE
| wxCMD_LINE_OPTION_MANDATORY
},
214 { wxCMD_LINE_NONE
, NULL
, NULL
, NULL
, (wxCmdLineParamType
)0, 0 }
217 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
219 switch (parser
.Parse())
239 void XmlResApp::ParseParams(const wxCmdLineParser
& cmdline
)
241 flagGettext
= cmdline
.Found(_T("g"));
242 flagVerbose
= cmdline
.Found(_T("v"));
243 flagCPP
= cmdline
.Found(_T("c"));
244 flagPython
= cmdline
.Found(_T("p"));
245 flagH
= flagCPP
&& cmdline
.Found(_T("e"));
248 if (!cmdline
.Found(_T("o"), &parOutput
))
251 parOutput
= wxEmptyString
;
255 parOutput
= _T("resource.cpp");
257 parOutput
= _T("resource.py");
259 parOutput
= _T("resource.xrs");
262 if (!parOutput
.empty())
264 wxFileName
fn(parOutput
);
266 parOutput
= fn
.GetFullPath();
267 parOutputPath
= wxPathOnly(parOutput
);
269 if (!parOutputPath
) parOutputPath
= _T(".");
271 if (!cmdline
.Found(_T("n"), &parFuncname
))
272 parFuncname
= _T("InitXmlResource");
274 for (size_t i
= 0; i
< cmdline
.GetParamCount(); i
++)
277 wxString fn
=wxFindFirstFile(cmdline
.GetParam(i
), wxFILE
);
284 parFiles
.Add(cmdline
.GetParam(i
));
292 void XmlResApp::CompileRes()
294 wxArrayString files
= PrepareTempFiles();
296 wxRemoveFile(parOutput
);
301 MakePackageCPP(files
);
306 MakePackagePython(files
);
308 MakePackageZIP(files
);
311 DeleteTempFiles(files
);
315 wxString
XmlResApp::GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
)
317 wxString name2
= name
;
318 name2
.Replace(_T(":"), _T("_"));
319 name2
.Replace(_T("/"), _T("_"));
320 name2
.Replace(_T("\\"), _T("_"));
321 name2
.Replace(_T("*"), _T("_"));
322 name2
.Replace(_T("?"), _T("_"));
324 wxString s
= wxFileNameFromPath(parOutput
) + _T("$") + name2
;
326 if (wxFileExists(s
) && flist
.Index(s
) == wxNOT_FOUND
)
328 for (int i
= 0;; i
++)
330 s
.Printf(wxFileNameFromPath(parOutput
) + _T("$%03i-") + name2
, i
);
331 if (!wxFileExists(s
) || flist
.Index(s
) != wxNOT_FOUND
)
338 wxArrayString
XmlResApp::PrepareTempFiles()
342 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
345 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
349 if (!doc
.Load(parFiles
[i
]))
351 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
356 wxString name
, ext
, path
;
357 wxSplitPath(parFiles
[i
], &path
, &name
, &ext
);
359 FindFilesInXML(doc
.GetRoot(), flist
, path
);
362 wxXmlNode
* node
= (doc
.GetRoot())->GetChildren();
363 wxString classValue
,nameValue
;
365 if(node
->GetName() == _T("object")
366 && node
->GetPropVal(_T("class"),&classValue
)
367 && node
->GetPropVal(_T("name"),&nameValue
)){
369 aXRCWndClassData
.Add(
370 XRCWndClassData(nameValue
,classValue
,node
)
373 node
= node
-> GetNext();
376 wxString internalName
= GetInternalFileName(parFiles
[i
], flist
);
378 doc
.Save(parOutputPath
+ wxFILE_SEP_PATH
+ internalName
);
379 flist
.Add(internalName
);
386 // Does 'node' contain filename information at all?
387 static bool NodeContainsFilename(wxXmlNode
*node
)
390 if (node
->GetName() == _T("bitmap"))
393 if (node
->GetName() == _T("icon"))
396 // URLs in wxHtmlWindow:
397 if (node
->GetName() == _T("url"))
401 wxXmlNode
*parent
= node
->GetParent();
402 if (parent
!= NULL
&&
403 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
404 (node
->GetName() == _T("focus") ||
405 node
->GetName() == _T("disabled") ||
406 node
->GetName() == _T("selected")))
409 // wxBitmap or wxIcon toplevel resources:
410 if (node
->GetName() == _T("object"))
412 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
413 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
420 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
421 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
423 // Is 'node' XML node element?
424 if (node
== NULL
) return;
425 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
427 bool containsFilename
= NodeContainsFilename(node
);
429 wxXmlNode
*n
= node
->GetChildren();
432 if (containsFilename
&&
433 (n
->GetType() == wxXML_TEXT_NODE
||
434 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
437 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
438 fullname
= n
->GetContent();
440 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
443 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
445 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
446 n
->SetContent(filename
);
448 if (flist
.Index(filename
) == wxNOT_FOUND
)
451 wxFileInputStream
sin(fullname
);
452 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
453 sin
.Read(sout
); // copy the stream
457 if (n
->GetType() == wxXML_ELEMENT_NODE
)
458 FindFilesInXML(n
, flist
, inputPath
);
466 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
468 for (size_t i
= 0; i
< flist
.Count(); i
++)
469 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
474 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
478 for (size_t i
= 0; i
< flist
.Count(); i
++)
479 files
+= flist
[i
] + _T(" ");
483 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
485 wxString cwd
= wxGetCwd();
486 wxSetWorkingDirectory(parOutputPath
);
487 int execres
= wxExecute(_T("zip -9 -j ") +
488 wxString(flagVerbose
? _T("\"") : _T("-q \"")) +
489 parOutput
+ _T("\" ") + files
, true);
490 wxSetWorkingDirectory(cwd
);
493 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
494 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
502 static wxString
FileToCppArray(wxString filename
, int num
)
507 wxFFile
file(filename
, wxT("rb"));
508 wxFileOffset offset
= file
.Length();
509 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
510 wxASSERT_MSG( offset
== wxFileOffset(size_t(offset
)) , wxT("Huge file not supported") );
511 size_t lng
= (size_t)offset
;
513 snum
.Printf(_T("%i"), num
);
514 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
515 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
516 // we cannot use string literals because MSVC is dumb wannabe compiler
517 // with arbitrary limitation to 2048 strings :(
519 unsigned char *buffer
= new unsigned char[lng
];
520 file
.Read(buffer
, lng
);
522 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
524 tmp
.Printf(_T("%i"), buffer
[i
]);
525 if (i
!= 0) output
<< _T(',');
532 linelng
+= tmp
.Length()+1;
537 output
+= _T("};\n\n");
543 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
545 wxFFile
file(parOutput
, wxT("wt"));
549 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
553 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
555 _T("#include <wx/wxprec.h>\n")
557 _T("#ifdef __BORLANDC__\n")
558 _T(" #pragma hdrstop\n")
562 _T("#include <wx/filesys.h>\n")
563 _T("#include <wx/fs_mem.h>\n")
564 _T("#include <wx/xrc/xmlres.h>\n")
565 _T("#include <wx/xrc/xh_all.h>\n")
568 for (i
= 0; i
< flist
.Count(); i
++)
570 FileToCppArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
573 _T("void ") + parFuncname
+ wxT("()\n")
576 _T(" // Check for memory FS. If not present, load the handler:\n")
578 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
579 _T(" wxFileSystem fsys;\n")
580 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
581 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
582 _T(" if (f) delete f;\n")
583 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
587 for (i
= 0; i
< flist
.Count(); i
++)
590 s
.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist
[i
] +
591 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i
, i
);
595 for (i
= 0; i
< parFiles
.Count(); i
++)
597 file
.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
598 GetInternalFileName(parFiles
[i
], flist
) + _T("\"));\n"));
601 file
.Write(_T("}\n"));
606 void XmlResApp::GenCPPHeader()
608 wxString fileSpec
= ((parOutput
.BeforeLast('.')).AfterLast('/')).AfterLast('\\');
609 wxString heaFileName
= fileSpec
+ _T(".h");
611 wxFFile
file(heaFileName
, wxT("wt"));
614 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
616 _T("#ifndef __") + fileSpec
+ _T("_h__\n")
617 _T("#define __") + fileSpec
+ _T("_h__\n")
619 for(size_t i
=0;i
<aXRCWndClassData
.Count();++i
){
620 aXRCWndClassData
.Item(i
).GenerateHeaderCode(file
);
625 + _T("();\n#endif\n"));
628 static wxString
FileToPythonArray(wxString filename
, int num
)
633 wxFFile
file(filename
, wxT("rb"));
634 wxFileOffset offset
= file
.Length();
635 wxASSERT_MSG( offset
>= 0 , wxT("Invalid file length") );
636 wxASSERT_MSG( offset
== wxFileOffset(size_t(offset
)) , wxT("Huge file not supported") );
637 size_t lng
= (size_t)offset
;
639 snum
.Printf(_T("%i"), num
);
640 output
= _T(" xml_res_file_") + snum
+ _T(" = '''\\\n");
642 unsigned char *buffer
= new unsigned char[lng
];
643 file
.Read(buffer
, lng
);
645 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
647 unsigned char c
= buffer
[i
];
653 else if (c
< 32 || c
> 127 || c
== '\'')
654 tmp
.Printf(_T("\\x%02x"), c
);
662 output
<< _T("\\\n");
665 linelng
+= tmp
.Length();
670 output
+= _T("'''\n\n");
676 void XmlResApp::MakePackagePython(const wxArrayString
& flist
)
678 wxFFile
file(parOutput
, wxT("wt"));
682 wxPrintf(_T("creating Python source file ") + parOutput
+ _T("...\n"));
686 _T("# This file was automatically generated by wxrc, do not edit by hand.\n")
689 _T("import wx.xrc\n\n")
693 file
.Write(_T("def ") + parFuncname
+ _T("():\n"));
695 for (i
= 0; i
< flist
.Count(); i
++)
697 FileToPythonArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
700 _T(" # check if the memory filesystem handler has been loaded yet, and load it if not\n")
701 _T(" wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n")
702 _T(" fsys = wx.FileSystem()\n")
703 _T(" f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n")
704 _T(" wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n")
705 _T(" if f is not None:\n")
708 _T(" wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n")
710 _T(" # load all the strings as memory files and load into XmlRes\n")
714 for (i
= 0; i
< flist
.Count(); i
++)
717 s
.Printf(_T(" wx.MemoryFSHandler.AddFile('XRC_resource/") + flist
[i
] +
718 _T("', xml_res_file_%i)\n"), i
);
721 for (i
= 0; i
< parFiles
.Count(); i
++)
723 file
.Write(_T(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/") +
724 GetInternalFileName(parFiles
[i
], flist
) + _T("')\n"));
727 file
.Write(_T("\n"));
732 void XmlResApp::OutputGettext()
734 wxArrayString str
= FindStrings();
737 if (parOutput
.empty())
740 fout
.Open(parOutput
, wxT("wt"));
742 for (size_t i
= 0; i
< str
.GetCount(); i
++)
743 fout
.Write(_T("_(\"") + str
[i
] + _T("\");\n"));
745 if (!parOutput
) fout
.Detach();
750 wxArrayString
XmlResApp::FindStrings()
752 wxArrayString arr
, a2
;
754 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
757 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
760 if (!doc
.Load(parFiles
[i
]))
762 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
766 a2
= FindStrings(doc
.GetRoot());
767 WX_APPEND_ARRAY(arr
, a2
);
775 static wxString
ConvertText(const wxString
& str
)
780 for (dt
= str
.c_str(); *dt
; dt
++)
784 if ( *(++dt
) == wxT('_') )
787 str2
<< wxT('&') << *dt
;
793 case wxT('\n') : str2
<< wxT("\\n"); break;
794 case wxT('\t') : str2
<< wxT("\\t"); break;
795 case wxT('\r') : str2
<< wxT("\\r"); break;
796 case wxT('\\') : if ((*(dt
+1) != 'n') &&
803 case wxT('"') : str2
<< wxT("\\\""); break;
804 default : str2
<< *dt
; break;
813 wxArrayString
XmlResApp::FindStrings(wxXmlNode
*node
)
818 if (n
== NULL
) return arr
;
819 n
= n
->GetChildren();
823 if ((node
->GetType() == wxXML_ELEMENT_NODE
) &&
824 // parent is an element, i.e. has subnodes...
825 (n
->GetType() == wxXML_TEXT_NODE
||
826 n
->GetType() == wxXML_CDATA_SECTION_NODE
) &&
827 // ...it is textnode...
829 node
/*not n!*/->GetName() == _T("label") ||
830 (node
/*not n!*/->GetName() == _T("value") &&
831 !n
->GetContent().IsNumber()) ||
832 node
/*not n!*/->GetName() == _T("help") ||
833 node
/*not n!*/->GetName() == _T("longhelp") ||
834 node
/*not n!*/->GetName() == _T("tooltip") ||
835 node
/*not n!*/->GetName() == _T("htmlcode") ||
836 node
/*not n!*/->GetName() == _T("title") ||
837 node
/*not n!*/->GetName() == _T("item")
839 // ...and known to contain translatable string
842 node
->GetPropVal(_T("translate"), _T("1")) != _T("0"))
844 arr
.Add(ConvertText(n
->GetContent()));
849 if (n
->GetType() == wxXML_ELEMENT_NODE
)
851 wxArrayString a2
= FindStrings(n
);
852 WX_APPEND_ARRAY(arr
, a2
);