1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik
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 (this file is usually all you
24 // need because it includes almost all "standard" wxWindows headers
29 #include "wx/cmdline.h"
30 #include "wx/xml/xml.h"
32 #include "wx/filename.h"
33 #include "wx/wfstream.h"
36 class XmlResApp
: public wxAppConsole
39 // don't use builtin cmd line parsing:
40 virtual bool OnInit() { return true; }
46 void ParseParams(const wxCmdLineParser
& cmdline
);
48 wxArrayString
PrepareTempFiles();
49 void FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
);
51 wxString
GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
);
52 void DeleteTempFiles(const wxArrayString
& flist
);
53 void MakePackageZIP(const wxArrayString
& flist
);
54 void MakePackageCPP(const wxArrayString
& flist
);
55 void MakePackagePython(const wxArrayString
& flist
);
58 wxArrayString
FindStrings();
59 wxArrayString
FindStrings(wxXmlNode
*node
);
61 bool flagVerbose
, flagCPP
, flagPython
, flagGettext
;
62 wxString parOutput
, parFuncname
, parOutputPath
;
63 wxArrayString parFiles
;
67 IMPLEMENT_APP_CONSOLE(XmlResApp
)
69 int XmlResApp::OnRun()
71 static const wxCmdLineEntryDesc cmdLineDesc
[] =
73 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show help message"),
74 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
75 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
76 { wxCMD_LINE_SWITCH
, _T("c"), _T("cpp-code"), _T("output C++ source rather than .rsc file") },
77 { wxCMD_LINE_SWITCH
, _T("p"), _T("python-code"), _T("output wxPython source rather than .rsc file") },
78 { wxCMD_LINE_SWITCH
, _T("g"), _T("gettext"), _T("output list of translatable strings (to stdout or file if -o used)") },
79 { wxCMD_LINE_OPTION
, _T("n"), _T("function"), _T("C++/Python function name (with -c or -p) [InitXmlResource]") },
80 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file [resource.xrs/cpp]") },
81 #if 0 // not yet implemented
82 { wxCMD_LINE_OPTION
, _T("l"), _T("list-of-handlers", _T("output list of neccessary handlers to this file" },
84 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file(s)"),
85 wxCMD_LINE_VAL_STRING
,
86 wxCMD_LINE_PARAM_MULTIPLE
| wxCMD_LINE_OPTION_MANDATORY
},
91 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
93 switch (parser
.Parse())
118 void XmlResApp::ParseParams(const wxCmdLineParser
& cmdline
)
120 flagGettext
= cmdline
.Found(_T("g"));
121 flagVerbose
= cmdline
.Found(_T("v"));
122 flagCPP
= cmdline
.Found(_T("c"));
123 flagPython
= cmdline
.Found(_T("p"));
125 if (!cmdline
.Found(_T("o"), &parOutput
))
128 parOutput
= wxEmptyString
;
132 parOutput
= _T("resource.cpp");
134 parOutput
= _T("resource.py");
136 parOutput
= _T("resource.xrs");
139 wxFileName
fn(parOutput
);
141 parOutput
= fn
.GetFullPath();
142 parOutputPath
= wxPathOnly(parOutput
);
143 if (!parOutputPath
) parOutputPath
= _T(".");
145 if (!cmdline
.Found(_T("n"), &parFuncname
))
146 parFuncname
= _T("InitXmlResource");
148 for (size_t i
= 0; i
< cmdline
.GetParamCount(); i
++)
151 wxString fn
=wxFindFirstFile(cmdline
.GetParam(i
), wxFILE
);
152 while (!fn
.IsEmpty())
158 parFiles
.Add(cmdline
.GetParam(i
));
166 void XmlResApp::CompileRes()
168 wxArrayString files
= PrepareTempFiles();
170 wxRemoveFile(parOutput
);
175 MakePackageCPP(files
);
177 MakePackagePython(files
);
179 MakePackageZIP(files
);
182 DeleteTempFiles(files
);
186 wxString
XmlResApp::GetInternalFileName(const wxString
& name
, const wxArrayString
& flist
)
188 wxString name2
= name
;
189 name2
.Replace(_T(":"), _T("_"));
190 name2
.Replace(_T("/"), _T("_"));
191 name2
.Replace(_T("\\"), _T("_"));
192 name2
.Replace(_T("*"), _T("_"));
193 name2
.Replace(_T("?"), _T("_"));
195 wxString s
= wxFileNameFromPath(parOutput
) + _T("$") + name2
;
197 if (wxFileExists(s
) && flist
.Index(s
) == wxNOT_FOUND
)
199 for (int i
= 0;; i
++)
201 s
.Printf(wxFileNameFromPath(parOutput
) + _T("$%03i-") + name2
, i
);
202 if (!wxFileExists(s
) || flist
.Index(s
) != wxNOT_FOUND
)
209 wxArrayString
XmlResApp::PrepareTempFiles()
213 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
216 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
220 if (!doc
.Load(parFiles
[i
]))
222 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
227 wxString name
, ext
, path
;
228 wxSplitPath(parFiles
[i
], &path
, &name
, &ext
);
230 FindFilesInXML(doc
.GetRoot(), flist
, path
);
232 wxString internalName
= GetInternalFileName(parFiles
[i
], flist
);
234 doc
.Save(parOutputPath
+ wxFILE_SEP_PATH
+ internalName
);
235 flist
.Add(internalName
);
242 // Does 'node' contain filename information at all?
243 static bool NodeContainsFilename(wxXmlNode
*node
)
246 if (node
->GetName() == _T("bitmap"))
249 // URLs in wxHtmlWindow:
250 if (node
->GetName() == _T("url"))
254 wxXmlNode
*parent
= node
->GetParent();
255 if (parent
!= NULL
&&
256 parent
->GetPropVal(_T("class"), _T("")) == _T("wxBitmapButton") &&
257 (node
->GetName() == _T("focus") ||
258 node
->GetName() == _T("disabled") ||
259 node
->GetName() == _T("selected")))
262 // wxBitmap or wxIcon toplevel resources:
263 if (node
->GetName() == _T("object"))
265 wxString klass
= node
->GetPropVal(_T("class"), wxEmptyString
);
266 if (klass
== _T("wxBitmap") || klass
== _T("wxIcon"))
273 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
274 void XmlResApp::FindFilesInXML(wxXmlNode
*node
, wxArrayString
& flist
, const wxString
& inputPath
)
276 // Is 'node' XML node element?
277 if (node
== NULL
) return;
278 if (node
->GetType() != wxXML_ELEMENT_NODE
) return;
280 bool containsFilename
= NodeContainsFilename(node
);
282 wxXmlNode
*n
= node
->GetChildren();
285 if (containsFilename
&&
286 (n
->GetType() == wxXML_TEXT_NODE
||
287 n
->GetType() == wxXML_CDATA_SECTION_NODE
))
290 if (wxIsAbsolutePath(n
->GetContent()) || inputPath
.empty())
291 fullname
= n
->GetContent();
293 fullname
= inputPath
+ wxFILE_SEP_PATH
+ n
->GetContent();
296 wxPrintf(_T("adding ") + fullname
+ _T("...\n"));
298 wxString filename
= GetInternalFileName(n
->GetContent(), flist
);
299 n
->SetContent(filename
);
301 if (flist
.Index(filename
) == wxNOT_FOUND
)
304 wxFileInputStream
sin(fullname
);
305 wxFileOutputStream
sout(parOutputPath
+ wxFILE_SEP_PATH
+ filename
);
306 sin
.Read(sout
); // copy the stream
310 if (n
->GetType() == wxXML_ELEMENT_NODE
)
311 FindFilesInXML(n
, flist
, inputPath
);
319 void XmlResApp::DeleteTempFiles(const wxArrayString
& flist
)
321 for (size_t i
= 0; i
< flist
.Count(); i
++)
322 wxRemoveFile(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
]);
327 void XmlResApp::MakePackageZIP(const wxArrayString
& flist
)
331 for (size_t i
= 0; i
< flist
.Count(); i
++)
332 files
+= flist
[i
] + _T(" ");
336 wxPrintf(_T("compressing ") + parOutput
+ _T("...\n"));
338 wxString cwd
= wxGetCwd();
339 wxSetWorkingDirectory(parOutputPath
);
340 int execres
= wxExecute(_T("zip -9 -j ") +
341 wxString(flagVerbose
? _T("") : _T("-q ")) +
342 parOutput
+ _T(" ") + files
, TRUE
);
343 wxSetWorkingDirectory(cwd
);
346 wxLogError(_T("Unable to execute zip program. Make sure it is in the path."));
347 wxLogError(_T("You can download it at http://www.cdrom.com/pub/infozip/"));
356 static wxString
FileToCppArray(wxString filename
, int num
)
361 wxFFile
file(filename
, wxT("rb"));
362 size_t lng
= file
.Length();
364 snum
.Printf(_T("%i"), num
);
365 output
.Printf(_T("static size_t xml_res_size_") + snum
+ _T(" = %i;\n"), lng
);
366 output
+= _T("static unsigned char xml_res_file_") + snum
+ _T("[] = {\n");
367 // we cannot use string literals because MSVC is dumb wannabe compiler
368 // with arbitrary limitation to 2048 strings :(
370 unsigned char *buffer
= new unsigned char[lng
];
371 file
.Read(buffer
, lng
);
373 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
375 tmp
.Printf(_T("%i"), buffer
[i
]);
376 if (i
!= 0) output
<< _T(',');
383 linelng
+= tmp
.Length()+1;
388 output
+= _T("};\n\n");
394 void XmlResApp::MakePackageCPP(const wxArrayString
& flist
)
396 wxFFile
file(parOutput
, wxT("wt"));
400 wxPrintf(_T("creating C++ source file ") + parOutput
+ _T("...\n"));
404 _T("// This file was automatically generated by wxrc, do not edit by hand.\n")
406 _T("#include <wx/wxprec.h>\n")
408 _T("#ifdef __BORLANDC__\n")
409 _T(" #pragma hdrstop\n")
412 _T("#ifndef WX_PRECOMP\n")
413 _T(" #include <wx/wx.h>\n")
416 _T("#include <wx/filesys.h>\n")
417 _T("#include <wx/fs_mem.h>\n")
418 _T("#include <wx/xrc/xmlres.h>\n")
419 _T("#include <wx/xrc/xh_all.h>\n")
422 for (i
= 0; i
< flist
.Count(); i
++)
424 FileToCppArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
427 _T("void ") + parFuncname
+ wxT("()\n")
430 _T(" // Check for memory FS. If not present, load the handler:\n")
432 _T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n")
433 _T(" wxFileSystem fsys;\n")
434 _T(" wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n")
435 _T(" wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n")
436 _T(" if (f) delete f;\n")
437 _T(" else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n")
441 for (i
= 0; i
< flist
.Count(); i
++)
444 s
.Printf(_T(" wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/") + flist
[i
] +
445 _T("\"), xml_res_file_%i, xml_res_size_%i);\n"), i
, i
);
449 for (i
= 0; i
< parFiles
.Count(); i
++)
451 file
.Write(_T(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/") +
452 GetInternalFileName(parFiles
[i
], flist
) + _T("\"));\n"));
455 file
.Write(_T("}\n"));
460 static wxString
FileToPythonArray(wxString filename
, int num
)
465 wxFFile
file(filename
, wxT("rb"));
466 size_t lng
= file
.Length();
468 snum
.Printf(_T("%i"), num
);
469 output
= _T(" xml_res_file_") + snum
+ _T(" = \"\"\"\\\n");
471 unsigned char *buffer
= new unsigned char[lng
];
472 file
.Read(buffer
, lng
);
474 for (size_t i
= 0, linelng
= 0; i
< lng
; i
++)
476 unsigned char c
= buffer
[i
];
482 else if (c
< 32 || c
> 127)
483 tmp
.Printf(_T("\\x%02x"), c
);
491 output
<< _T("\\\n");
494 linelng
+= tmp
.Length();
499 output
+= _T("\"\"\"\n\n");
505 void XmlResApp::MakePackagePython(const wxArrayString
& flist
)
507 wxFFile
file(parOutput
, wxT("wt"));
511 wxPrintf(_T("creating Python source file ") + parOutput
+ _T("...\n"));
515 _T("# This file was automatically generated by wxrc, do not edit by hand.\n")
517 _T("from wxPython.wx import *\n")
518 _T("from wxPython.xrc import *\n\n")
522 file
.Write(_T("def ") + parFuncname
+ _T("():\n"));
524 for (i
= 0; i
< flist
.Count(); i
++)
526 FileToPythonArray(parOutputPath
+ wxFILE_SEP_PATH
+ flist
[i
], i
));
528 for (i
= 0; i
< flist
.Count(); i
++)
531 s
.Printf(_T(" wxXmlResource_Get().LoadFromString(xml_res_file_%i)\n"), i
);
538 void XmlResApp::OutputGettext()
540 wxArrayString str
= FindStrings();
543 if (!parOutput
) fout
.Attach(stdout
);
544 else fout
.Open(parOutput
, wxT("wt"));
546 for (size_t i
= 0; i
< str
.GetCount(); i
++)
547 fout
.Write(_T("_(\"") + str
[i
] + _T("\");\n"));
549 if (!parOutput
) fout
.Detach();
554 wxArrayString
XmlResApp::FindStrings()
556 wxArrayString arr
, a2
;
558 for (size_t i
= 0; i
< parFiles
.Count(); i
++)
561 wxPrintf(_T("processing ") + parFiles
[i
] + _T("...\n"));
564 if (!doc
.Load(parFiles
[i
]))
566 wxLogError(_T("Error parsing file ") + parFiles
[i
]);
570 a2
= FindStrings(doc
.GetRoot());
571 WX_APPEND_ARRAY(arr
, a2
);
579 static wxString
ConvertText(const wxString
& str
)
584 for (dt
= str
.c_str(); *dt
; dt
++)
588 if ( *(++dt
) == wxT('_') )
591 str2
<< wxT('&') << *dt
;
597 case wxT('\n') : str2
<< wxT("\\n"); break;
598 case wxT('\t') : str2
<< wxT("\\t"); break;
599 case wxT('\r') : str2
<< wxT("\\r"); break;
600 case wxT('\\') : if ((*(dt
+1) != 'n') &&
607 case wxT('"') : str2
<< wxT("\\\""); break;
608 default : str2
<< *dt
; break;
617 wxArrayString
XmlResApp::FindStrings(wxXmlNode
*node
)
622 if (n
== NULL
) return arr
;
623 n
= n
->GetChildren();
627 if ((node
->GetType() == wxXML_ELEMENT_NODE
) &&
628 // parent is an element, i.e. has subnodes...
629 (n
->GetType() == wxXML_TEXT_NODE
||
630 n
->GetType() == wxXML_CDATA_SECTION_NODE
) &&
631 // ...it is textnode...
633 node
/*not n!*/->GetName() == _T("label") ||
634 (node
/*not n!*/->GetName() == _T("value") &&
635 !n
->GetContent().IsNumber()) ||
636 node
/*not n!*/->GetName() == _T("help") ||
637 node
/*not n!*/->GetName() == _T("longhelp") ||
638 node
/*not n!*/->GetName() == _T("tooltip") ||
639 node
/*not n!*/->GetName() == _T("htmlcode") ||
640 node
/*not n!*/->GetName() == _T("title") ||
641 node
/*not n!*/->GetName() == _T("item")
643 // ...and known to contain translatable string
645 arr
.Add(ConvertText(n
->GetContent()));
649 if (n
->GetType() == wxXML_ELEMENT_NODE
)
651 wxArrayString a2
= FindStrings(n
);
652 WX_APPEND_ARRAY(arr
, a2
);