xrc.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: xrc.h
  3. // Purpose: topic overview
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /**
  8. @page overview_xrc XML Based Resource System (XRC)
  9. @tableofcontents
  10. The XML-based resource system, known as XRC, allows user interface elements
  11. such as dialogs, menu bars and toolbars, to be stored in text files and loaded
  12. into the application at run-time. XRC files can also be compiled into binary
  13. XRS files or C++ code (the former makes it possible to store all resources in a
  14. single file and the latter is useful when you want to embed the resources into
  15. the executable).
  16. There are several advantages to using XRC resources:
  17. @li Recompiling and linking an application is not necessary if the resources
  18. change.
  19. @li If you use a dialog designer that generates C++ code, it can be hard to
  20. reintegrate this into existing C++ code. Separation of resources and code
  21. is a more elegant solution.
  22. @li You can choose between different alternative resource files at run time, if
  23. necessary.
  24. @li The XRC format uses sizers for flexibility, allowing dialogs to be
  25. resizable and highly portable.
  26. @li The XRC format is a wxWidgets standard, and can be generated or
  27. postprocessed by any program that understands it. As it is based on the XML
  28. standard, existing XML editors can be used for simple editing purposes.
  29. XRC was written by Vaclav Slavik.
  30. @see wxXmlResource, wxXmlResourceHandler, @ref overview_xrcformat
  31. @section overview_xrc_gettingstarted Getting Started with XRC
  32. <b> Creating an XRC file </b>
  33. You will need to write an XRC file. Though this @e can be done by hand in a
  34. text editor, for all but the smallest files it is advisable to use a
  35. specialised tool. Examples of these include:
  36. @e Non-free:
  37. @li wxDesigner <http://www.wxdesigner-software.de/>, a commercial dialog
  38. designer/RAD tool.
  39. @li DialogBlocks <http://www.anthemion.co.uk/dialogblocks/>, a commercial
  40. dialog editor.
  41. @e Free:
  42. @li XRCed <http://xrced.sf.net/>, a wxPython-based dialog editor that you
  43. can find in the wxPython/tools subdirectory of the wxWidgets SVN archive.
  44. @li wxFormBuilder <http://wxformbuilder.org/>, a C++-based dialog editor that
  45. can output C++, XRC or python.
  46. There's a more complete list at <http://www.wxwidgets.org/wiki/index.php/Tools>
  47. This small demonstration XRC file contains a simple dialog:
  48. @code
  49. <?xml version="1.0" ?>
  50. <resource version="2.3.0.1">
  51. <object class="wxDialog" name="SimpleDialog">
  52. <title>Simple dialog</title>
  53. <object class="wxBoxSizer">
  54. <orient>wxVERTICAL</orient>
  55. <object class="sizeritem">
  56. <object class="wxTextCtrl" name="text"/>
  57. <option>1</option>
  58. <flag>wxALL|wxEXPAND</flag>
  59. <border>10</border>
  60. </object>
  61. <object class="sizeritem">
  62. <object class="wxBoxSizer">
  63. <object class="sizeritem">
  64. <object class="wxButton" name="clickme_btn">
  65. <label>Click</label>
  66. </object>
  67. <flag>wxRIGHT</flag>
  68. <border>10</border>
  69. </object>
  70. <object class="sizeritem">
  71. <object class="wxButton" name="wxID_OK">
  72. <label>OK</label>
  73. </object>
  74. <flag>wxLEFT</flag>
  75. <border>10</border>
  76. </object>
  77. <orient>wxHORIZONTAL</orient>
  78. </object>
  79. <flag>wxALL|wxALIGN_CENTRE</flag>
  80. <border>10</border>
  81. </object>
  82. </object>
  83. </object>
  84. </resource>
  85. @endcode
  86. You can keep all your XRC elements together in one file, or split them between
  87. several.
  88. <b> Loading XRC files </b>
  89. Before you can use XRC in an app, it must first be loaded. This code fragment
  90. shows how to load a single XRC file "resource.xrc" from the current working
  91. directory, plus all the *.xrc files contained in the subdirectory "rc".
  92. @code
  93. #include "wx/xrc/xmlres.h"
  94. bool MyApp::OnInit()
  95. {
  96. ...
  97. wxXmlResource::Get()->InitAllHandlers();
  98. wxXmlResource::Get()->Load("resource.xrc");
  99. wxXmlResource::Get()->LoadAllFiles("rc");
  100. ...
  101. }
  102. @endcode
  103. It's normal to load any XRC files at the beginning of an app. Though it is
  104. possible to unload a file later, it's seldom necessary.
  105. <b> Using an XRC item </b>
  106. The XRC file(s) are now loaded into the app's virtual filesystem. From there,
  107. you must do another sort of load when you want to use an individual object.
  108. Yes, it's confusingly named, but you first Load() the file, and later load each
  109. top-level object when its needed.
  110. This is how you would use the above simple dialog in your code.
  111. @code
  112. void MyClass::ShowDialog()
  113. {
  114. wxDialog dlg;
  115. if (wxXmlResource::Get()->LoadDialog(&dlg, NULL, "SimpleDialog"))
  116. dlg.ShowModal();
  117. }
  118. @endcode
  119. See how simple the code is. All the instantiation is done invisibly by the XRC
  120. system.
  121. Though you'll most often use wxXmlResource::LoadDialog, there are also
  122. equivalents that load a frame, a menu etc; and the generic
  123. wxXmlResource::LoadObject. See wxXmlResource for more details.
  124. <b> Accessing XRC child controls </b>
  125. The last section showed how to load top-level windows like dialogs, but what
  126. about child windows like the wxTextCtrl named "text" that the dialog contains?
  127. You can't 'load' an individual child control in the same way. Instead you use
  128. the XRCCTRL macro to get a pointer to the child. To expand the previous code:
  129. @code
  130. void MyClass::ShowDialog()
  131. {
  132. wxDialog dlg;
  133. if (!wxXmlResource::Get()->LoadDialog(&dlg, NULL, "SimpleDialog"))
  134. return;
  135. wxTextCtrl* pText = XRCCTRL(dlg, "text", wxTextCtrl);
  136. if (pText)
  137. pText->ChangeValue("This is a simple dialog");
  138. dlg.ShowModal();
  139. }
  140. @endcode
  141. XRCCTRL takes a reference to the parent container and uses wxWindow::FindWindow
  142. to search inside it for a wxWindow with the supplied name (here "text"). It
  143. returns a pointer to that control, cast to the type in the third parameter; so
  144. a similar effect could be obtained by writing:
  145. @code
  146. pText = (wxTextCtrl*)(dlg.FindWindowByName("text"));
  147. @endcode
  148. <b> XRC and IDs </b>
  149. The ID of a control is often needed, e.g. for use in an event table
  150. or with wxEvtHandler::Bind. It can easily be found by passing the name of the
  151. control to the XRCID macro:
  152. @code
  153. void MyClass::ShowDialog()
  154. {
  155. wxDialog dlg;
  156. if (!wxXmlResource::Get()->LoadDialog(&dlg, NULL, "SimpleDialog"))
  157. return;
  158. XRCCTRL(dlg, "text", wxTextCtrl)->Bind(wxEVT_COMMAND_TEXT_UPDATED,
  159. wxTextEventHandler(MyClass::OnTextEntered), this, XRCID("text"));
  160. XRCCTRL(dlg, "clickme_btn", wxButton)->Bind(wxEVT_COMMAND_BUTTON_CLICKED,
  161. wxCommandEventHandler(MyClass::OnClickme), this, XRCID("clickme_btn"));
  162. dlg.ShowModal();
  163. }
  164. @endcode
  165. A few points to note:
  166. @li The value of the int returned by XRCID("foo") is guaranteed to be unique
  167. within an app.
  168. @li However that value isn't predictable, and you shouldn't rely on it being
  169. consistent between runs. It certainly won't be the same in different apps.
  170. @li @ref page_stockitems such as wxID_OK work correctly without requiring XRCID
  171. (because, internally, XRCID("wxID_OK") is mapped to wxID_OK).
  172. @li Both XRCID and XRCCTRL use the 'name' of the control (as in
  173. wxWindow::GetName). This is different from the label that the user sees on
  174. e.g. a wxButton.
  175. <b> Subclassing in XRC </b>
  176. You will often want to use subclassed wx controls in your code. There are three
  177. ways to do this from XRC:
  178. @li Very rarely you might need to
  179. @ref overview_xrcformat_extending_custom "create your own wxXmlResourceHandler"
  180. @li Occasionally wxXmlResource::AttachUnknownControl may be best. See
  181. @ref overview_xrcformat_extending_unknown
  182. @li Usually though, the simple 'subclass' keyword will suffice.
  183. Suppose you wanted the wxTextCtrl named "text" to be created as your derived
  184. class MyTextCtrl. The only change needed in the XRC file would be in this line:
  185. @code
  186. <object class="wxTextCtrl" name="text" subclass="MyTextCtrl"/>
  187. @endcode
  188. The only change in your code would be to use MyTextCtrl in XRCCTRL. However for
  189. the subclass to be created successfully, it's important to ensure that it uses
  190. wxWidget's RTTI mechanism: see @ref overview_xrcformat_extending_subclass for
  191. the details.
  192. @section overview_xrc_xrcsample The XRC sample
  193. A major resource for learning how to use XRC is the @sample{xrc}. This
  194. demonstrates all of the standard uses of XRC, and some of the less common ones.
  195. It is strongly suggested that you run it, and look at the well-commented
  196. source code to see how it works.
  197. @section overview_xrc_binaryresourcefiles Binary Resource Files
  198. To compile binary resource files, use the command-line @c wxrc utility. It
  199. takes one or more file parameters (the input XRC files) and the following
  200. switches and options:
  201. @li -h (--help): Show a help message.
  202. @li -v (--verbose): Show verbose logging information.
  203. @li -c (--cpp-code): Write C++ source rather than a XRS file.
  204. @li -e (--extra-cpp-code): If used together with -c, generates C++ header file
  205. containing class definitions for the windows defined by the XRC file (see
  206. special subsection).
  207. @li -u (--uncompressed): Do not compress XML files (C++ only).
  208. @li -g (--gettext): Output underscore-wrapped strings that poEdit or gettext
  209. can scan. Outputs to stdout, or a file if -o is used.
  210. @li -n (--function) @<name@>: Specify C++ function name (use with -c).
  211. @li -o (--output) @<filename@>: Specify the output file, such as resource.xrs
  212. or resource.cpp.
  213. @li -l (--list-of-handlers) @<filename@>: Output a list of necessary handlers
  214. to this file.
  215. For example:
  216. @code
  217. $ wxrc resource.xrc
  218. $ wxrc resource.xrc -o resource.xrs
  219. $ wxrc resource.xrc -v -c -o resource.cpp
  220. @endcode
  221. @note XRS file is essentially a renamed ZIP archive which means that you can
  222. manipulate it with standard ZIP tools. Note that if you are using XRS files,
  223. you have to initialize the wxFileSystem archive handler first! It is a simple
  224. thing to do:
  225. @code
  226. #include <wx/filesys.h>
  227. #include <wx/fs_arc.h>
  228. ...
  229. wxFileSystem::AddHandler(new wxArchiveFSHandler);
  230. @endcode
  231. @section overview_xrc_embeddedresource Using Embedded Resources
  232. It is sometimes useful to embed resources in the executable itself instead of
  233. loading an external file (e.g. when your app is small and consists only of one
  234. exe file). XRC provides means to convert resources into regular C++ file that
  235. can be compiled and included in the executable.
  236. Use the @c -c switch to @c wxrc utility to produce C++ file with embedded
  237. resources. This file will contain a function called @c InitXmlResource (unless
  238. you override this with a command line switch). Use it to load the resource:
  239. @code
  240. extern void InitXmlResource(); // defined in generated file
  241. ...
  242. wxXmlResource::Get()->InitAllHandlers();
  243. InitXmlResource();
  244. ...
  245. @endcode
  246. @section overview_xrc_cppheader C++ header file generation
  247. Using the @c -e switch together with @c -c, a C++ header file is written
  248. containing class definitions for the GUI windows defined in the XRC file. This
  249. code generation can make it easier to use XRC and automate program development.
  250. The classes can be used as basis for development, freeing the programmer from
  251. dealing with most of the XRC specifics (e.g. @c XRCCTRL).
  252. For each top level window defined in the XRC file a C++ class definition is
  253. generated, containing as class members the named widgets of the window. A
  254. default constructor for each class is also generated. Inside the constructor
  255. all XRC loading is done and all class members representing widgets are
  256. initialized.
  257. A simple example will help understand how the scheme works. Suppose you have a
  258. XRC file defining a top level window @c TestWnd_Base, which subclasses wxFrame
  259. (any other class like @c wxDialog will do also), and has subwidgets wxTextCtrl A
  260. and wxButton B.
  261. The XRC file and corresponding class definition in the header file will be
  262. something like:
  263. @code
  264. <?xml version="1.0"?>
  265. <resource version="2.3.0.1">
  266. <object class="wxFrame" name="TestWnd_Base">
  267. <size>-1,-1</size>
  268. <title>Test</title>
  269. <object class="wxBoxSizer">
  270. <orient>wxHORIZONTAL</orient>
  271. <object class="sizeritem">
  272. <object class="wxTextCtrl" name="A">
  273. <label>Test label</label>
  274. </object>
  275. </object>
  276. <object class="sizeritem">
  277. <object class="wxButton" name="B">
  278. <label>Test button</label>
  279. </object>
  280. </object>
  281. </object>
  282. </object>
  283. </resource>
  284. class TestWnd_Base : public wxFrame
  285. {
  286. protected:
  287. wxTextCtrl* A;
  288. wxButton* B;
  289. private:
  290. void InitWidgetsFromXRC()
  291. {
  292. wxXmlResource::Get()->LoadObject(this, NULL, "TestWnd", "wxFrame");
  293. A = XRCCTRL(*this, "A", wxTextCtrl);
  294. B = XRCCTRL(*this, "B", wxButton);
  295. }
  296. public:
  297. TestWnd::TestWnd()
  298. {
  299. InitWidgetsFromXRC();
  300. }
  301. };
  302. @endcode
  303. The generated window class can be used as basis for the full window class. The
  304. class members which represent widgets may be accessed by name instead of using
  305. @c XRCCTRL every time you wish to reference them (note that they are
  306. @c protected class members), though you must still use @c XRCID to refer to
  307. widget IDs in the event table.
  308. Example:
  309. @code
  310. #include "resource.h"
  311. class TestWnd : public TestWnd_Base
  312. {
  313. public:
  314. TestWnd()
  315. {
  316. // A, B already initialised at this point
  317. A->SetValue("Updated in TestWnd::TestWnd");
  318. B->SetValue("Nice :)");
  319. }
  320. void OnBPressed(wxEvent& event)
  321. {
  322. Close();
  323. }
  324. DECLARE_EVENT_TABLE();
  325. };
  326. BEGIN_EVENT_TABLE(TestWnd,TestWnd_Base)
  327. EVT_BUTTON(XRCID("B"), TestWnd::OnBPressed)
  328. END_EVENT_TABLE()
  329. @endcode
  330. It is also possible to access the wxSizerItem of a sizer that is part of a
  331. resource. This can be done using @c XRCSIZERITEM as shown.
  332. The resource file can have something like this for a sizer item.
  333. @code
  334. <object class="spacer" name="area">
  335. <size>400, 300</size>
  336. </object>
  337. @endcode
  338. The code can then access the sizer item by using @c XRCSIZERITEM and @c XRCID
  339. together.
  340. @code
  341. wxSizerItem* item = XRCSIZERITEM(*this, "area");
  342. @endcode
  343. @section overview_xrc_newresourcehandlers Adding New Resource Handlers
  344. Adding a new resource handler is pretty easy.
  345. Typically, to add an handler for the @c MyControl class, you'll want to create
  346. the @c xh_mycontrol.h and @c xh_mycontrol.cpp files.
  347. The header needs to contains the @c MyControlXmlHandler class definition:
  348. @code
  349. class MyControlXmlHandler : public wxXmlResourceHandler
  350. {
  351. public:
  352. // Constructor.
  353. MyControlXmlHandler();
  354. // Creates the control and returns a pointer to it.
  355. virtual wxObject *DoCreateResource();
  356. // Returns true if we know how to create a control for the given node.
  357. virtual bool CanHandle(wxXmlNode *node);
  358. // Register with wxWidgets' dynamic class subsystem.
  359. DECLARE_DYNAMIC_CLASS(MyControlXmlHandler)
  360. };
  361. @endcode
  362. The implementation of your custom XML handler will typically look as:
  363. @code
  364. // Register with wxWidgets' dynamic class subsystem.
  365. IMPLEMENT_DYNAMIC_CLASS(MyControlXmlHandler, wxXmlResourceHandler)
  366. MyControlXmlHandler::MyControlXmlHandler()
  367. {
  368. // this call adds support for all wxWidgets class styles
  369. // (e.g. wxBORDER_SIMPLE, wxBORDER_SUNKEN, wxWS_EX_* etc etc)
  370. AddWindowStyles();
  371. // if MyControl class supports e.g. MYCONTROL_DEFAULT_STYLE
  372. // you should use:
  373. // XRC_ADD_STYLE(MYCONTROL_DEFAULT_STYLE);
  374. }
  375. wxObject *MyControlXmlHandler::DoCreateResource()
  376. {
  377. // the following macro will init a pointer named "control"
  378. // with a new instance of the MyControl class, but will NOT
  379. // Create() it!
  380. XRC_MAKE_INSTANCE(control, MyControl)
  381. // this is the point where you'll typically need to do the most
  382. // important changes: here the control is created and initialized.
  383. // You'll want to use the wxXmlResourceHandler's getters to
  384. // do most of your work.
  385. // If e.g. the MyControl::Create function looks like:
  386. //
  387. // bool MyControl::Create(wxWindow *parent, int id,
  388. // const wxBitmap &first, const wxPoint &posFirst,
  389. // const wxBitmap &second, const wxPoint &posSecond,
  390. // const wxString &theTitle, const wxFont &titleFont,
  391. // const wxPoint &pos, const wxSize &size,
  392. // long style = MYCONTROL_DEFAULT_STYLE,
  393. // const wxString &name = wxT("MyControl"));
  394. //
  395. // Then the XRC for your component should look like:
  396. //
  397. // <object class="MyControl" name="some_name">
  398. // <first-bitmap>first.xpm</first-bitmap>
  399. // <second-bitmap>text.xpm</second-bitmap>
  400. // <first-pos>3,3</first-pos>
  401. // <second-pos>4,4</second-pos>
  402. // <the-title>a title</the-title>
  403. // <title-font>
  404. // <!-- Standard XRC tags for a font: <size>, <style>, <weight>, etc -->
  405. // </title-font>
  406. // <!-- XRC also accepts other usual tags for wxWindow-derived classes:
  407. // like e.g. <name>, <style>, <size>, <position>, etc -->
  408. // </object>
  409. //
  410. // And the code to read your custom tags from the XRC file is just:
  411. control->Create(m_parentAsWindow, GetID(),
  412. GetBitmap(wxT("first-bitmap")),
  413. GetPosition(wxT("first-pos")),
  414. GetBitmap(wxT("second-bitmap")),
  415. GetPosition(wxT("second-pos")),
  416. GetText(wxT("the-title")),
  417. GetFont(wxT("title-font")),
  418. GetPosition(), GetSize(), GetStyle(), GetName());
  419. SetupWindow(control);
  420. return control;
  421. }
  422. bool MyControlXmlHandler::CanHandle(wxXmlNode *node)
  423. {
  424. // this function tells XRC system that this handler can parse
  425. // the <object class="MyControl"> tags
  426. return IsOfClass(node, wxT("MyControl"));
  427. }
  428. @endcode
  429. You may want to check the wxXmlResourceHandler documentation to see how many
  430. built-in getters it contains. It's very easy to retrieve also complex
  431. structures out of XRC files using them.
  432. */