]> git.saurik.com Git - wxWidgets.git/blob - utils/wxrc/wxrc.cpp
Bring osx class naming into line with the other ports.
[wxWidgets.git] / utils / wxrc / wxrc.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: wxrc.cpp
3 // Purpose: XML resource compiler
4 // Author: Vaclav Slavik, Eduardo Marques <edrdo@netcabo.pt>
5 // Created: 2000/03/05
6 // RCS-ID: $Id$
7 // Copyright: (c) 2000 Vaclav Slavik
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx/wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 // for all others, include the necessary headers
19 #ifndef WX_PRECOMP
20 #include "wx/app.h"
21 #include "wx/log.h"
22 #include "wx/wxcrtvararg.h"
23 #endif
24
25 #include "wx/cmdline.h"
26 #include "wx/xml/xml.h"
27 #include "wx/ffile.h"
28 #include "wx/filename.h"
29 #include "wx/wfstream.h"
30 #include "wx/utils.h"
31 #include "wx/hashset.h"
32 #include "wx/mimetype.h"
33 #include "wx/vector.h"
34
35 WX_DECLARE_HASH_SET(wxString, wxStringHash, wxStringEqual, StringSet);
36
37 class XRCWidgetData
38 {
39 public:
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; }
44 private:
45 wxString m_class;
46 wxString m_name;
47 };
48
49 #include "wx/arrimpl.cpp"
50 WX_DECLARE_OBJARRAY(XRCWidgetData,ArrayOfXRCWidgetData);
51 WX_DEFINE_OBJARRAY(ArrayOfXRCWidgetData)
52
53 class XRCWndClassData
54 {
55 private:
56 wxString m_className;
57 wxString m_parentClassName;
58 StringSet m_ancestorClassNames;
59 ArrayOfXRCWidgetData m_wdata;
60
61 void BrowseXmlNode(wxXmlNode* node)
62 {
63 wxString classValue;
64 wxString nameValue;
65 wxXmlNode* children;
66 while (node)
67 {
68 if (node->GetName() == wxT("object")
69 && node->GetAttribute(wxT("class"),&classValue)
70 && node->GetAttribute(wxT("name"),&nameValue))
71 {
72 m_wdata.Add(XRCWidgetData(nameValue,classValue));
73 }
74 children = node->GetChildren();
75 if (children)
76 BrowseXmlNode(children);
77 node = node->GetNext();
78 }
79 }
80
81 public:
82 XRCWndClassData(const wxString& className,
83 const wxString& parentClassName,
84 const wxXmlNode* node) :
85 m_className(className) , m_parentClassName(parentClassName)
86 {
87 if ( className == wxT("wxMenu") )
88 {
89 m_ancestorClassNames.insert(wxT("wxMenu"));
90 m_ancestorClassNames.insert(wxT("wxMenuBar"));
91 }
92 else if ( className == wxT("wxMDIChildFrame") )
93 {
94 m_ancestorClassNames.insert(wxT("wxMDIParentFrame"));
95 }
96 else if( className == wxT("wxMenuBar") ||
97 className == wxT("wxStatusBar") ||
98 className == wxT("wxToolBar") )
99 {
100 m_ancestorClassNames.insert(wxT("wxFrame"));
101 }
102 else
103 {
104 m_ancestorClassNames.insert(wxT("wxWindow"));
105 }
106
107 BrowseXmlNode(node->GetChildren());
108 }
109
110 const ArrayOfXRCWidgetData& GetWidgetData()
111 {
112 return m_wdata;
113 }
114
115 bool CanBeUsedWithXRCCTRL(const wxString& name)
116 {
117 if (name == wxT("tool") ||
118 name == wxT("data") ||
119 name == wxT("unknown") ||
120 name == wxT("notebookpage") ||
121 name == wxT("separator") ||
122 name == wxT("sizeritem") ||
123 name == wxT("wxMenu") ||
124 name == wxT("wxMenuBar") ||
125 name == wxT("wxMenuItem") ||
126 name.EndsWith(wxT("Sizer")) )
127 {
128 return false;
129 }
130 return true;
131 }
132
133 void GenerateHeaderCode(wxFFile& file)
134 {
135
136 file.Write(wxT("class ") + m_className + wxT(" : public ") + m_parentClassName
137 + wxT(" {\nprotected:\n"));
138 size_t i;
139 for(i=0;i<m_wdata.GetCount();++i)
140 {
141 const XRCWidgetData& w = m_wdata.Item(i);
142 if( !CanBeUsedWithXRCCTRL(w.GetClass()) ) continue;
143 if( w.GetName().empty() ) continue;
144 file.Write(
145 wxT(" ") + w.GetClass() + wxT("* ") + w.GetName()
146 + wxT(";\n"));
147 }
148 file.Write(wxT("\nprivate:\n void InitWidgetsFromXRC(wxWindow *parent){\n")
149 wxT(" wxXmlResource::Get()->LoadObject(this,parent,wxT(\"")
150 + m_className
151 + wxT("\"), wxT(\"")
152 + m_parentClassName
153 + wxT("\"));\n"));
154 for(i=0;i<m_wdata.GetCount();++i)
155 {
156 const XRCWidgetData& w = m_wdata.Item(i);
157 if( !CanBeUsedWithXRCCTRL(w.GetClass()) ) continue;
158 if( w.GetName().empty() ) continue;
159 file.Write( wxT(" ")
160 + w.GetName()
161 + wxT(" = XRCCTRL(*this,\"")
162 + w.GetName()
163 + wxT("\",")
164 + w.GetClass()
165 + wxT(");\n"));
166 }
167 file.Write(wxT(" }\n"));
168
169 file.Write( wxT("public:\n"));
170
171 if ( m_ancestorClassNames.size() == 1 )
172 {
173 file.Write
174 (
175 m_className +
176 wxT("(") +
177 *m_ancestorClassNames.begin() +
178 wxT(" *parent=NULL){\n") +
179 wxT(" InitWidgetsFromXRC((wxWindow *)parent);\n")
180 wxT(" }\n")
181 wxT("};\n")
182 );
183 }
184 else
185 {
186 file.Write(m_className + wxT("(){\n") +
187 wxT(" InitWidgetsFromXRC(NULL);\n")
188 wxT(" }\n")
189 wxT("};\n"));
190
191 for ( StringSet::const_iterator it = m_ancestorClassNames.begin();
192 it != m_ancestorClassNames.end();
193 ++it )
194 {
195 file.Write(m_className + wxT("(") + *it + wxT(" *parent){\n") +
196 wxT(" InitWidgetsFromXRC((wxWindow *)parent);\n")
197 wxT(" }\n")
198 wxT("};\n"));
199 }
200 }
201 }
202 };
203 WX_DECLARE_OBJARRAY(XRCWndClassData,ArrayOfXRCWndClassData);
204 WX_DEFINE_OBJARRAY(ArrayOfXRCWndClassData)
205
206 struct ExtractedString
207 {
208 ExtractedString() : lineNo(-1) {}
209 ExtractedString(const wxString& str_,
210 const wxString& filename_, int lineNo_)
211 : str(str_), filename(filename_), lineNo(lineNo_)
212 {}
213
214 wxString str;
215
216 wxString filename;
217 int lineNo;
218 };
219
220 typedef wxVector<ExtractedString> ExtractedStrings;
221
222
223 class XmlResApp : public wxAppConsole
224 {
225 public:
226 // don't use builtin cmd line parsing:
227 virtual bool OnInit() { return true; }
228 virtual int OnRun();
229
230 private:
231 void ParseParams(const wxCmdLineParser& cmdline);
232 void CompileRes();
233 wxArrayString PrepareTempFiles();
234 void FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath);
235
236 wxString GetInternalFileName(const wxString& name, const wxArrayString& flist);
237 void DeleteTempFiles(const wxArrayString& flist);
238 void MakePackageZIP(const wxArrayString& flist);
239 void MakePackageCPP(const wxArrayString& flist);
240 void MakePackagePython(const wxArrayString& flist);
241
242 void OutputGettext();
243 ExtractedStrings FindStrings();
244 ExtractedStrings FindStrings(const wxString& filename, wxXmlNode *node);
245
246 bool flagVerbose, flagCPP, flagPython, flagGettext;
247 wxString parOutput, parFuncname, parOutputPath;
248 wxArrayString parFiles;
249 int retCode;
250
251 ArrayOfXRCWndClassData aXRCWndClassData;
252 bool flagH;
253 void GenCPPHeader();
254 };
255
256 IMPLEMENT_APP_CONSOLE(XmlResApp)
257
258 int XmlResApp::OnRun()
259 {
260 static const wxCmdLineEntryDesc cmdLineDesc[] =
261 {
262 { wxCMD_LINE_SWITCH, "h", "help", "show help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
263 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
264 { wxCMD_LINE_SWITCH, "e", "extra-cpp-code", "output C++ header file with XRC derived classes" },
265 { wxCMD_LINE_SWITCH, "c", "cpp-code", "output C++ source rather than .rsc file" },
266 { wxCMD_LINE_SWITCH, "p", "python-code", "output wxPython source rather than .rsc file" },
267 { wxCMD_LINE_SWITCH, "g", "gettext", "output list of translatable strings (to stdout or file if -o used)" },
268 { wxCMD_LINE_OPTION, "n", "function", "C++/Python function name (with -c or -p) [InitXmlResource]" },
269 { wxCMD_LINE_OPTION, "o", "output", "output file [resource.xrs/cpp]" },
270 #if 0 // not yet implemented
271 { wxCMD_LINE_OPTION, "l", "list-of-handlers", "output list of necessary handlers to this file" },
272 #endif
273 { wxCMD_LINE_PARAM, NULL, NULL, "input file(s)",
274 wxCMD_LINE_VAL_STRING,
275 wxCMD_LINE_PARAM_MULTIPLE | wxCMD_LINE_OPTION_MANDATORY },
276
277 wxCMD_LINE_DESC_END
278 };
279
280 wxCmdLineParser parser(cmdLineDesc, argc, argv);
281
282 switch (parser.Parse())
283 {
284 case -1:
285 return 0;
286
287 case 0:
288 retCode = 0;
289 ParseParams(parser);
290 if (flagGettext)
291 OutputGettext();
292 else
293 CompileRes();
294 return retCode;
295 }
296 return 1;
297 }
298
299
300
301
302 void XmlResApp::ParseParams(const wxCmdLineParser& cmdline)
303 {
304 flagGettext = cmdline.Found("g");
305 flagVerbose = cmdline.Found("v");
306 flagCPP = cmdline.Found("c");
307 flagPython = cmdline.Found("p");
308 flagH = flagCPP && cmdline.Found("e");
309
310
311 if (!cmdline.Found("o", &parOutput))
312 {
313 if (flagGettext)
314 parOutput = wxEmptyString;
315 else
316 {
317 if (flagCPP)
318 parOutput = wxT("resource.cpp");
319 else if (flagPython)
320 parOutput = wxT("resource.py");
321 else
322 parOutput = wxT("resource.xrs");
323 }
324 }
325 if (!parOutput.empty())
326 {
327 wxFileName fn(parOutput);
328 fn.Normalize();
329 parOutput = fn.GetFullPath();
330 parOutputPath = wxPathOnly(parOutput);
331 }
332 if (!parOutputPath) parOutputPath = wxT(".");
333
334 if (!cmdline.Found("n", &parFuncname))
335 parFuncname = wxT("InitXmlResource");
336
337 for (size_t i = 0; i < cmdline.GetParamCount(); i++)
338 {
339 #ifdef __WINDOWS__
340 wxString fn=wxFindFirstFile(cmdline.GetParam(i), wxFILE);
341 while (!fn.empty())
342 {
343 parFiles.Add(fn);
344 fn=wxFindNextFile();
345 }
346 #else
347 parFiles.Add(cmdline.GetParam(i));
348 #endif
349 }
350 }
351
352
353
354
355 void XmlResApp::CompileRes()
356 {
357 wxArrayString files = PrepareTempFiles();
358
359 wxRemoveFile(parOutput);
360
361 if (!retCode)
362 {
363 if (flagCPP){
364 MakePackageCPP(files);
365 if (flagH)
366 GenCPPHeader();
367 }
368 else if (flagPython)
369 MakePackagePython(files);
370 else
371 MakePackageZIP(files);
372 }
373
374 DeleteTempFiles(files);
375 }
376
377
378 wxString XmlResApp::GetInternalFileName(const wxString& name, const wxArrayString& flist)
379 {
380 wxString name2 = name;
381 name2.Replace(wxT(":"), wxT("_"));
382 name2.Replace(wxT("/"), wxT("_"));
383 name2.Replace(wxT("\\"), wxT("_"));
384 name2.Replace(wxT("*"), wxT("_"));
385 name2.Replace(wxT("?"), wxT("_"));
386
387 wxString s = wxFileNameFromPath(parOutput) + wxT("$") + name2;
388
389 if (wxFileExists(s) && flist.Index(s) == wxNOT_FOUND)
390 {
391 for (int i = 0;; i++)
392 {
393 s.Printf(wxFileNameFromPath(parOutput) + wxT("$%03i-") + name2, i);
394 if (!wxFileExists(s) || flist.Index(s) != wxNOT_FOUND)
395 break;
396 }
397 }
398 return s;
399 }
400
401 wxArrayString XmlResApp::PrepareTempFiles()
402 {
403 wxArrayString flist;
404
405 for (size_t i = 0; i < parFiles.GetCount(); i++)
406 {
407 if (flagVerbose)
408 wxPrintf(wxT("processing ") + parFiles[i] + wxT("...\n"));
409
410 wxXmlDocument doc;
411
412 if (!doc.Load(parFiles[i]))
413 {
414 wxLogError(wxT("Error parsing file ") + parFiles[i]);
415 retCode = 1;
416 continue;
417 }
418
419 wxString name, ext, path;
420 wxFileName::SplitPath(parFiles[i], &path, &name, &ext);
421
422 FindFilesInXML(doc.GetRoot(), flist, path);
423 if (flagH)
424 {
425 wxXmlNode* node = (doc.GetRoot())->GetChildren();
426 wxString classValue,nameValue;
427 while(node){
428 if(node->GetName() == wxT("object")
429 && node->GetAttribute(wxT("class"),&classValue)
430 && node->GetAttribute(wxT("name"),&nameValue)){
431
432 aXRCWndClassData.Add(
433 XRCWndClassData(nameValue,classValue,node)
434 );
435 }
436 node = node -> GetNext();
437 }
438 }
439 wxString internalName = GetInternalFileName(parFiles[i], flist);
440
441 doc.Save(parOutputPath + wxFILE_SEP_PATH + internalName);
442 flist.Add(internalName);
443 }
444
445 return flist;
446 }
447
448
449 // Does 'node' contain filename information at all?
450 static bool NodeContainsFilename(wxXmlNode *node)
451 {
452 const wxString name = node->GetName();
453
454 // Any bitmaps (bitmap2 is used for disabled toolbar buttons):
455 if ( name == wxT("bitmap") || name == wxT("bitmap2") )
456 return true;
457
458 if ( name == wxT("icon") )
459 return true;
460
461 // wxBitmapButton:
462 wxXmlNode *parent = node->GetParent();
463 if (parent != NULL &&
464 parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxBitmapButton") &&
465 (name == wxT("focus") ||
466 name == wxT("disabled") ||
467 name == wxT("hover") ||
468 name == wxT("selected")))
469 return true;
470
471 // wxBitmap or wxIcon toplevel resources:
472 if ( name == wxT("object") )
473 {
474 wxString klass = node->GetAttribute(wxT("class"), wxEmptyString);
475 if (klass == wxT("wxBitmap") ||
476 klass == wxT("wxIcon") ||
477 klass == wxT("data") )
478 return true;
479 }
480
481 // URLs in wxHtmlWindow:
482 if ( name == wxT("url") &&
483 parent != NULL &&
484 parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxHtmlWindow") )
485 {
486 // FIXME: this is wrong for e.g. http:// URLs
487 return true;
488 }
489
490 return false;
491 }
492
493 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
494 void XmlResApp::FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath)
495 {
496 // Is 'node' XML node element?
497 if (node == NULL) return;
498 if (node->GetType() != wxXML_ELEMENT_NODE) return;
499
500 bool containsFilename = NodeContainsFilename(node);
501
502 wxXmlNode *n = node->GetChildren();
503 while (n)
504 {
505 if (containsFilename &&
506 (n->GetType() == wxXML_TEXT_NODE ||
507 n->GetType() == wxXML_CDATA_SECTION_NODE))
508 {
509 wxString fullname;
510 if (wxIsAbsolutePath(n->GetContent()) || inputPath.empty())
511 fullname = n->GetContent();
512 else
513 fullname = inputPath + wxFILE_SEP_PATH + n->GetContent();
514
515 if (flagVerbose)
516 wxPrintf(wxT("adding ") + fullname + wxT("...\n"));
517
518 wxString filename = GetInternalFileName(n->GetContent(), flist);
519 n->SetContent(filename);
520
521 if (flist.Index(filename) == wxNOT_FOUND)
522 flist.Add(filename);
523
524 wxFileInputStream sin(fullname);
525 wxFileOutputStream sout(parOutputPath + wxFILE_SEP_PATH + filename);
526 sin.Read(sout); // copy the stream
527 }
528
529 // subnodes:
530 if (n->GetType() == wxXML_ELEMENT_NODE)
531 FindFilesInXML(n, flist, inputPath);
532
533 n = n->GetNext();
534 }
535 }
536
537
538
539 void XmlResApp::DeleteTempFiles(const wxArrayString& flist)
540 {
541 for (size_t i = 0; i < flist.GetCount(); i++)
542 wxRemoveFile(parOutputPath + wxFILE_SEP_PATH + flist[i]);
543 }
544
545
546
547 void XmlResApp::MakePackageZIP(const wxArrayString& flist)
548 {
549 wxString files;
550
551 for (size_t i = 0; i < flist.GetCount(); i++)
552 files += flist[i] + wxT(" ");
553 files.RemoveLast();
554
555 if (flagVerbose)
556 wxPrintf(wxT("compressing ") + parOutput + wxT("...\n"));
557
558 wxString cwd = wxGetCwd();
559 wxSetWorkingDirectory(parOutputPath);
560 int execres = wxExecute(wxT("zip -9 -j ") +
561 wxString(flagVerbose ? wxT("\"") : wxT("-q \"")) +
562 parOutput + wxT("\" ") + files, true);
563 wxSetWorkingDirectory(cwd);
564 if (execres == -1)
565 {
566 wxLogError(wxT("Unable to execute zip program. Make sure it is in the path."));
567 wxLogError(wxT("You can download it at http://www.cdrom.com/pub/infozip/"));
568 retCode = 1;
569 return;
570 }
571 }
572
573
574
575 static wxString FileToCppArray(wxString filename, int num)
576 {
577 wxString output;
578 wxString tmp;
579 wxString snum;
580 wxFFile file(filename, wxT("rb"));
581 wxFileOffset offset = file.Length();
582 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
583
584 const size_t lng = wx_truncate_cast(size_t, offset);
585 wxASSERT_MSG( static_cast<wxFileOffset>(lng) == offset,
586 wxT("Huge file not supported") );
587
588 snum.Printf(wxT("%i"), num);
589 output.Printf(wxT("static size_t xml_res_size_") + snum + wxT(" = %lu;\n"),
590 static_cast<unsigned long>(lng));
591 output += wxT("static unsigned char xml_res_file_") + snum + wxT("[] = {\n");
592 // we cannot use string literals because MSVC is dumb wannabe compiler
593 // with arbitrary limitation to 2048 strings :(
594
595 unsigned char *buffer = new unsigned char[lng];
596 file.Read(buffer, lng);
597
598 for (size_t i = 0, linelng = 0; i < lng; i++)
599 {
600 tmp.Printf(wxT("%i"), buffer[i]);
601 if (i != 0) output << wxT(',');
602 if (linelng > 70)
603 {
604 linelng = 0;
605 output << wxT("\n");
606 }
607 output << tmp;
608 linelng += tmp.Length()+1;
609 }
610
611 delete[] buffer;
612
613 output += wxT("};\n\n");
614
615 return output;
616 }
617
618
619 void XmlResApp::MakePackageCPP(const wxArrayString& flist)
620 {
621 wxFFile file(parOutput, wxT("wt"));
622 unsigned i;
623
624 if (flagVerbose)
625 wxPrintf(wxT("creating C++ source file ") + parOutput + wxT("...\n"));
626
627 file.Write(""
628 "//\n"
629 "// This file was automatically generated by wxrc, do not edit by hand.\n"
630 "//\n\n"
631 "#include <wx/wxprec.h>\n"
632 "\n"
633 "#ifdef __BORLANDC__\n"
634 " #pragma hdrstop\n"
635 "#endif\n"
636 "\n"
637 ""
638 "#include <wx/filesys.h>\n"
639 "#include <wx/fs_mem.h>\n"
640 "#include <wx/xrc/xmlres.h>\n"
641 "#include <wx/xrc/xh_all.h>\n"
642 "\n"
643 "#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805\n"
644 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
645 " wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)\n"
646 "#else\n"
647 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
648 " wxMemoryFSHandler::AddFile(name, data, size)\n"
649 "#endif\n"
650 "\n");
651
652 for (i = 0; i < flist.GetCount(); i++)
653 file.Write(
654 FileToCppArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
655
656 file.Write(""
657 "void " + parFuncname + "()\n"
658 "{\n"
659 "\n"
660 " // Check for memory FS. If not present, load the handler:\n"
661 " {\n"
662 " wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n"
663 " wxFileSystem fsys;\n"
664 " wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n"
665 " wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n"
666 " if (f) delete f;\n"
667 " else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n"
668 " }\n"
669 "\n");
670
671 for (i = 0; i < flist.GetCount(); i++)
672 {
673 wxString s;
674
675 wxString mime;
676 wxString ext = wxFileName(flist[i]).GetExt();
677 if ( ext.Lower() == wxT("xrc") )
678 mime = wxT("text/xml");
679 #if wxUSE_MIMETYPE
680 else
681 {
682 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
683 if ( ft )
684 {
685 ft->GetMimeType(&mime);
686 delete ft;
687 }
688 }
689 #endif // wxUSE_MIMETYPE
690
691 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
692 "\"), xml_res_file_%u, xml_res_size_%u, wxT(\"%s\"));\n",
693 i, i, mime.c_str());
694 file.Write(s);
695 }
696
697 for (i = 0; i < parFiles.GetCount(); i++)
698 {
699 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" +
700 GetInternalFileName(parFiles[i], flist) + "\"));\n");
701 }
702
703 file.Write("}\n");
704
705
706 }
707
708 void XmlResApp::GenCPPHeader()
709 {
710 // Generate the output header in the same directory as the source file.
711 wxFileName headerName(parOutput);
712 headerName.SetExt("h");
713
714 wxFFile file(headerName.GetFullPath(), wxT("wt"));
715 file.Write(
716 "//\n"
717 "// This file was automatically generated by wxrc, do not edit by hand.\n"
718 "//\n\n"
719 "#ifndef __" + headerName.GetName() + "_h__\n"
720 "#define __" + headerName.GetName() + "_h__\n"
721 );
722 for(size_t i=0;i<aXRCWndClassData.GetCount();++i){
723 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
724 }
725 file.Write(
726 "\nvoid \n"
727 + parFuncname
728 + "();\n#endif\n");
729 }
730
731 static wxString FileToPythonArray(wxString filename, int num)
732 {
733 wxString output;
734 wxString tmp;
735 wxString snum;
736 wxFFile file(filename, wxT("rb"));
737 wxFileOffset offset = file.Length();
738 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
739
740 const size_t lng = wx_truncate_cast(size_t, offset);
741 wxASSERT_MSG( static_cast<wxFileOffset>(lng) == offset,
742 wxT("Huge file not supported") );
743
744 snum.Printf(wxT("%i"), num);
745 output = " xml_res_file_" + snum + " = '''\\\n";
746
747 unsigned char *buffer = new unsigned char[lng];
748 file.Read(buffer, lng);
749
750 for (size_t i = 0, linelng = 0; i < lng; i++)
751 {
752 unsigned char c = buffer[i];
753 if (c == '\n')
754 {
755 tmp = (wxChar)c;
756 linelng = 0;
757 }
758 else if (c < 32 || c > 127 || c == '\'')
759 tmp.Printf(wxT("\\x%02x"), c);
760 else if (c == '\\')
761 tmp = wxT("\\\\");
762 else
763 tmp = (wxChar)c;
764 if (linelng > 70)
765 {
766 linelng = 0;
767 output << wxT("\\\n");
768 }
769 output << tmp;
770 linelng += tmp.Length();
771 }
772
773 delete[] buffer;
774
775 output += wxT("'''\n\n");
776
777 return output;
778 }
779
780
781 void XmlResApp::MakePackagePython(const wxArrayString& flist)
782 {
783 wxFFile file(parOutput, wxT("wt"));
784 unsigned i;
785
786 if (flagVerbose)
787 wxPrintf(wxT("creating Python source file ") + parOutput + wxT("...\n"));
788
789 file.Write(
790 "#\n"
791 "# This file was automatically generated by wxrc, do not edit by hand.\n"
792 "#\n\n"
793 "import wx\n"
794 "import wx.xrc\n\n"
795 );
796
797
798 file.Write("def " + parFuncname + "():\n");
799
800 for (i = 0; i < flist.GetCount(); i++)
801 file.Write(
802 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
803
804 file.Write(
805 " # check if the memory filesystem handler has been loaded yet, and load it if not\n"
806 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
807 " fsys = wx.FileSystem()\n"
808 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
809 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
810 " if f is not None:\n"
811 " f.Destroy()\n"
812 " else:\n"
813 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
814 "\n"
815 " # load all the strings as memory files and load into XmlRes\n"
816 );
817
818
819 for (i = 0; i < flist.GetCount(); i++)
820 {
821 wxString s;
822 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] +
823 "', xml_res_file_%u)\n", i);
824 file.Write(s);
825 }
826 for (i = 0; i < parFiles.GetCount(); i++)
827 {
828 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" +
829 GetInternalFileName(parFiles[i], flist) + "')\n");
830 }
831
832 file.Write("\n");
833 }
834
835
836
837 void XmlResApp::OutputGettext()
838 {
839 ExtractedStrings str = FindStrings();
840
841 wxFFile fout;
842 if (parOutput.empty())
843 fout.Attach(stdout);
844 else
845 fout.Open(parOutput, wxT("wt"));
846
847 for (ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i)
848 {
849 const wxFileName filename(i->filename);
850
851 wxString s;
852 s.Printf("#line %d \"%s\"\n",
853 i->lineNo, filename.GetFullPath(wxPATH_UNIX));
854
855 fout.Write(s);
856 fout.Write("_(\"" + i->str + "\");\n");
857 }
858
859 if (!parOutput) fout.Detach();
860 }
861
862
863
864 ExtractedStrings XmlResApp::FindStrings()
865 {
866 ExtractedStrings arr, a2;
867
868 for (size_t i = 0; i < parFiles.GetCount(); i++)
869 {
870 if (flagVerbose)
871 wxPrintf(wxT("processing ") + parFiles[i] + wxT("...\n"));
872
873 wxXmlDocument doc;
874 if (!doc.Load(parFiles[i]))
875 {
876 wxLogError(wxT("Error parsing file ") + parFiles[i]);
877 retCode = 1;
878 continue;
879 }
880 a2 = FindStrings(parFiles[i], doc.GetRoot());
881
882 WX_APPEND_ARRAY(arr, a2);
883 }
884
885 return arr;
886 }
887
888
889
890 static wxString ConvertText(const wxString& str)
891 {
892 wxString str2;
893 const wxChar *dt;
894
895 for (dt = str.c_str(); *dt; dt++)
896 {
897 if (*dt == wxT('_'))
898 {
899 if ( *(++dt) == wxT('_') )
900 str2 << wxT('_');
901 else
902 str2 << wxT('&') << *dt;
903 }
904 else
905 {
906 switch (*dt)
907 {
908 case wxT('\n') : str2 << wxT("\\n"); break;
909 case wxT('\t') : str2 << wxT("\\t"); break;
910 case wxT('\r') : str2 << wxT("\\r"); break;
911 case wxT('\\') : if ((*(dt+1) != 'n') &&
912 (*(dt+1) != 't') &&
913 (*(dt+1) != 'r'))
914 str2 << wxT("\\\\");
915 else
916 str2 << wxT("\\");
917 break;
918 case wxT('"') : str2 << wxT("\\\""); break;
919 default : str2 << *dt; break;
920 }
921 }
922 }
923
924 return str2;
925 }
926
927
928 ExtractedStrings
929 XmlResApp::FindStrings(const wxString& filename, wxXmlNode *node)
930 {
931 ExtractedStrings arr;
932
933 wxXmlNode *n = node;
934 if (n == NULL) return arr;
935 n = n->GetChildren();
936
937 while (n)
938 {
939 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
940 // parent is an element, i.e. has subnodes...
941 (n->GetType() == wxXML_TEXT_NODE ||
942 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
943 // ...it is textnode...
944 (
945 node/*not n!*/->GetName() == wxT("label") ||
946 (node/*not n!*/->GetName() == wxT("value") &&
947 !n->GetContent().IsNumber()) ||
948 node/*not n!*/->GetName() == wxT("help") ||
949 node/*not n!*/->GetName() == wxT("longhelp") ||
950 node/*not n!*/->GetName() == wxT("tooltip") ||
951 node/*not n!*/->GetName() == wxT("htmlcode") ||
952 node/*not n!*/->GetName() == wxT("title") ||
953 node/*not n!*/->GetName() == wxT("item")
954 ))
955 // ...and known to contain translatable string
956 {
957 if (!flagGettext ||
958 node->GetAttribute(wxT("translate"), wxT("1")) != wxT("0"))
959 {
960 arr.push_back
961 (
962 ExtractedString
963 (
964 ConvertText(n->GetContent()),
965 filename,
966 n->GetLineNumber()
967 )
968 );
969 }
970 }
971
972 // subnodes:
973 if (n->GetType() == wxXML_ELEMENT_NODE)
974 {
975 ExtractedStrings a2 = FindStrings(filename, n);
976 WX_APPEND_ARRAY(arr, a2);
977 }
978
979 n = n->GetNext();
980 }
981 return arr;
982 }