Debian Codegraph @

wxcrafter/src/wxrc.cpp

raw
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wxrc.cpp
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik, Eduardo Marques <[email protected]>
5 // Created: 2000/03/05
6 // RCS-ID: $Id$
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 #include "wxrc.h"
12
13 #include "wxc_project_metadata.h"
14
15 #include <wx/arrimpl.cpp>
16
17 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData)
18 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData)
19
20 int wxcXmlResourceCmp::Run(const wxString& inXrcFile, const wxString& outputCppFile, const wxString& functionName)
21 {
22 m_outputCppFile = outputCppFile;
23 m_xrcFile = inXrcFile;
24 m_functionName = functionName;
25 m_retCode = 0;
26 m_outputPath = wxFileName(m_outputCppFile).GetPath();
27 CompileRes();
28 return m_retCode;
29 }
30
31 void wxcXmlResourceCmp::CompileRes()
32 {
33 wxArrayString files = PrepareTempFiles();
34
35 wxRemoveFile(m_outputCppFile);
36
37 if(!m_retCode) {
38 MakePackageCPP(files);
39 }
40 DeleteTempFiles(files);
41 }
42
43 wxString wxcXmlResourceCmp::GetInternalFileName(const wxString& name, const wxArrayString& flist)
44 {
45 wxString name2 = name;
46 name2.Replace(wxT(":"), wxT("_"));
47 name2.Replace(wxT("/"), wxT("_"));
48 name2.Replace(wxT("\\"), wxT("_"));
49 name2.Replace(wxT("*"), wxT("_"));
50 name2.Replace(wxT("?"), wxT("_"));
51
52 wxString s = wxFileNameFromPath(m_outputCppFile) + wxT("$") + name2;
53
54 if(wxFileExists(s) && flist.Index(s) == wxNOT_FOUND) {
55 for(int i = 0;; i++) {
56 s.Printf(wxFileNameFromPath(m_outputCppFile) + wxT("$%03i-") + name2, i);
57 if(!wxFileExists(s) || flist.Index(s) != wxNOT_FOUND)
58 break;
59 }
60 }
61 return s;
62 }
63
64 wxArrayString wxcXmlResourceCmp::PrepareTempFiles()
65 {
66 wxArrayString flist;
67 wxXmlDocument doc;
68
69 if(!doc.Load(m_xrcFile)) {
70 m_retCode = 1;
71 return wxArrayString();
72 }
73
74 wxString name, ext, path;
75 wxFileName::SplitPath(m_xrcFile, &path, &name, &ext);
76 FindFilesInXML(doc.GetRoot(), flist, path);
77 wxString internalName = GetInternalFileName(m_xrcFile, flist);
78
79 doc.Save(m_outputPath + wxFILE_SEP_PATH + internalName);
80 flist.Add(internalName);
81
82 return flist;
83 }
84
85 // Does 'node' contain filename information at all?
86 static bool NodeContainsFilename(wxXmlNode* node)
87 {
88 const wxString name = node->GetName();
89
90 // Any bitmaps (bitmap2 is used for disabled toolbar buttons):
91 if(name == wxT("bitmap") || name == wxT("bitmap2"))
92 return true;
93
94 if(name == wxT("icon"))
95 return true;
96
97 // wxBitmapButton:
98 wxXmlNode* parent = node->GetParent();
99 if(parent != NULL && parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxBitmapButton") &&
100 (name == wxT("focus") || name == wxT("disabled") || name == wxT("hover") || name == wxT("selected")))
101 return true;
102
103 // wxBitmap or wxIcon toplevel resources:
104 if(name == wxT("object")) {
105 wxString klass = node->GetAttribute(wxT("class"), wxEmptyString);
106 if(klass == wxT("wxBitmap") || klass == wxT("wxIcon") || klass == wxT("data"))
107 return true;
108 }
109
110 // URLs in wxHtmlWindow:
111 if(name == wxT("url") && parent != NULL && parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxHtmlWindow")) {
112 // FIXME: this is wrong for e.g. http:// URLs
113 return true;
114 }
115
116 return false;
117 }
118
119 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
120 void wxcXmlResourceCmp::FindFilesInXML(wxXmlNode* node, wxArrayString& flist, const wxString& inputPath)
121 {
122 // Is 'node' XML node element?
123 if(node == NULL)
124 return;
125 if(node->GetType() != wxXML_ELEMENT_NODE)
126 return;
127
128 bool containsFilename = NodeContainsFilename(node);
129
130 wxXmlNode* n = node->GetChildren();
131 while(n) {
132 if(containsFilename && (n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE)) {
133 wxString fullname;
134 if(wxIsAbsolutePath(n->GetContent()) || inputPath.empty())
135 fullname = n->GetContent();
136 else
137 fullname = inputPath + wxFILE_SEP_PATH + n->GetContent();
138
139 wxString filename = GetInternalFileName(n->GetContent(), flist);
140 n->SetContent(filename);
141
142 if(flist.Index(filename) == wxNOT_FOUND)
143 flist.Add(filename);
144
145 wxFileInputStream sin(fullname);
146 wxFileOutputStream sout(m_outputPath + wxFILE_SEP_PATH + filename);
147 sin.Read(sout); // copy the stream
148 }
149
150 // subnodes:
151 if(n->GetType() == wxXML_ELEMENT_NODE)
152 FindFilesInXML(n, flist, inputPath);
153
154 n = n->GetNext();
155 }
156 }
157
158 void wxcXmlResourceCmp::DeleteTempFiles(const wxArrayString& flist)
159 {
160 for(size_t i = 0; i < flist.GetCount(); i++)
161 wxRemoveFile(m_outputPath + wxFILE_SEP_PATH + flist[i]);
162 }
163
164 static wxString FileToCppArray(wxString filename, int num)
165 {
166 wxString output;
167 wxString tmp;
168 wxString snum;
169 wxFFile file(filename, wxT("rb"));
170 wxFileOffset offset = file.Length();
171 wxASSERT_MSG(offset >= 0, wxT("Invalid file length"));
172
173 const size_t lng = wx_truncate_cast(size_t, offset);
174 wxASSERT_MSG(static_cast<wxFileOffset>(lng) == offset, wxT("Huge file not supported"));
175
176 snum.Printf(wxT("%i"), num);
177 output.Printf(wxT("static size_t xml_res_size_") + snum + wxT(" = %lu;\n"), static_cast<unsigned long>(lng));
178 output += wxT("static unsigned char xml_res_file_") + snum + wxT("[] = {\n");
179 // we cannot use string literals because MSVC is dumb wannabe compiler
180 // with arbitrary limitation to 2048 strings :(
181
182 unsigned char* buffer = new unsigned char[lng];
183 file.Read(buffer, lng);
184
185 for(size_t i = 0, linelng = 0; i < lng; i++) {
186 tmp.Printf(wxT("%i"), buffer[i]);
187 if(i != 0)
188 output << wxT(',');
189 if(linelng > 70) {
190 linelng = 0;
191 output << wxT("\n");
192 }
193 output << tmp;
194 linelng += tmp.Length() + 1;
195 }
196
197 delete[] buffer;
198
199 output += wxT("};\n\n");
200
201 return output;
202 }
203
204 void wxcXmlResourceCmp::MakePackageCPP(const wxArrayString& flist)
205 {
206 wxFFile file(m_outputCppFile, wxT("wt"));
207 unsigned i;
208
209 file.Write(""
210 "//\n"
211 "// This file was automatically generated by wxrc, do not edit by hand.\n"
212 "//\n\n"
213 "#include <wx/wxprec.h>\n"
214 "\n"
215 "#ifdef __BORLANDC__\n"
216 " #pragma hdrstop\n"
217 "#endif\n"
218 "\n"
219 ""
220 "#include <wx/filesys.h>\n"
221 "#include <wx/fs_mem.h>\n"
222 "#include <wx/xrc/xmlres.h>\n"
223 "#include <wx/xrc/xh_all.h>\n"
224 "\n"
225 "#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805\n"
226 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
227 " wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)\n"
228 "#else\n"
229 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
230 " wxMemoryFSHandler::AddFile(name, data, size)\n"
231 "#endif\n"
232 "\n");
233
234 for(i = 0; i < flist.GetCount(); i++)
235 file.Write(FileToCppArray(m_outputPath + wxFILE_SEP_PATH + flist[i], i));
236
237 file.Write(""
238 "void " +
239 m_functionName +
240 "()\n"
241 "{\n"
242 "\n"
243 " // Check for memory FS. If not present, load the handler:\n"
244 " {\n"
245 " wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n"
246 " wxFileSystem fsys;\n"
247 " wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n"
248 " wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n"
249 " if (f) delete f;\n");
250 if(wxcProjectMetadata::Get().IsAddHandlers()) {
251 file.Write(" else wxFileSystem::AddHandler(new wxMemoryFSHandlerBase);\n");
252 }
253 file.Write(" }\n\n");
254 for(i = 0; i < flist.GetCount(); i++) {
255 wxString s;
256
257 wxString mime;
258 wxString ext = wxFileName(flist[i]).GetExt();
259 if(ext.Lower() == wxT("xrc"))
260 mime = wxT("text/xml");
261 #if wxUSE_MIMETYPE
262 else {
263 wxFileType* ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
264 if(ft) {
265 ft->GetMimeType(&mime);
266 delete ft;
267 }
268 }
269 #endif // wxUSE_MIMETYPE
270
271 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
272 "\"), xml_res_file_%u, xml_res_size_%u, wxT(\"%s\"));\n",
273 i, i, mime.c_str());
274 file.Write(s);
275 }
276
277 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" + GetInternalFileName(m_xrcFile, flist) +
278 "\"));\n");
279 file.Write("}\n");
280 }
281
282 void wxcXmlResourceCmp::GenCPPHeader()
283 {
284 // Generate the output header in the same directory as the source file.
285 wxFileName headerName(m_outputCppFile);
286 headerName.SetExt(wxcProjectMetadata::Get().GetHeaderFileExt());
287
288 wxFFile file(headerName.GetFullPath(), wxT("wt"));
289 file.Write("//\n"
290 "// This file was automatically generated by wxrc, do not edit by hand.\n"
291 "//\n\n"
292 "#ifndef __" +
293 headerName.GetName() + "_" + headerName.GetExt() +
294 "__\n"
295 "#define __" +
296 headerName.GetName() + "_" + headerName.GetExt() + "__\n");
297 for(size_t i = 0; i < aXRCWndClassData.GetCount(); ++i) {
298 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
299 }
300 file.Write("\nvoid \n" + m_functionName + "();\n#endif\n");
301 }
302
303 static wxString FileToPythonArray(wxString filename, int num)
304 {
305 wxString output;
306 wxString tmp;
307 wxString snum;
308 wxFFile file(filename, wxT("rb"));
309 wxFileOffset offset = file.Length();
310 wxASSERT_MSG(offset >= 0, wxT("Invalid file length"));
311
312 const size_t lng = wx_truncate_cast(size_t, offset);
313 wxASSERT_MSG(static_cast<wxFileOffset>(lng) == offset, wxT("Huge file not supported"));
314
315 snum.Printf(wxT("%i"), num);
316 output = " xml_res_file_" + snum + " = '''\\\n";
317
318 unsigned char* buffer = new unsigned char[lng];
319 file.Read(buffer, lng);
320
321 for(size_t i = 0, linelng = 0; i < lng; i++) {
322 unsigned char c = buffer[i];
323 if(c == '\n') {
324 tmp = (wxChar)c;
325 linelng = 0;
326 } else if(c < 32 || c > 127 || c == '\'')
327 tmp.Printf(wxT("\\x%02x"), c);
328 else if(c == '\\')
329 tmp = wxT("\\\\");
330 else
331 tmp = (wxChar)c;
332 if(linelng > 70) {
333 linelng = 0;
334 output << wxT("\\\n");
335 }
336 output << tmp;
337 linelng += tmp.Length();
338 }
339
340 delete[] buffer;
341
342 output += wxT("'''\n\n");
343
344 return output;
345 }
346
347 void wxcXmlResourceCmp::MakePackagePython(const wxArrayString& flist)
348 {
349 wxFFile file(m_outputCppFile, wxT("wt"));
350 unsigned i;
351
352 file.Write("#\n"
353 "# This file was automatically generated by wxrc, do not edit by hand.\n"
354 "#\n\n"
355 "import wx\n"
356 "import wx.xrc\n\n");
357
358 file.Write("def " + m_functionName + "():\n");
359
360 for(i = 0; i < flist.GetCount(); i++)
361 file.Write(FileToPythonArray(m_outputPath + wxFILE_SEP_PATH + flist[i], i));
362
363 file.Write(" # check if the memory filesystem handler has been loaded yet, and load it if not\n"
364 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
365 " fsys = wx.FileSystem()\n"
366 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
367 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
368 " if f is not None:\n"
369 " f.Destroy()\n"
370 " else:\n"
371 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
372 "\n"
373 " # load all the strings as memory files and load into XmlRes\n");
374
375 for(i = 0; i < flist.GetCount(); i++) {
376 wxString s;
377 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] + "', xml_res_file_%u)\n", i);
378 file.Write(s);
379 }
380 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" + GetInternalFileName(m_xrcFile, flist) +
381 "')\n");
382 file.Write("\n");
383 }
384
385 void wxcXmlResourceCmp::OutputGettext()
386 {
387 ExtractedStrings str = FindStrings();
388
389 wxFFile fout;
390 if(m_outputCppFile.empty())
391 fout.Attach(stdout);
392 else
393 fout.Open(m_outputCppFile, wxT("wt"));
394
395 for(ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i) {
396 const wxFileName filename(i->filename);
397
398 wxString s;
399 s.Printf("#line %d \"%s\"\n", i->lineNo, filename.GetFullPath(wxPATH_UNIX));
400
401 fout.Write(s);
402 fout.Write("_(\"" + i->str + "\");\n");
403 }
404
405 if(!m_outputCppFile)
406 fout.Detach();
407 }
408
409 ExtractedStrings wxcXmlResourceCmp::FindStrings()
410 {
411 ExtractedStrings arr, a2;
412
413 wxXmlDocument doc;
414 if(!doc.Load(m_xrcFile)) {
415 m_retCode = 1;
416 return arr;
417 }
418 a2 = FindStrings(m_xrcFile, doc.GetRoot());
419
420 WX_APPEND_ARRAY(arr, a2);
421 return arr;
422 }
423 #if 0
424 static wxString ConvertText(const wxString& str)
425 {
426 wxString str2;
427 const wxChar *dt;
428
429 for (dt = str.c_str(); *dt; dt++) {
430 if (*dt == wxT('_')) {
431 if ( *(dt+1) == 0 )
432 str2 << wxT('_');
433 else if ( *(++dt) == wxT('_') )
434 str2 << wxT('_');
435 else
436 str2 << wxT('&') << *dt;
437 } else {
438 switch (*dt) {
439 case wxT('\n') :
440 str2 << wxT("\\n");
441 break;
442 case wxT('\t') :
443 str2 << wxT("\\t");
444 break;
445 case wxT('\r') :
446 str2 << wxT("\\r");
447 break;
448 case wxT('\\') :
449 if ((*(dt+1) != 'n') &&
450 (*(dt+1) != 't') &&
451 (*(dt+1) != 'r'))
452 str2 << wxT("\\\\");
453 else
454 str2 << wxT("\\");
455 break;
456 case wxT('"') :
457 str2 << wxT("\\\"");
458 break;
459 default :
460 str2 << *dt;
461 break;
462 }
463 }
464 }
465
466 return str2;
467 }
468 #endif
469
470 ExtractedStrings wxcXmlResourceCmp::FindStrings(const wxString& filename, wxXmlNode* node)
471 {
472 ExtractedStrings arr;
473
474 wxXmlNode* n = node;
475 if(n == NULL)
476 return arr;
477 n = n->GetChildren();
478
479 while(n) {
480 if((node->GetType() == wxXML_ELEMENT_NODE) &&
481 // parent is an element, i.e. has subnodes...
482 (n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE) &&
483 // ...it is textnode...
484 (node /*not n!*/->GetName() == wxT("label") ||
485 (node /*not n!*/->GetName() == wxT("value") && !n->GetContent().IsNumber()) ||
486 node /*not n!*/->GetName() == wxT("help") || node /*not n!*/->GetName() == wxT("longhelp") ||
487 node /*not n!*/->GetName() == wxT("tooltip") || node /*not n!*/->GetName() == wxT("htmlcode") ||
488 node /*not n!*/->GetName() == wxT("title") || node /*not n!*/->GetName() == wxT("item")))
489 // ...and known to contain translatable string
490 // subnodes:
491 if(n->GetType() == wxXML_ELEMENT_NODE) {
492 ExtractedStrings a2 = FindStrings(filename, n);
493 WX_APPEND_ARRAY(arr, a2);
494 }
495
496 n = n->GetNext();
497 }
498 return arr;
499 }