]> git.saurik.com Git - wxWidgets.git/blob - utils/wxrc/wxrc.cpp
using scan-line polygon conversion for constructing wxregion
[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 if ( wxFileExists(parOutput) )
360 wxRemoveFile(parOutput);
361
362 if (!retCode)
363 {
364 if (flagCPP){
365 MakePackageCPP(files);
366 if (flagH)
367 GenCPPHeader();
368 }
369 else if (flagPython)
370 MakePackagePython(files);
371 else
372 MakePackageZIP(files);
373 }
374
375 DeleteTempFiles(files);
376 }
377
378
379 wxString XmlResApp::GetInternalFileName(const wxString& name, const wxArrayString& flist)
380 {
381 wxString name2 = name;
382 name2.Replace(wxT(":"), wxT("_"));
383 name2.Replace(wxT("/"), wxT("_"));
384 name2.Replace(wxT("\\"), wxT("_"));
385 name2.Replace(wxT("*"), wxT("_"));
386 name2.Replace(wxT("?"), wxT("_"));
387
388 wxString s = wxFileNameFromPath(parOutput) + wxT("$") + name2;
389
390 if (wxFileExists(s) && flist.Index(s) == wxNOT_FOUND)
391 {
392 for (int i = 0;; i++)
393 {
394 s.Printf(wxFileNameFromPath(parOutput) + wxT("$%03i-") + name2, i);
395 if (!wxFileExists(s) || flist.Index(s) != wxNOT_FOUND)
396 break;
397 }
398 }
399 return s;
400 }
401
402 wxArrayString XmlResApp::PrepareTempFiles()
403 {
404 wxArrayString flist;
405
406 for (size_t i = 0; i < parFiles.GetCount(); i++)
407 {
408 if (flagVerbose)
409 wxPrintf(wxT("processing ") + parFiles[i] + wxT("...\n"));
410
411 wxXmlDocument doc;
412
413 if (!doc.Load(parFiles[i]))
414 {
415 wxLogError(wxT("Error parsing file ") + parFiles[i]);
416 retCode = 1;
417 continue;
418 }
419
420 wxString name, ext, path;
421 wxFileName::SplitPath(parFiles[i], &path, &name, &ext);
422
423 FindFilesInXML(doc.GetRoot(), flist, path);
424 if (flagH)
425 {
426 wxXmlNode* node = (doc.GetRoot())->GetChildren();
427 wxString classValue,nameValue;
428 while(node){
429 if(node->GetName() == wxT("object")
430 && node->GetAttribute(wxT("class"),&classValue)
431 && node->GetAttribute(wxT("name"),&nameValue)){
432
433 aXRCWndClassData.Add(
434 XRCWndClassData(nameValue,classValue,node)
435 );
436 }
437 node = node -> GetNext();
438 }
439 }
440 wxString internalName = GetInternalFileName(parFiles[i], flist);
441
442 doc.Save(parOutputPath + wxFILE_SEP_PATH + internalName);
443 flist.Add(internalName);
444 }
445
446 return flist;
447 }
448
449
450 // Does 'node' contain filename information at all?
451 static bool NodeContainsFilename(wxXmlNode *node)
452 {
453 const wxString name = node->GetName();
454
455 // Any bitmaps (bitmap2 is used for disabled toolbar buttons):
456 if ( name == wxT("bitmap") || name == wxT("bitmap2") )
457 return true;
458
459 if ( name == wxT("icon") )
460 return true;
461
462 // wxBitmapButton:
463 wxXmlNode *parent = node->GetParent();
464 if (parent != NULL &&
465 parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxBitmapButton") &&
466 (name == wxT("focus") ||
467 name == wxT("disabled") ||
468 name == wxT("hover") ||
469 name == wxT("selected")))
470 return true;
471
472 // wxBitmap or wxIcon toplevel resources:
473 if ( name == wxT("object") )
474 {
475 wxString klass = node->GetAttribute(wxT("class"), wxEmptyString);
476 if (klass == wxT("wxBitmap") ||
477 klass == wxT("wxIcon") ||
478 klass == wxT("data") )
479 return true;
480 }
481
482 // URLs in wxHtmlWindow:
483 if ( name == wxT("url") &&
484 parent != NULL &&
485 parent->GetAttribute(wxT("class"), wxT("")) == wxT("wxHtmlWindow") )
486 {
487 // FIXME: this is wrong for e.g. http:// URLs
488 return true;
489 }
490
491 return false;
492 }
493
494 // find all files mentioned in structure, e.g. <bitmap>filename</bitmap>
495 void XmlResApp::FindFilesInXML(wxXmlNode *node, wxArrayString& flist, const wxString& inputPath)
496 {
497 // Is 'node' XML node element?
498 if (node == NULL) return;
499 if (node->GetType() != wxXML_ELEMENT_NODE) return;
500
501 bool containsFilename = NodeContainsFilename(node);
502
503 wxXmlNode *n = node->GetChildren();
504 while (n)
505 {
506 if (containsFilename &&
507 (n->GetType() == wxXML_TEXT_NODE ||
508 n->GetType() == wxXML_CDATA_SECTION_NODE))
509 {
510 wxString fullname;
511 if (wxIsAbsolutePath(n->GetContent()) || inputPath.empty())
512 fullname = n->GetContent();
513 else
514 fullname = inputPath + wxFILE_SEP_PATH + n->GetContent();
515
516 if (flagVerbose)
517 wxPrintf(wxT("adding ") + fullname + wxT("...\n"));
518
519 wxString filename = GetInternalFileName(n->GetContent(), flist);
520 n->SetContent(filename);
521
522 if (flist.Index(filename) == wxNOT_FOUND)
523 flist.Add(filename);
524
525 wxFileInputStream sin(fullname);
526 wxFileOutputStream sout(parOutputPath + wxFILE_SEP_PATH + filename);
527 sin.Read(sout); // copy the stream
528 }
529
530 // subnodes:
531 if (n->GetType() == wxXML_ELEMENT_NODE)
532 FindFilesInXML(n, flist, inputPath);
533
534 n = n->GetNext();
535 }
536 }
537
538
539
540 void XmlResApp::DeleteTempFiles(const wxArrayString& flist)
541 {
542 for (size_t i = 0; i < flist.GetCount(); i++)
543 wxRemoveFile(parOutputPath + wxFILE_SEP_PATH + flist[i]);
544 }
545
546
547
548 void XmlResApp::MakePackageZIP(const wxArrayString& flist)
549 {
550 wxString files;
551
552 for (size_t i = 0; i < flist.GetCount(); i++)
553 files += flist[i] + wxT(" ");
554 files.RemoveLast();
555
556 if (flagVerbose)
557 wxPrintf(wxT("compressing ") + parOutput + wxT("...\n"));
558
559 wxString cwd = wxGetCwd();
560 wxSetWorkingDirectory(parOutputPath);
561 int execres = wxExecute(wxT("zip -9 -j ") +
562 wxString(flagVerbose ? wxT("\"") : wxT("-q \"")) +
563 parOutput + wxT("\" ") + files, true);
564 wxSetWorkingDirectory(cwd);
565 if (execres == -1)
566 {
567 wxLogError(wxT("Unable to execute zip program. Make sure it is in the path."));
568 wxLogError(wxT("You can download it at http://www.cdrom.com/pub/infozip/"));
569 retCode = 1;
570 return;
571 }
572 }
573
574
575
576 static wxString FileToCppArray(wxString filename, int num)
577 {
578 wxString output;
579 wxString tmp;
580 wxString snum;
581 wxFFile file(filename, wxT("rb"));
582 wxFileOffset offset = file.Length();
583 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
584
585 const size_t lng = wx_truncate_cast(size_t, offset);
586 wxASSERT_MSG( static_cast<wxFileOffset>(lng) == offset,
587 wxT("Huge file not supported") );
588
589 snum.Printf(wxT("%i"), num);
590 output.Printf(wxT("static size_t xml_res_size_") + snum + wxT(" = %lu;\n"),
591 static_cast<unsigned long>(lng));
592 output += wxT("static unsigned char xml_res_file_") + snum + wxT("[] = {\n");
593 // we cannot use string literals because MSVC is dumb wannabe compiler
594 // with arbitrary limitation to 2048 strings :(
595
596 unsigned char *buffer = new unsigned char[lng];
597 file.Read(buffer, lng);
598
599 for (size_t i = 0, linelng = 0; i < lng; i++)
600 {
601 tmp.Printf(wxT("%i"), buffer[i]);
602 if (i != 0) output << wxT(',');
603 if (linelng > 70)
604 {
605 linelng = 0;
606 output << wxT("\n");
607 }
608 output << tmp;
609 linelng += tmp.Length()+1;
610 }
611
612 delete[] buffer;
613
614 output += wxT("};\n\n");
615
616 return output;
617 }
618
619
620 void XmlResApp::MakePackageCPP(const wxArrayString& flist)
621 {
622 wxFFile file(parOutput, wxT("wt"));
623 unsigned i;
624
625 if (flagVerbose)
626 wxPrintf(wxT("creating C++ source file ") + parOutput + wxT("...\n"));
627
628 file.Write(""
629 "//\n"
630 "// This file was automatically generated by wxrc, do not edit by hand.\n"
631 "//\n\n"
632 "#include <wx/wxprec.h>\n"
633 "\n"
634 "#ifdef __BORLANDC__\n"
635 " #pragma hdrstop\n"
636 "#endif\n"
637 "\n"
638 ""
639 "#include <wx/filesys.h>\n"
640 "#include <wx/fs_mem.h>\n"
641 "#include <wx/xrc/xmlres.h>\n"
642 "#include <wx/xrc/xh_all.h>\n"
643 "\n"
644 "#if wxCHECK_VERSION(2,8,5) && wxABI_VERSION >= 20805\n"
645 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
646 " wxMemoryFSHandler::AddFileWithMimeType(name, data, size, mime)\n"
647 "#else\n"
648 " #define XRC_ADD_FILE(name, data, size, mime) \\\n"
649 " wxMemoryFSHandler::AddFile(name, data, size)\n"
650 "#endif\n"
651 "\n");
652
653 for (i = 0; i < flist.GetCount(); i++)
654 file.Write(
655 FileToCppArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
656
657 file.Write(""
658 "void " + parFuncname + "()\n"
659 "{\n"
660 "\n"
661 " // Check for memory FS. If not present, load the handler:\n"
662 " {\n"
663 " wxMemoryFSHandler::AddFile(wxT(\"XRC_resource/dummy_file\"), wxT(\"dummy one\"));\n"
664 " wxFileSystem fsys;\n"
665 " wxFSFile *f = fsys.OpenFile(wxT(\"memory:XRC_resource/dummy_file\"));\n"
666 " wxMemoryFSHandler::RemoveFile(wxT(\"XRC_resource/dummy_file\"));\n"
667 " if (f) delete f;\n"
668 " else wxFileSystem::AddHandler(new wxMemoryFSHandler);\n"
669 " }\n"
670 "\n");
671
672 for (i = 0; i < flist.GetCount(); i++)
673 {
674 wxString s;
675
676 wxString mime;
677 wxString ext = wxFileName(flist[i]).GetExt();
678 if ( ext.Lower() == wxT("xrc") )
679 mime = wxT("text/xml");
680 #if wxUSE_MIMETYPE
681 else
682 {
683 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
684 if ( ft )
685 {
686 ft->GetMimeType(&mime);
687 delete ft;
688 }
689 }
690 #endif // wxUSE_MIMETYPE
691
692 s.Printf(" XRC_ADD_FILE(wxT(\"XRC_resource/" + flist[i] +
693 "\"), xml_res_file_%u, xml_res_size_%u, wxT(\"%s\"));\n",
694 i, i, mime.c_str());
695 file.Write(s);
696 }
697
698 for (i = 0; i < parFiles.GetCount(); i++)
699 {
700 file.Write(" wxXmlResource::Get()->Load(wxT(\"memory:XRC_resource/" +
701 GetInternalFileName(parFiles[i], flist) + "\"));\n");
702 }
703
704 file.Write("}\n");
705
706
707 }
708
709 void XmlResApp::GenCPPHeader()
710 {
711 // Generate the output header in the same directory as the source file.
712 wxFileName headerName(parOutput);
713 headerName.SetExt("h");
714
715 wxFFile file(headerName.GetFullPath(), wxT("wt"));
716 file.Write(
717 "//\n"
718 "// This file was automatically generated by wxrc, do not edit by hand.\n"
719 "//\n\n"
720 "#ifndef __" + headerName.GetName() + "_h__\n"
721 "#define __" + headerName.GetName() + "_h__\n"
722 );
723 for(size_t i=0;i<aXRCWndClassData.GetCount();++i){
724 aXRCWndClassData.Item(i).GenerateHeaderCode(file);
725 }
726 file.Write(
727 "\nvoid \n"
728 + parFuncname
729 + "();\n#endif\n");
730 }
731
732 static wxString FileToPythonArray(wxString filename, int num)
733 {
734 wxString output;
735 wxString tmp;
736 wxString snum;
737 wxFFile file(filename, wxT("rb"));
738 wxFileOffset offset = file.Length();
739 wxASSERT_MSG( offset >= 0 , wxT("Invalid file length") );
740
741 const size_t lng = wx_truncate_cast(size_t, offset);
742 wxASSERT_MSG( static_cast<wxFileOffset>(lng) == offset,
743 wxT("Huge file not supported") );
744
745 snum.Printf(wxT("%i"), num);
746 output = " xml_res_file_" + snum + " = '''\\\n";
747
748 unsigned char *buffer = new unsigned char[lng];
749 file.Read(buffer, lng);
750
751 for (size_t i = 0, linelng = 0; i < lng; i++)
752 {
753 unsigned char c = buffer[i];
754 if (c == '\n')
755 {
756 tmp = (wxChar)c;
757 linelng = 0;
758 }
759 else if (c < 32 || c > 127 || c == '\'')
760 tmp.Printf(wxT("\\x%02x"), c);
761 else if (c == '\\')
762 tmp = wxT("\\\\");
763 else
764 tmp = (wxChar)c;
765 if (linelng > 70)
766 {
767 linelng = 0;
768 output << wxT("\\\n");
769 }
770 output << tmp;
771 linelng += tmp.Length();
772 }
773
774 delete[] buffer;
775
776 output += wxT("'''\n\n");
777
778 return output;
779 }
780
781
782 void XmlResApp::MakePackagePython(const wxArrayString& flist)
783 {
784 wxFFile file(parOutput, wxT("wt"));
785 unsigned i;
786
787 if (flagVerbose)
788 wxPrintf(wxT("creating Python source file ") + parOutput + wxT("...\n"));
789
790 file.Write(
791 "#\n"
792 "# This file was automatically generated by wxrc, do not edit by hand.\n"
793 "#\n\n"
794 "import wx\n"
795 "import wx.xrc\n\n"
796 );
797
798
799 file.Write("def " + parFuncname + "():\n");
800
801 for (i = 0; i < flist.GetCount(); i++)
802 file.Write(
803 FileToPythonArray(parOutputPath + wxFILE_SEP_PATH + flist[i], i));
804
805 file.Write(
806 " # check if the memory filesystem handler has been loaded yet, and load it if not\n"
807 " wx.MemoryFSHandler.AddFile('XRC_resource/dummy_file', 'dummy value')\n"
808 " fsys = wx.FileSystem()\n"
809 " f = fsys.OpenFile('memory:XRC_resource/dummy_file')\n"
810 " wx.MemoryFSHandler.RemoveFile('XRC_resource/dummy_file')\n"
811 " if f is not None:\n"
812 " f.Destroy()\n"
813 " else:\n"
814 " wx.FileSystem.AddHandler(wx.MemoryFSHandler())\n"
815 "\n"
816 " # load all the strings as memory files and load into XmlRes\n"
817 );
818
819
820 for (i = 0; i < flist.GetCount(); i++)
821 {
822 wxString s;
823 s.Printf(" wx.MemoryFSHandler.AddFile('XRC_resource/" + flist[i] +
824 "', xml_res_file_%u)\n", i);
825 file.Write(s);
826 }
827 for (i = 0; i < parFiles.GetCount(); i++)
828 {
829 file.Write(" wx.xrc.XmlResource.Get().Load('memory:XRC_resource/" +
830 GetInternalFileName(parFiles[i], flist) + "')\n");
831 }
832
833 file.Write("\n");
834 }
835
836
837
838 void XmlResApp::OutputGettext()
839 {
840 ExtractedStrings str = FindStrings();
841
842 wxFFile fout;
843 if (parOutput.empty())
844 fout.Attach(stdout);
845 else
846 fout.Open(parOutput, wxT("wt"));
847
848 for (ExtractedStrings::const_iterator i = str.begin(); i != str.end(); ++i)
849 {
850 const wxFileName filename(i->filename);
851
852 wxString s;
853 s.Printf("#line %d \"%s\"\n",
854 i->lineNo, filename.GetFullPath(wxPATH_UNIX));
855
856 fout.Write(s);
857 fout.Write("_(\"" + i->str + "\");\n");
858 }
859
860 if (!parOutput) fout.Detach();
861 }
862
863
864
865 ExtractedStrings XmlResApp::FindStrings()
866 {
867 ExtractedStrings arr, a2;
868
869 for (size_t i = 0; i < parFiles.GetCount(); i++)
870 {
871 if (flagVerbose)
872 wxPrintf(wxT("processing ") + parFiles[i] + wxT("...\n"));
873
874 wxXmlDocument doc;
875 if (!doc.Load(parFiles[i]))
876 {
877 wxLogError(wxT("Error parsing file ") + parFiles[i]);
878 retCode = 1;
879 continue;
880 }
881 a2 = FindStrings(parFiles[i], doc.GetRoot());
882
883 WX_APPEND_ARRAY(arr, a2);
884 }
885
886 return arr;
887 }
888
889
890
891 static wxString ConvertText(const wxString& str)
892 {
893 wxString str2;
894 const wxChar *dt;
895
896 for (dt = str.c_str(); *dt; dt++)
897 {
898 if (*dt == wxT('_'))
899 {
900 if ( *(dt+1) == 0 )
901 str2 << wxT('_');
902 else if ( *(++dt) == wxT('_') )
903 str2 << wxT('_');
904 else
905 str2 << wxT('&') << *dt;
906 }
907 else
908 {
909 switch (*dt)
910 {
911 case wxT('\n') : str2 << wxT("\\n"); break;
912 case wxT('\t') : str2 << wxT("\\t"); break;
913 case wxT('\r') : str2 << wxT("\\r"); break;
914 case wxT('\\') : if ((*(dt+1) != 'n') &&
915 (*(dt+1) != 't') &&
916 (*(dt+1) != 'r'))
917 str2 << wxT("\\\\");
918 else
919 str2 << wxT("\\");
920 break;
921 case wxT('"') : str2 << wxT("\\\""); break;
922 default : str2 << *dt; break;
923 }
924 }
925 }
926
927 return str2;
928 }
929
930
931 ExtractedStrings
932 XmlResApp::FindStrings(const wxString& filename, wxXmlNode *node)
933 {
934 ExtractedStrings arr;
935
936 wxXmlNode *n = node;
937 if (n == NULL) return arr;
938 n = n->GetChildren();
939
940 while (n)
941 {
942 if ((node->GetType() == wxXML_ELEMENT_NODE) &&
943 // parent is an element, i.e. has subnodes...
944 (n->GetType() == wxXML_TEXT_NODE ||
945 n->GetType() == wxXML_CDATA_SECTION_NODE) &&
946 // ...it is textnode...
947 (
948 node/*not n!*/->GetName() == wxT("label") ||
949 (node/*not n!*/->GetName() == wxT("value") &&
950 !n->GetContent().IsNumber()) ||
951 node/*not n!*/->GetName() == wxT("help") ||
952 node/*not n!*/->GetName() == wxT("longhelp") ||
953 node/*not n!*/->GetName() == wxT("tooltip") ||
954 node/*not n!*/->GetName() == wxT("htmlcode") ||
955 node/*not n!*/->GetName() == wxT("title") ||
956 node/*not n!*/->GetName() == wxT("item") ||
957 node/*not n!*/->GetName() == wxT("message") ||
958 node/*not n!*/->GetName() == wxT("note") ||
959 node/*not n!*/->GetName() == wxT("defaultdirectory") ||
960 node/*not n!*/->GetName() == wxT("defaultfilename") ||
961 node/*not n!*/->GetName() == wxT("defaultfolder") ||
962 node/*not n!*/->GetName() == wxT("filter") ||
963 node/*not n!*/->GetName() == wxT("caption")
964 ))
965 // ...and known to contain translatable string
966 {
967 if (!flagGettext ||
968 node->GetAttribute(wxT("translate"), wxT("1")) != wxT("0"))
969 {
970 arr.push_back
971 (
972 ExtractedString
973 (
974 ConvertText(n->GetContent()),
975 filename,
976 n->GetLineNumber()
977 )
978 );
979 }
980 }
981
982 // subnodes:
983 if (n->GetType() == wxXML_ELEMENT_NODE)
984 {
985 ExtractedStrings a2 = FindStrings(filename, n);
986 WX_APPEND_ARRAY(arr, a2);
987 }
988
989 n = n->GetNext();
990 }
991 return arr;
992 }